index.cjs.js 829 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var app = require('@firebase/app');
  4. var component = require('@firebase/component');
  5. var logger = require('@firebase/logger');
  6. var util = require('@firebase/util');
  7. var webchannelWrapper = require('@firebase/webchannel-wrapper');
  8. const b = "@firebase/firestore";
  9. /**
  10. * @license
  11. * Copyright 2017 Google LLC
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License");
  14. * you may not use this file except in compliance with the License.
  15. * You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS,
  21. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. * See the License for the specific language governing permissions and
  23. * limitations under the License.
  24. */
  25. /**
  26. * Simple wrapper around a nullable UID. Mostly exists to make code more
  27. * readable.
  28. */
  29. class V {
  30. constructor(t) {
  31. this.uid = t;
  32. }
  33. isAuthenticated() {
  34. return null != this.uid;
  35. }
  36. /**
  37. * Returns a key representing this user, suitable for inclusion in a
  38. * dictionary.
  39. */ toKey() {
  40. return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
  41. }
  42. isEqual(t) {
  43. return t.uid === this.uid;
  44. }
  45. }
  46. /** A user with a null UID. */ V.UNAUTHENTICATED = new V(null),
  47. // TODO(mikelehen): Look into getting a proper uid-equivalent for
  48. // non-FirebaseAuth providers.
  49. V.GOOGLE_CREDENTIALS = new V("google-credentials-uid"), V.FIRST_PARTY = new V("first-party-uid"),
  50. V.MOCK_USER = new V("mock-user");
  51. /**
  52. * @license
  53. * Copyright 2017 Google LLC
  54. *
  55. * Licensed under the Apache License, Version 2.0 (the "License");
  56. * you may not use this file except in compliance with the License.
  57. * You may obtain a copy of the License at
  58. *
  59. * http://www.apache.org/licenses/LICENSE-2.0
  60. *
  61. * Unless required by applicable law or agreed to in writing, software
  62. * distributed under the License is distributed on an "AS IS" BASIS,
  63. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  64. * See the License for the specific language governing permissions and
  65. * limitations under the License.
  66. */
  67. let S = "9.23.0";
  68. /**
  69. * @license
  70. * Copyright 2017 Google LLC
  71. *
  72. * Licensed under the Apache License, Version 2.0 (the "License");
  73. * you may not use this file except in compliance with the License.
  74. * You may obtain a copy of the License at
  75. *
  76. * http://www.apache.org/licenses/LICENSE-2.0
  77. *
  78. * Unless required by applicable law or agreed to in writing, software
  79. * distributed under the License is distributed on an "AS IS" BASIS,
  80. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  81. * See the License for the specific language governing permissions and
  82. * limitations under the License.
  83. */
  84. const D = new logger.Logger("@firebase/firestore");
  85. // Helper methods are needed because variables can't be exported as read/write
  86. function C() {
  87. return D.logLevel;
  88. }
  89. /**
  90. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  91. *
  92. * @param logLevel - The verbosity you set for activity and error logging. Can
  93. * be any of the following values:
  94. *
  95. * <ul>
  96. * <li>`debug` for the most verbose logging level, primarily for
  97. * debugging.</li>
  98. * <li>`error` to log errors only.</li>
  99. * <li><code>`silent` to turn off logging.</li>
  100. * </ul>
  101. */ function x(t) {
  102. D.setLogLevel(t);
  103. }
  104. function N(t, ...e) {
  105. if (D.logLevel <= logger.LogLevel.DEBUG) {
  106. const n = e.map($);
  107. D.debug(`Firestore (${S}): ${t}`, ...n);
  108. }
  109. }
  110. function k(t, ...e) {
  111. if (D.logLevel <= logger.LogLevel.ERROR) {
  112. const n = e.map($);
  113. D.error(`Firestore (${S}): ${t}`, ...n);
  114. }
  115. }
  116. /**
  117. * @internal
  118. */ function M(t, ...e) {
  119. if (D.logLevel <= logger.LogLevel.WARN) {
  120. const n = e.map($);
  121. D.warn(`Firestore (${S}): ${t}`, ...n);
  122. }
  123. }
  124. /**
  125. * Converts an additional log parameter to a string representation.
  126. */ function $(t) {
  127. if ("string" == typeof t) return t;
  128. try {
  129. return e = t, JSON.stringify(e);
  130. } catch (e) {
  131. // Converting to JSON failed, just log the object directly
  132. return t;
  133. }
  134. /**
  135. * @license
  136. * Copyright 2020 Google LLC
  137. *
  138. * Licensed under the Apache License, Version 2.0 (the "License");
  139. * you may not use this file except in compliance with the License.
  140. * You may obtain a copy of the License at
  141. *
  142. * http://www.apache.org/licenses/LICENSE-2.0
  143. *
  144. * Unless required by applicable law or agreed to in writing, software
  145. * distributed under the License is distributed on an "AS IS" BASIS,
  146. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  147. * See the License for the specific language governing permissions and
  148. * limitations under the License.
  149. */
  150. /** Formats an object as a JSON string, suitable for logging. */
  151. var e;
  152. }
  153. /**
  154. * @license
  155. * Copyright 2017 Google LLC
  156. *
  157. * Licensed under the Apache License, Version 2.0 (the "License");
  158. * you may not use this file except in compliance with the License.
  159. * You may obtain a copy of the License at
  160. *
  161. * http://www.apache.org/licenses/LICENSE-2.0
  162. *
  163. * Unless required by applicable law or agreed to in writing, software
  164. * distributed under the License is distributed on an "AS IS" BASIS,
  165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  166. * See the License for the specific language governing permissions and
  167. * limitations under the License.
  168. */
  169. /**
  170. * Unconditionally fails, throwing an Error with the given message.
  171. * Messages are stripped in production builds.
  172. *
  173. * Returns `never` and can be used in expressions:
  174. * @example
  175. * let futureVar = fail('not implemented yet');
  176. */ function O(t = "Unexpected state") {
  177. // Log the failure in addition to throw an exception, just in case the
  178. // exception is swallowed.
  179. const e = `FIRESTORE (${S}) INTERNAL ASSERTION FAILED: ` + t;
  180. // NOTE: We don't use FirestoreError here because these are internal failures
  181. // that cannot be handled by the user. (Also it would create a circular
  182. // dependency between the error and assert modules which doesn't work.)
  183. throw k(e), new Error(e);
  184. }
  185. /**
  186. * Fails if the given assertion condition is false, throwing an Error with the
  187. * given message if it did.
  188. *
  189. * Messages are stripped in production builds.
  190. */ function F(t, e) {
  191. t || O();
  192. }
  193. /**
  194. * Fails if the given assertion condition is false, throwing an Error with the
  195. * given message if it did.
  196. *
  197. * The code of callsites invoking this function are stripped out in production
  198. * builds. Any side-effects of code within the debugAssert() invocation will not
  199. * happen in this case.
  200. *
  201. * @internal
  202. */ function B(t, e) {
  203. t || O();
  204. }
  205. /**
  206. * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
  207. * instance of `T` before casting.
  208. */ function L(t,
  209. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  210. e) {
  211. return t;
  212. }
  213. /**
  214. * @license
  215. * Copyright 2017 Google LLC
  216. *
  217. * Licensed under the Apache License, Version 2.0 (the "License");
  218. * you may not use this file except in compliance with the License.
  219. * You may obtain a copy of the License at
  220. *
  221. * http://www.apache.org/licenses/LICENSE-2.0
  222. *
  223. * Unless required by applicable law or agreed to in writing, software
  224. * distributed under the License is distributed on an "AS IS" BASIS,
  225. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  226. * See the License for the specific language governing permissions and
  227. * limitations under the License.
  228. */ const q = {
  229. // Causes are copied from:
  230. // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  231. /** Not an error; returned on success. */
  232. OK: "ok",
  233. /** The operation was cancelled (typically by the caller). */
  234. CANCELLED: "cancelled",
  235. /** Unknown error or an error from a different error domain. */
  236. UNKNOWN: "unknown",
  237. /**
  238. * Client specified an invalid argument. Note that this differs from
  239. * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
  240. * problematic regardless of the state of the system (e.g., a malformed file
  241. * name).
  242. */
  243. INVALID_ARGUMENT: "invalid-argument",
  244. /**
  245. * Deadline expired before operation could complete. For operations that
  246. * change the state of the system, this error may be returned even if the
  247. * operation has completed successfully. For example, a successful response
  248. * from a server could have been delayed long enough for the deadline to
  249. * expire.
  250. */
  251. DEADLINE_EXCEEDED: "deadline-exceeded",
  252. /** Some requested entity (e.g., file or directory) was not found. */
  253. NOT_FOUND: "not-found",
  254. /**
  255. * Some entity that we attempted to create (e.g., file or directory) already
  256. * exists.
  257. */
  258. ALREADY_EXISTS: "already-exists",
  259. /**
  260. * The caller does not have permission to execute the specified operation.
  261. * PERMISSION_DENIED must not be used for rejections caused by exhausting
  262. * some resource (use RESOURCE_EXHAUSTED instead for those errors).
  263. * PERMISSION_DENIED must not be used if the caller can not be identified
  264. * (use UNAUTHENTICATED instead for those errors).
  265. */
  266. PERMISSION_DENIED: "permission-denied",
  267. /**
  268. * The request does not have valid authentication credentials for the
  269. * operation.
  270. */
  271. UNAUTHENTICATED: "unauthenticated",
  272. /**
  273. * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  274. * entire file system is out of space.
  275. */
  276. RESOURCE_EXHAUSTED: "resource-exhausted",
  277. /**
  278. * Operation was rejected because the system is not in a state required for
  279. * the operation's execution. For example, directory to be deleted may be
  280. * non-empty, an rmdir operation is applied to a non-directory, etc.
  281. *
  282. * A litmus test that may help a service implementor in deciding
  283. * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  284. * (a) Use UNAVAILABLE if the client can retry just the failing call.
  285. * (b) Use ABORTED if the client should retry at a higher-level
  286. * (e.g., restarting a read-modify-write sequence).
  287. * (c) Use FAILED_PRECONDITION if the client should not retry until
  288. * the system state has been explicitly fixed. E.g., if an "rmdir"
  289. * fails because the directory is non-empty, FAILED_PRECONDITION
  290. * should be returned since the client should not retry unless
  291. * they have first fixed up the directory by deleting files from it.
  292. * (d) Use FAILED_PRECONDITION if the client performs conditional
  293. * REST Get/Update/Delete on a resource and the resource on the
  294. * server does not match the condition. E.g., conflicting
  295. * read-modify-write on the same resource.
  296. */
  297. FAILED_PRECONDITION: "failed-precondition",
  298. /**
  299. * The operation was aborted, typically due to a concurrency issue like
  300. * sequencer check failures, transaction aborts, etc.
  301. *
  302. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  303. * and UNAVAILABLE.
  304. */
  305. ABORTED: "aborted",
  306. /**
  307. * Operation was attempted past the valid range. E.g., seeking or reading
  308. * past end of file.
  309. *
  310. * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
  311. * if the system state changes. For example, a 32-bit file system will
  312. * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
  313. * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  314. * an offset past the current file size.
  315. *
  316. * There is a fair bit of overlap between FAILED_PRECONDITION and
  317. * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  318. * when it applies so that callers who are iterating through a space can
  319. * easily look for an OUT_OF_RANGE error to detect when they are done.
  320. */
  321. OUT_OF_RANGE: "out-of-range",
  322. /** Operation is not implemented or not supported/enabled in this service. */
  323. UNIMPLEMENTED: "unimplemented",
  324. /**
  325. * Internal errors. Means some invariants expected by underlying System has
  326. * been broken. If you see one of these errors, Something is very broken.
  327. */
  328. INTERNAL: "internal",
  329. /**
  330. * The service is currently unavailable. This is a most likely a transient
  331. * condition and may be corrected by retrying with a backoff.
  332. *
  333. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  334. * and UNAVAILABLE.
  335. */
  336. UNAVAILABLE: "unavailable",
  337. /** Unrecoverable data loss or corruption. */
  338. DATA_LOSS: "data-loss"
  339. };
  340. /** An error returned by a Firestore operation. */ class U extends util.FirebaseError {
  341. /** @hideconstructor */
  342. constructor(
  343. /**
  344. * The backend error code associated with this error.
  345. */
  346. t,
  347. /**
  348. * A custom error description.
  349. */
  350. e) {
  351. super(t, e), this.code = t, this.message = e,
  352. // HACK: We write a toString property directly because Error is not a real
  353. // class and so inheritance does not work correctly. We could alternatively
  354. // do the same "back-door inheritance" trick that FirebaseError does.
  355. this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
  356. }
  357. }
  358. /**
  359. * @license
  360. * Copyright 2017 Google LLC
  361. *
  362. * Licensed under the Apache License, Version 2.0 (the "License");
  363. * you may not use this file except in compliance with the License.
  364. * You may obtain a copy of the License at
  365. *
  366. * http://www.apache.org/licenses/LICENSE-2.0
  367. *
  368. * Unless required by applicable law or agreed to in writing, software
  369. * distributed under the License is distributed on an "AS IS" BASIS,
  370. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  371. * See the License for the specific language governing permissions and
  372. * limitations under the License.
  373. */ class K {
  374. constructor() {
  375. this.promise = new Promise(((t, e) => {
  376. this.resolve = t, this.reject = e;
  377. }));
  378. }
  379. }
  380. /**
  381. * @license
  382. * Copyright 2017 Google LLC
  383. *
  384. * Licensed under the Apache License, Version 2.0 (the "License");
  385. * you may not use this file except in compliance with the License.
  386. * You may obtain a copy of the License at
  387. *
  388. * http://www.apache.org/licenses/LICENSE-2.0
  389. *
  390. * Unless required by applicable law or agreed to in writing, software
  391. * distributed under the License is distributed on an "AS IS" BASIS,
  392. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  393. * See the License for the specific language governing permissions and
  394. * limitations under the License.
  395. */ class G {
  396. constructor(t, e) {
  397. this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`);
  398. }
  399. }
  400. /**
  401. * A CredentialsProvider that always yields an empty token.
  402. * @internal
  403. */ class Q {
  404. getToken() {
  405. return Promise.resolve(null);
  406. }
  407. invalidateToken() {}
  408. start(t, e) {
  409. // Fire with initial user.
  410. t.enqueueRetryable((() => e(V.UNAUTHENTICATED)));
  411. }
  412. shutdown() {}
  413. }
  414. /**
  415. * A CredentialsProvider that always returns a constant token. Used for
  416. * emulator token mocking.
  417. */ class j {
  418. constructor(t) {
  419. this.token = t,
  420. /**
  421. * Stores the listener registered with setChangeListener()
  422. * This isn't actually necessary since the UID never changes, but we use this
  423. * to verify the listen contract is adhered to in tests.
  424. */
  425. this.changeListener = null;
  426. }
  427. getToken() {
  428. return Promise.resolve(this.token);
  429. }
  430. invalidateToken() {}
  431. start(t, e) {
  432. this.changeListener = e,
  433. // Fire with initial user.
  434. t.enqueueRetryable((() => e(this.token.user)));
  435. }
  436. shutdown() {
  437. this.changeListener = null;
  438. }
  439. }
  440. class z {
  441. constructor(t) {
  442. this.t = t,
  443. /** Tracks the current User. */
  444. this.currentUser = V.UNAUTHENTICATED,
  445. /**
  446. * Counter used to detect if the token changed while a getToken request was
  447. * outstanding.
  448. */
  449. this.i = 0, this.forceRefresh = !1, this.auth = null;
  450. }
  451. start(t, e) {
  452. let n = this.i;
  453. // A change listener that prevents double-firing for the same token change.
  454. const s = t => this.i !== n ? (n = this.i, e(t)) : Promise.resolve();
  455. // A promise that can be waited on to block on the next token change.
  456. // This promise is re-created after each change.
  457. let i = new K;
  458. this.o = () => {
  459. this.i++, this.currentUser = this.u(), i.resolve(), i = new K, t.enqueueRetryable((() => s(this.currentUser)));
  460. };
  461. const r = () => {
  462. const e = i;
  463. t.enqueueRetryable((async () => {
  464. await e.promise, await s(this.currentUser);
  465. }));
  466. }, o = t => {
  467. N("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = t, this.auth.addAuthTokenListener(this.o),
  468. r();
  469. };
  470. this.t.onInit((t => o(t))),
  471. // Our users can initialize Auth right after Firestore, so we give it
  472. // a chance to register itself with the component framework before we
  473. // determine whether to start up in unauthenticated mode.
  474. setTimeout((() => {
  475. if (!this.auth) {
  476. const t = this.t.getImmediate({
  477. optional: !0
  478. });
  479. t ? o(t) : (
  480. // If auth is still not available, proceed with `null` user
  481. N("FirebaseAuthCredentialsProvider", "Auth not yet detected"), i.resolve(), i = new K);
  482. }
  483. }), 0), r();
  484. }
  485. getToken() {
  486. // Take note of the current value of the tokenCounter so that this method
  487. // can fail (with an ABORTED error) if there is a token change while the
  488. // request is outstanding.
  489. const t = this.i, e = this.forceRefresh;
  490. return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e =>
  491. // Cancel the request since the token changed while the request was
  492. // outstanding so the response is potentially for a previous user (which
  493. // user, we can't be sure).
  494. this.i !== t ? (N("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."),
  495. this.getToken()) : e ? (F("string" == typeof e.accessToken), new G(e.accessToken, this.currentUser)) : null)) : Promise.resolve(null);
  496. }
  497. invalidateToken() {
  498. this.forceRefresh = !0;
  499. }
  500. shutdown() {
  501. this.auth && this.auth.removeAuthTokenListener(this.o);
  502. }
  503. // Auth.getUid() can return null even with a user logged in. It is because
  504. // getUid() is synchronous, but the auth code populating Uid is asynchronous.
  505. // This method should only be called in the AuthTokenListener callback
  506. // to guarantee to get the actual user.
  507. u() {
  508. const t = this.auth && this.auth.getUid();
  509. return F(null === t || "string" == typeof t), new V(t);
  510. }
  511. }
  512. /*
  513. * FirstPartyToken provides a fresh token each time its value
  514. * is requested, because if the token is too old, requests will be rejected.
  515. * Technically this may no longer be necessary since the SDK should gracefully
  516. * recover from unauthenticated errors (see b/33147818 for context), but it's
  517. * safer to keep the implementation as-is.
  518. */ class W {
  519. constructor(t, e, n) {
  520. this.h = t, this.l = e, this.m = n, this.type = "FirstParty", this.user = V.FIRST_PARTY,
  521. this.g = new Map;
  522. }
  523. /**
  524. * Gets an authorization token, using a provided factory function, or return
  525. * null.
  526. */ p() {
  527. return this.m ? this.m() : null;
  528. }
  529. get headers() {
  530. this.g.set("X-Goog-AuthUser", this.h);
  531. // Use array notation to prevent minification
  532. const t = this.p();
  533. return t && this.g.set("Authorization", t), this.l && this.g.set("X-Goog-Iam-Authorization-Token", this.l),
  534. this.g;
  535. }
  536. }
  537. /*
  538. * Provides user credentials required for the Firestore JavaScript SDK
  539. * to authenticate the user, using technique that is only available
  540. * to applications hosted by Google.
  541. */ class H {
  542. constructor(t, e, n) {
  543. this.h = t, this.l = e, this.m = n;
  544. }
  545. getToken() {
  546. return Promise.resolve(new W(this.h, this.l, this.m));
  547. }
  548. start(t, e) {
  549. // Fire with initial uid.
  550. t.enqueueRetryable((() => e(V.FIRST_PARTY)));
  551. }
  552. shutdown() {}
  553. invalidateToken() {}
  554. }
  555. class J {
  556. constructor(t) {
  557. this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
  558. }
  559. }
  560. class Y {
  561. constructor(t) {
  562. this.I = t, this.forceRefresh = !1, this.appCheck = null, this.T = null;
  563. }
  564. start(t, e) {
  565. const n = t => {
  566. null != t.error && N("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${t.error.message}`);
  567. const n = t.token !== this.T;
  568. return this.T = t.token, N("FirebaseAppCheckTokenProvider", `Received ${n ? "new" : "existing"} token.`),
  569. n ? e(t.token) : Promise.resolve();
  570. };
  571. this.o = e => {
  572. t.enqueueRetryable((() => n(e)));
  573. };
  574. const s = t => {
  575. N("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = t, this.appCheck.addTokenListener(this.o);
  576. };
  577. this.I.onInit((t => s(t))),
  578. // Our users can initialize AppCheck after Firestore, so we give it
  579. // a chance to register itself with the component framework.
  580. setTimeout((() => {
  581. if (!this.appCheck) {
  582. const t = this.I.getImmediate({
  583. optional: !0
  584. });
  585. t ? s(t) :
  586. // If AppCheck is still not available, proceed without it.
  587. N("FirebaseAppCheckTokenProvider", "AppCheck not yet detected");
  588. }
  589. }), 0);
  590. }
  591. getToken() {
  592. const t = this.forceRefresh;
  593. return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(t).then((t => t ? (F("string" == typeof t.token),
  594. this.T = t.token, new J(t.token)) : null)) : Promise.resolve(null);
  595. }
  596. invalidateToken() {
  597. this.forceRefresh = !0;
  598. }
  599. shutdown() {
  600. this.appCheck && this.appCheck.removeTokenListener(this.o);
  601. }
  602. }
  603. /**
  604. * An AppCheck token provider that always yields an empty token.
  605. * @internal
  606. */ class X {
  607. getToken() {
  608. return Promise.resolve(new J(""));
  609. }
  610. invalidateToken() {}
  611. start(t, e) {}
  612. shutdown() {}
  613. }
  614. /**
  615. * Builds a CredentialsProvider depending on the type of
  616. * the credentials passed in.
  617. */
  618. /**
  619. * @license
  620. * Copyright 2020 Google LLC
  621. *
  622. * Licensed under the Apache License, Version 2.0 (the "License");
  623. * you may not use this file except in compliance with the License.
  624. * You may obtain a copy of the License at
  625. *
  626. * http://www.apache.org/licenses/LICENSE-2.0
  627. *
  628. * Unless required by applicable law or agreed to in writing, software
  629. * distributed under the License is distributed on an "AS IS" BASIS,
  630. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  631. * See the License for the specific language governing permissions and
  632. * limitations under the License.
  633. */
  634. /**
  635. * Generates `nBytes` of random bytes.
  636. *
  637. * If `nBytes < 0` , an error will be thrown.
  638. */
  639. function Z(t) {
  640. // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
  641. const e =
  642. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  643. "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);
  644. if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else
  645. // Falls back to Math.random
  646. for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());
  647. return n;
  648. }
  649. /**
  650. * @license
  651. * Copyright 2017 Google LLC
  652. *
  653. * Licensed under the Apache License, Version 2.0 (the "License");
  654. * you may not use this file except in compliance with the License.
  655. * You may obtain a copy of the License at
  656. *
  657. * http://www.apache.org/licenses/LICENSE-2.0
  658. *
  659. * Unless required by applicable law or agreed to in writing, software
  660. * distributed under the License is distributed on an "AS IS" BASIS,
  661. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  662. * See the License for the specific language governing permissions and
  663. * limitations under the License.
  664. */ class tt {
  665. static A() {
  666. // Alphanumeric characters
  667. const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length;
  668. // The largest byte value that is a multiple of `char.length`.
  669. let n = "";
  670. for (;n.length < 20; ) {
  671. const s = Z(40);
  672. for (let i = 0; i < s.length; ++i)
  673. // Only accept values that are [0, maxMultiple), this ensures they can
  674. // be evenly mapped to indices of `chars` via a modulo operation.
  675. n.length < 20 && s[i] < e && (n += t.charAt(s[i] % t.length));
  676. }
  677. return n;
  678. }
  679. }
  680. function et(t, e) {
  681. return t < e ? -1 : t > e ? 1 : 0;
  682. }
  683. /** Helper to compare arrays using isEqual(). */ function nt(t, e, n) {
  684. return t.length === e.length && t.every(((t, s) => n(t, e[s])));
  685. }
  686. /**
  687. * Returns the immediate lexicographically-following string. This is useful to
  688. * construct an inclusive range for indexeddb iterators.
  689. */ function st(t) {
  690. // Return the input string, with an additional NUL byte appended.
  691. return t + "\0";
  692. }
  693. /**
  694. * @license
  695. * Copyright 2017 Google LLC
  696. *
  697. * Licensed under the Apache License, Version 2.0 (the "License");
  698. * you may not use this file except in compliance with the License.
  699. * You may obtain a copy of the License at
  700. *
  701. * http://www.apache.org/licenses/LICENSE-2.0
  702. *
  703. * Unless required by applicable law or agreed to in writing, software
  704. * distributed under the License is distributed on an "AS IS" BASIS,
  705. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  706. * See the License for the specific language governing permissions and
  707. * limitations under the License.
  708. */
  709. // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
  710. /**
  711. * A `Timestamp` represents a point in time independent of any time zone or
  712. * calendar, represented as seconds and fractions of seconds at nanosecond
  713. * resolution in UTC Epoch time.
  714. *
  715. * It is encoded using the Proleptic Gregorian Calendar which extends the
  716. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  717. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  718. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  719. * 9999-12-31T23:59:59.999999999Z.
  720. *
  721. * For examples and further specifications, refer to the
  722. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  723. */
  724. class it {
  725. /**
  726. * Creates a new timestamp.
  727. *
  728. * @param seconds - The number of seconds of UTC time since Unix epoch
  729. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  730. * 9999-12-31T23:59:59Z inclusive.
  731. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  732. * resolution. Negative second values with fractions must still have
  733. * non-negative nanoseconds values that count forward in time. Must be
  734. * from 0 to 999,999,999 inclusive.
  735. */
  736. constructor(
  737. /**
  738. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  739. */
  740. t,
  741. /**
  742. * The fractions of a second at nanosecond resolution.*
  743. */
  744. e) {
  745. if (this.seconds = t, this.nanoseconds = e, e < 0) throw new U(q.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  746. if (e >= 1e9) throw new U(q.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  747. if (t < -62135596800) throw new U(q.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  748. // This will break in the year 10,000.
  749. if (t >= 253402300800) throw new U(q.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  750. }
  751. /**
  752. * Creates a new timestamp with the current date, with millisecond precision.
  753. *
  754. * @returns a new timestamp representing the current date.
  755. */ static now() {
  756. return it.fromMillis(Date.now());
  757. }
  758. /**
  759. * Creates a new timestamp from the given date.
  760. *
  761. * @param date - The date to initialize the `Timestamp` from.
  762. * @returns A new `Timestamp` representing the same point in time as the given
  763. * date.
  764. */ static fromDate(t) {
  765. return it.fromMillis(t.getTime());
  766. }
  767. /**
  768. * Creates a new timestamp from the given number of milliseconds.
  769. *
  770. * @param milliseconds - Number of milliseconds since Unix epoch
  771. * 1970-01-01T00:00:00Z.
  772. * @returns A new `Timestamp` representing the same point in time as the given
  773. * number of milliseconds.
  774. */ static fromMillis(t) {
  775. const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));
  776. return new it(e, n);
  777. }
  778. /**
  779. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  780. * causes a loss of precision since `Date` objects only support millisecond
  781. * precision.
  782. *
  783. * @returns JavaScript `Date` object representing the same point in time as
  784. * this `Timestamp`, with millisecond precision.
  785. */ toDate() {
  786. return new Date(this.toMillis());
  787. }
  788. /**
  789. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  790. * epoch). This operation causes a loss of precision.
  791. *
  792. * @returns The point in time corresponding to this timestamp, represented as
  793. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  794. */ toMillis() {
  795. return 1e3 * this.seconds + this.nanoseconds / 1e6;
  796. }
  797. _compareTo(t) {
  798. return this.seconds === t.seconds ? et(this.nanoseconds, t.nanoseconds) : et(this.seconds, t.seconds);
  799. }
  800. /**
  801. * Returns true if this `Timestamp` is equal to the provided one.
  802. *
  803. * @param other - The `Timestamp` to compare against.
  804. * @returns true if this `Timestamp` is equal to the provided one.
  805. */ isEqual(t) {
  806. return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
  807. }
  808. /** Returns a textual representation of this `Timestamp`. */ toString() {
  809. return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
  810. }
  811. /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {
  812. return {
  813. seconds: this.seconds,
  814. nanoseconds: this.nanoseconds
  815. };
  816. }
  817. /**
  818. * Converts this object to a primitive string, which allows `Timestamp` objects
  819. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  820. */ valueOf() {
  821. // This method returns a string of the form <seconds>.<nanoseconds> where
  822. // <seconds> is translated to have a non-negative value and both <seconds>
  823. // and <nanoseconds> are left-padded with zeroes to be a consistent length.
  824. // Strings with this format then have a lexiographical ordering that matches
  825. // the expected ordering. The <seconds> translation is done to avoid having
  826. // a leading negative sign (i.e. a leading '-' character) in its string
  827. // representation, which would affect its lexiographical ordering.
  828. const t = this.seconds - -62135596800;
  829. // Note: Up to 12 decimal digits are required to represent all valid
  830. // 'seconds' values.
  831. return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
  832. }
  833. }
  834. /**
  835. * @license
  836. * Copyright 2017 Google LLC
  837. *
  838. * Licensed under the Apache License, Version 2.0 (the "License");
  839. * you may not use this file except in compliance with the License.
  840. * You may obtain a copy of the License at
  841. *
  842. * http://www.apache.org/licenses/LICENSE-2.0
  843. *
  844. * Unless required by applicable law or agreed to in writing, software
  845. * distributed under the License is distributed on an "AS IS" BASIS,
  846. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  847. * See the License for the specific language governing permissions and
  848. * limitations under the License.
  849. */
  850. /**
  851. * A version of a document in Firestore. This corresponds to the version
  852. * timestamp, such as update_time or read_time.
  853. */ class rt {
  854. constructor(t) {
  855. this.timestamp = t;
  856. }
  857. static fromTimestamp(t) {
  858. return new rt(t);
  859. }
  860. static min() {
  861. return new rt(new it(0, 0));
  862. }
  863. static max() {
  864. return new rt(new it(253402300799, 999999999));
  865. }
  866. compareTo(t) {
  867. return this.timestamp._compareTo(t.timestamp);
  868. }
  869. isEqual(t) {
  870. return this.timestamp.isEqual(t.timestamp);
  871. }
  872. /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {
  873. // Convert to microseconds.
  874. return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
  875. }
  876. toString() {
  877. return "SnapshotVersion(" + this.timestamp.toString() + ")";
  878. }
  879. toTimestamp() {
  880. return this.timestamp;
  881. }
  882. }
  883. /**
  884. * @license
  885. * Copyright 2017 Google LLC
  886. *
  887. * Licensed under the Apache License, Version 2.0 (the "License");
  888. * you may not use this file except in compliance with the License.
  889. * You may obtain a copy of the License at
  890. *
  891. * http://www.apache.org/licenses/LICENSE-2.0
  892. *
  893. * Unless required by applicable law or agreed to in writing, software
  894. * distributed under the License is distributed on an "AS IS" BASIS,
  895. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  896. * See the License for the specific language governing permissions and
  897. * limitations under the License.
  898. */
  899. /**
  900. * Path represents an ordered sequence of string segments.
  901. */
  902. class ot {
  903. constructor(t, e, n) {
  904. void 0 === e ? e = 0 : e > t.length && O(), void 0 === n ? n = t.length - e : n > t.length - e && O(),
  905. this.segments = t, this.offset = e, this.len = n;
  906. }
  907. get length() {
  908. return this.len;
  909. }
  910. isEqual(t) {
  911. return 0 === ot.comparator(this, t);
  912. }
  913. child(t) {
  914. const e = this.segments.slice(this.offset, this.limit());
  915. return t instanceof ot ? t.forEach((t => {
  916. e.push(t);
  917. })) : e.push(t), this.construct(e);
  918. }
  919. /** The index of one past the last segment of the path. */ limit() {
  920. return this.offset + this.length;
  921. }
  922. popFirst(t) {
  923. return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);
  924. }
  925. popLast() {
  926. return this.construct(this.segments, this.offset, this.length - 1);
  927. }
  928. firstSegment() {
  929. return this.segments[this.offset];
  930. }
  931. lastSegment() {
  932. return this.get(this.length - 1);
  933. }
  934. get(t) {
  935. return this.segments[this.offset + t];
  936. }
  937. isEmpty() {
  938. return 0 === this.length;
  939. }
  940. isPrefixOf(t) {
  941. if (t.length < this.length) return !1;
  942. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  943. return !0;
  944. }
  945. isImmediateParentOf(t) {
  946. if (this.length + 1 !== t.length) return !1;
  947. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  948. return !0;
  949. }
  950. forEach(t) {
  951. for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);
  952. }
  953. toArray() {
  954. return this.segments.slice(this.offset, this.limit());
  955. }
  956. static comparator(t, e) {
  957. const n = Math.min(t.length, e.length);
  958. for (let s = 0; s < n; s++) {
  959. const n = t.get(s), i = e.get(s);
  960. if (n < i) return -1;
  961. if (n > i) return 1;
  962. }
  963. return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
  964. }
  965. }
  966. /**
  967. * A slash-separated path for navigating resources (documents and collections)
  968. * within Firestore.
  969. *
  970. * @internal
  971. */ class ut extends ot {
  972. construct(t, e, n) {
  973. return new ut(t, e, n);
  974. }
  975. canonicalString() {
  976. // NOTE: The client is ignorant of any path segments containing escape
  977. // sequences (e.g. __id123__) and just passes them through raw (they exist
  978. // for legacy reasons and should not be used frequently).
  979. return this.toArray().join("/");
  980. }
  981. toString() {
  982. return this.canonicalString();
  983. }
  984. /**
  985. * Creates a resource path from the given slash-delimited string. If multiple
  986. * arguments are provided, all components are combined. Leading and trailing
  987. * slashes from all components are ignored.
  988. */ static fromString(...t) {
  989. // NOTE: The client is ignorant of any path segments containing escape
  990. // sequences (e.g. __id123__) and just passes them through raw (they exist
  991. // for legacy reasons and should not be used frequently).
  992. const e = [];
  993. for (const n of t) {
  994. if (n.indexOf("//") >= 0) throw new U(q.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);
  995. // Strip leading and traling slashed.
  996. e.push(...n.split("/").filter((t => t.length > 0)));
  997. }
  998. return new ut(e);
  999. }
  1000. static emptyPath() {
  1001. return new ut([]);
  1002. }
  1003. }
  1004. const ct = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
  1005. /**
  1006. * A dot-separated path for navigating sub-objects within a document.
  1007. * @internal
  1008. */ class at extends ot {
  1009. construct(t, e, n) {
  1010. return new at(t, e, n);
  1011. }
  1012. /**
  1013. * Returns true if the string could be used as a segment in a field path
  1014. * without escaping.
  1015. */ static isValidIdentifier(t) {
  1016. return ct.test(t);
  1017. }
  1018. canonicalString() {
  1019. return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"),
  1020. at.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join(".");
  1021. }
  1022. toString() {
  1023. return this.canonicalString();
  1024. }
  1025. /**
  1026. * Returns true if this field references the key of a document.
  1027. */ isKeyField() {
  1028. return 1 === this.length && "__name__" === this.get(0);
  1029. }
  1030. /**
  1031. * The field designating the key of a document.
  1032. */ static keyField() {
  1033. return new at([ "__name__" ]);
  1034. }
  1035. /**
  1036. * Parses a field string from the given server-formatted string.
  1037. *
  1038. * - Splitting the empty string is not allowed (for now at least).
  1039. * - Empty segments within the string (e.g. if there are two consecutive
  1040. * separators) are not allowed.
  1041. *
  1042. * TODO(b/37244157): we should make this more strict. Right now, it allows
  1043. * non-identifier path components, even if they aren't escaped.
  1044. */ static fromServerFormat(t) {
  1045. const e = [];
  1046. let n = "", s = 0;
  1047. const i = () => {
  1048. if (0 === n.length) throw new U(q.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
  1049. e.push(n), n = "";
  1050. };
  1051. let r = !1;
  1052. for (;s < t.length; ) {
  1053. const e = t[s];
  1054. if ("\\" === e) {
  1055. if (s + 1 === t.length) throw new U(q.INVALID_ARGUMENT, "Path has trailing escape character: " + t);
  1056. const e = t[s + 1];
  1057. if ("\\" !== e && "." !== e && "`" !== e) throw new U(q.INVALID_ARGUMENT, "Path has invalid escape sequence: " + t);
  1058. n += e, s += 2;
  1059. } else "`" === e ? (r = !r, s++) : "." !== e || r ? (n += e, s++) : (i(), s++);
  1060. }
  1061. if (i(), r) throw new U(q.INVALID_ARGUMENT, "Unterminated ` in path: " + t);
  1062. return new at(e);
  1063. }
  1064. static emptyPath() {
  1065. return new at([]);
  1066. }
  1067. }
  1068. /**
  1069. * @license
  1070. * Copyright 2017 Google LLC
  1071. *
  1072. * Licensed under the Apache License, Version 2.0 (the "License");
  1073. * you may not use this file except in compliance with the License.
  1074. * You may obtain a copy of the License at
  1075. *
  1076. * http://www.apache.org/licenses/LICENSE-2.0
  1077. *
  1078. * Unless required by applicable law or agreed to in writing, software
  1079. * distributed under the License is distributed on an "AS IS" BASIS,
  1080. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1081. * See the License for the specific language governing permissions and
  1082. * limitations under the License.
  1083. */
  1084. /**
  1085. * @internal
  1086. */ class ht {
  1087. constructor(t) {
  1088. this.path = t;
  1089. }
  1090. static fromPath(t) {
  1091. return new ht(ut.fromString(t));
  1092. }
  1093. static fromName(t) {
  1094. return new ht(ut.fromString(t).popFirst(5));
  1095. }
  1096. static empty() {
  1097. return new ht(ut.emptyPath());
  1098. }
  1099. get collectionGroup() {
  1100. return this.path.popLast().lastSegment();
  1101. }
  1102. /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {
  1103. return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
  1104. }
  1105. /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {
  1106. return this.path.get(this.path.length - 2);
  1107. }
  1108. /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {
  1109. return this.path.popLast();
  1110. }
  1111. isEqual(t) {
  1112. return null !== t && 0 === ut.comparator(this.path, t.path);
  1113. }
  1114. toString() {
  1115. return this.path.toString();
  1116. }
  1117. static comparator(t, e) {
  1118. return ut.comparator(t.path, e.path);
  1119. }
  1120. static isDocumentKey(t) {
  1121. return t.length % 2 == 0;
  1122. }
  1123. /**
  1124. * Creates and returns a new document key with the given segments.
  1125. *
  1126. * @param segments - The segments of the path to the document
  1127. * @returns A new instance of DocumentKey
  1128. */ static fromSegments(t) {
  1129. return new ht(new ut(t.slice()));
  1130. }
  1131. }
  1132. /**
  1133. * @license
  1134. * Copyright 2021 Google LLC
  1135. *
  1136. * Licensed under the Apache License, Version 2.0 (the "License");
  1137. * you may not use this file except in compliance with the License.
  1138. * You may obtain a copy of the License at
  1139. *
  1140. * http://www.apache.org/licenses/LICENSE-2.0
  1141. *
  1142. * Unless required by applicable law or agreed to in writing, software
  1143. * distributed under the License is distributed on an "AS IS" BASIS,
  1144. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1145. * See the License for the specific language governing permissions and
  1146. * limitations under the License.
  1147. */
  1148. /**
  1149. * The initial mutation batch id for each index. Gets updated during index
  1150. * backfill.
  1151. */
  1152. /**
  1153. * An index definition for field indexes in Firestore.
  1154. *
  1155. * Every index is associated with a collection. The definition contains a list
  1156. * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or
  1157. * `CONTAINS` for ArrayContains/ArrayContainsAny queries).
  1158. *
  1159. * Unlike the backend, the SDK does not differentiate between collection or
  1160. * collection group-scoped indices. Every index can be used for both single
  1161. * collection and collection group queries.
  1162. */
  1163. class lt {
  1164. constructor(
  1165. /**
  1166. * The index ID. Returns -1 if the index ID is not available (e.g. the index
  1167. * has not yet been persisted).
  1168. */
  1169. t,
  1170. /** The collection ID this index applies to. */
  1171. e,
  1172. /** The field segments for this index. */
  1173. n,
  1174. /** Shows how up-to-date the index is for the current user. */
  1175. s) {
  1176. this.indexId = t, this.collectionGroup = e, this.fields = n, this.indexState = s;
  1177. }
  1178. }
  1179. /** An ID for an index that has not yet been added to persistence. */
  1180. /** Returns the ArrayContains/ArrayContainsAny segment for this index. */
  1181. function ft(t) {
  1182. return t.fields.find((t => 2 /* IndexKind.CONTAINS */ === t.kind));
  1183. }
  1184. /** Returns all directional (ascending/descending) segments for this index. */ function dt(t) {
  1185. return t.fields.filter((t => 2 /* IndexKind.CONTAINS */ !== t.kind));
  1186. }
  1187. /**
  1188. * Returns the order of the document key component for the given index.
  1189. *
  1190. * PORTING NOTE: This is only used in the Web IndexedDb implementation.
  1191. */
  1192. /**
  1193. * Compares indexes by collection group and segments. Ignores update time and
  1194. * index ID.
  1195. */
  1196. function wt(t, e) {
  1197. let n = et(t.collectionGroup, e.collectionGroup);
  1198. if (0 !== n) return n;
  1199. for (let s = 0; s < Math.min(t.fields.length, e.fields.length); ++s) if (n = mt(t.fields[s], e.fields[s]),
  1200. 0 !== n) return n;
  1201. return et(t.fields.length, e.fields.length);
  1202. }
  1203. /** Returns a debug representation of the field index */ lt.UNKNOWN_ID = -1;
  1204. /** An index component consisting of field path and index type. */
  1205. class _t {
  1206. constructor(
  1207. /** The field path of the component. */
  1208. t,
  1209. /** The fields sorting order. */
  1210. e) {
  1211. this.fieldPath = t, this.kind = e;
  1212. }
  1213. }
  1214. function mt(t, e) {
  1215. const n = at.comparator(t.fieldPath, e.fieldPath);
  1216. return 0 !== n ? n : et(t.kind, e.kind);
  1217. }
  1218. /**
  1219. * Stores the "high water mark" that indicates how updated the Index is for the
  1220. * current user.
  1221. */ class gt {
  1222. constructor(
  1223. /**
  1224. * Indicates when the index was last updated (relative to other indexes).
  1225. */
  1226. t,
  1227. /** The the latest indexed read time, document and batch id. */
  1228. e) {
  1229. this.sequenceNumber = t, this.offset = e;
  1230. }
  1231. /** The state of an index that has not yet been backfilled. */ static empty() {
  1232. return new gt(0, It.min());
  1233. }
  1234. }
  1235. /**
  1236. * Creates an offset that matches all documents with a read time higher than
  1237. * `readTime`.
  1238. */ function yt(t, e) {
  1239. // We want to create an offset that matches all documents with a read time
  1240. // greater than the provided read time. To do so, we technically need to
  1241. // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use
  1242. // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use
  1243. // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches
  1244. // all valid document IDs.
  1245. const n = t.toTimestamp().seconds, s = t.toTimestamp().nanoseconds + 1, i = rt.fromTimestamp(1e9 === s ? new it(n + 1, 0) : new it(n, s));
  1246. return new It(i, ht.empty(), e);
  1247. }
  1248. /** Creates a new offset based on the provided document. */ function pt(t) {
  1249. return new It(t.readTime, t.key, -1);
  1250. }
  1251. /**
  1252. * Stores the latest read time, document and batch ID that were processed for an
  1253. * index.
  1254. */ class It {
  1255. constructor(
  1256. /**
  1257. * The latest read time version that has been indexed by Firestore for this
  1258. * field index.
  1259. */
  1260. t,
  1261. /**
  1262. * The key of the last document that was indexed for this query. Use
  1263. * `DocumentKey.empty()` if no document has been indexed.
  1264. */
  1265. e,
  1266. /*
  1267. * The largest mutation batch id that's been processed by Firestore.
  1268. */
  1269. n) {
  1270. this.readTime = t, this.documentKey = e, this.largestBatchId = n;
  1271. }
  1272. /** Returns an offset that sorts before all regular offsets. */ static min() {
  1273. return new It(rt.min(), ht.empty(), -1);
  1274. }
  1275. /** Returns an offset that sorts after all regular offsets. */ static max() {
  1276. return new It(rt.max(), ht.empty(), -1);
  1277. }
  1278. }
  1279. function Tt(t, e) {
  1280. let n = t.readTime.compareTo(e.readTime);
  1281. return 0 !== n ? n : (n = ht.comparator(t.documentKey, e.documentKey), 0 !== n ? n : et(t.largestBatchId, e.largestBatchId));
  1282. }
  1283. /**
  1284. * @license
  1285. * Copyright 2020 Google LLC
  1286. *
  1287. * Licensed under the Apache License, Version 2.0 (the "License");
  1288. * you may not use this file except in compliance with the License.
  1289. * You may obtain a copy of the License at
  1290. *
  1291. * http://www.apache.org/licenses/LICENSE-2.0
  1292. *
  1293. * Unless required by applicable law or agreed to in writing, software
  1294. * distributed under the License is distributed on an "AS IS" BASIS,
  1295. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1296. * See the License for the specific language governing permissions and
  1297. * limitations under the License.
  1298. */ const Et = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";
  1299. /**
  1300. * A base class representing a persistence transaction, encapsulating both the
  1301. * transaction's sequence numbers as well as a list of onCommitted listeners.
  1302. *
  1303. * When you call Persistence.runTransaction(), it will create a transaction and
  1304. * pass it to your callback. You then pass it to any method that operates
  1305. * on persistence.
  1306. */ class At {
  1307. constructor() {
  1308. this.onCommittedListeners = [];
  1309. }
  1310. addOnCommittedListener(t) {
  1311. this.onCommittedListeners.push(t);
  1312. }
  1313. raiseOnCommittedEvent() {
  1314. this.onCommittedListeners.forEach((t => t()));
  1315. }
  1316. }
  1317. /**
  1318. * @license
  1319. * Copyright 2017 Google LLC
  1320. *
  1321. * Licensed under the Apache License, Version 2.0 (the "License");
  1322. * you may not use this file except in compliance with the License.
  1323. * You may obtain a copy of the License at
  1324. *
  1325. * http://www.apache.org/licenses/LICENSE-2.0
  1326. *
  1327. * Unless required by applicable law or agreed to in writing, software
  1328. * distributed under the License is distributed on an "AS IS" BASIS,
  1329. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1330. * See the License for the specific language governing permissions and
  1331. * limitations under the License.
  1332. */
  1333. /**
  1334. * Verifies the error thrown by a LocalStore operation. If a LocalStore
  1335. * operation fails because the primary lease has been taken by another client,
  1336. * we ignore the error (the persistence layer will immediately call
  1337. * `applyPrimaryLease` to propagate the primary state change). All other errors
  1338. * are re-thrown.
  1339. *
  1340. * @param err - An error returned by a LocalStore operation.
  1341. * @returns A Promise that resolves after we recovered, or the original error.
  1342. */ async function vt(t) {
  1343. if (t.code !== q.FAILED_PRECONDITION || t.message !== Et) throw t;
  1344. N("LocalStore", "Unexpectedly lost primary lease");
  1345. }
  1346. /**
  1347. * @license
  1348. * Copyright 2017 Google LLC
  1349. *
  1350. * Licensed under the Apache License, Version 2.0 (the "License");
  1351. * you may not use this file except in compliance with the License.
  1352. * You may obtain a copy of the License at
  1353. *
  1354. * http://www.apache.org/licenses/LICENSE-2.0
  1355. *
  1356. * Unless required by applicable law or agreed to in writing, software
  1357. * distributed under the License is distributed on an "AS IS" BASIS,
  1358. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1359. * See the License for the specific language governing permissions and
  1360. * limitations under the License.
  1361. */
  1362. /**
  1363. * PersistencePromise is essentially a re-implementation of Promise except
  1364. * it has a .next() method instead of .then() and .next() and .catch() callbacks
  1365. * are executed synchronously when a PersistencePromise resolves rather than
  1366. * asynchronously (Promise implementations use setImmediate() or similar).
  1367. *
  1368. * This is necessary to interoperate with IndexedDB which will automatically
  1369. * commit transactions if control is returned to the event loop without
  1370. * synchronously initiating another operation on the transaction.
  1371. *
  1372. * NOTE: .then() and .catch() only allow a single consumer, unlike normal
  1373. * Promises.
  1374. */ class Rt {
  1375. constructor(t) {
  1376. // NOTE: next/catchCallback will always point to our own wrapper functions,
  1377. // not the user's raw next() or catch() callbacks.
  1378. this.nextCallback = null, this.catchCallback = null,
  1379. // When the operation resolves, we'll set result or error and mark isDone.
  1380. this.result = void 0, this.error = void 0, this.isDone = !1,
  1381. // Set to true when .then() or .catch() are called and prevents additional
  1382. // chaining.
  1383. this.callbackAttached = !1, t((t => {
  1384. this.isDone = !0, this.result = t, this.nextCallback &&
  1385. // value should be defined unless T is Void, but we can't express
  1386. // that in the type system.
  1387. this.nextCallback(t);
  1388. }), (t => {
  1389. this.isDone = !0, this.error = t, this.catchCallback && this.catchCallback(t);
  1390. }));
  1391. }
  1392. catch(t) {
  1393. return this.next(void 0, t);
  1394. }
  1395. next(t, e) {
  1396. return this.callbackAttached && O(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(e, this.error) : this.wrapSuccess(t, this.result) : new Rt(((n, s) => {
  1397. this.nextCallback = e => {
  1398. this.wrapSuccess(t, e).next(n, s);
  1399. }, this.catchCallback = t => {
  1400. this.wrapFailure(e, t).next(n, s);
  1401. };
  1402. }));
  1403. }
  1404. toPromise() {
  1405. return new Promise(((t, e) => {
  1406. this.next(t, e);
  1407. }));
  1408. }
  1409. wrapUserFunction(t) {
  1410. try {
  1411. const e = t();
  1412. return e instanceof Rt ? e : Rt.resolve(e);
  1413. } catch (t) {
  1414. return Rt.reject(t);
  1415. }
  1416. }
  1417. wrapSuccess(t, e) {
  1418. return t ? this.wrapUserFunction((() => t(e))) : Rt.resolve(e);
  1419. }
  1420. wrapFailure(t, e) {
  1421. return t ? this.wrapUserFunction((() => t(e))) : Rt.reject(e);
  1422. }
  1423. static resolve(t) {
  1424. return new Rt(((e, n) => {
  1425. e(t);
  1426. }));
  1427. }
  1428. static reject(t) {
  1429. return new Rt(((e, n) => {
  1430. n(t);
  1431. }));
  1432. }
  1433. static waitFor(
  1434. // Accept all Promise types in waitFor().
  1435. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1436. t) {
  1437. return new Rt(((e, n) => {
  1438. let s = 0, i = 0, r = !1;
  1439. t.forEach((t => {
  1440. ++s, t.next((() => {
  1441. ++i, r && i === s && e();
  1442. }), (t => n(t)));
  1443. })), r = !0, i === s && e();
  1444. }));
  1445. }
  1446. /**
  1447. * Given an array of predicate functions that asynchronously evaluate to a
  1448. * boolean, implements a short-circuiting `or` between the results. Predicates
  1449. * will be evaluated until one of them returns `true`, then stop. The final
  1450. * result will be whether any of them returned `true`.
  1451. */ static or(t) {
  1452. let e = Rt.resolve(!1);
  1453. for (const n of t) e = e.next((t => t ? Rt.resolve(t) : n()));
  1454. return e;
  1455. }
  1456. static forEach(t, e) {
  1457. const n = [];
  1458. return t.forEach(((t, s) => {
  1459. n.push(e.call(this, t, s));
  1460. })), this.waitFor(n);
  1461. }
  1462. /**
  1463. * Concurrently map all array elements through asynchronous function.
  1464. */ static mapArray(t, e) {
  1465. return new Rt(((n, s) => {
  1466. const i = t.length, r = new Array(i);
  1467. let o = 0;
  1468. for (let u = 0; u < i; u++) {
  1469. const c = u;
  1470. e(t[c]).next((t => {
  1471. r[c] = t, ++o, o === i && n(r);
  1472. }), (t => s(t)));
  1473. }
  1474. }));
  1475. }
  1476. /**
  1477. * An alternative to recursive PersistencePromise calls, that avoids
  1478. * potential memory problems from unbounded chains of promises.
  1479. *
  1480. * The `action` will be called repeatedly while `condition` is true.
  1481. */ static doWhile(t, e) {
  1482. return new Rt(((n, s) => {
  1483. const i = () => {
  1484. !0 === t() ? e().next((() => {
  1485. i();
  1486. }), s) : n();
  1487. };
  1488. i();
  1489. }));
  1490. }
  1491. }
  1492. /**
  1493. * @license
  1494. * Copyright 2017 Google LLC
  1495. *
  1496. * Licensed under the Apache License, Version 2.0 (the "License");
  1497. * you may not use this file except in compliance with the License.
  1498. * You may obtain a copy of the License at
  1499. *
  1500. * http://www.apache.org/licenses/LICENSE-2.0
  1501. *
  1502. * Unless required by applicable law or agreed to in writing, software
  1503. * distributed under the License is distributed on an "AS IS" BASIS,
  1504. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1505. * See the License for the specific language governing permissions and
  1506. * limitations under the License.
  1507. */
  1508. // References to `window` are guarded by SimpleDb.isAvailable()
  1509. /* eslint-disable no-restricted-globals */
  1510. /**
  1511. * Wraps an IDBTransaction and exposes a store() method to get a handle to a
  1512. * specific object store.
  1513. */
  1514. class Pt {
  1515. constructor(t, e) {
  1516. this.action = t, this.transaction = e, this.aborted = !1,
  1517. /**
  1518. * A `Promise` that resolves with the result of the IndexedDb transaction.
  1519. */
  1520. this.v = new K, this.transaction.oncomplete = () => {
  1521. this.v.resolve();
  1522. }, this.transaction.onabort = () => {
  1523. e.error ? this.v.reject(new St(t, e.error)) : this.v.resolve();
  1524. }, this.transaction.onerror = e => {
  1525. const n = kt(e.target.error);
  1526. this.v.reject(new St(t, n));
  1527. };
  1528. }
  1529. static open(t, e, n, s) {
  1530. try {
  1531. return new Pt(e, t.transaction(s, n));
  1532. } catch (t) {
  1533. throw new St(e, t);
  1534. }
  1535. }
  1536. get R() {
  1537. return this.v.promise;
  1538. }
  1539. abort(t) {
  1540. t && this.v.reject(t), this.aborted || (N("SimpleDb", "Aborting transaction:", t ? t.message : "Client-initiated abort"),
  1541. this.aborted = !0, this.transaction.abort());
  1542. }
  1543. P() {
  1544. // If the browser supports V3 IndexedDB, we invoke commit() explicitly to
  1545. // speed up index DB processing if the event loop remains blocks.
  1546. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1547. const t = this.transaction;
  1548. this.aborted || "function" != typeof t.commit || t.commit();
  1549. }
  1550. /**
  1551. * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
  1552. * operations performed on the SimpleDbStore happen within the context of this
  1553. * transaction and it cannot be used anymore once the transaction is
  1554. * completed.
  1555. *
  1556. * Note that we can't actually enforce that the KeyType and ValueType are
  1557. * correct, but they allow type safety through the rest of the consuming code.
  1558. */ store(t) {
  1559. const e = this.transaction.objectStore(t);
  1560. return new Ct(e);
  1561. }
  1562. }
  1563. /**
  1564. * Provides a wrapper around IndexedDb with a simplified interface that uses
  1565. * Promise-like return values to chain operations. Real promises cannot be used
  1566. * since .then() continuations are executed asynchronously (e.g. via
  1567. * .setImmediate), which would cause IndexedDB to end the transaction.
  1568. * See PersistencePromise for more details.
  1569. */ class bt {
  1570. /*
  1571. * Creates a new SimpleDb wrapper for IndexedDb database `name`.
  1572. *
  1573. * Note that `version` must not be a downgrade. IndexedDB does not support
  1574. * downgrading the schema version. We currently do not support any way to do
  1575. * versioning outside of IndexedDB's versioning mechanism, as only
  1576. * version-upgrade transactions are allowed to do things like create
  1577. * objectstores.
  1578. */
  1579. constructor(t, e, n) {
  1580. this.name = t, this.version = e, this.V = n;
  1581. // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the
  1582. // bug we're checking for should exist in iOS >= 12.2 and < 13, but for
  1583. // whatever reason it's much harder to hit after 12.2 so we only proactively
  1584. // log on 12.2.
  1585. 12.2 === bt.S(util.getUA()) && k("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");
  1586. }
  1587. /** Deletes the specified database. */ static delete(t) {
  1588. return N("SimpleDb", "Removing database:", t), xt(window.indexedDB.deleteDatabase(t)).toPromise();
  1589. }
  1590. /** Returns true if IndexedDB is available in the current environment. */ static D() {
  1591. if (!util.isIndexedDBAvailable()) return !1;
  1592. if (bt.C()) return !0;
  1593. // We extensively use indexed array values and compound keys,
  1594. // which IE and Edge do not support. However, they still have indexedDB
  1595. // defined on the window, so we need to check for them here and make sure
  1596. // to return that persistence is not enabled for those browsers.
  1597. // For tracking support of this feature, see here:
  1598. // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/
  1599. // Check the UA string to find out the browser.
  1600. const t = util.getUA(), e = bt.S(t), n = 0 < e && e < 10, s = bt.N(t), i = 0 < s && s < 4.5;
  1601. // IE 10
  1602. // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
  1603. // IE 11
  1604. // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
  1605. // Edge
  1606. // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,
  1607. // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
  1608. // iOS Safari: Disable for users running iOS version < 10.
  1609. return !(t.indexOf("MSIE ") > 0 || t.indexOf("Trident/") > 0 || t.indexOf("Edge/") > 0 || n || i);
  1610. }
  1611. /**
  1612. * Returns true if the backing IndexedDB store is the Node IndexedDBShim
  1613. * (see https://github.com/axemclion/IndexedDBShim).
  1614. */ static C() {
  1615. var t;
  1616. return "undefined" != typeof process && "YES" === (null === (t = process.env) || void 0 === t ? void 0 : t.k);
  1617. }
  1618. /** Helper to get a typed SimpleDbStore from a transaction. */ static M(t, e) {
  1619. return t.store(e);
  1620. }
  1621. // visible for testing
  1622. /** Parse User Agent to determine iOS version. Returns -1 if not found. */
  1623. static S(t) {
  1624. const e = t.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = e ? e[1].split("_").slice(0, 2).join(".") : "-1";
  1625. return Number(n);
  1626. }
  1627. // visible for testing
  1628. /** Parse User Agent to determine Android version. Returns -1 if not found. */
  1629. static N(t) {
  1630. const e = t.match(/Android ([\d.]+)/i), n = e ? e[1].split(".").slice(0, 2).join(".") : "-1";
  1631. return Number(n);
  1632. }
  1633. /**
  1634. * Opens the specified database, creating or upgrading it if necessary.
  1635. */ async $(t) {
  1636. return this.db || (N("SimpleDb", "Opening database:", this.name), this.db = await new Promise(((e, n) => {
  1637. // TODO(mikelehen): Investigate browser compatibility.
  1638. // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
  1639. // suggests IE9 and older WebKit browsers handle upgrade
  1640. // differently. They expect setVersion, as described here:
  1641. // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion
  1642. const s = indexedDB.open(this.name, this.version);
  1643. s.onsuccess = t => {
  1644. const n = t.target.result;
  1645. e(n);
  1646. }, s.onblocked = () => {
  1647. n(new St(t, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."));
  1648. }, s.onerror = e => {
  1649. const s = e.target.error;
  1650. "VersionError" === s.name ? n(new U(q.FAILED_PRECONDITION, "A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")) : "InvalidStateError" === s.name ? n(new U(q.FAILED_PRECONDITION, "Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: " + s)) : n(new St(t, s));
  1651. }, s.onupgradeneeded = t => {
  1652. N("SimpleDb", 'Database "' + this.name + '" requires upgrade from version:', t.oldVersion);
  1653. const e = t.target.result;
  1654. this.V.O(e, s.transaction, t.oldVersion, this.version).next((() => {
  1655. N("SimpleDb", "Database upgrade to version " + this.version + " complete");
  1656. }));
  1657. };
  1658. }))), this.F && (this.db.onversionchange = t => this.F(t)), this.db;
  1659. }
  1660. B(t) {
  1661. this.F = t, this.db && (this.db.onversionchange = e => t(e));
  1662. }
  1663. async runTransaction(t, e, n, s) {
  1664. const i = "readonly" === e;
  1665. let r = 0;
  1666. for (;;) {
  1667. ++r;
  1668. try {
  1669. this.db = await this.$(t);
  1670. const e = Pt.open(this.db, t, i ? "readonly" : "readwrite", n), r = s(e).next((t => (e.P(),
  1671. t))).catch((t => (
  1672. // Abort the transaction if there was an error.
  1673. e.abort(t), Rt.reject(t)))).toPromise();
  1674. // As noted above, errors are propagated by aborting the transaction. So
  1675. // we swallow any error here to avoid the browser logging it as unhandled.
  1676. return r.catch((() => {})),
  1677. // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
  1678. // fire), but still return the original transactionFnResult back to the
  1679. // caller.
  1680. await e.R, r;
  1681. } catch (t) {
  1682. const e = t, n = "FirebaseError" !== e.name && r < 3;
  1683. // TODO(schmidt-sebastian): We could probably be smarter about this and
  1684. // not retry exceptions that are likely unrecoverable (such as quota
  1685. // exceeded errors).
  1686. // Note: We cannot use an instanceof check for FirestoreException, since the
  1687. // exception is wrapped in a generic error by our async/await handling.
  1688. if (N("SimpleDb", "Transaction failed with error:", e.message, "Retrying:", n),
  1689. this.close(), !n) return Promise.reject(e);
  1690. }
  1691. }
  1692. }
  1693. close() {
  1694. this.db && this.db.close(), this.db = void 0;
  1695. }
  1696. }
  1697. /**
  1698. * A controller for iterating over a key range or index. It allows an iterate
  1699. * callback to delete the currently-referenced object, or jump to a new key
  1700. * within the key range or index.
  1701. */ class Vt {
  1702. constructor(t) {
  1703. this.L = t, this.q = !1, this.U = null;
  1704. }
  1705. get isDone() {
  1706. return this.q;
  1707. }
  1708. get K() {
  1709. return this.U;
  1710. }
  1711. set cursor(t) {
  1712. this.L = t;
  1713. }
  1714. /**
  1715. * This function can be called to stop iteration at any point.
  1716. */ done() {
  1717. this.q = !0;
  1718. }
  1719. /**
  1720. * This function can be called to skip to that next key, which could be
  1721. * an index or a primary key.
  1722. */ G(t) {
  1723. this.U = t;
  1724. }
  1725. /**
  1726. * Delete the current cursor value from the object store.
  1727. *
  1728. * NOTE: You CANNOT do this with a keysOnly query.
  1729. */ delete() {
  1730. return xt(this.L.delete());
  1731. }
  1732. }
  1733. /** An error that wraps exceptions that thrown during IndexedDB execution. */ class St extends U {
  1734. constructor(t, e) {
  1735. super(q.UNAVAILABLE, `IndexedDB transaction '${t}' failed: ${e}`), this.name = "IndexedDbTransactionError";
  1736. }
  1737. }
  1738. /** Verifies whether `e` is an IndexedDbTransactionError. */ function Dt(t) {
  1739. // Use name equality, as instanceof checks on errors don't work with errors
  1740. // that wrap other errors.
  1741. return "IndexedDbTransactionError" === t.name;
  1742. }
  1743. /**
  1744. * A wrapper around an IDBObjectStore providing an API that:
  1745. *
  1746. * 1) Has generic KeyType / ValueType parameters to provide strongly-typed
  1747. * methods for acting against the object store.
  1748. * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every
  1749. * method return a PersistencePromise instead.
  1750. * 3) Provides a higher-level API to avoid needing to do excessive wrapping of
  1751. * intermediate IndexedDB types (IDBCursorWithValue, etc.)
  1752. */ class Ct {
  1753. constructor(t) {
  1754. this.store = t;
  1755. }
  1756. put(t, e) {
  1757. let n;
  1758. return void 0 !== e ? (N("SimpleDb", "PUT", this.store.name, t, e), n = this.store.put(e, t)) : (N("SimpleDb", "PUT", this.store.name, "<auto-key>", t),
  1759. n = this.store.put(t)), xt(n);
  1760. }
  1761. /**
  1762. * Adds a new value into an Object Store and returns the new key. Similar to
  1763. * IndexedDb's `add()`, this method will fail on primary key collisions.
  1764. *
  1765. * @param value - The object to write.
  1766. * @returns The key of the value to add.
  1767. */ add(t) {
  1768. N("SimpleDb", "ADD", this.store.name, t, t);
  1769. return xt(this.store.add(t));
  1770. }
  1771. /**
  1772. * Gets the object with the specified key from the specified store, or null
  1773. * if no object exists with the specified key.
  1774. *
  1775. * @key The key of the object to get.
  1776. * @returns The object with the specified key or null if no object exists.
  1777. */ get(t) {
  1778. // We're doing an unsafe cast to ValueType.
  1779. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1780. return xt(this.store.get(t)).next((e => (
  1781. // Normalize nonexistence to null.
  1782. void 0 === e && (e = null), N("SimpleDb", "GET", this.store.name, t, e), e)));
  1783. }
  1784. delete(t) {
  1785. N("SimpleDb", "DELETE", this.store.name, t);
  1786. return xt(this.store.delete(t));
  1787. }
  1788. /**
  1789. * If we ever need more of the count variants, we can add overloads. For now,
  1790. * all we need is to count everything in a store.
  1791. *
  1792. * Returns the number of rows in the store.
  1793. */ count() {
  1794. N("SimpleDb", "COUNT", this.store.name);
  1795. return xt(this.store.count());
  1796. }
  1797. j(t, e) {
  1798. const n = this.options(t, e);
  1799. // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly
  1800. // 20% faster. Unfortunately, getAll() does not support custom indices.
  1801. if (n.index || "function" != typeof this.store.getAll) {
  1802. const t = this.cursor(n), e = [];
  1803. return this.W(t, ((t, n) => {
  1804. e.push(n);
  1805. })).next((() => e));
  1806. }
  1807. {
  1808. const t = this.store.getAll(n.range);
  1809. return new Rt(((e, n) => {
  1810. t.onerror = t => {
  1811. n(t.target.error);
  1812. }, t.onsuccess = t => {
  1813. e(t.target.result);
  1814. };
  1815. }));
  1816. }
  1817. }
  1818. /**
  1819. * Loads the first `count` elements from the provided index range. Loads all
  1820. * elements if no limit is provided.
  1821. */ H(t, e) {
  1822. const n = this.store.getAll(t, null === e ? void 0 : e);
  1823. return new Rt(((t, e) => {
  1824. n.onerror = t => {
  1825. e(t.target.error);
  1826. }, n.onsuccess = e => {
  1827. t(e.target.result);
  1828. };
  1829. }));
  1830. }
  1831. J(t, e) {
  1832. N("SimpleDb", "DELETE ALL", this.store.name);
  1833. const n = this.options(t, e);
  1834. n.Y = !1;
  1835. const s = this.cursor(n);
  1836. return this.W(s, ((t, e, n) => n.delete()));
  1837. }
  1838. X(t, e) {
  1839. let n;
  1840. e ? n = t : (n = {}, e = t);
  1841. const s = this.cursor(n);
  1842. return this.W(s, e);
  1843. }
  1844. /**
  1845. * Iterates over a store, but waits for the given callback to complete for
  1846. * each entry before iterating the next entry. This allows the callback to do
  1847. * asynchronous work to determine if this iteration should continue.
  1848. *
  1849. * The provided callback should return `true` to continue iteration, and
  1850. * `false` otherwise.
  1851. */ Z(t) {
  1852. const e = this.cursor({});
  1853. return new Rt(((n, s) => {
  1854. e.onerror = t => {
  1855. const e = kt(t.target.error);
  1856. s(e);
  1857. }, e.onsuccess = e => {
  1858. const s = e.target.result;
  1859. s ? t(s.primaryKey, s.value).next((t => {
  1860. t ? s.continue() : n();
  1861. })) : n();
  1862. };
  1863. }));
  1864. }
  1865. W(t, e) {
  1866. const n = [];
  1867. return new Rt(((s, i) => {
  1868. t.onerror = t => {
  1869. i(t.target.error);
  1870. }, t.onsuccess = t => {
  1871. const i = t.target.result;
  1872. if (!i) return void s();
  1873. const r = new Vt(i), o = e(i.primaryKey, i.value, r);
  1874. if (o instanceof Rt) {
  1875. const t = o.catch((t => (r.done(), Rt.reject(t))));
  1876. n.push(t);
  1877. }
  1878. r.isDone ? s() : null === r.K ? i.continue() : i.continue(r.K);
  1879. };
  1880. })).next((() => Rt.waitFor(n)));
  1881. }
  1882. options(t, e) {
  1883. let n;
  1884. return void 0 !== t && ("string" == typeof t ? n = t : e = t), {
  1885. index: n,
  1886. range: e
  1887. };
  1888. }
  1889. cursor(t) {
  1890. let e = "next";
  1891. if (t.reverse && (e = "prev"), t.index) {
  1892. const n = this.store.index(t.index);
  1893. return t.Y ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);
  1894. }
  1895. return this.store.openCursor(t.range, e);
  1896. }
  1897. }
  1898. /**
  1899. * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror
  1900. * handlers to resolve / reject the PersistencePromise as appropriate.
  1901. */ function xt(t) {
  1902. return new Rt(((e, n) => {
  1903. t.onsuccess = t => {
  1904. const n = t.target.result;
  1905. e(n);
  1906. }, t.onerror = t => {
  1907. const e = kt(t.target.error);
  1908. n(e);
  1909. };
  1910. }));
  1911. }
  1912. // Guard so we only report the error once.
  1913. let Nt = !1;
  1914. function kt(t) {
  1915. const e = bt.S(util.getUA());
  1916. if (e >= 12.2 && e < 13) {
  1917. const e = "An internal error was encountered in the Indexed Database server";
  1918. if (t.message.indexOf(e) >= 0) {
  1919. // Wrap error in a more descriptive one.
  1920. const t = new U("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);
  1921. return Nt || (Nt = !0,
  1922. // Throw a global exception outside of this promise chain, for the user to
  1923. // potentially catch.
  1924. setTimeout((() => {
  1925. throw t;
  1926. }), 0)), t;
  1927. }
  1928. }
  1929. return t;
  1930. }
  1931. /** This class is responsible for the scheduling of Index Backfiller. */
  1932. class Mt {
  1933. constructor(t, e) {
  1934. this.asyncQueue = t, this.tt = e, this.task = null;
  1935. }
  1936. start() {
  1937. this.et(15e3);
  1938. }
  1939. stop() {
  1940. this.task && (this.task.cancel(), this.task = null);
  1941. }
  1942. get started() {
  1943. return null !== this.task;
  1944. }
  1945. et(t) {
  1946. N("IndexBackiller", `Scheduled in ${t}ms`), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */ , t, (async () => {
  1947. this.task = null;
  1948. try {
  1949. N("IndexBackiller", `Documents written: ${await this.tt.nt()}`);
  1950. } catch (t) {
  1951. Dt(t) ? N("IndexBackiller", "Ignoring IndexedDB error during index backfill: ", t) : await vt(t);
  1952. }
  1953. await this.et(6e4);
  1954. }));
  1955. }
  1956. }
  1957. /** Implements the steps for backfilling indexes. */ class $t {
  1958. constructor(
  1959. /**
  1960. * LocalStore provides access to IndexManager and LocalDocumentView.
  1961. * These properties will update when the user changes. Consequently,
  1962. * making a local copy of IndexManager and LocalDocumentView will require
  1963. * updates over time. The simpler solution is to rely on LocalStore to have
  1964. * an up-to-date references to IndexManager and LocalDocumentStore.
  1965. */
  1966. t, e) {
  1967. this.localStore = t, this.persistence = e;
  1968. }
  1969. async nt(t = 50) {
  1970. return this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (e => this.st(e, t)));
  1971. }
  1972. /** Writes index entries until the cap is reached. Returns the number of documents processed. */ st(t, e) {
  1973. const n = new Set;
  1974. let s = e, i = !0;
  1975. return Rt.doWhile((() => !0 === i && s > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(t).next((e => {
  1976. if (null !== e && !n.has(e)) return N("IndexBackiller", `Processing collection: ${e}`),
  1977. this.it(t, e, s).next((t => {
  1978. s -= t, n.add(e);
  1979. }));
  1980. i = !1;
  1981. })))).next((() => e - s));
  1982. }
  1983. /**
  1984. * Writes entries for the provided collection group. Returns the number of documents processed.
  1985. */ it(t, e, n) {
  1986. // Use the earliest offset of all field indexes to query the local cache.
  1987. return this.localStore.indexManager.getMinOffsetFromCollectionGroup(t, e).next((s => this.localStore.localDocuments.getNextDocuments(t, e, s, n).next((n => {
  1988. const i = n.changes;
  1989. return this.localStore.indexManager.updateIndexEntries(t, i).next((() => this.rt(s, n))).next((n => (N("IndexBackiller", `Updating offset: ${n}`),
  1990. this.localStore.indexManager.updateCollectionGroup(t, e, n)))).next((() => i.size));
  1991. }))));
  1992. }
  1993. /** Returns the next offset based on the provided documents. */ rt(t, e) {
  1994. let n = t;
  1995. return e.changes.forEach(((t, e) => {
  1996. const s = pt(e);
  1997. Tt(s, n) > 0 && (n = s);
  1998. })), new It(n.readTime, n.documentKey, Math.max(e.batchId, t.largestBatchId));
  1999. }
  2000. }
  2001. /**
  2002. * @license
  2003. * Copyright 2018 Google LLC
  2004. *
  2005. * Licensed under the Apache License, Version 2.0 (the "License");
  2006. * you may not use this file except in compliance with the License.
  2007. * You may obtain a copy of the License at
  2008. *
  2009. * http://www.apache.org/licenses/LICENSE-2.0
  2010. *
  2011. * Unless required by applicable law or agreed to in writing, software
  2012. * distributed under the License is distributed on an "AS IS" BASIS,
  2013. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2014. * See the License for the specific language governing permissions and
  2015. * limitations under the License.
  2016. */
  2017. /**
  2018. * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to
  2019. * exceed. All subsequent calls to next will return increasing values. If provided with a
  2020. * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as
  2021. * well as write out sequence numbers that it produces via `next()`.
  2022. */ class Ot {
  2023. constructor(t, e) {
  2024. this.previousValue = t, e && (e.sequenceNumberHandler = t => this.ot(t), this.ut = t => e.writeSequenceNumber(t));
  2025. }
  2026. ot(t) {
  2027. return this.previousValue = Math.max(t, this.previousValue), this.previousValue;
  2028. }
  2029. next() {
  2030. const t = ++this.previousValue;
  2031. return this.ut && this.ut(t), t;
  2032. }
  2033. }
  2034. Ot.ct = -1;
  2035. /**
  2036. * Returns whether a variable is either undefined or null.
  2037. */
  2038. function Ft(t) {
  2039. return null == t;
  2040. }
  2041. /** Returns whether the value represents -0. */ function Bt(t) {
  2042. // Detect if the value is -0.0. Based on polyfill from
  2043. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  2044. return 0 === t && 1 / t == -1 / 0;
  2045. }
  2046. /**
  2047. * Returns whether a value is an integer and in the safe integer range
  2048. * @param value - The value to test for being an integer and in the safe range
  2049. */ function Lt(t) {
  2050. return "number" == typeof t && Number.isInteger(t) && !Bt(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;
  2051. }
  2052. /**
  2053. * @license
  2054. * Copyright 2017 Google LLC
  2055. *
  2056. * Licensed under the Apache License, Version 2.0 (the "License");
  2057. * you may not use this file except in compliance with the License.
  2058. * You may obtain a copy of the License at
  2059. *
  2060. * http://www.apache.org/licenses/LICENSE-2.0
  2061. *
  2062. * Unless required by applicable law or agreed to in writing, software
  2063. * distributed under the License is distributed on an "AS IS" BASIS,
  2064. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2065. * See the License for the specific language governing permissions and
  2066. * limitations under the License.
  2067. */
  2068. /**
  2069. * Encodes a resource path into a IndexedDb-compatible string form.
  2070. */
  2071. function qt(t) {
  2072. let e = "";
  2073. for (let n = 0; n < t.length; n++) e.length > 0 && (e = Kt(e)), e = Ut(t.get(n), e);
  2074. return Kt(e);
  2075. }
  2076. /** Encodes a single segment of a resource path into the given result */ function Ut(t, e) {
  2077. let n = e;
  2078. const s = t.length;
  2079. for (let e = 0; e < s; e++) {
  2080. const s = t.charAt(e);
  2081. switch (s) {
  2082. case "\0":
  2083. n += "";
  2084. break;
  2085. case "":
  2086. n += "";
  2087. break;
  2088. default:
  2089. n += s;
  2090. }
  2091. }
  2092. return n;
  2093. }
  2094. /** Encodes a path separator into the given result */ function Kt(t) {
  2095. return t + "";
  2096. }
  2097. /**
  2098. * Decodes the given IndexedDb-compatible string form of a resource path into
  2099. * a ResourcePath instance. Note that this method is not suitable for use with
  2100. * decoding resource names from the server; those are One Platform format
  2101. * strings.
  2102. */ function Gt(t) {
  2103. // Event the empty path must encode as a path of at least length 2. A path
  2104. // with exactly 2 must be the empty path.
  2105. const e = t.length;
  2106. if (F(e >= 2), 2 === e) return F("" === t.charAt(0) && "" === t.charAt(1)), ut.emptyPath();
  2107. // Escape characters cannot exist past the second-to-last position in the
  2108. // source value.
  2109. const __PRIVATE_lastReasonableEscapeIndex = e - 2, n = [];
  2110. let s = "";
  2111. for (let i = 0; i < e; ) {
  2112. // The last two characters of a valid encoded path must be a separator, so
  2113. // there must be an end to this segment.
  2114. const e = t.indexOf("", i);
  2115. (e < 0 || e > __PRIVATE_lastReasonableEscapeIndex) && O();
  2116. switch (t.charAt(e + 1)) {
  2117. case "":
  2118. const r = t.substring(i, e);
  2119. let o;
  2120. 0 === s.length ?
  2121. // Avoid copying for the common case of a segment that excludes \0
  2122. // and \001
  2123. o = r : (s += r, o = s, s = ""), n.push(o);
  2124. break;
  2125. case "":
  2126. s += t.substring(i, e), s += "\0";
  2127. break;
  2128. case "":
  2129. // The escape character can be used in the output to encode itself.
  2130. s += t.substring(i, e + 1);
  2131. break;
  2132. default:
  2133. O();
  2134. }
  2135. i = e + 2;
  2136. }
  2137. return new ut(n);
  2138. }
  2139. /**
  2140. * @license
  2141. * Copyright 2022 Google LLC
  2142. *
  2143. * Licensed under the Apache License, Version 2.0 (the "License");
  2144. * you may not use this file except in compliance with the License.
  2145. * You may obtain a copy of the License at
  2146. *
  2147. * http://www.apache.org/licenses/LICENSE-2.0
  2148. *
  2149. * Unless required by applicable law or agreed to in writing, software
  2150. * distributed under the License is distributed on an "AS IS" BASIS,
  2151. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2152. * See the License for the specific language governing permissions and
  2153. * limitations under the License.
  2154. */ const Qt = [ "userId", "batchId" ];
  2155. /**
  2156. * @license
  2157. * Copyright 2022 Google LLC
  2158. *
  2159. * Licensed under the Apache License, Version 2.0 (the "License");
  2160. * you may not use this file except in compliance with the License.
  2161. * You may obtain a copy of the License at
  2162. *
  2163. * http://www.apache.org/licenses/LICENSE-2.0
  2164. *
  2165. * Unless required by applicable law or agreed to in writing, software
  2166. * distributed under the License is distributed on an "AS IS" BASIS,
  2167. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2168. * See the License for the specific language governing permissions and
  2169. * limitations under the License.
  2170. */
  2171. /**
  2172. * Name of the IndexedDb object store.
  2173. *
  2174. * Note that the name 'owner' is chosen to ensure backwards compatibility with
  2175. * older clients that only supported single locked access to the persistence
  2176. * layer.
  2177. */
  2178. /**
  2179. * Creates a [userId, encodedPath] key for use in the DbDocumentMutations
  2180. * index to iterate over all at document mutations for a given path or lower.
  2181. */
  2182. function jt(t, e) {
  2183. return [ t, qt(e) ];
  2184. }
  2185. /**
  2186. * Creates a full index key of [userId, encodedPath, batchId] for inserting
  2187. * and deleting into the DbDocumentMutations index.
  2188. */ function zt(t, e, n) {
  2189. return [ t, qt(e), n ];
  2190. }
  2191. /**
  2192. * Because we store all the useful information for this store in the key,
  2193. * there is no useful information to store as the value. The raw (unencoded)
  2194. * path cannot be stored because IndexedDb doesn't store prototype
  2195. * information.
  2196. */ const Wt = {}, Ht = [ "prefixPath", "collectionGroup", "readTime", "documentId" ], Jt = [ "prefixPath", "collectionGroup", "documentId" ], Yt = [ "collectionGroup", "readTime", "prefixPath", "documentId" ], Xt = [ "canonicalId", "targetId" ], Zt = [ "targetId", "path" ], te = [ "path", "targetId" ], ee = [ "collectionId", "parent" ], ne = [ "indexId", "uid" ], se = [ "uid", "sequenceNumber" ], ie = [ "indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey" ], re = [ "indexId", "uid", "orderedDocumentKey" ], oe = [ "userId", "collectionPath", "documentId" ], ue = [ "userId", "collectionPath", "largestBatchId" ], ce = [ "userId", "collectionGroup", "largestBatchId" ], ae = [ ...[ ...[ ...[ ...[ "mutationQueues", "mutations", "documentMutations", "remoteDocuments", "targets", "owner", "targetGlobal", "targetDocuments" ], "clientMetadata" ], "remoteDocumentGlobal" ], "collectionParents" ], "bundles", "namedQueries" ], he = [ ...ae, "documentOverlays" ], le = [ "mutationQueues", "mutations", "documentMutations", "remoteDocumentsV14", "targets", "owner", "targetGlobal", "targetDocuments", "clientMetadata", "remoteDocumentGlobal", "collectionParents", "bundles", "namedQueries", "documentOverlays" ], fe = le, de = [ ...fe, "indexConfiguration", "indexState", "indexEntries" ];
  2197. /**
  2198. * @license
  2199. * Copyright 2020 Google LLC
  2200. *
  2201. * Licensed under the Apache License, Version 2.0 (the "License");
  2202. * you may not use this file except in compliance with the License.
  2203. * You may obtain a copy of the License at
  2204. *
  2205. * http://www.apache.org/licenses/LICENSE-2.0
  2206. *
  2207. * Unless required by applicable law or agreed to in writing, software
  2208. * distributed under the License is distributed on an "AS IS" BASIS,
  2209. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2210. * See the License for the specific language governing permissions and
  2211. * limitations under the License.
  2212. */
  2213. class we extends At {
  2214. constructor(t, e) {
  2215. super(), this.ht = t, this.currentSequenceNumber = e;
  2216. }
  2217. }
  2218. function _e(t, e) {
  2219. const n = L(t);
  2220. return bt.M(n.ht, e);
  2221. }
  2222. /**
  2223. * @license
  2224. * Copyright 2017 Google LLC
  2225. *
  2226. * Licensed under the Apache License, Version 2.0 (the "License");
  2227. * you may not use this file except in compliance with the License.
  2228. * You may obtain a copy of the License at
  2229. *
  2230. * http://www.apache.org/licenses/LICENSE-2.0
  2231. *
  2232. * Unless required by applicable law or agreed to in writing, software
  2233. * distributed under the License is distributed on an "AS IS" BASIS,
  2234. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2235. * See the License for the specific language governing permissions and
  2236. * limitations under the License.
  2237. */ function me(t) {
  2238. let e = 0;
  2239. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;
  2240. return e;
  2241. }
  2242. function ge(t, e) {
  2243. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);
  2244. }
  2245. function ye(t) {
  2246. for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
  2247. return !0;
  2248. }
  2249. /**
  2250. * @license
  2251. * Copyright 2017 Google LLC
  2252. *
  2253. * Licensed under the Apache License, Version 2.0 (the "License");
  2254. * you may not use this file except in compliance with the License.
  2255. * You may obtain a copy of the License at
  2256. *
  2257. * http://www.apache.org/licenses/LICENSE-2.0
  2258. *
  2259. * Unless required by applicable law or agreed to in writing, software
  2260. * distributed under the License is distributed on an "AS IS" BASIS,
  2261. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2262. * See the License for the specific language governing permissions and
  2263. * limitations under the License.
  2264. */
  2265. // An immutable sorted map implementation, based on a Left-leaning Red-Black
  2266. // tree.
  2267. class pe {
  2268. constructor(t, e) {
  2269. this.comparator = t, this.root = e || Te.EMPTY;
  2270. }
  2271. // Returns a copy of the map, with the specified key/value added or replaced.
  2272. insert(t, e) {
  2273. return new pe(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, Te.BLACK, null, null));
  2274. }
  2275. // Returns a copy of the map, with the specified key removed.
  2276. remove(t) {
  2277. return new pe(this.comparator, this.root.remove(t, this.comparator).copy(null, null, Te.BLACK, null, null));
  2278. }
  2279. // Returns the value of the node with the given key, or null.
  2280. get(t) {
  2281. let e = this.root;
  2282. for (;!e.isEmpty(); ) {
  2283. const n = this.comparator(t, e.key);
  2284. if (0 === n) return e.value;
  2285. n < 0 ? e = e.left : n > 0 && (e = e.right);
  2286. }
  2287. return null;
  2288. }
  2289. // Returns the index of the element in this sorted map, or -1 if it doesn't
  2290. // exist.
  2291. indexOf(t) {
  2292. // Number of nodes that were pruned when descending right
  2293. let e = 0, n = this.root;
  2294. for (;!n.isEmpty(); ) {
  2295. const s = this.comparator(t, n.key);
  2296. if (0 === s) return e + n.left.size;
  2297. s < 0 ? n = n.left : (
  2298. // Count all nodes left of the node plus the node itself
  2299. e += n.left.size + 1, n = n.right);
  2300. }
  2301. // Node not found
  2302. return -1;
  2303. }
  2304. isEmpty() {
  2305. return this.root.isEmpty();
  2306. }
  2307. // Returns the total number of nodes in the map.
  2308. get size() {
  2309. return this.root.size;
  2310. }
  2311. // Returns the minimum key in the map.
  2312. minKey() {
  2313. return this.root.minKey();
  2314. }
  2315. // Returns the maximum key in the map.
  2316. maxKey() {
  2317. return this.root.maxKey();
  2318. }
  2319. // Traverses the map in key order and calls the specified action function
  2320. // for each key/value pair. If action returns true, traversal is aborted.
  2321. // Returns the first truthy value returned by action, or the last falsey
  2322. // value returned by action.
  2323. inorderTraversal(t) {
  2324. return this.root.inorderTraversal(t);
  2325. }
  2326. forEach(t) {
  2327. this.inorderTraversal(((e, n) => (t(e, n), !1)));
  2328. }
  2329. toString() {
  2330. const t = [];
  2331. return this.inorderTraversal(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(", ")}}`;
  2332. }
  2333. // Traverses the map in reverse key order and calls the specified action
  2334. // function for each key/value pair. If action returns true, traversal is
  2335. // aborted.
  2336. // Returns the first truthy value returned by action, or the last falsey
  2337. // value returned by action.
  2338. reverseTraversal(t) {
  2339. return this.root.reverseTraversal(t);
  2340. }
  2341. // Returns an iterator over the SortedMap.
  2342. getIterator() {
  2343. return new Ie(this.root, null, this.comparator, !1);
  2344. }
  2345. getIteratorFrom(t) {
  2346. return new Ie(this.root, t, this.comparator, !1);
  2347. }
  2348. getReverseIterator() {
  2349. return new Ie(this.root, null, this.comparator, !0);
  2350. }
  2351. getReverseIteratorFrom(t) {
  2352. return new Ie(this.root, t, this.comparator, !0);
  2353. }
  2354. }
  2355. // end SortedMap
  2356. // An iterator over an LLRBNode.
  2357. class Ie {
  2358. constructor(t, e, n, s) {
  2359. this.isReverse = s, this.nodeStack = [];
  2360. let i = 1;
  2361. for (;!t.isEmpty(); ) if (i = e ? n(t.key, e) : 1,
  2362. // flip the comparison if we're going in reverse
  2363. e && s && (i *= -1), i < 0)
  2364. // This node is less than our start key. ignore it
  2365. t = this.isReverse ? t.left : t.right; else {
  2366. if (0 === i) {
  2367. // This node is exactly equal to our start key. Push it on the stack,
  2368. // but stop iterating;
  2369. this.nodeStack.push(t);
  2370. break;
  2371. }
  2372. // This node is greater than our start key, add it to the stack and move
  2373. // to the next one
  2374. this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;
  2375. }
  2376. }
  2377. getNext() {
  2378. let t = this.nodeStack.pop();
  2379. const e = {
  2380. key: t.key,
  2381. value: t.value
  2382. };
  2383. if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t),
  2384. t = t.left;
  2385. return e;
  2386. }
  2387. hasNext() {
  2388. return this.nodeStack.length > 0;
  2389. }
  2390. peek() {
  2391. if (0 === this.nodeStack.length) return null;
  2392. const t = this.nodeStack[this.nodeStack.length - 1];
  2393. return {
  2394. key: t.key,
  2395. value: t.value
  2396. };
  2397. }
  2398. }
  2399. // end SortedMapIterator
  2400. // Represents a node in a Left-leaning Red-Black tree.
  2401. class Te {
  2402. constructor(t, e, n, s, i) {
  2403. this.key = t, this.value = e, this.color = null != n ? n : Te.RED, this.left = null != s ? s : Te.EMPTY,
  2404. this.right = null != i ? i : Te.EMPTY, this.size = this.left.size + 1 + this.right.size;
  2405. }
  2406. // Returns a copy of the current node, optionally replacing pieces of it.
  2407. copy(t, e, n, s, i) {
  2408. return new Te(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != s ? s : this.left, null != i ? i : this.right);
  2409. }
  2410. isEmpty() {
  2411. return !1;
  2412. }
  2413. // Traverses the tree in key order and calls the specified action function
  2414. // for each node. If action returns true, traversal is aborted.
  2415. // Returns the first truthy value returned by action, or the last falsey
  2416. // value returned by action.
  2417. inorderTraversal(t) {
  2418. return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);
  2419. }
  2420. // Traverses the tree in reverse key order and calls the specified action
  2421. // function for each node. If action returns true, traversal is aborted.
  2422. // Returns the first truthy value returned by action, or the last falsey
  2423. // value returned by action.
  2424. reverseTraversal(t) {
  2425. return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);
  2426. }
  2427. // Returns the minimum node in the tree.
  2428. min() {
  2429. return this.left.isEmpty() ? this : this.left.min();
  2430. }
  2431. // Returns the maximum key in the tree.
  2432. minKey() {
  2433. return this.min().key;
  2434. }
  2435. // Returns the maximum key in the tree.
  2436. maxKey() {
  2437. return this.right.isEmpty() ? this.key : this.right.maxKey();
  2438. }
  2439. // Returns new tree, with the key/value added.
  2440. insert(t, e, n) {
  2441. let s = this;
  2442. const i = n(t, s.key);
  2443. return s = i < 0 ? s.copy(null, null, null, s.left.insert(t, e, n), null) : 0 === i ? s.copy(null, e, null, null, null) : s.copy(null, null, null, null, s.right.insert(t, e, n)),
  2444. s.fixUp();
  2445. }
  2446. removeMin() {
  2447. if (this.left.isEmpty()) return Te.EMPTY;
  2448. let t = this;
  2449. return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null),
  2450. t.fixUp();
  2451. }
  2452. // Returns new tree, with the specified item removed.
  2453. remove(t, e) {
  2454. let n, s = this;
  2455. if (e(t, s.key) < 0) s.left.isEmpty() || s.left.isRed() || s.left.left.isRed() || (s = s.moveRedLeft()),
  2456. s = s.copy(null, null, null, s.left.remove(t, e), null); else {
  2457. if (s.left.isRed() && (s = s.rotateRight()), s.right.isEmpty() || s.right.isRed() || s.right.left.isRed() || (s = s.moveRedRight()),
  2458. 0 === e(t, s.key)) {
  2459. if (s.right.isEmpty()) return Te.EMPTY;
  2460. n = s.right.min(), s = s.copy(n.key, n.value, null, null, s.right.removeMin());
  2461. }
  2462. s = s.copy(null, null, null, null, s.right.remove(t, e));
  2463. }
  2464. return s.fixUp();
  2465. }
  2466. isRed() {
  2467. return this.color;
  2468. }
  2469. // Returns new tree after performing any needed rotations.
  2470. fixUp() {
  2471. let t = this;
  2472. return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()),
  2473. t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;
  2474. }
  2475. moveRedLeft() {
  2476. let t = this.colorFlip();
  2477. return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()),
  2478. t = t.rotateLeft(), t = t.colorFlip()), t;
  2479. }
  2480. moveRedRight() {
  2481. let t = this.colorFlip();
  2482. return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t;
  2483. }
  2484. rotateLeft() {
  2485. const t = this.copy(null, null, Te.RED, null, this.right.left);
  2486. return this.right.copy(null, null, this.color, t, null);
  2487. }
  2488. rotateRight() {
  2489. const t = this.copy(null, null, Te.RED, this.left.right, null);
  2490. return this.left.copy(null, null, this.color, null, t);
  2491. }
  2492. colorFlip() {
  2493. const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);
  2494. return this.copy(null, null, !this.color, t, e);
  2495. }
  2496. // For testing.
  2497. checkMaxDepth() {
  2498. const t = this.check();
  2499. return Math.pow(2, t) <= this.size + 1;
  2500. }
  2501. // In a balanced RB tree, the black-depth (number of black nodes) from root to
  2502. // leaves is equal on both sides. This function verifies that or asserts.
  2503. check() {
  2504. if (this.isRed() && this.left.isRed()) throw O();
  2505. if (this.right.isRed()) throw O();
  2506. const t = this.left.check();
  2507. if (t !== this.right.check()) throw O();
  2508. return t + (this.isRed() ? 0 : 1);
  2509. }
  2510. }
  2511. // end LLRBNode
  2512. // Empty node is shared between all LLRB trees.
  2513. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2514. Te.EMPTY = null, Te.RED = !0, Te.BLACK = !1;
  2515. // end LLRBEmptyNode
  2516. Te.EMPTY = new
  2517. // Represents an empty node (a leaf node in the Red-Black Tree).
  2518. class {
  2519. constructor() {
  2520. this.size = 0;
  2521. }
  2522. get key() {
  2523. throw O();
  2524. }
  2525. get value() {
  2526. throw O();
  2527. }
  2528. get color() {
  2529. throw O();
  2530. }
  2531. get left() {
  2532. throw O();
  2533. }
  2534. get right() {
  2535. throw O();
  2536. }
  2537. // Returns a copy of the current node.
  2538. copy(t, e, n, s, i) {
  2539. return this;
  2540. }
  2541. // Returns a copy of the tree, with the specified key/value added.
  2542. insert(t, e, n) {
  2543. return new Te(t, e);
  2544. }
  2545. // Returns a copy of the tree, with the specified key removed.
  2546. remove(t, e) {
  2547. return this;
  2548. }
  2549. isEmpty() {
  2550. return !0;
  2551. }
  2552. inorderTraversal(t) {
  2553. return !1;
  2554. }
  2555. reverseTraversal(t) {
  2556. return !1;
  2557. }
  2558. minKey() {
  2559. return null;
  2560. }
  2561. maxKey() {
  2562. return null;
  2563. }
  2564. isRed() {
  2565. return !1;
  2566. }
  2567. // For testing.
  2568. checkMaxDepth() {
  2569. return !0;
  2570. }
  2571. check() {
  2572. return 0;
  2573. }
  2574. };
  2575. /**
  2576. * @license
  2577. * Copyright 2017 Google LLC
  2578. *
  2579. * Licensed under the Apache License, Version 2.0 (the "License");
  2580. * you may not use this file except in compliance with the License.
  2581. * You may obtain a copy of the License at
  2582. *
  2583. * http://www.apache.org/licenses/LICENSE-2.0
  2584. *
  2585. * Unless required by applicable law or agreed to in writing, software
  2586. * distributed under the License is distributed on an "AS IS" BASIS,
  2587. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2588. * See the License for the specific language governing permissions and
  2589. * limitations under the License.
  2590. */
  2591. /**
  2592. * SortedSet is an immutable (copy-on-write) collection that holds elements
  2593. * in order specified by the provided comparator.
  2594. *
  2595. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  2596. * be equal!
  2597. */
  2598. class Ee {
  2599. constructor(t) {
  2600. this.comparator = t, this.data = new pe(this.comparator);
  2601. }
  2602. has(t) {
  2603. return null !== this.data.get(t);
  2604. }
  2605. first() {
  2606. return this.data.minKey();
  2607. }
  2608. last() {
  2609. return this.data.maxKey();
  2610. }
  2611. get size() {
  2612. return this.data.size;
  2613. }
  2614. indexOf(t) {
  2615. return this.data.indexOf(t);
  2616. }
  2617. /** Iterates elements in order defined by "comparator" */ forEach(t) {
  2618. this.data.inorderTraversal(((e, n) => (t(e), !1)));
  2619. }
  2620. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */ forEachInRange(t, e) {
  2621. const n = this.data.getIteratorFrom(t[0]);
  2622. for (;n.hasNext(); ) {
  2623. const s = n.getNext();
  2624. if (this.comparator(s.key, t[1]) >= 0) return;
  2625. e(s.key);
  2626. }
  2627. }
  2628. /**
  2629. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  2630. */ forEachWhile(t, e) {
  2631. let n;
  2632. for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) {
  2633. if (!t(n.getNext().key)) return;
  2634. }
  2635. }
  2636. /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {
  2637. const e = this.data.getIteratorFrom(t);
  2638. return e.hasNext() ? e.getNext().key : null;
  2639. }
  2640. getIterator() {
  2641. return new Ae(this.data.getIterator());
  2642. }
  2643. getIteratorFrom(t) {
  2644. return new Ae(this.data.getIteratorFrom(t));
  2645. }
  2646. /** Inserts or updates an element */ add(t) {
  2647. return this.copy(this.data.remove(t).insert(t, !0));
  2648. }
  2649. /** Deletes an element */ delete(t) {
  2650. return this.has(t) ? this.copy(this.data.remove(t)) : this;
  2651. }
  2652. isEmpty() {
  2653. return this.data.isEmpty();
  2654. }
  2655. unionWith(t) {
  2656. let e = this;
  2657. // Make sure `result` always refers to the larger one of the two sets.
  2658. return e.size < t.size && (e = t, t = this), t.forEach((t => {
  2659. e = e.add(t);
  2660. })), e;
  2661. }
  2662. isEqual(t) {
  2663. if (!(t instanceof Ee)) return !1;
  2664. if (this.size !== t.size) return !1;
  2665. const e = this.data.getIterator(), n = t.data.getIterator();
  2666. for (;e.hasNext(); ) {
  2667. const t = e.getNext().key, s = n.getNext().key;
  2668. if (0 !== this.comparator(t, s)) return !1;
  2669. }
  2670. return !0;
  2671. }
  2672. toArray() {
  2673. const t = [];
  2674. return this.forEach((e => {
  2675. t.push(e);
  2676. })), t;
  2677. }
  2678. toString() {
  2679. const t = [];
  2680. return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")";
  2681. }
  2682. copy(t) {
  2683. const e = new Ee(this.comparator);
  2684. return e.data = t, e;
  2685. }
  2686. }
  2687. class Ae {
  2688. constructor(t) {
  2689. this.iter = t;
  2690. }
  2691. getNext() {
  2692. return this.iter.getNext().key;
  2693. }
  2694. hasNext() {
  2695. return this.iter.hasNext();
  2696. }
  2697. }
  2698. /**
  2699. * Compares two sorted sets for equality using their natural ordering. The
  2700. * method computes the intersection and invokes `onAdd` for every element that
  2701. * is in `after` but not `before`. `onRemove` is invoked for every element in
  2702. * `before` but missing from `after`.
  2703. *
  2704. * The method creates a copy of both `before` and `after` and runs in O(n log
  2705. * n), where n is the size of the two lists.
  2706. *
  2707. * @param before - The elements that exist in the original set.
  2708. * @param after - The elements to diff against the original set.
  2709. * @param comparator - The comparator for the elements in before and after.
  2710. * @param onAdd - A function to invoke for every element that is part of `
  2711. * after` but not `before`.
  2712. * @param onRemove - A function to invoke for every element that is part of
  2713. * `before` but not `after`.
  2714. */
  2715. /**
  2716. * Returns the next element from the iterator or `undefined` if none available.
  2717. */
  2718. function ve(t) {
  2719. return t.hasNext() ? t.getNext() : void 0;
  2720. }
  2721. /**
  2722. * @license
  2723. * Copyright 2020 Google LLC
  2724. *
  2725. * Licensed under the Apache License, Version 2.0 (the "License");
  2726. * you may not use this file except in compliance with the License.
  2727. * You may obtain a copy of the License at
  2728. *
  2729. * http://www.apache.org/licenses/LICENSE-2.0
  2730. *
  2731. * Unless required by applicable law or agreed to in writing, software
  2732. * distributed under the License is distributed on an "AS IS" BASIS,
  2733. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2734. * See the License for the specific language governing permissions and
  2735. * limitations under the License.
  2736. */
  2737. /**
  2738. * Provides a set of fields that can be used to partially patch a document.
  2739. * FieldMask is used in conjunction with ObjectValue.
  2740. * Examples:
  2741. * foo - Overwrites foo entirely with the provided value. If foo is not
  2742. * present in the companion ObjectValue, the field is deleted.
  2743. * foo.bar - Overwrites only the field bar of the object foo.
  2744. * If foo is not an object, foo is replaced with an object
  2745. * containing foo
  2746. */ class Re {
  2747. constructor(t) {
  2748. this.fields = t,
  2749. // TODO(dimond): validation of FieldMask
  2750. // Sort the field mask to support `FieldMask.isEqual()` and assert below.
  2751. t.sort(at.comparator);
  2752. }
  2753. static empty() {
  2754. return new Re([]);
  2755. }
  2756. /**
  2757. * Returns a new FieldMask object that is the result of adding all the given
  2758. * fields paths to this field mask.
  2759. */ unionWith(t) {
  2760. let e = new Ee(at.comparator);
  2761. for (const t of this.fields) e = e.add(t);
  2762. for (const n of t) e = e.add(n);
  2763. return new Re(e.toArray());
  2764. }
  2765. /**
  2766. * Verifies that `fieldPath` is included by at least one field in this field
  2767. * mask.
  2768. *
  2769. * This is an O(n) operation, where `n` is the size of the field mask.
  2770. */ covers(t) {
  2771. for (const e of this.fields) if (e.isPrefixOf(t)) return !0;
  2772. return !1;
  2773. }
  2774. isEqual(t) {
  2775. return nt(this.fields, t.fields, ((t, e) => t.isEqual(e)));
  2776. }
  2777. }
  2778. /**
  2779. * @license
  2780. * Copyright 2023 Google LLC
  2781. *
  2782. * Licensed under the Apache License, Version 2.0 (the "License");
  2783. * you may not use this file except in compliance with the License.
  2784. * You may obtain a copy of the License at
  2785. *
  2786. * http://www.apache.org/licenses/LICENSE-2.0
  2787. *
  2788. * Unless required by applicable law or agreed to in writing, software
  2789. * distributed under the License is distributed on an "AS IS" BASIS,
  2790. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2791. * See the License for the specific language governing permissions and
  2792. * limitations under the License.
  2793. */
  2794. /**
  2795. * An error encountered while decoding base64 string.
  2796. */ class Pe extends Error {
  2797. constructor() {
  2798. super(...arguments), this.name = "Base64DecodeError";
  2799. }
  2800. }
  2801. /**
  2802. * @license
  2803. * Copyright 2020 Google LLC
  2804. *
  2805. * Licensed under the Apache License, Version 2.0 (the "License");
  2806. * you may not use this file except in compliance with the License.
  2807. * You may obtain a copy of the License at
  2808. *
  2809. * http://www.apache.org/licenses/LICENSE-2.0
  2810. *
  2811. * Unless required by applicable law or agreed to in writing, software
  2812. * distributed under the License is distributed on an "AS IS" BASIS,
  2813. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2814. * See the License for the specific language governing permissions and
  2815. * limitations under the License.
  2816. */
  2817. /** Converts a Base64 encoded string to a binary string. */
  2818. /** True if and only if the Base64 conversion functions are available. */
  2819. function be() {
  2820. return "undefined" != typeof atob;
  2821. }
  2822. /**
  2823. * @license
  2824. * Copyright 2020 Google LLC
  2825. *
  2826. * Licensed under the Apache License, Version 2.0 (the "License");
  2827. * you may not use this file except in compliance with the License.
  2828. * You may obtain a copy of the License at
  2829. *
  2830. * http://www.apache.org/licenses/LICENSE-2.0
  2831. *
  2832. * Unless required by applicable law or agreed to in writing, software
  2833. * distributed under the License is distributed on an "AS IS" BASIS,
  2834. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2835. * See the License for the specific language governing permissions and
  2836. * limitations under the License.
  2837. */
  2838. /**
  2839. * Immutable class that represents a "proto" byte string.
  2840. *
  2841. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  2842. * sent on the wire. This class abstracts away this differentiation by holding
  2843. * the proto byte string in a common class that must be converted into a string
  2844. * before being sent as a proto.
  2845. * @internal
  2846. */ class Ve {
  2847. constructor(t) {
  2848. this.binaryString = t;
  2849. }
  2850. static fromBase64String(t) {
  2851. const e = function(t) {
  2852. try {
  2853. return atob(t);
  2854. } catch (t) {
  2855. // Check that `DOMException` is defined before using it to avoid
  2856. // "ReferenceError: Property 'DOMException' doesn't exist" in react-native.
  2857. // (https://github.com/firebase/firebase-js-sdk/issues/7115)
  2858. throw "undefined" != typeof DOMException && t instanceof DOMException ? new Pe("Invalid base64 string: " + t) : t;
  2859. }
  2860. }
  2861. /** Converts a binary string to a Base64 encoded string. */ (t);
  2862. return new Ve(e);
  2863. }
  2864. static fromUint8Array(t) {
  2865. // TODO(indexing); Remove the copy of the byte string here as this method
  2866. // is frequently called during indexing.
  2867. const e =
  2868. /**
  2869. * Helper function to convert an Uint8array to a binary string.
  2870. */
  2871. function(t) {
  2872. let e = "";
  2873. for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);
  2874. return e;
  2875. }
  2876. /**
  2877. * Helper function to convert a binary string to an Uint8Array.
  2878. */ (t);
  2879. return new Ve(e);
  2880. }
  2881. [Symbol.iterator]() {
  2882. let t = 0;
  2883. return {
  2884. next: () => t < this.binaryString.length ? {
  2885. value: this.binaryString.charCodeAt(t++),
  2886. done: !1
  2887. } : {
  2888. value: void 0,
  2889. done: !0
  2890. }
  2891. };
  2892. }
  2893. toBase64() {
  2894. return t = this.binaryString, btoa(t);
  2895. var t;
  2896. }
  2897. toUint8Array() {
  2898. return function(t) {
  2899. const e = new Uint8Array(t.length);
  2900. for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  2901. return e;
  2902. }
  2903. /**
  2904. * @license
  2905. * Copyright 2020 Google LLC
  2906. *
  2907. * Licensed under the Apache License, Version 2.0 (the "License");
  2908. * you may not use this file except in compliance with the License.
  2909. * You may obtain a copy of the License at
  2910. *
  2911. * http://www.apache.org/licenses/LICENSE-2.0
  2912. *
  2913. * Unless required by applicable law or agreed to in writing, software
  2914. * distributed under the License is distributed on an "AS IS" BASIS,
  2915. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2916. * See the License for the specific language governing permissions and
  2917. * limitations under the License.
  2918. */
  2919. // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
  2920. (this.binaryString);
  2921. }
  2922. approximateByteSize() {
  2923. return 2 * this.binaryString.length;
  2924. }
  2925. compareTo(t) {
  2926. return et(this.binaryString, t.binaryString);
  2927. }
  2928. isEqual(t) {
  2929. return this.binaryString === t.binaryString;
  2930. }
  2931. }
  2932. Ve.EMPTY_BYTE_STRING = new Ve("");
  2933. const Se = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  2934. /**
  2935. * Converts the possible Proto values for a timestamp value into a "seconds and
  2936. * nanos" representation.
  2937. */ function De(t) {
  2938. // The json interface (for the browser) will return an iso timestamp string,
  2939. // while the proto js library (for node) will return a
  2940. // google.protobuf.Timestamp instance.
  2941. if (F(!!t), "string" == typeof t) {
  2942. // The date string can have higher precision (nanos) than the Date class
  2943. // (millis), so we do some custom parsing here.
  2944. // Parse the nanos right out of the string.
  2945. let e = 0;
  2946. const n = Se.exec(t);
  2947. if (F(!!n), n[1]) {
  2948. // Pad the fraction out to 9 digits (nanos).
  2949. let t = n[1];
  2950. t = (t + "000000000").substr(0, 9), e = Number(t);
  2951. }
  2952. // Parse the date to get the seconds.
  2953. const s = new Date(t);
  2954. return {
  2955. seconds: Math.floor(s.getTime() / 1e3),
  2956. nanos: e
  2957. };
  2958. }
  2959. return {
  2960. seconds: Ce(t.seconds),
  2961. nanos: Ce(t.nanos)
  2962. };
  2963. }
  2964. /**
  2965. * Converts the possible Proto types for numbers into a JavaScript number.
  2966. * Returns 0 if the value is not numeric.
  2967. */ function Ce(t) {
  2968. // TODO(bjornick): Handle int64 greater than 53 bits.
  2969. return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0;
  2970. }
  2971. /** Converts the possible Proto types for Blobs into a ByteString. */ function xe(t) {
  2972. return "string" == typeof t ? Ve.fromBase64String(t) : Ve.fromUint8Array(t);
  2973. }
  2974. /**
  2975. * @license
  2976. * Copyright 2020 Google LLC
  2977. *
  2978. * Licensed under the Apache License, Version 2.0 (the "License");
  2979. * you may not use this file except in compliance with the License.
  2980. * You may obtain a copy of the License at
  2981. *
  2982. * http://www.apache.org/licenses/LICENSE-2.0
  2983. *
  2984. * Unless required by applicable law or agreed to in writing, software
  2985. * distributed under the License is distributed on an "AS IS" BASIS,
  2986. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2987. * See the License for the specific language governing permissions and
  2988. * limitations under the License.
  2989. */
  2990. /**
  2991. * Represents a locally-applied ServerTimestamp.
  2992. *
  2993. * Server Timestamps are backed by MapValues that contain an internal field
  2994. * `__type__` with a value of `server_timestamp`. The previous value and local
  2995. * write time are stored in its `__previous_value__` and `__local_write_time__`
  2996. * fields respectively.
  2997. *
  2998. * Notes:
  2999. * - ServerTimestampValue instances are created as the result of applying a
  3000. * transform. They can only exist in the local view of a document. Therefore
  3001. * they do not need to be parsed or serialized.
  3002. * - When evaluated locally (e.g. for snapshot.data()), they by default
  3003. * evaluate to `null`. This behavior can be configured by passing custom
  3004. * FieldValueOptions to value().
  3005. * - With respect to other ServerTimestampValues, they sort by their
  3006. * localWriteTime.
  3007. */ function Ne(t) {
  3008. var e, n;
  3009. return "server_timestamp" === (null === (n = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);
  3010. }
  3011. /**
  3012. * Creates a new ServerTimestamp proto value (using the internal format).
  3013. */
  3014. /**
  3015. * Returns the value of the field before this ServerTimestamp was set.
  3016. *
  3017. * Preserving the previous values allows the user to display the last resoled
  3018. * value until the backend responds with the timestamp.
  3019. */
  3020. function ke(t) {
  3021. const e = t.mapValue.fields.__previous_value__;
  3022. return Ne(e) ? ke(e) : e;
  3023. }
  3024. /**
  3025. * Returns the local time at which this timestamp was first set.
  3026. */ function Me(t) {
  3027. const e = De(t.mapValue.fields.__local_write_time__.timestampValue);
  3028. return new it(e.seconds, e.nanos);
  3029. }
  3030. /**
  3031. * @license
  3032. * Copyright 2017 Google LLC
  3033. *
  3034. * Licensed under the Apache License, Version 2.0 (the "License");
  3035. * you may not use this file except in compliance with the License.
  3036. * You may obtain a copy of the License at
  3037. *
  3038. * http://www.apache.org/licenses/LICENSE-2.0
  3039. *
  3040. * Unless required by applicable law or agreed to in writing, software
  3041. * distributed under the License is distributed on an "AS IS" BASIS,
  3042. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3043. * See the License for the specific language governing permissions and
  3044. * limitations under the License.
  3045. */ class $e {
  3046. /**
  3047. * Constructs a DatabaseInfo using the provided host, databaseId and
  3048. * persistenceKey.
  3049. *
  3050. * @param databaseId - The database to use.
  3051. * @param appId - The Firebase App Id.
  3052. * @param persistenceKey - A unique identifier for this Firestore's local
  3053. * storage (used in conjunction with the databaseId).
  3054. * @param host - The Firestore backend host to connect to.
  3055. * @param ssl - Whether to use SSL when connecting.
  3056. * @param forceLongPolling - Whether to use the forceLongPolling option
  3057. * when using WebChannel as the network transport.
  3058. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  3059. * option when using WebChannel as the network transport.
  3060. * @param longPollingOptions Options that configure long-polling.
  3061. * @param useFetchStreams Whether to use the Fetch API instead of
  3062. * XMLHTTPRequest
  3063. */
  3064. constructor(t, e, n, s, i, r, o, u, c) {
  3065. this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = s, this.ssl = i,
  3066. this.forceLongPolling = r, this.autoDetectLongPolling = o, this.longPollingOptions = u,
  3067. this.useFetchStreams = c;
  3068. }
  3069. }
  3070. /** The default database name for a project. */
  3071. /**
  3072. * Represents the database ID a Firestore client is associated with.
  3073. * @internal
  3074. */
  3075. class Oe {
  3076. constructor(t, e) {
  3077. this.projectId = t, this.database = e || "(default)";
  3078. }
  3079. static empty() {
  3080. return new Oe("", "");
  3081. }
  3082. get isDefaultDatabase() {
  3083. return "(default)" === this.database;
  3084. }
  3085. isEqual(t) {
  3086. return t instanceof Oe && t.projectId === this.projectId && t.database === this.database;
  3087. }
  3088. }
  3089. /**
  3090. * @license
  3091. * Copyright 2020 Google LLC
  3092. *
  3093. * Licensed under the Apache License, Version 2.0 (the "License");
  3094. * you may not use this file except in compliance with the License.
  3095. * You may obtain a copy of the License at
  3096. *
  3097. * http://www.apache.org/licenses/LICENSE-2.0
  3098. *
  3099. * Unless required by applicable law or agreed to in writing, software
  3100. * distributed under the License is distributed on an "AS IS" BASIS,
  3101. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3102. * See the License for the specific language governing permissions and
  3103. * limitations under the License.
  3104. */
  3105. const Fe = {
  3106. mapValue: {
  3107. fields: {
  3108. __type__: {
  3109. stringValue: "__max__"
  3110. }
  3111. }
  3112. }
  3113. }, Be = {
  3114. nullValue: "NULL_VALUE"
  3115. };
  3116. /** Extracts the backend's type order for the provided value. */
  3117. function Le(t) {
  3118. return "nullValue" in t ? 0 /* TypeOrder.NullValue */ : "booleanValue" in t ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in t ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in t ? 5 /* TypeOrder.StringValue */ : "bytesValue" in t ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in t ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in t ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in t ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in t ? Ne(t) ? 4 /* TypeOrder.ServerTimestampValue */ : en(t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : O();
  3119. }
  3120. /** Tests `left` and `right` for equality based on the backend semantics. */ function qe(t, e) {
  3121. if (t === e) return !0;
  3122. const n = Le(t);
  3123. if (n !== Le(e)) return !1;
  3124. switch (n) {
  3125. case 0 /* TypeOrder.NullValue */ :
  3126. case 9007199254740991 /* TypeOrder.MaxValue */ :
  3127. return !0;
  3128. case 1 /* TypeOrder.BooleanValue */ :
  3129. return t.booleanValue === e.booleanValue;
  3130. case 4 /* TypeOrder.ServerTimestampValue */ :
  3131. return Me(t).isEqual(Me(e));
  3132. case 3 /* TypeOrder.TimestampValue */ :
  3133. return function(t, e) {
  3134. if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length)
  3135. // Use string equality for ISO 8601 timestamps
  3136. return t.timestampValue === e.timestampValue;
  3137. const n = De(t.timestampValue), s = De(e.timestampValue);
  3138. return n.seconds === s.seconds && n.nanos === s.nanos;
  3139. }(t, e);
  3140. case 5 /* TypeOrder.StringValue */ :
  3141. return t.stringValue === e.stringValue;
  3142. case 6 /* TypeOrder.BlobValue */ :
  3143. return function(t, e) {
  3144. return xe(t.bytesValue).isEqual(xe(e.bytesValue));
  3145. }(t, e);
  3146. case 7 /* TypeOrder.RefValue */ :
  3147. return t.referenceValue === e.referenceValue;
  3148. case 8 /* TypeOrder.GeoPointValue */ :
  3149. return function(t, e) {
  3150. return Ce(t.geoPointValue.latitude) === Ce(e.geoPointValue.latitude) && Ce(t.geoPointValue.longitude) === Ce(e.geoPointValue.longitude);
  3151. }(t, e);
  3152. case 2 /* TypeOrder.NumberValue */ :
  3153. return function(t, e) {
  3154. if ("integerValue" in t && "integerValue" in e) return Ce(t.integerValue) === Ce(e.integerValue);
  3155. if ("doubleValue" in t && "doubleValue" in e) {
  3156. const n = Ce(t.doubleValue), s = Ce(e.doubleValue);
  3157. return n === s ? Bt(n) === Bt(s) : isNaN(n) && isNaN(s);
  3158. }
  3159. return !1;
  3160. }(t, e);
  3161. case 9 /* TypeOrder.ArrayValue */ :
  3162. return nt(t.arrayValue.values || [], e.arrayValue.values || [], qe);
  3163. case 10 /* TypeOrder.ObjectValue */ :
  3164. return function(t, e) {
  3165. const n = t.mapValue.fields || {}, s = e.mapValue.fields || {};
  3166. if (me(n) !== me(s)) return !1;
  3167. for (const t in n) if (n.hasOwnProperty(t) && (void 0 === s[t] || !qe(n[t], s[t]))) return !1;
  3168. return !0;
  3169. }
  3170. /** Returns true if the ArrayValue contains the specified element. */ (t, e);
  3171. default:
  3172. return O();
  3173. }
  3174. }
  3175. function Ue(t, e) {
  3176. return void 0 !== (t.values || []).find((t => qe(t, e)));
  3177. }
  3178. function Ke(t, e) {
  3179. if (t === e) return 0;
  3180. const n = Le(t), s = Le(e);
  3181. if (n !== s) return et(n, s);
  3182. switch (n) {
  3183. case 0 /* TypeOrder.NullValue */ :
  3184. case 9007199254740991 /* TypeOrder.MaxValue */ :
  3185. return 0;
  3186. case 1 /* TypeOrder.BooleanValue */ :
  3187. return et(t.booleanValue, e.booleanValue);
  3188. case 2 /* TypeOrder.NumberValue */ :
  3189. return function(t, e) {
  3190. const n = Ce(t.integerValue || t.doubleValue), s = Ce(e.integerValue || e.doubleValue);
  3191. return n < s ? -1 : n > s ? 1 : n === s ? 0 :
  3192. // one or both are NaN.
  3193. isNaN(n) ? isNaN(s) ? 0 : -1 : 1;
  3194. }(t, e);
  3195. case 3 /* TypeOrder.TimestampValue */ :
  3196. return Ge(t.timestampValue, e.timestampValue);
  3197. case 4 /* TypeOrder.ServerTimestampValue */ :
  3198. return Ge(Me(t), Me(e));
  3199. case 5 /* TypeOrder.StringValue */ :
  3200. return et(t.stringValue, e.stringValue);
  3201. case 6 /* TypeOrder.BlobValue */ :
  3202. return function(t, e) {
  3203. const n = xe(t), s = xe(e);
  3204. return n.compareTo(s);
  3205. }(t.bytesValue, e.bytesValue);
  3206. case 7 /* TypeOrder.RefValue */ :
  3207. return function(t, e) {
  3208. const n = t.split("/"), s = e.split("/");
  3209. for (let t = 0; t < n.length && t < s.length; t++) {
  3210. const e = et(n[t], s[t]);
  3211. if (0 !== e) return e;
  3212. }
  3213. return et(n.length, s.length);
  3214. }(t.referenceValue, e.referenceValue);
  3215. case 8 /* TypeOrder.GeoPointValue */ :
  3216. return function(t, e) {
  3217. const n = et(Ce(t.latitude), Ce(e.latitude));
  3218. if (0 !== n) return n;
  3219. return et(Ce(t.longitude), Ce(e.longitude));
  3220. }(t.geoPointValue, e.geoPointValue);
  3221. case 9 /* TypeOrder.ArrayValue */ :
  3222. return function(t, e) {
  3223. const n = t.values || [], s = e.values || [];
  3224. for (let t = 0; t < n.length && t < s.length; ++t) {
  3225. const e = Ke(n[t], s[t]);
  3226. if (e) return e;
  3227. }
  3228. return et(n.length, s.length);
  3229. }(t.arrayValue, e.arrayValue);
  3230. case 10 /* TypeOrder.ObjectValue */ :
  3231. return function(t, e) {
  3232. if (t === Fe.mapValue && e === Fe.mapValue) return 0;
  3233. if (t === Fe.mapValue) return 1;
  3234. if (e === Fe.mapValue) return -1;
  3235. const n = t.fields || {}, s = Object.keys(n), i = e.fields || {}, r = Object.keys(i);
  3236. // Even though MapValues are likely sorted correctly based on their insertion
  3237. // order (e.g. when received from the backend), local modifications can bring
  3238. // elements out of order. We need to re-sort the elements to ensure that
  3239. // canonical IDs are independent of insertion order.
  3240. s.sort(), r.sort();
  3241. for (let t = 0; t < s.length && t < r.length; ++t) {
  3242. const e = et(s[t], r[t]);
  3243. if (0 !== e) return e;
  3244. const o = Ke(n[s[t]], i[r[t]]);
  3245. if (0 !== o) return o;
  3246. }
  3247. return et(s.length, r.length);
  3248. }
  3249. /**
  3250. * Generates the canonical ID for the provided field value (as used in Target
  3251. * serialization).
  3252. */ (t.mapValue, e.mapValue);
  3253. default:
  3254. throw O();
  3255. }
  3256. }
  3257. function Ge(t, e) {
  3258. if ("string" == typeof t && "string" == typeof e && t.length === e.length) return et(t, e);
  3259. const n = De(t), s = De(e), i = et(n.seconds, s.seconds);
  3260. return 0 !== i ? i : et(n.nanos, s.nanos);
  3261. }
  3262. function Qe(t) {
  3263. return je(t);
  3264. }
  3265. function je(t) {
  3266. return "nullValue" in t ? "null" : "booleanValue" in t ? "" + t.booleanValue : "integerValue" in t ? "" + t.integerValue : "doubleValue" in t ? "" + t.doubleValue : "timestampValue" in t ? function(t) {
  3267. const e = De(t);
  3268. return `time(${e.seconds},${e.nanos})`;
  3269. }(t.timestampValue) : "stringValue" in t ? t.stringValue : "bytesValue" in t ? xe(t.bytesValue).toBase64() : "referenceValue" in t ? (n = t.referenceValue,
  3270. ht.fromName(n).toString()) : "geoPointValue" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : "arrayValue" in t ? function(t) {
  3271. let e = "[", n = !0;
  3272. for (const s of t.values || []) n ? n = !1 : e += ",", e += je(s);
  3273. return e + "]";
  3274. }
  3275. /**
  3276. * Returns an approximate (and wildly inaccurate) in-memory size for the field
  3277. * value.
  3278. *
  3279. * The memory size takes into account only the actual user data as it resides
  3280. * in memory and ignores object overhead.
  3281. */ (t.arrayValue) : "mapValue" in t ? function(t) {
  3282. // Iteration order in JavaScript is not guaranteed. To ensure that we generate
  3283. // matching canonical IDs for identical maps, we need to sort the keys.
  3284. const e = Object.keys(t.fields || {}).sort();
  3285. let n = "{", s = !0;
  3286. for (const i of e) s ? s = !1 : n += ",", n += `${i}:${je(t.fields[i])}`;
  3287. return n + "}";
  3288. }(t.mapValue) : O();
  3289. var e, n;
  3290. }
  3291. function ze(t) {
  3292. switch (Le(t)) {
  3293. case 0 /* TypeOrder.NullValue */ :
  3294. case 1 /* TypeOrder.BooleanValue */ :
  3295. return 4;
  3296. case 2 /* TypeOrder.NumberValue */ :
  3297. return 8;
  3298. case 3 /* TypeOrder.TimestampValue */ :
  3299. case 8 /* TypeOrder.GeoPointValue */ :
  3300. // GeoPoints are made up of two distinct numbers (latitude + longitude)
  3301. return 16;
  3302. case 4 /* TypeOrder.ServerTimestampValue */ :
  3303. const e = ke(t);
  3304. return e ? 16 + ze(e) : 16;
  3305. case 5 /* TypeOrder.StringValue */ :
  3306. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:
  3307. // "JavaScript's String type is [...] a set of elements of 16-bit unsigned
  3308. // integer values"
  3309. return 2 * t.stringValue.length;
  3310. case 6 /* TypeOrder.BlobValue */ :
  3311. return xe(t.bytesValue).approximateByteSize();
  3312. case 7 /* TypeOrder.RefValue */ :
  3313. return t.referenceValue.length;
  3314. case 9 /* TypeOrder.ArrayValue */ :
  3315. return (t.arrayValue.values || []).reduce(((t, e) => t + ze(e)), 0);
  3316. case 10 /* TypeOrder.ObjectValue */ :
  3317. return function(t) {
  3318. let e = 0;
  3319. return ge(t.fields, ((t, n) => {
  3320. e += t.length + ze(n);
  3321. })), e;
  3322. }(t.mapValue);
  3323. default:
  3324. throw O();
  3325. }
  3326. }
  3327. /** Returns a reference value for the provided database and key. */
  3328. function We(t, e) {
  3329. return {
  3330. referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`
  3331. };
  3332. }
  3333. /** Returns true if `value` is an IntegerValue . */ function He(t) {
  3334. return !!t && "integerValue" in t;
  3335. }
  3336. /** Returns true if `value` is a DoubleValue. */
  3337. /** Returns true if `value` is an ArrayValue. */
  3338. function Je(t) {
  3339. return !!t && "arrayValue" in t;
  3340. }
  3341. /** Returns true if `value` is a NullValue. */ function Ye(t) {
  3342. return !!t && "nullValue" in t;
  3343. }
  3344. /** Returns true if `value` is NaN. */ function Xe(t) {
  3345. return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
  3346. }
  3347. /** Returns true if `value` is a MapValue. */ function Ze(t) {
  3348. return !!t && "mapValue" in t;
  3349. }
  3350. /** Creates a deep copy of `source`. */ function tn(t) {
  3351. if (t.geoPointValue) return {
  3352. geoPointValue: Object.assign({}, t.geoPointValue)
  3353. };
  3354. if (t.timestampValue && "object" == typeof t.timestampValue) return {
  3355. timestampValue: Object.assign({}, t.timestampValue)
  3356. };
  3357. if (t.mapValue) {
  3358. const e = {
  3359. mapValue: {
  3360. fields: {}
  3361. }
  3362. };
  3363. return ge(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = tn(n))), e;
  3364. }
  3365. if (t.arrayValue) {
  3366. const e = {
  3367. arrayValue: {
  3368. values: []
  3369. }
  3370. };
  3371. for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = tn(t.arrayValue.values[n]);
  3372. return e;
  3373. }
  3374. return Object.assign({}, t);
  3375. }
  3376. /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function en(t) {
  3377. return "__max__" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;
  3378. }
  3379. /** Returns the lowest value for the given value type (inclusive). */ function nn(t) {
  3380. return "nullValue" in t ? Be : "booleanValue" in t ? {
  3381. booleanValue: !1
  3382. } : "integerValue" in t || "doubleValue" in t ? {
  3383. doubleValue: NaN
  3384. } : "timestampValue" in t ? {
  3385. timestampValue: {
  3386. seconds: Number.MIN_SAFE_INTEGER
  3387. }
  3388. } : "stringValue" in t ? {
  3389. stringValue: ""
  3390. } : "bytesValue" in t ? {
  3391. bytesValue: ""
  3392. } : "referenceValue" in t ? We(Oe.empty(), ht.empty()) : "geoPointValue" in t ? {
  3393. geoPointValue: {
  3394. latitude: -90,
  3395. longitude: -180
  3396. }
  3397. } : "arrayValue" in t ? {
  3398. arrayValue: {}
  3399. } : "mapValue" in t ? {
  3400. mapValue: {}
  3401. } : O();
  3402. }
  3403. /** Returns the largest value for the given value type (exclusive). */ function sn(t) {
  3404. return "nullValue" in t ? {
  3405. booleanValue: !1
  3406. } : "booleanValue" in t ? {
  3407. doubleValue: NaN
  3408. } : "integerValue" in t || "doubleValue" in t ? {
  3409. timestampValue: {
  3410. seconds: Number.MIN_SAFE_INTEGER
  3411. }
  3412. } : "timestampValue" in t ? {
  3413. stringValue: ""
  3414. } : "stringValue" in t ? {
  3415. bytesValue: ""
  3416. } : "bytesValue" in t ? We(Oe.empty(), ht.empty()) : "referenceValue" in t ? {
  3417. geoPointValue: {
  3418. latitude: -90,
  3419. longitude: -180
  3420. }
  3421. } : "geoPointValue" in t ? {
  3422. arrayValue: {}
  3423. } : "arrayValue" in t ? {
  3424. mapValue: {}
  3425. } : "mapValue" in t ? Fe : O();
  3426. }
  3427. function rn(t, e) {
  3428. const n = Ke(t.value, e.value);
  3429. return 0 !== n ? n : t.inclusive && !e.inclusive ? -1 : !t.inclusive && e.inclusive ? 1 : 0;
  3430. }
  3431. function on(t, e) {
  3432. const n = Ke(t.value, e.value);
  3433. return 0 !== n ? n : t.inclusive && !e.inclusive ? 1 : !t.inclusive && e.inclusive ? -1 : 0;
  3434. }
  3435. /**
  3436. * @license
  3437. * Copyright 2017 Google LLC
  3438. *
  3439. * Licensed under the Apache License, Version 2.0 (the "License");
  3440. * you may not use this file except in compliance with the License.
  3441. * You may obtain a copy of the License at
  3442. *
  3443. * http://www.apache.org/licenses/LICENSE-2.0
  3444. *
  3445. * Unless required by applicable law or agreed to in writing, software
  3446. * distributed under the License is distributed on an "AS IS" BASIS,
  3447. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3448. * See the License for the specific language governing permissions and
  3449. * limitations under the License.
  3450. */
  3451. /**
  3452. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  3453. * ability to add and remove fields (via the ObjectValueBuilder).
  3454. */ class un {
  3455. constructor(t) {
  3456. this.value = t;
  3457. }
  3458. static empty() {
  3459. return new un({
  3460. mapValue: {}
  3461. });
  3462. }
  3463. /**
  3464. * Returns the value at the given path or null.
  3465. *
  3466. * @param path - the path to search
  3467. * @returns The value at the path or null if the path is not set.
  3468. */ field(t) {
  3469. if (t.isEmpty()) return this.value;
  3470. {
  3471. let e = this.value;
  3472. for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)],
  3473. !Ze(e)) return null;
  3474. return e = (e.mapValue.fields || {})[t.lastSegment()], e || null;
  3475. }
  3476. }
  3477. /**
  3478. * Sets the field to the provided value.
  3479. *
  3480. * @param path - The field path to set.
  3481. * @param value - The value to set.
  3482. */ set(t, e) {
  3483. this.getFieldsMap(t.popLast())[t.lastSegment()] = tn(e);
  3484. }
  3485. /**
  3486. * Sets the provided fields to the provided values.
  3487. *
  3488. * @param data - A map of fields to values (or null for deletes).
  3489. */ setAll(t) {
  3490. let e = at.emptyPath(), n = {}, s = [];
  3491. t.forEach(((t, i) => {
  3492. if (!e.isImmediateParentOf(i)) {
  3493. // Insert the accumulated changes at this parent location
  3494. const t = this.getFieldsMap(e);
  3495. this.applyChanges(t, n, s), n = {}, s = [], e = i.popLast();
  3496. }
  3497. t ? n[i.lastSegment()] = tn(t) : s.push(i.lastSegment());
  3498. }));
  3499. const i = this.getFieldsMap(e);
  3500. this.applyChanges(i, n, s);
  3501. }
  3502. /**
  3503. * Removes the field at the specified path. If there is no field at the
  3504. * specified path, nothing is changed.
  3505. *
  3506. * @param path - The field path to remove.
  3507. */ delete(t) {
  3508. const e = this.field(t.popLast());
  3509. Ze(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];
  3510. }
  3511. isEqual(t) {
  3512. return qe(this.value, t.value);
  3513. }
  3514. /**
  3515. * Returns the map that contains the leaf element of `path`. If the parent
  3516. * entry does not yet exist, or if it is not a map, a new map will be created.
  3517. */ getFieldsMap(t) {
  3518. let e = this.value;
  3519. e.mapValue.fields || (e.mapValue = {
  3520. fields: {}
  3521. });
  3522. for (let n = 0; n < t.length; ++n) {
  3523. let s = e.mapValue.fields[t.get(n)];
  3524. Ze(s) && s.mapValue.fields || (s = {
  3525. mapValue: {
  3526. fields: {}
  3527. }
  3528. }, e.mapValue.fields[t.get(n)] = s), e = s;
  3529. }
  3530. return e.mapValue.fields;
  3531. }
  3532. /**
  3533. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  3534. * entries.
  3535. */ applyChanges(t, e, n) {
  3536. ge(e, ((e, n) => t[e] = n));
  3537. for (const e of n) delete t[e];
  3538. }
  3539. clone() {
  3540. return new un(tn(this.value));
  3541. }
  3542. }
  3543. /**
  3544. * Returns a FieldMask built from all fields in a MapValue.
  3545. */ function cn(t) {
  3546. const e = [];
  3547. return ge(t.fields, ((t, n) => {
  3548. const s = new at([ t ]);
  3549. if (Ze(n)) {
  3550. const t = cn(n.mapValue).fields;
  3551. if (0 === t.length)
  3552. // Preserve the empty map by adding it to the FieldMask.
  3553. e.push(s); else
  3554. // For nested and non-empty ObjectValues, add the FieldPath of the
  3555. // leaf nodes.
  3556. for (const n of t) e.push(s.child(n));
  3557. } else
  3558. // For nested and non-empty ObjectValues, add the FieldPath of the leaf
  3559. // nodes.
  3560. e.push(s);
  3561. })), new Re(e);
  3562. }
  3563. /**
  3564. * @license
  3565. * Copyright 2017 Google LLC
  3566. *
  3567. * Licensed under the Apache License, Version 2.0 (the "License");
  3568. * you may not use this file except in compliance with the License.
  3569. * You may obtain a copy of the License at
  3570. *
  3571. * http://www.apache.org/licenses/LICENSE-2.0
  3572. *
  3573. * Unless required by applicable law or agreed to in writing, software
  3574. * distributed under the License is distributed on an "AS IS" BASIS,
  3575. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3576. * See the License for the specific language governing permissions and
  3577. * limitations under the License.
  3578. */
  3579. /**
  3580. * Represents a document in Firestore with a key, version, data and whether it
  3581. * has local mutations applied to it.
  3582. *
  3583. * Documents can transition between states via `convertToFoundDocument()`,
  3584. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  3585. * not transition to one of these states even after all mutations have been
  3586. * applied, `isValidDocument()` returns false and the document should be removed
  3587. * from all views.
  3588. */ class an {
  3589. constructor(t, e, n, s, i, r, o) {
  3590. this.key = t, this.documentType = e, this.version = n, this.readTime = s, this.createTime = i,
  3591. this.data = r, this.documentState = o;
  3592. }
  3593. /**
  3594. * Creates a document with no known version or data, but which can serve as
  3595. * base document for mutations.
  3596. */ static newInvalidDocument(t) {
  3597. return new an(t, 0 /* DocumentType.INVALID */ ,
  3598. /* version */ rt.min(),
  3599. /* readTime */ rt.min(),
  3600. /* createTime */ rt.min(), un.empty(), 0 /* DocumentState.SYNCED */);
  3601. }
  3602. /**
  3603. * Creates a new document that is known to exist with the given data at the
  3604. * given version.
  3605. */ static newFoundDocument(t, e, n, s) {
  3606. return new an(t, 1 /* DocumentType.FOUND_DOCUMENT */ ,
  3607. /* version */ e,
  3608. /* readTime */ rt.min(),
  3609. /* createTime */ n, s, 0 /* DocumentState.SYNCED */);
  3610. }
  3611. /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {
  3612. return new an(t, 2 /* DocumentType.NO_DOCUMENT */ ,
  3613. /* version */ e,
  3614. /* readTime */ rt.min(),
  3615. /* createTime */ rt.min(), un.empty(), 0 /* DocumentState.SYNCED */);
  3616. }
  3617. /**
  3618. * Creates a new document that is known to exist at the given version but
  3619. * whose data is not known (e.g. a document that was updated without a known
  3620. * base document).
  3621. */ static newUnknownDocument(t, e) {
  3622. return new an(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3623. /* version */ e,
  3624. /* readTime */ rt.min(),
  3625. /* createTime */ rt.min(), un.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
  3626. }
  3627. /**
  3628. * Changes the document type to indicate that it exists and that its version
  3629. * and data are known.
  3630. */ convertToFoundDocument(t, e) {
  3631. // If a document is switching state from being an invalid or deleted
  3632. // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
  3633. // update from Watch or due to applying a local set mutation on top
  3634. // of a deleted document, our best guess about its createTime would be the
  3635. // version at which the document transitioned to a FOUND_DOCUMENT.
  3636. return !this.createTime.isEqual(rt.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t),
  3637. this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e,
  3638. this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3639. }
  3640. /**
  3641. * Changes the document type to indicate that it doesn't exist at the given
  3642. * version.
  3643. */ convertToNoDocument(t) {
  3644. return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ ,
  3645. this.data = un.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3646. }
  3647. /**
  3648. * Changes the document type to indicate that it exists at a given version but
  3649. * that its data is not known (e.g. a document that was updated without a known
  3650. * base document).
  3651. */ convertToUnknownDocument(t) {
  3652. return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3653. this.data = un.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ ,
  3654. this;
  3655. }
  3656. setHasCommittedMutations() {
  3657. return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;
  3658. }
  3659. setHasLocalMutations() {
  3660. return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = rt.min(),
  3661. this;
  3662. }
  3663. setReadTime(t) {
  3664. return this.readTime = t, this;
  3665. }
  3666. get hasLocalMutations() {
  3667. return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;
  3668. }
  3669. get hasCommittedMutations() {
  3670. return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;
  3671. }
  3672. get hasPendingWrites() {
  3673. return this.hasLocalMutations || this.hasCommittedMutations;
  3674. }
  3675. isValidDocument() {
  3676. return 0 /* DocumentType.INVALID */ !== this.documentType;
  3677. }
  3678. isFoundDocument() {
  3679. return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;
  3680. }
  3681. isNoDocument() {
  3682. return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;
  3683. }
  3684. isUnknownDocument() {
  3685. return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;
  3686. }
  3687. isEqual(t) {
  3688. return t instanceof an && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);
  3689. }
  3690. mutableCopy() {
  3691. return new an(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  3692. }
  3693. toString() {
  3694. return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;
  3695. }
  3696. }
  3697. /**
  3698. * Compares the value for field `field` in the provided documents. Throws if
  3699. * the field does not exist in both documents.
  3700. */
  3701. /**
  3702. * @license
  3703. * Copyright 2022 Google LLC
  3704. *
  3705. * Licensed under the Apache License, Version 2.0 (the "License");
  3706. * you may not use this file except in compliance with the License.
  3707. * You may obtain a copy of the License at
  3708. *
  3709. * http://www.apache.org/licenses/LICENSE-2.0
  3710. *
  3711. * Unless required by applicable law or agreed to in writing, software
  3712. * distributed under the License is distributed on an "AS IS" BASIS,
  3713. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3714. * See the License for the specific language governing permissions and
  3715. * limitations under the License.
  3716. */
  3717. /**
  3718. * Represents a bound of a query.
  3719. *
  3720. * The bound is specified with the given components representing a position and
  3721. * whether it's just before or just after the position (relative to whatever the
  3722. * query order is).
  3723. *
  3724. * The position represents a logical index position for a query. It's a prefix
  3725. * of values for the (potentially implicit) order by clauses of a query.
  3726. *
  3727. * Bound provides a function to determine whether a document comes before or
  3728. * after a bound. This is influenced by whether the position is just before or
  3729. * just after the provided values.
  3730. */
  3731. class hn {
  3732. constructor(t, e) {
  3733. this.position = t, this.inclusive = e;
  3734. }
  3735. }
  3736. function ln(t, e, n) {
  3737. let s = 0;
  3738. for (let i = 0; i < t.position.length; i++) {
  3739. const r = e[i], o = t.position[i];
  3740. if (r.field.isKeyField()) s = ht.comparator(ht.fromName(o.referenceValue), n.key); else {
  3741. s = Ke(o, n.data.field(r.field));
  3742. }
  3743. if ("desc" /* Direction.DESCENDING */ === r.dir && (s *= -1), 0 !== s) break;
  3744. }
  3745. return s;
  3746. }
  3747. /**
  3748. * Returns true if a document sorts after a bound using the provided sort
  3749. * order.
  3750. */ function fn(t, e) {
  3751. if (null === t) return null === e;
  3752. if (null === e) return !1;
  3753. if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;
  3754. for (let n = 0; n < t.position.length; n++) {
  3755. if (!qe(t.position[n], e.position[n])) return !1;
  3756. }
  3757. return !0;
  3758. }
  3759. /**
  3760. * @license
  3761. * Copyright 2022 Google LLC
  3762. *
  3763. * Licensed under the Apache License, Version 2.0 (the "License");
  3764. * you may not use this file except in compliance with the License.
  3765. * You may obtain a copy of the License at
  3766. *
  3767. * http://www.apache.org/licenses/LICENSE-2.0
  3768. *
  3769. * Unless required by applicable law or agreed to in writing, software
  3770. * distributed under the License is distributed on an "AS IS" BASIS,
  3771. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3772. * See the License for the specific language governing permissions and
  3773. * limitations under the License.
  3774. */
  3775. /**
  3776. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  3777. */ class dn {
  3778. constructor(t, e = "asc" /* Direction.ASCENDING */) {
  3779. this.field = t, this.dir = e;
  3780. }
  3781. }
  3782. function wn(t, e) {
  3783. return t.dir === e.dir && t.field.isEqual(e.field);
  3784. }
  3785. /**
  3786. * @license
  3787. * Copyright 2022 Google LLC
  3788. *
  3789. * Licensed under the Apache License, Version 2.0 (the "License");
  3790. * you may not use this file except in compliance with the License.
  3791. * You may obtain a copy of the License at
  3792. *
  3793. * http://www.apache.org/licenses/LICENSE-2.0
  3794. *
  3795. * Unless required by applicable law or agreed to in writing, software
  3796. * distributed under the License is distributed on an "AS IS" BASIS,
  3797. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3798. * See the License for the specific language governing permissions and
  3799. * limitations under the License.
  3800. */ class _n {}
  3801. class mn extends _n {
  3802. constructor(t, e, n) {
  3803. super(), this.field = t, this.op = e, this.value = n;
  3804. }
  3805. /**
  3806. * Creates a filter based on the provided arguments.
  3807. */ static create(t, e, n) {
  3808. return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, n) : new Pn(t, e, n) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new Dn(t, n) : "in" /* Operator.IN */ === e ? new Cn(t, n) : "not-in" /* Operator.NOT_IN */ === e ? new xn(t, n) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new Nn(t, n) : new mn(t, e, n);
  3809. }
  3810. static createKeyFieldInFilter(t, e, n) {
  3811. return "in" /* Operator.IN */ === e ? new bn(t, n) : new Vn(t, n);
  3812. }
  3813. matches(t) {
  3814. const e = t.data.field(this.field);
  3815. // Types do not have to match in NOT_EQUAL filters.
  3816. return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(Ke(e, this.value)) : null !== e && Le(this.value) === Le(e) && this.matchesComparison(Ke(e, this.value));
  3817. // Only compare types with matching backend order (such as double and int).
  3818. }
  3819. matchesComparison(t) {
  3820. switch (this.op) {
  3821. case "<" /* Operator.LESS_THAN */ :
  3822. return t < 0;
  3823. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  3824. return t <= 0;
  3825. case "==" /* Operator.EQUAL */ :
  3826. return 0 === t;
  3827. case "!=" /* Operator.NOT_EQUAL */ :
  3828. return 0 !== t;
  3829. case ">" /* Operator.GREATER_THAN */ :
  3830. return t > 0;
  3831. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  3832. return t >= 0;
  3833. default:
  3834. return O();
  3835. }
  3836. }
  3837. isInequality() {
  3838. return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0;
  3839. }
  3840. getFlattenedFilters() {
  3841. return [ this ];
  3842. }
  3843. getFilters() {
  3844. return [ this ];
  3845. }
  3846. getFirstInequalityField() {
  3847. return this.isInequality() ? this.field : null;
  3848. }
  3849. }
  3850. class gn extends _n {
  3851. constructor(t, e) {
  3852. super(), this.filters = t, this.op = e, this.lt = null;
  3853. }
  3854. /**
  3855. * Creates a filter based on the provided arguments.
  3856. */ static create(t, e) {
  3857. return new gn(t, e);
  3858. }
  3859. matches(t) {
  3860. return yn(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t)));
  3861. }
  3862. getFlattenedFilters() {
  3863. return null !== this.lt || (this.lt = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])),
  3864. this.lt;
  3865. }
  3866. // Returns a mutable copy of `this.filters`
  3867. getFilters() {
  3868. return Object.assign([], this.filters);
  3869. }
  3870. getFirstInequalityField() {
  3871. const t = this.ft((t => t.isInequality()));
  3872. return null !== t ? t.field : null;
  3873. }
  3874. // Performs a depth-first search to find and return the first FieldFilter in the composite filter
  3875. // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
  3876. // predicate.
  3877. ft(t) {
  3878. for (const e of this.getFlattenedFilters()) if (t(e)) return e;
  3879. return null;
  3880. }
  3881. }
  3882. function yn(t) {
  3883. return "and" /* CompositeOperator.AND */ === t.op;
  3884. }
  3885. function pn(t) {
  3886. return "or" /* CompositeOperator.OR */ === t.op;
  3887. }
  3888. /**
  3889. * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.
  3890. */ function In(t) {
  3891. return Tn(t) && yn(t);
  3892. }
  3893. /**
  3894. * Returns true if this filter does not contain any composite filters. Returns false otherwise.
  3895. */ function Tn(t) {
  3896. for (const e of t.filters) if (e instanceof gn) return !1;
  3897. return !0;
  3898. }
  3899. function En(t) {
  3900. if (t instanceof mn)
  3901. // TODO(b/29183165): Technically, this won't be unique if two values have
  3902. // the same description, such as the int 3 and the string "3". So we should
  3903. // add the types in here somehow, too.
  3904. return t.field.canonicalString() + t.op.toString() + Qe(t.value);
  3905. if (In(t))
  3906. // Older SDK versions use an implicit AND operation between their filters.
  3907. // In the new SDK versions, the developer may use an explicit AND filter.
  3908. // To stay consistent with the old usages, we add a special case to ensure
  3909. // the canonical ID for these two are the same. For example:
  3910. // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same
  3911. // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`.
  3912. return t.filters.map((t => En(t))).join(",");
  3913. {
  3914. // filter instanceof CompositeFilter
  3915. const e = t.filters.map((t => En(t))).join(",");
  3916. return `${t.op}(${e})`;
  3917. }
  3918. }
  3919. function An(t, e) {
  3920. return t instanceof mn ? function(t, e) {
  3921. return e instanceof mn && t.op === e.op && t.field.isEqual(e.field) && qe(t.value, e.value);
  3922. }(t, e) : t instanceof gn ? function(t, e) {
  3923. if (e instanceof gn && t.op === e.op && t.filters.length === e.filters.length) {
  3924. return t.filters.reduce(((t, n, s) => t && An(n, e.filters[s])), !0);
  3925. }
  3926. return !1;
  3927. }
  3928. /**
  3929. * Returns a new composite filter that contains all filter from
  3930. * `compositeFilter` plus all the given filters in `otherFilters`.
  3931. */ (t, e) : void O();
  3932. }
  3933. function vn(t, e) {
  3934. const n = t.filters.concat(e);
  3935. return gn.create(n, t.op);
  3936. }
  3937. /** Returns a debug description for `filter`. */ function Rn(t) {
  3938. return t instanceof mn ? function(t) {
  3939. return `${t.field.canonicalString()} ${t.op} ${Qe(t.value)}`;
  3940. }
  3941. /** Filter that matches on key fields (i.e. '__name__'). */ (t) : t instanceof gn ? function(t) {
  3942. return t.op.toString() + " {" + t.getFilters().map(Rn).join(" ,") + "}";
  3943. }(t) : "Filter";
  3944. }
  3945. class Pn extends mn {
  3946. constructor(t, e, n) {
  3947. super(t, e, n), this.key = ht.fromName(n.referenceValue);
  3948. }
  3949. matches(t) {
  3950. const e = ht.comparator(t.key, this.key);
  3951. return this.matchesComparison(e);
  3952. }
  3953. }
  3954. /** Filter that matches on key fields within an array. */ class bn extends mn {
  3955. constructor(t, e) {
  3956. super(t, "in" /* Operator.IN */ , e), this.keys = Sn("in" /* Operator.IN */ , e);
  3957. }
  3958. matches(t) {
  3959. return this.keys.some((e => e.isEqual(t.key)));
  3960. }
  3961. }
  3962. /** Filter that matches on key fields not present within an array. */ class Vn extends mn {
  3963. constructor(t, e) {
  3964. super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = Sn("not-in" /* Operator.NOT_IN */ , e);
  3965. }
  3966. matches(t) {
  3967. return !this.keys.some((e => e.isEqual(t.key)));
  3968. }
  3969. }
  3970. function Sn(t, e) {
  3971. var n;
  3972. return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => ht.fromName(t.referenceValue)));
  3973. }
  3974. /** A Filter that implements the array-contains operator. */ class Dn extends mn {
  3975. constructor(t, e) {
  3976. super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e);
  3977. }
  3978. matches(t) {
  3979. const e = t.data.field(this.field);
  3980. return Je(e) && Ue(e.arrayValue, this.value);
  3981. }
  3982. }
  3983. /** A Filter that implements the IN operator. */ class Cn extends mn {
  3984. constructor(t, e) {
  3985. super(t, "in" /* Operator.IN */ , e);
  3986. }
  3987. matches(t) {
  3988. const e = t.data.field(this.field);
  3989. return null !== e && Ue(this.value.arrayValue, e);
  3990. }
  3991. }
  3992. /** A Filter that implements the not-in operator. */ class xn extends mn {
  3993. constructor(t, e) {
  3994. super(t, "not-in" /* Operator.NOT_IN */ , e);
  3995. }
  3996. matches(t) {
  3997. if (Ue(this.value.arrayValue, {
  3998. nullValue: "NULL_VALUE"
  3999. })) return !1;
  4000. const e = t.data.field(this.field);
  4001. return null !== e && !Ue(this.value.arrayValue, e);
  4002. }
  4003. }
  4004. /** A Filter that implements the array-contains-any operator. */ class Nn extends mn {
  4005. constructor(t, e) {
  4006. super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e);
  4007. }
  4008. matches(t) {
  4009. const e = t.data.field(this.field);
  4010. return !(!Je(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => Ue(this.value.arrayValue, t)));
  4011. }
  4012. }
  4013. /**
  4014. * @license
  4015. * Copyright 2019 Google LLC
  4016. *
  4017. * Licensed under the Apache License, Version 2.0 (the "License");
  4018. * you may not use this file except in compliance with the License.
  4019. * You may obtain a copy of the License at
  4020. *
  4021. * http://www.apache.org/licenses/LICENSE-2.0
  4022. *
  4023. * Unless required by applicable law or agreed to in writing, software
  4024. * distributed under the License is distributed on an "AS IS" BASIS,
  4025. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4026. * See the License for the specific language governing permissions and
  4027. * limitations under the License.
  4028. */
  4029. // Visible for testing
  4030. class kn {
  4031. constructor(t, e = null, n = [], s = [], i = null, r = null, o = null) {
  4032. this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = s, this.limit = i,
  4033. this.startAt = r, this.endAt = o, this.dt = null;
  4034. }
  4035. }
  4036. /**
  4037. * Initializes a Target with a path and optional additional query constraints.
  4038. * Path must currently be empty if this is a collection group query.
  4039. *
  4040. * NOTE: you should always construct `Target` from `Query.toTarget` instead of
  4041. * using this factory method, because `Query` provides an implicit `orderBy`
  4042. * property.
  4043. */ function Mn(t, e = null, n = [], s = [], i = null, r = null, o = null) {
  4044. return new kn(t, e, n, s, i, r, o);
  4045. }
  4046. function $n(t) {
  4047. const e = L(t);
  4048. if (null === e.dt) {
  4049. let t = e.path.canonicalString();
  4050. null !== e.collectionGroup && (t += "|cg:" + e.collectionGroup), t += "|f:", t += e.filters.map((t => En(t))).join(","),
  4051. t += "|ob:", t += e.orderBy.map((t => function(t) {
  4052. // TODO(b/29183165): Make this collision robust.
  4053. return t.field.canonicalString() + t.dir;
  4054. }(t))).join(","), Ft(e.limit) || (t += "|l:", t += e.limit), e.startAt && (t += "|lb:",
  4055. t += e.startAt.inclusive ? "b:" : "a:", t += e.startAt.position.map((t => Qe(t))).join(",")),
  4056. e.endAt && (t += "|ub:", t += e.endAt.inclusive ? "a:" : "b:", t += e.endAt.position.map((t => Qe(t))).join(",")),
  4057. e.dt = t;
  4058. }
  4059. return e.dt;
  4060. }
  4061. function On(t, e) {
  4062. if (t.limit !== e.limit) return !1;
  4063. if (t.orderBy.length !== e.orderBy.length) return !1;
  4064. for (let n = 0; n < t.orderBy.length; n++) if (!wn(t.orderBy[n], e.orderBy[n])) return !1;
  4065. if (t.filters.length !== e.filters.length) return !1;
  4066. for (let n = 0; n < t.filters.length; n++) if (!An(t.filters[n], e.filters[n])) return !1;
  4067. return t.collectionGroup === e.collectionGroup && (!!t.path.isEqual(e.path) && (!!fn(t.startAt, e.startAt) && fn(t.endAt, e.endAt)));
  4068. }
  4069. function Fn(t) {
  4070. return ht.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  4071. }
  4072. /** Returns the field filters that target the given field path. */ function Bn(t, e) {
  4073. return t.filters.filter((t => t instanceof mn && t.field.isEqual(e)));
  4074. }
  4075. /**
  4076. * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
  4077. * filters. Returns `null` if there are no such filters.
  4078. */
  4079. /**
  4080. * Returns the value to use as the lower bound for ascending index segment at
  4081. * the provided `fieldPath` (or the upper bound for an descending segment).
  4082. */
  4083. function Ln(t, e, n) {
  4084. let s = Be, i = !0;
  4085. // Process all filters to find a value for the current field segment
  4086. for (const n of Bn(t, e)) {
  4087. let t = Be, e = !0;
  4088. switch (n.op) {
  4089. case "<" /* Operator.LESS_THAN */ :
  4090. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  4091. t = nn(n.value);
  4092. break;
  4093. case "==" /* Operator.EQUAL */ :
  4094. case "in" /* Operator.IN */ :
  4095. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  4096. t = n.value;
  4097. break;
  4098. case ">" /* Operator.GREATER_THAN */ :
  4099. t = n.value, e = !1;
  4100. break;
  4101. case "!=" /* Operator.NOT_EQUAL */ :
  4102. case "not-in" /* Operator.NOT_IN */ :
  4103. t = Be;
  4104. // Remaining filters cannot be used as lower bounds.
  4105. }
  4106. rn({
  4107. value: s,
  4108. inclusive: i
  4109. }, {
  4110. value: t,
  4111. inclusive: e
  4112. }) < 0 && (s = t, i = e);
  4113. }
  4114. // If there is an additional bound, compare the values against the existing
  4115. // range to see if we can narrow the scope.
  4116. if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {
  4117. if (t.orderBy[r].field.isEqual(e)) {
  4118. const t = n.position[r];
  4119. rn({
  4120. value: s,
  4121. inclusive: i
  4122. }, {
  4123. value: t,
  4124. inclusive: n.inclusive
  4125. }) < 0 && (s = t, i = n.inclusive);
  4126. break;
  4127. }
  4128. }
  4129. return {
  4130. value: s,
  4131. inclusive: i
  4132. };
  4133. }
  4134. /**
  4135. * Returns the value to use as the upper bound for ascending index segment at
  4136. * the provided `fieldPath` (or the lower bound for a descending segment).
  4137. */ function qn(t, e, n) {
  4138. let s = Fe, i = !0;
  4139. // Process all filters to find a value for the current field segment
  4140. for (const n of Bn(t, e)) {
  4141. let t = Fe, e = !0;
  4142. switch (n.op) {
  4143. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  4144. case ">" /* Operator.GREATER_THAN */ :
  4145. t = sn(n.value), e = !1;
  4146. break;
  4147. case "==" /* Operator.EQUAL */ :
  4148. case "in" /* Operator.IN */ :
  4149. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  4150. t = n.value;
  4151. break;
  4152. case "<" /* Operator.LESS_THAN */ :
  4153. t = n.value, e = !1;
  4154. break;
  4155. case "!=" /* Operator.NOT_EQUAL */ :
  4156. case "not-in" /* Operator.NOT_IN */ :
  4157. t = Fe;
  4158. // Remaining filters cannot be used as upper bounds.
  4159. }
  4160. on({
  4161. value: s,
  4162. inclusive: i
  4163. }, {
  4164. value: t,
  4165. inclusive: e
  4166. }) > 0 && (s = t, i = e);
  4167. }
  4168. // If there is an additional bound, compare the values against the existing
  4169. // range to see if we can narrow the scope.
  4170. if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {
  4171. if (t.orderBy[r].field.isEqual(e)) {
  4172. const t = n.position[r];
  4173. on({
  4174. value: s,
  4175. inclusive: i
  4176. }, {
  4177. value: t,
  4178. inclusive: n.inclusive
  4179. }) > 0 && (s = t, i = n.inclusive);
  4180. break;
  4181. }
  4182. }
  4183. return {
  4184. value: s,
  4185. inclusive: i
  4186. };
  4187. }
  4188. /** Returns the number of segments of a perfect index for this target. */
  4189. /**
  4190. * @license
  4191. * Copyright 2017 Google LLC
  4192. *
  4193. * Licensed under the Apache License, Version 2.0 (the "License");
  4194. * you may not use this file except in compliance with the License.
  4195. * You may obtain a copy of the License at
  4196. *
  4197. * http://www.apache.org/licenses/LICENSE-2.0
  4198. *
  4199. * Unless required by applicable law or agreed to in writing, software
  4200. * distributed under the License is distributed on an "AS IS" BASIS,
  4201. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4202. * See the License for the specific language governing permissions and
  4203. * limitations under the License.
  4204. */
  4205. /**
  4206. * Query encapsulates all the query attributes we support in the SDK. It can
  4207. * be run against the LocalStore, as well as be converted to a `Target` to
  4208. * query the RemoteStore results.
  4209. *
  4210. * Visible for testing.
  4211. */
  4212. class Un {
  4213. /**
  4214. * Initializes a Query with a path and optional additional query constraints.
  4215. * Path must currently be empty if this is a collection group query.
  4216. */
  4217. constructor(t, e = null, n = [], s = [], i = null, r = "F" /* LimitType.First */ , o = null, u = null) {
  4218. this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = s,
  4219. this.limit = i, this.limitType = r, this.startAt = o, this.endAt = u, this.wt = null,
  4220. // The corresponding `Target` of this `Query` instance.
  4221. this._t = null, this.startAt, this.endAt;
  4222. }
  4223. }
  4224. /** Creates a new Query instance with the options provided. */ function Kn(t, e, n, s, i, r, o, u) {
  4225. return new Un(t, e, n, s, i, r, o, u);
  4226. }
  4227. /** Creates a new Query for a query that matches all documents at `path` */ function Gn(t) {
  4228. return new Un(t);
  4229. }
  4230. /**
  4231. * Helper to convert a collection group query into a collection query at a
  4232. * specific path. This is used when executing collection group queries, since
  4233. * we have to split the query into a set of collection queries at multiple
  4234. * paths.
  4235. */
  4236. /**
  4237. * Returns true if this query does not specify any query constraints that
  4238. * could remove results.
  4239. */
  4240. function Qn(t) {
  4241. return 0 === t.filters.length && null === t.limit && null == t.startAt && null == t.endAt && (0 === t.explicitOrderBy.length || 1 === t.explicitOrderBy.length && t.explicitOrderBy[0].field.isKeyField());
  4242. }
  4243. function jn(t) {
  4244. return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;
  4245. }
  4246. function zn(t) {
  4247. for (const e of t.filters) {
  4248. const t = e.getFirstInequalityField();
  4249. if (null !== t) return t;
  4250. }
  4251. return null;
  4252. }
  4253. /**
  4254. * Creates a new Query for a collection group query that matches all documents
  4255. * within the provided collection group.
  4256. */
  4257. /**
  4258. * Returns whether the query matches a collection group rather than a specific
  4259. * collection.
  4260. */
  4261. function Wn(t) {
  4262. return null !== t.collectionGroup;
  4263. }
  4264. /**
  4265. * Returns the implicit order by constraint that is used to execute the Query,
  4266. * which can be different from the order by constraints the user provided (e.g.
  4267. * the SDK and backend always orders by `__name__`).
  4268. */ function Hn(t) {
  4269. const e = L(t);
  4270. if (null === e.wt) {
  4271. e.wt = [];
  4272. const t = zn(e), n = jn(e);
  4273. if (null !== t && null === n)
  4274. // In order to implicitly add key ordering, we must also add the
  4275. // inequality filter field for it to be a valid query.
  4276. // Note that the default inequality field and key ordering is ascending.
  4277. t.isKeyField() || e.wt.push(new dn(t)), e.wt.push(new dn(at.keyField(), "asc" /* Direction.ASCENDING */)); else {
  4278. let t = !1;
  4279. for (const n of e.explicitOrderBy) e.wt.push(n), n.field.isKeyField() && (t = !0);
  4280. if (!t) {
  4281. // The order of the implicit key ordering always matches the last
  4282. // explicit order by
  4283. const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */;
  4284. e.wt.push(new dn(at.keyField(), t));
  4285. }
  4286. }
  4287. }
  4288. return e.wt;
  4289. }
  4290. /**
  4291. * Converts this `Query` instance to it's corresponding `Target` representation.
  4292. */ function Jn(t) {
  4293. const e = L(t);
  4294. if (!e._t) if ("F" /* LimitType.First */ === e.limitType) e._t = Mn(e.path, e.collectionGroup, Hn(e), e.filters, e.limit, e.startAt, e.endAt); else {
  4295. // Flip the orderBy directions since we want the last results
  4296. const t = [];
  4297. for (const n of Hn(e)) {
  4298. const e = "desc" /* Direction.DESCENDING */ === n.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */;
  4299. t.push(new dn(n.field, e));
  4300. }
  4301. // We need to swap the cursors to match the now-flipped query ordering.
  4302. const n = e.endAt ? new hn(e.endAt.position, e.endAt.inclusive) : null, s = e.startAt ? new hn(e.startAt.position, e.startAt.inclusive) : null;
  4303. // Now return as a LimitType.First query.
  4304. e._t = Mn(e.path, e.collectionGroup, t, e.filters, e.limit, n, s);
  4305. }
  4306. return e._t;
  4307. }
  4308. function Yn(t, e) {
  4309. e.getFirstInequalityField(), zn(t);
  4310. const n = t.filters.concat([ e ]);
  4311. return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);
  4312. }
  4313. function Xn(t, e, n) {
  4314. return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);
  4315. }
  4316. function Zn(t, e) {
  4317. return On(Jn(t), Jn(e)) && t.limitType === e.limitType;
  4318. }
  4319. // TODO(b/29183165): This is used to get a unique string from a query to, for
  4320. // example, use as a dictionary key, but the implementation is subject to
  4321. // collisions. Make it collision-free.
  4322. function ts(t) {
  4323. return `${$n(Jn(t))}|lt:${t.limitType}`;
  4324. }
  4325. function es(t) {
  4326. return `Query(target=${function(t) {
  4327. let e = t.path.canonicalString();
  4328. return null !== t.collectionGroup && (e += " collectionGroup=" + t.collectionGroup),
  4329. t.filters.length > 0 && (e += `, filters: [${t.filters.map((t => Rn(t))).join(", ")}]`),
  4330. Ft(t.limit) || (e += ", limit: " + t.limit), t.orderBy.length > 0 && (e += `, orderBy: [${t.orderBy.map((t => function(t) {
  4331. return `${t.field.canonicalString()} (${t.dir})`;
  4332. }(t))).join(", ")}]`), t.startAt && (e += ", startAt: ", e += t.startAt.inclusive ? "b:" : "a:",
  4333. e += t.startAt.position.map((t => Qe(t))).join(",")), t.endAt && (e += ", endAt: ",
  4334. e += t.endAt.inclusive ? "a:" : "b:", e += t.endAt.position.map((t => Qe(t))).join(",")),
  4335. `Target(${e})`;
  4336. }(Jn(t))}; limitType=${t.limitType})`;
  4337. }
  4338. /** Returns whether `doc` matches the constraints of `query`. */ function ns(t, e) {
  4339. return e.isFoundDocument() && function(t, e) {
  4340. const n = e.key.path;
  4341. return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : ht.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);
  4342. }
  4343. /**
  4344. * A document must have a value for every ordering clause in order to show up
  4345. * in the results.
  4346. */ (t, e) && function(t, e) {
  4347. // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).
  4348. // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must
  4349. // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due
  4350. // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a".
  4351. // A document with content of {b:1} matches the filters, but does not match the orderBy because
  4352. // it's missing the field 'a'.
  4353. for (const n of Hn(t))
  4354. // order by key always matches
  4355. if (!n.field.isKeyField() && null === e.data.field(n.field)) return !1;
  4356. return !0;
  4357. }(t, e) && function(t, e) {
  4358. for (const n of t.filters) if (!n.matches(e)) return !1;
  4359. return !0;
  4360. }
  4361. /** Makes sure a document is within the bounds, if provided. */ (t, e) && function(t, e) {
  4362. if (t.startAt && !
  4363. /**
  4364. * Returns true if a document sorts before a bound using the provided sort
  4365. * order.
  4366. */
  4367. function(t, e, n) {
  4368. const s = ln(t, e, n);
  4369. return t.inclusive ? s <= 0 : s < 0;
  4370. }(t.startAt, Hn(t), e)) return !1;
  4371. if (t.endAt && !function(t, e, n) {
  4372. const s = ln(t, e, n);
  4373. return t.inclusive ? s >= 0 : s > 0;
  4374. }(t.endAt, Hn(t), e)) return !1;
  4375. return !0;
  4376. }
  4377. /**
  4378. * Returns the collection group that this query targets.
  4379. *
  4380. * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
  4381. * synchronization for query results.
  4382. */ (t, e);
  4383. }
  4384. function ss(t) {
  4385. return t.collectionGroup || (t.path.length % 2 == 1 ? t.path.lastSegment() : t.path.get(t.path.length - 2));
  4386. }
  4387. /**
  4388. * Returns a new comparator function that can be used to compare two documents
  4389. * based on the Query's ordering constraint.
  4390. */ function is(t) {
  4391. return (e, n) => {
  4392. let s = !1;
  4393. for (const i of Hn(t)) {
  4394. const t = rs(i, e, n);
  4395. if (0 !== t) return t;
  4396. s = s || i.field.isKeyField();
  4397. }
  4398. return 0;
  4399. };
  4400. }
  4401. function rs(t, e, n) {
  4402. const s = t.field.isKeyField() ? ht.comparator(e.key, n.key) : function(t, e, n) {
  4403. const s = e.data.field(t), i = n.data.field(t);
  4404. return null !== s && null !== i ? Ke(s, i) : O();
  4405. }(t.field, e, n);
  4406. switch (t.dir) {
  4407. case "asc" /* Direction.ASCENDING */ :
  4408. return s;
  4409. case "desc" /* Direction.DESCENDING */ :
  4410. return -1 * s;
  4411. default:
  4412. return O();
  4413. }
  4414. }
  4415. /**
  4416. * @license
  4417. * Copyright 2017 Google LLC
  4418. *
  4419. * Licensed under the Apache License, Version 2.0 (the "License");
  4420. * you may not use this file except in compliance with the License.
  4421. * You may obtain a copy of the License at
  4422. *
  4423. * http://www.apache.org/licenses/LICENSE-2.0
  4424. *
  4425. * Unless required by applicable law or agreed to in writing, software
  4426. * distributed under the License is distributed on an "AS IS" BASIS,
  4427. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4428. * See the License for the specific language governing permissions and
  4429. * limitations under the License.
  4430. */
  4431. /**
  4432. * A map implementation that uses objects as keys. Objects must have an
  4433. * associated equals function and must be immutable. Entries in the map are
  4434. * stored together with the key being produced from the mapKeyFn. This map
  4435. * automatically handles collisions of keys.
  4436. */ class os {
  4437. constructor(t, e) {
  4438. this.mapKeyFn = t, this.equalsFn = e,
  4439. /**
  4440. * The inner map for a key/value pair. Due to the possibility of collisions we
  4441. * keep a list of entries that we do a linear search through to find an actual
  4442. * match. Note that collisions should be rare, so we still expect near
  4443. * constant time lookups in practice.
  4444. */
  4445. this.inner = {},
  4446. /** The number of entries stored in the map */
  4447. this.innerSize = 0;
  4448. }
  4449. /** Get a value for this key, or undefined if it does not exist. */ get(t) {
  4450. const e = this.mapKeyFn(t), n = this.inner[e];
  4451. if (void 0 !== n) for (const [e, s] of n) if (this.equalsFn(e, t)) return s;
  4452. }
  4453. has(t) {
  4454. return void 0 !== this.get(t);
  4455. }
  4456. /** Put this key and value in the map. */ set(t, e) {
  4457. const n = this.mapKeyFn(t), s = this.inner[n];
  4458. if (void 0 === s) return this.inner[n] = [ [ t, e ] ], void this.innerSize++;
  4459. for (let n = 0; n < s.length; n++) if (this.equalsFn(s[n][0], t))
  4460. // This is updating an existing entry and does not increase `innerSize`.
  4461. return void (s[n] = [ t, e ]);
  4462. s.push([ t, e ]), this.innerSize++;
  4463. }
  4464. /**
  4465. * Remove this key from the map. Returns a boolean if anything was deleted.
  4466. */ delete(t) {
  4467. const e = this.mapKeyFn(t), n = this.inner[e];
  4468. if (void 0 === n) return !1;
  4469. for (let s = 0; s < n.length; s++) if (this.equalsFn(n[s][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(s, 1),
  4470. this.innerSize--, !0;
  4471. return !1;
  4472. }
  4473. forEach(t) {
  4474. ge(this.inner, ((e, n) => {
  4475. for (const [e, s] of n) t(e, s);
  4476. }));
  4477. }
  4478. isEmpty() {
  4479. return ye(this.inner);
  4480. }
  4481. size() {
  4482. return this.innerSize;
  4483. }
  4484. }
  4485. /**
  4486. * @license
  4487. * Copyright 2017 Google LLC
  4488. *
  4489. * Licensed under the Apache License, Version 2.0 (the "License");
  4490. * you may not use this file except in compliance with the License.
  4491. * You may obtain a copy of the License at
  4492. *
  4493. * http://www.apache.org/licenses/LICENSE-2.0
  4494. *
  4495. * Unless required by applicable law or agreed to in writing, software
  4496. * distributed under the License is distributed on an "AS IS" BASIS,
  4497. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4498. * See the License for the specific language governing permissions and
  4499. * limitations under the License.
  4500. */ const us = new pe(ht.comparator);
  4501. function cs() {
  4502. return us;
  4503. }
  4504. const as = new pe(ht.comparator);
  4505. function hs(...t) {
  4506. let e = as;
  4507. for (const n of t) e = e.insert(n.key, n);
  4508. return e;
  4509. }
  4510. function ls(t) {
  4511. let e = as;
  4512. return t.forEach(((t, n) => e = e.insert(t, n.overlayedDocument))), e;
  4513. }
  4514. function fs() {
  4515. return ws();
  4516. }
  4517. function ds() {
  4518. return ws();
  4519. }
  4520. function ws() {
  4521. return new os((t => t.toString()), ((t, e) => t.isEqual(e)));
  4522. }
  4523. const _s = new pe(ht.comparator);
  4524. const ms = new Ee(ht.comparator);
  4525. function gs(...t) {
  4526. let e = ms;
  4527. for (const n of t) e = e.add(n);
  4528. return e;
  4529. }
  4530. const ys = new Ee(et);
  4531. function ps() {
  4532. return ys;
  4533. }
  4534. /**
  4535. * @license
  4536. * Copyright 2020 Google LLC
  4537. *
  4538. * Licensed under the Apache License, Version 2.0 (the "License");
  4539. * you may not use this file except in compliance with the License.
  4540. * You may obtain a copy of the License at
  4541. *
  4542. * http://www.apache.org/licenses/LICENSE-2.0
  4543. *
  4544. * Unless required by applicable law or agreed to in writing, software
  4545. * distributed under the License is distributed on an "AS IS" BASIS,
  4546. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4547. * See the License for the specific language governing permissions and
  4548. * limitations under the License.
  4549. */
  4550. /**
  4551. * Returns an DoubleValue for `value` that is encoded based the serializer's
  4552. * `useProto3Json` setting.
  4553. */ function Is(t, e) {
  4554. if (t.useProto3Json) {
  4555. if (isNaN(e)) return {
  4556. doubleValue: "NaN"
  4557. };
  4558. if (e === 1 / 0) return {
  4559. doubleValue: "Infinity"
  4560. };
  4561. if (e === -1 / 0) return {
  4562. doubleValue: "-Infinity"
  4563. };
  4564. }
  4565. return {
  4566. doubleValue: Bt(e) ? "-0" : e
  4567. };
  4568. }
  4569. /**
  4570. * Returns an IntegerValue for `value`.
  4571. */ function Ts(t) {
  4572. return {
  4573. integerValue: "" + t
  4574. };
  4575. }
  4576. /**
  4577. * Returns a value for a number that's appropriate to put into a proto.
  4578. * The return value is an IntegerValue if it can safely represent the value,
  4579. * otherwise a DoubleValue is returned.
  4580. */ function Es(t, e) {
  4581. return Lt(e) ? Ts(e) : Is(t, e);
  4582. }
  4583. /**
  4584. * @license
  4585. * Copyright 2018 Google LLC
  4586. *
  4587. * Licensed under the Apache License, Version 2.0 (the "License");
  4588. * you may not use this file except in compliance with the License.
  4589. * You may obtain a copy of the License at
  4590. *
  4591. * http://www.apache.org/licenses/LICENSE-2.0
  4592. *
  4593. * Unless required by applicable law or agreed to in writing, software
  4594. * distributed under the License is distributed on an "AS IS" BASIS,
  4595. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4596. * See the License for the specific language governing permissions and
  4597. * limitations under the License.
  4598. */
  4599. /** Used to represent a field transform on a mutation. */ class As {
  4600. constructor() {
  4601. // Make sure that the structural type of `TransformOperation` is unique.
  4602. // See https://github.com/microsoft/TypeScript/issues/5451
  4603. this._ = void 0;
  4604. }
  4605. }
  4606. /**
  4607. * Computes the local transform result against the provided `previousValue`,
  4608. * optionally using the provided localWriteTime.
  4609. */ function vs(t, e, n) {
  4610. return t instanceof bs ? function(t, e) {
  4611. const n = {
  4612. fields: {
  4613. __type__: {
  4614. stringValue: "server_timestamp"
  4615. },
  4616. __local_write_time__: {
  4617. timestampValue: {
  4618. seconds: t.seconds,
  4619. nanos: t.nanoseconds
  4620. }
  4621. }
  4622. }
  4623. };
  4624. // We should avoid storing deeply nested server timestamp map values
  4625. // because we never use the intermediate "previous values".
  4626. // For example:
  4627. // previous: 42L, add: t1, result: t1 -> 42L
  4628. // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)
  4629. // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)
  4630. // `getPreviousValue` recursively traverses server timestamps to find the
  4631. // least recent Value.
  4632. return e && Ne(e) && (e = ke(e)), e && (n.fields.__previous_value__ = e),
  4633. {
  4634. mapValue: n
  4635. };
  4636. }(n, e) : t instanceof Vs ? Ss(t, e) : t instanceof Ds ? Cs(t, e) : function(t, e) {
  4637. // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit
  4638. // precision and resolves overflows by reducing precision, we do not
  4639. // manually cap overflows at 2^63.
  4640. const n = Ps(t, e), s = Ns(n) + Ns(t.gt);
  4641. return He(n) && He(t.gt) ? Ts(s) : Is(t.serializer, s);
  4642. }(t, e);
  4643. }
  4644. /**
  4645. * Computes a final transform result after the transform has been acknowledged
  4646. * by the server, potentially using the server-provided transformResult.
  4647. */ function Rs(t, e, n) {
  4648. // The server just sends null as the transform result for array operations,
  4649. // so we have to calculate a result the same as we do for local
  4650. // applications.
  4651. return t instanceof Vs ? Ss(t, e) : t instanceof Ds ? Cs(t, e) : n;
  4652. }
  4653. /**
  4654. * If this transform operation is not idempotent, returns the base value to
  4655. * persist for this transform. If a base value is returned, the transform
  4656. * operation is always applied to this base value, even if document has
  4657. * already been updated.
  4658. *
  4659. * Base values provide consistent behavior for non-idempotent transforms and
  4660. * allow us to return the same latency-compensated value even if the backend
  4661. * has already applied the transform operation. The base value is null for
  4662. * idempotent transforms, as they can be re-played even if the backend has
  4663. * already applied them.
  4664. *
  4665. * @returns a base value to store along with the mutation, or null for
  4666. * idempotent transforms.
  4667. */ function Ps(t, e) {
  4668. return t instanceof xs ? He(n = e) || function(t) {
  4669. return !!t && "doubleValue" in t;
  4670. }
  4671. /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (n) ? e : {
  4672. integerValue: 0
  4673. } : null;
  4674. var n;
  4675. }
  4676. /** Transforms a value into a server-generated timestamp. */
  4677. class bs extends As {}
  4678. /** Transforms an array value via a union operation. */ class Vs extends As {
  4679. constructor(t) {
  4680. super(), this.elements = t;
  4681. }
  4682. }
  4683. function Ss(t, e) {
  4684. const n = ks(e);
  4685. for (const e of t.elements) n.some((t => qe(t, e))) || n.push(e);
  4686. return {
  4687. arrayValue: {
  4688. values: n
  4689. }
  4690. };
  4691. }
  4692. /** Transforms an array value via a remove operation. */ class Ds extends As {
  4693. constructor(t) {
  4694. super(), this.elements = t;
  4695. }
  4696. }
  4697. function Cs(t, e) {
  4698. let n = ks(e);
  4699. for (const e of t.elements) n = n.filter((t => !qe(t, e)));
  4700. return {
  4701. arrayValue: {
  4702. values: n
  4703. }
  4704. };
  4705. }
  4706. /**
  4707. * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
  4708. * transforms. Converts all field values to integers or doubles, but unlike the
  4709. * backend does not cap integer values at 2^63. Instead, JavaScript number
  4710. * arithmetic is used and precision loss can occur for values greater than 2^53.
  4711. */ class xs extends As {
  4712. constructor(t, e) {
  4713. super(), this.serializer = t, this.gt = e;
  4714. }
  4715. }
  4716. function Ns(t) {
  4717. return Ce(t.integerValue || t.doubleValue);
  4718. }
  4719. function ks(t) {
  4720. return Je(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];
  4721. }
  4722. /**
  4723. * @license
  4724. * Copyright 2017 Google LLC
  4725. *
  4726. * Licensed under the Apache License, Version 2.0 (the "License");
  4727. * you may not use this file except in compliance with the License.
  4728. * You may obtain a copy of the License at
  4729. *
  4730. * http://www.apache.org/licenses/LICENSE-2.0
  4731. *
  4732. * Unless required by applicable law or agreed to in writing, software
  4733. * distributed under the License is distributed on an "AS IS" BASIS,
  4734. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4735. * See the License for the specific language governing permissions and
  4736. * limitations under the License.
  4737. */
  4738. /** A field path and the TransformOperation to perform upon it. */ class Ms {
  4739. constructor(t, e) {
  4740. this.field = t, this.transform = e;
  4741. }
  4742. }
  4743. function $s(t, e) {
  4744. return t.field.isEqual(e.field) && function(t, e) {
  4745. return t instanceof Vs && e instanceof Vs || t instanceof Ds && e instanceof Ds ? nt(t.elements, e.elements, qe) : t instanceof xs && e instanceof xs ? qe(t.gt, e.gt) : t instanceof bs && e instanceof bs;
  4746. }(t.transform, e.transform);
  4747. }
  4748. /** The result of successfully applying a mutation to the backend. */
  4749. class Os {
  4750. constructor(
  4751. /**
  4752. * The version at which the mutation was committed:
  4753. *
  4754. * - For most operations, this is the updateTime in the WriteResult.
  4755. * - For deletes, the commitTime of the WriteResponse (because deletes are
  4756. * not stored and have no updateTime).
  4757. *
  4758. * Note that these versions can be different: No-op writes will not change
  4759. * the updateTime even though the commitTime advances.
  4760. */
  4761. t,
  4762. /**
  4763. * The resulting fields returned from the backend after a mutation
  4764. * containing field transforms has been committed. Contains one FieldValue
  4765. * for each FieldTransform that was in the mutation.
  4766. *
  4767. * Will be empty if the mutation did not contain any field transforms.
  4768. */
  4769. e) {
  4770. this.version = t, this.transformResults = e;
  4771. }
  4772. }
  4773. /**
  4774. * Encodes a precondition for a mutation. This follows the model that the
  4775. * backend accepts with the special case of an explicit "empty" precondition
  4776. * (meaning no precondition).
  4777. */ class Fs {
  4778. constructor(t, e) {
  4779. this.updateTime = t, this.exists = e;
  4780. }
  4781. /** Creates a new empty Precondition. */ static none() {
  4782. return new Fs;
  4783. }
  4784. /** Creates a new Precondition with an exists flag. */ static exists(t) {
  4785. return new Fs(void 0, t);
  4786. }
  4787. /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) {
  4788. return new Fs(t);
  4789. }
  4790. /** Returns whether this Precondition is empty. */ get isNone() {
  4791. return void 0 === this.updateTime && void 0 === this.exists;
  4792. }
  4793. isEqual(t) {
  4794. return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
  4795. }
  4796. }
  4797. /** Returns true if the preconditions is valid for the given document. */ function Bs(t, e) {
  4798. return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();
  4799. }
  4800. /**
  4801. * A mutation describes a self-contained change to a document. Mutations can
  4802. * create, replace, delete, and update subsets of documents.
  4803. *
  4804. * Mutations not only act on the value of the document but also its version.
  4805. *
  4806. * For local mutations (mutations that haven't been committed yet), we preserve
  4807. * the existing version for Set and Patch mutations. For Delete mutations, we
  4808. * reset the version to 0.
  4809. *
  4810. * Here's the expected transition table.
  4811. *
  4812. * MUTATION APPLIED TO RESULTS IN
  4813. *
  4814. * SetMutation Document(v3) Document(v3)
  4815. * SetMutation NoDocument(v3) Document(v0)
  4816. * SetMutation InvalidDocument(v0) Document(v0)
  4817. * PatchMutation Document(v3) Document(v3)
  4818. * PatchMutation NoDocument(v3) NoDocument(v3)
  4819. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  4820. * DeleteMutation Document(v3) NoDocument(v0)
  4821. * DeleteMutation NoDocument(v3) NoDocument(v0)
  4822. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  4823. *
  4824. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  4825. * the resulting version for Set and Patch mutations. As deletes have no
  4826. * explicit update time, we use the commitTime of the WriteResponse for
  4827. * Delete mutations.
  4828. *
  4829. * If a mutation is acknowledged by the backend but fails the precondition check
  4830. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  4831. * the updated version.
  4832. *
  4833. * Field transforms are used only with Patch and Set Mutations. We use the
  4834. * `updateTransforms` message to store transforms, rather than the `transforms`s
  4835. * messages.
  4836. *
  4837. * ## Subclassing Notes
  4838. *
  4839. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  4840. * applyToLocalView() to implement the actual behavior of applying the mutation
  4841. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  4842. * example).
  4843. */ class Ls {}
  4844. /**
  4845. * A utility method to calculate a `Mutation` representing the overlay from the
  4846. * final state of the document, and a `FieldMask` representing the fields that
  4847. * are mutated by the local mutations.
  4848. */ function qs(t, e) {
  4849. if (!t.hasLocalMutations || e && 0 === e.fields.length) return null;
  4850. // mask is null when sets or deletes are applied to the current document.
  4851. if (null === e) return t.isNoDocument() ? new Ys(t.key, Fs.none()) : new js(t.key, t.data, Fs.none());
  4852. {
  4853. const n = t.data, s = un.empty();
  4854. let i = new Ee(at.comparator);
  4855. for (let t of e.fields) if (!i.has(t)) {
  4856. let e = n.field(t);
  4857. // If we are deleting a nested field, we take the immediate parent as
  4858. // the mask used to construct the resulting mutation.
  4859. // Justification: Nested fields can create parent fields implicitly. If
  4860. // only a leaf entry is deleted in later mutations, the parent field
  4861. // should still remain, but we may have lost this information.
  4862. // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).
  4863. // This leaves the final result (foo, {}). Despite the fact that `doc`
  4864. // has the correct result, `foo` is not in `mask`, and the resulting
  4865. // mutation would miss `foo`.
  4866. null === e && t.length > 1 && (t = t.popLast(), e = n.field(t)), null === e ? s.delete(t) : s.set(t, e),
  4867. i = i.add(t);
  4868. }
  4869. return new zs(t.key, s, new Re(i.toArray()), Fs.none());
  4870. }
  4871. }
  4872. /**
  4873. * Applies this mutation to the given document for the purposes of computing a
  4874. * new remote document. If the input document doesn't match the expected state
  4875. * (e.g. it is invalid or outdated), the document type may transition to
  4876. * unknown.
  4877. *
  4878. * @param mutation - The mutation to apply.
  4879. * @param document - The document to mutate. The input document can be an
  4880. * invalid document if the client has no knowledge of the pre-mutation state
  4881. * of the document.
  4882. * @param mutationResult - The result of applying the mutation from the backend.
  4883. */ function Us(t, e, n) {
  4884. t instanceof js ? function(t, e, n) {
  4885. // Unlike setMutationApplyToLocalView, if we're applying a mutation to a
  4886. // remote document the server has accepted the mutation so the precondition
  4887. // must have held.
  4888. const s = t.value.clone(), i = Hs(t.fieldTransforms, e, n.transformResults);
  4889. s.setAll(i), e.convertToFoundDocument(n.version, s).setHasCommittedMutations();
  4890. }(t, e, n) : t instanceof zs ? function(t, e, n) {
  4891. if (!Bs(t.precondition, e))
  4892. // Since the mutation was not rejected, we know that the precondition
  4893. // matched on the backend. We therefore must not have the expected version
  4894. // of the document in our cache and convert to an UnknownDocument with a
  4895. // known updateTime.
  4896. return void e.convertToUnknownDocument(n.version);
  4897. const s = Hs(t.fieldTransforms, e, n.transformResults), i = e.data;
  4898. i.setAll(Ws(t)), i.setAll(s), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();
  4899. }(t, e, n) : function(t, e, n) {
  4900. // Unlike applyToLocalView, if we're applying a mutation to a remote
  4901. // document the server has accepted the mutation so the precondition must
  4902. // have held.
  4903. e.convertToNoDocument(n.version).setHasCommittedMutations();
  4904. }(0, e, n);
  4905. }
  4906. /**
  4907. * Applies this mutation to the given document for the purposes of computing
  4908. * the new local view of a document. If the input document doesn't match the
  4909. * expected state, the document is not modified.
  4910. *
  4911. * @param mutation - The mutation to apply.
  4912. * @param document - The document to mutate. The input document can be an
  4913. * invalid document if the client has no knowledge of the pre-mutation state
  4914. * of the document.
  4915. * @param previousMask - The fields that have been updated before applying this mutation.
  4916. * @param localWriteTime - A timestamp indicating the local write time of the
  4917. * batch this mutation is a part of.
  4918. * @returns A `FieldMask` representing the fields that are changed by applying this mutation.
  4919. */ function Ks(t, e, n, s) {
  4920. return t instanceof js ? function(t, e, n, s) {
  4921. if (!Bs(t.precondition, e))
  4922. // The mutation failed to apply (e.g. a document ID created with add()
  4923. // caused a name collision).
  4924. return n;
  4925. const i = t.value.clone(), r = Js(t.fieldTransforms, s, e);
  4926. return i.setAll(r), e.convertToFoundDocument(e.version, i).setHasLocalMutations(),
  4927. null;
  4928. // SetMutation overwrites all fields.
  4929. }
  4930. /**
  4931. * A mutation that modifies fields of the document at the given key with the
  4932. * given values. The values are applied through a field mask:
  4933. *
  4934. * * When a field is in both the mask and the values, the corresponding field
  4935. * is updated.
  4936. * * When a field is in neither the mask nor the values, the corresponding
  4937. * field is unmodified.
  4938. * * When a field is in the mask but not in the values, the corresponding field
  4939. * is deleted.
  4940. * * When a field is not in the mask but is in the values, the values map is
  4941. * ignored.
  4942. */ (t, e, n, s) : t instanceof zs ? function(t, e, n, s) {
  4943. if (!Bs(t.precondition, e)) return n;
  4944. const i = Js(t.fieldTransforms, s, e), r = e.data;
  4945. if (r.setAll(Ws(t)), r.setAll(i), e.convertToFoundDocument(e.version, r).setHasLocalMutations(),
  4946. null === n) return null;
  4947. return n.unionWith(t.fieldMask.fields).unionWith(t.fieldTransforms.map((t => t.field)));
  4948. }
  4949. /**
  4950. * Returns a FieldPath/Value map with the content of the PatchMutation.
  4951. */ (t, e, n, s) : function(t, e, n) {
  4952. if (Bs(t.precondition, e)) return e.convertToNoDocument(e.version).setHasLocalMutations(),
  4953. null;
  4954. return n;
  4955. }
  4956. /**
  4957. * A mutation that verifies the existence of the document at the given key with
  4958. * the provided precondition.
  4959. *
  4960. * The `verify` operation is only used in Transactions, and this class serves
  4961. * primarily to facilitate serialization into protos.
  4962. */ (t, e, n);
  4963. }
  4964. /**
  4965. * If this mutation is not idempotent, returns the base value to persist with
  4966. * this mutation. If a base value is returned, the mutation is always applied
  4967. * to this base value, even if document has already been updated.
  4968. *
  4969. * The base value is a sparse object that consists of only the document
  4970. * fields for which this mutation contains a non-idempotent transformation
  4971. * (e.g. a numeric increment). The provided value guarantees consistent
  4972. * behavior for non-idempotent transforms and allow us to return the same
  4973. * latency-compensated value even if the backend has already applied the
  4974. * mutation. The base value is null for idempotent mutations, as they can be
  4975. * re-played even if the backend has already applied them.
  4976. *
  4977. * @returns a base value to store along with the mutation, or null for
  4978. * idempotent mutations.
  4979. */ function Gs(t, e) {
  4980. let n = null;
  4981. for (const s of t.fieldTransforms) {
  4982. const t = e.data.field(s.field), i = Ps(s.transform, t || null);
  4983. null != i && (null === n && (n = un.empty()), n.set(s.field, i));
  4984. }
  4985. return n || null;
  4986. }
  4987. function Qs(t, e) {
  4988. return t.type === e.type && (!!t.key.isEqual(e.key) && (!!t.precondition.isEqual(e.precondition) && (!!function(t, e) {
  4989. return void 0 === t && void 0 === e || !(!t || !e) && nt(t, e, ((t, e) => $s(t, e)));
  4990. }(t.fieldTransforms, e.fieldTransforms) && (0 /* MutationType.Set */ === t.type ? t.value.isEqual(e.value) : 1 /* MutationType.Patch */ !== t.type || t.data.isEqual(e.data) && t.fieldMask.isEqual(e.fieldMask)))));
  4991. }
  4992. /**
  4993. * A mutation that creates or replaces the document at the given key with the
  4994. * object value contents.
  4995. */ class js extends Ls {
  4996. constructor(t, e, n, s = []) {
  4997. super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = s,
  4998. this.type = 0 /* MutationType.Set */;
  4999. }
  5000. getFieldMask() {
  5001. return null;
  5002. }
  5003. }
  5004. class zs extends Ls {
  5005. constructor(t, e, n, s, i = []) {
  5006. super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = s,
  5007. this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;
  5008. }
  5009. getFieldMask() {
  5010. return this.fieldMask;
  5011. }
  5012. }
  5013. function Ws(t) {
  5014. const e = new Map;
  5015. return t.fieldMask.fields.forEach((n => {
  5016. if (!n.isEmpty()) {
  5017. const s = t.data.field(n);
  5018. e.set(n, s);
  5019. }
  5020. })), e;
  5021. }
  5022. /**
  5023. * Creates a list of "transform results" (a transform result is a field value
  5024. * representing the result of applying a transform) for use after a mutation
  5025. * containing transforms has been acknowledged by the server.
  5026. *
  5027. * @param fieldTransforms - The field transforms to apply the result to.
  5028. * @param mutableDocument - The current state of the document after applying all
  5029. * previous mutations.
  5030. * @param serverTransformResults - The transform results received by the server.
  5031. * @returns The transform results list.
  5032. */ function Hs(t, e, n) {
  5033. const s = new Map;
  5034. F(t.length === n.length);
  5035. for (let i = 0; i < n.length; i++) {
  5036. const r = t[i], o = r.transform, u = e.data.field(r.field);
  5037. s.set(r.field, Rs(o, u, n[i]));
  5038. }
  5039. return s;
  5040. }
  5041. /**
  5042. * Creates a list of "transform results" (a transform result is a field value
  5043. * representing the result of applying a transform) for use when applying a
  5044. * transform locally.
  5045. *
  5046. * @param fieldTransforms - The field transforms to apply the result to.
  5047. * @param localWriteTime - The local time of the mutation (used to
  5048. * generate ServerTimestampValues).
  5049. * @param mutableDocument - The document to apply transforms on.
  5050. * @returns The transform results list.
  5051. */ function Js(t, e, n) {
  5052. const s = new Map;
  5053. for (const i of t) {
  5054. const t = i.transform, r = n.data.field(i.field);
  5055. s.set(i.field, vs(t, r, e));
  5056. }
  5057. return s;
  5058. }
  5059. /** A mutation that deletes the document at the given key. */ class Ys extends Ls {
  5060. constructor(t, e) {
  5061. super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ ,
  5062. this.fieldTransforms = [];
  5063. }
  5064. getFieldMask() {
  5065. return null;
  5066. }
  5067. }
  5068. class Xs extends Ls {
  5069. constructor(t, e) {
  5070. super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ ,
  5071. this.fieldTransforms = [];
  5072. }
  5073. getFieldMask() {
  5074. return null;
  5075. }
  5076. }
  5077. /**
  5078. * @license
  5079. * Copyright 2017 Google LLC
  5080. *
  5081. * Licensed under the Apache License, Version 2.0 (the "License");
  5082. * you may not use this file except in compliance with the License.
  5083. * You may obtain a copy of the License at
  5084. *
  5085. * http://www.apache.org/licenses/LICENSE-2.0
  5086. *
  5087. * Unless required by applicable law or agreed to in writing, software
  5088. * distributed under the License is distributed on an "AS IS" BASIS,
  5089. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5090. * See the License for the specific language governing permissions and
  5091. * limitations under the License.
  5092. */
  5093. /**
  5094. * A batch of mutations that will be sent as one unit to the backend.
  5095. */ class Zs {
  5096. /**
  5097. * @param batchId - The unique ID of this mutation batch.
  5098. * @param localWriteTime - The original write time of this mutation.
  5099. * @param baseMutations - Mutations that are used to populate the base
  5100. * values when this mutation is applied locally. This can be used to locally
  5101. * overwrite values that are persisted in the remote document cache. Base
  5102. * mutations are never sent to the backend.
  5103. * @param mutations - The user-provided mutations in this mutation batch.
  5104. * User-provided mutations are applied both locally and remotely on the
  5105. * backend.
  5106. */
  5107. constructor(t, e, n, s) {
  5108. this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = s;
  5109. }
  5110. /**
  5111. * Applies all the mutations in this MutationBatch to the specified document
  5112. * to compute the state of the remote document
  5113. *
  5114. * @param document - The document to apply mutations to.
  5115. * @param batchResult - The result of applying the MutationBatch to the
  5116. * backend.
  5117. */ applyToRemoteDocument(t, e) {
  5118. const n = e.mutationResults;
  5119. for (let e = 0; e < this.mutations.length; e++) {
  5120. const s = this.mutations[e];
  5121. if (s.key.isEqual(t.key)) {
  5122. Us(s, t, n[e]);
  5123. }
  5124. }
  5125. }
  5126. /**
  5127. * Computes the local view of a document given all the mutations in this
  5128. * batch.
  5129. *
  5130. * @param document - The document to apply mutations to.
  5131. * @param mutatedFields - Fields that have been updated before applying this mutation batch.
  5132. * @returns A `FieldMask` representing all the fields that are mutated.
  5133. */ applyToLocalView(t, e) {
  5134. // First, apply the base state. This allows us to apply non-idempotent
  5135. // transform against a consistent set of values.
  5136. for (const n of this.baseMutations) n.key.isEqual(t.key) && (e = Ks(n, t, e, this.localWriteTime));
  5137. // Second, apply all user-provided mutations.
  5138. for (const n of this.mutations) n.key.isEqual(t.key) && (e = Ks(n, t, e, this.localWriteTime));
  5139. return e;
  5140. }
  5141. /**
  5142. * Computes the local view for all provided documents given the mutations in
  5143. * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
  5144. * replace all the mutation applications.
  5145. */ applyToLocalDocumentSet(t, e) {
  5146. // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations
  5147. // directly (as done in `applyToLocalView()`), we can reduce the complexity
  5148. // to O(n).
  5149. const n = ds();
  5150. return this.mutations.forEach((s => {
  5151. const i = t.get(s.key), r = i.overlayedDocument;
  5152. // TODO(mutabledocuments): This method should take a MutableDocumentMap
  5153. // and we should remove this cast.
  5154. let o = this.applyToLocalView(r, i.mutatedFields);
  5155. // Set mutatedFields to null if the document is only from local mutations.
  5156. // This creates a Set or Delete mutation, instead of trying to create a
  5157. // patch mutation as the overlay.
  5158. o = e.has(s.key) ? null : o;
  5159. const u = qs(r, o);
  5160. null !== u && n.set(s.key, u), r.isValidDocument() || r.convertToNoDocument(rt.min());
  5161. })), n;
  5162. }
  5163. keys() {
  5164. return this.mutations.reduce(((t, e) => t.add(e.key)), gs());
  5165. }
  5166. isEqual(t) {
  5167. return this.batchId === t.batchId && nt(this.mutations, t.mutations, ((t, e) => Qs(t, e))) && nt(this.baseMutations, t.baseMutations, ((t, e) => Qs(t, e)));
  5168. }
  5169. }
  5170. /** The result of applying a mutation batch to the backend. */ class ti {
  5171. constructor(t, e, n,
  5172. /**
  5173. * A pre-computed mapping from each mutated document to the resulting
  5174. * version.
  5175. */
  5176. s) {
  5177. this.batch = t, this.commitVersion = e, this.mutationResults = n, this.docVersions = s;
  5178. }
  5179. /**
  5180. * Creates a new MutationBatchResult for the given batch and results. There
  5181. * must be one result for each mutation in the batch. This static factory
  5182. * caches a document=&gt;version mapping (docVersions).
  5183. */ static from(t, e, n) {
  5184. F(t.mutations.length === n.length);
  5185. let s = _s;
  5186. const i = t.mutations;
  5187. for (let t = 0; t < i.length; t++) s = s.insert(i[t].key, n[t].version);
  5188. return new ti(t, e, n, s);
  5189. }
  5190. }
  5191. /**
  5192. * @license
  5193. * Copyright 2022 Google LLC
  5194. *
  5195. * Licensed under the Apache License, Version 2.0 (the "License");
  5196. * you may not use this file except in compliance with the License.
  5197. * You may obtain a copy of the License at
  5198. *
  5199. * http://www.apache.org/licenses/LICENSE-2.0
  5200. *
  5201. * Unless required by applicable law or agreed to in writing, software
  5202. * distributed under the License is distributed on an "AS IS" BASIS,
  5203. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5204. * See the License for the specific language governing permissions and
  5205. * limitations under the License.
  5206. */
  5207. /**
  5208. * Representation of an overlay computed by Firestore.
  5209. *
  5210. * Holds information about a mutation and the largest batch id in Firestore when
  5211. * the mutation was created.
  5212. */ class ei {
  5213. constructor(t, e) {
  5214. this.largestBatchId = t, this.mutation = e;
  5215. }
  5216. getKey() {
  5217. return this.mutation.key;
  5218. }
  5219. isEqual(t) {
  5220. return null !== t && this.mutation === t.mutation;
  5221. }
  5222. toString() {
  5223. return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`;
  5224. }
  5225. }
  5226. /**
  5227. * @license
  5228. * Copyright 2023 Google LLC
  5229. *
  5230. * Licensed under the Apache License, Version 2.0 (the "License");
  5231. * you may not use this file except in compliance with the License.
  5232. * You may obtain a copy of the License at
  5233. *
  5234. * http://www.apache.org/licenses/LICENSE-2.0
  5235. *
  5236. * Unless required by applicable law or agreed to in writing, software
  5237. * distributed under the License is distributed on an "AS IS" BASIS,
  5238. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5239. * See the License for the specific language governing permissions and
  5240. * limitations under the License.
  5241. */
  5242. /**
  5243. * Concrete implementation of the Aggregate type.
  5244. */ class ni {
  5245. constructor(t, e, n) {
  5246. this.alias = t, this.yt = e, this.fieldPath = n;
  5247. }
  5248. }
  5249. /**
  5250. * @license
  5251. * Copyright 2017 Google LLC
  5252. *
  5253. * Licensed under the Apache License, Version 2.0 (the "License");
  5254. * you may not use this file except in compliance with the License.
  5255. * You may obtain a copy of the License at
  5256. *
  5257. * http://www.apache.org/licenses/LICENSE-2.0
  5258. *
  5259. * Unless required by applicable law or agreed to in writing, software
  5260. * distributed under the License is distributed on an "AS IS" BASIS,
  5261. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5262. * See the License for the specific language governing permissions and
  5263. * limitations under the License.
  5264. */ class si {
  5265. constructor(t, e) {
  5266. this.count = t, this.unchangedNames = e;
  5267. }
  5268. }
  5269. /**
  5270. * @license
  5271. * Copyright 2017 Google LLC
  5272. *
  5273. * Licensed under the Apache License, Version 2.0 (the "License");
  5274. * you may not use this file except in compliance with the License.
  5275. * You may obtain a copy of the License at
  5276. *
  5277. * http://www.apache.org/licenses/LICENSE-2.0
  5278. *
  5279. * Unless required by applicable law or agreed to in writing, software
  5280. * distributed under the License is distributed on an "AS IS" BASIS,
  5281. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5282. * See the License for the specific language governing permissions and
  5283. * limitations under the License.
  5284. */
  5285. /**
  5286. * Error Codes describing the different ways GRPC can fail. These are copied
  5287. * directly from GRPC's sources here:
  5288. *
  5289. * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  5290. *
  5291. * Important! The names of these identifiers matter because the string forms
  5292. * are used for reverse lookups from the webchannel stream. Do NOT change the
  5293. * names of these identifiers or change this into a const enum.
  5294. */ var ii, ri;
  5295. /**
  5296. * Determines whether an error code represents a permanent error when received
  5297. * in response to a non-write operation.
  5298. *
  5299. * See isPermanentWriteError for classifying write errors.
  5300. */
  5301. function oi(t) {
  5302. switch (t) {
  5303. default:
  5304. return O();
  5305. case q.CANCELLED:
  5306. case q.UNKNOWN:
  5307. case q.DEADLINE_EXCEEDED:
  5308. case q.RESOURCE_EXHAUSTED:
  5309. case q.INTERNAL:
  5310. case q.UNAVAILABLE:
  5311. // Unauthenticated means something went wrong with our token and we need
  5312. // to retry with new credentials which will happen automatically.
  5313. case q.UNAUTHENTICATED:
  5314. return !1;
  5315. case q.INVALID_ARGUMENT:
  5316. case q.NOT_FOUND:
  5317. case q.ALREADY_EXISTS:
  5318. case q.PERMISSION_DENIED:
  5319. case q.FAILED_PRECONDITION:
  5320. // Aborted might be retried in some scenarios, but that is dependant on
  5321. // the context and should handled individually by the calling code.
  5322. // See https://cloud.google.com/apis/design/errors.
  5323. case q.ABORTED:
  5324. case q.OUT_OF_RANGE:
  5325. case q.UNIMPLEMENTED:
  5326. case q.DATA_LOSS:
  5327. return !0;
  5328. }
  5329. }
  5330. /**
  5331. * Determines whether an error code represents a permanent error when received
  5332. * in response to a write operation.
  5333. *
  5334. * Write operations must be handled specially because as of b/119437764, ABORTED
  5335. * errors on the write stream should be retried too (even though ABORTED errors
  5336. * are not generally retryable).
  5337. *
  5338. * Note that during the initial handshake on the write stream an ABORTED error
  5339. * signals that we should discard our stream token (i.e. it is permanent). This
  5340. * means a handshake error should be classified with isPermanentError, above.
  5341. */
  5342. /**
  5343. * Maps an error Code from GRPC status code number, like 0, 1, or 14. These
  5344. * are not the same as HTTP status codes.
  5345. *
  5346. * @returns The Code equivalent to the given GRPC status code. Fails if there
  5347. * is no match.
  5348. */
  5349. function ui(t) {
  5350. if (void 0 === t)
  5351. // This shouldn't normally happen, but in certain error cases (like trying
  5352. // to send invalid proto messages) we may get an error with no GRPC code.
  5353. return k("GRPC error has no .code"), q.UNKNOWN;
  5354. switch (t) {
  5355. case ii.OK:
  5356. return q.OK;
  5357. case ii.CANCELLED:
  5358. return q.CANCELLED;
  5359. case ii.UNKNOWN:
  5360. return q.UNKNOWN;
  5361. case ii.DEADLINE_EXCEEDED:
  5362. return q.DEADLINE_EXCEEDED;
  5363. case ii.RESOURCE_EXHAUSTED:
  5364. return q.RESOURCE_EXHAUSTED;
  5365. case ii.INTERNAL:
  5366. return q.INTERNAL;
  5367. case ii.UNAVAILABLE:
  5368. return q.UNAVAILABLE;
  5369. case ii.UNAUTHENTICATED:
  5370. return q.UNAUTHENTICATED;
  5371. case ii.INVALID_ARGUMENT:
  5372. return q.INVALID_ARGUMENT;
  5373. case ii.NOT_FOUND:
  5374. return q.NOT_FOUND;
  5375. case ii.ALREADY_EXISTS:
  5376. return q.ALREADY_EXISTS;
  5377. case ii.PERMISSION_DENIED:
  5378. return q.PERMISSION_DENIED;
  5379. case ii.FAILED_PRECONDITION:
  5380. return q.FAILED_PRECONDITION;
  5381. case ii.ABORTED:
  5382. return q.ABORTED;
  5383. case ii.OUT_OF_RANGE:
  5384. return q.OUT_OF_RANGE;
  5385. case ii.UNIMPLEMENTED:
  5386. return q.UNIMPLEMENTED;
  5387. case ii.DATA_LOSS:
  5388. return q.DATA_LOSS;
  5389. default:
  5390. return O();
  5391. }
  5392. }
  5393. /**
  5394. * Converts an HTTP response's error status to the equivalent error code.
  5395. *
  5396. * @param status - An HTTP error response status ("FAILED_PRECONDITION",
  5397. * "UNKNOWN", etc.)
  5398. * @returns The equivalent Code. Non-matching responses are mapped to
  5399. * Code.UNKNOWN.
  5400. */ (ri = ii || (ii = {}))[ri.OK = 0] = "OK", ri[ri.CANCELLED = 1] = "CANCELLED",
  5401. ri[ri.UNKNOWN = 2] = "UNKNOWN", ri[ri.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT",
  5402. ri[ri.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", ri[ri.NOT_FOUND = 5] = "NOT_FOUND",
  5403. ri[ri.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", ri[ri.PERMISSION_DENIED = 7] = "PERMISSION_DENIED",
  5404. ri[ri.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", ri[ri.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED",
  5405. ri[ri.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", ri[ri.ABORTED = 10] = "ABORTED",
  5406. ri[ri.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", ri[ri.UNIMPLEMENTED = 12] = "UNIMPLEMENTED",
  5407. ri[ri.INTERNAL = 13] = "INTERNAL", ri[ri.UNAVAILABLE = 14] = "UNAVAILABLE", ri[ri.DATA_LOSS = 15] = "DATA_LOSS";
  5408. /**
  5409. * @license
  5410. * Copyright 2023 Google LLC
  5411. *
  5412. * Licensed under the Apache License, Version 2.0 (the "License");
  5413. * you may not use this file except in compliance with the License.
  5414. * You may obtain a copy of the License at
  5415. *
  5416. * http://www.apache.org/licenses/LICENSE-2.0
  5417. *
  5418. * Unless required by applicable law or agreed to in writing, software
  5419. * distributed under the License is distributed on an "AS IS" BASIS,
  5420. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5421. * See the License for the specific language governing permissions and
  5422. * limitations under the License.
  5423. */
  5424. /**
  5425. * Manages "testing hooks", hooks into the internals of the SDK to verify
  5426. * internal state and events during integration tests. Do not use this class
  5427. * except for testing purposes.
  5428. *
  5429. * There are two ways to retrieve the global singleton instance of this class:
  5430. * 1. The `instance` property, which returns null if the global singleton
  5431. * instance has not been created. Use this property if the caller should
  5432. * "do nothing" if there are no testing hooks registered, such as when
  5433. * delivering an event to notify registered callbacks.
  5434. * 2. The `getOrCreateInstance()` method, which creates the global singleton
  5435. * instance if it has not been created. Use this method if the instance is
  5436. * needed to, for example, register a callback.
  5437. *
  5438. * @internal
  5439. */
  5440. class ci {
  5441. constructor() {
  5442. this.onExistenceFilterMismatchCallbacks = new Map;
  5443. }
  5444. /**
  5445. * Returns the singleton instance of this class, or null if it has not been
  5446. * initialized.
  5447. */ static get instance() {
  5448. return ai;
  5449. }
  5450. /**
  5451. * Returns the singleton instance of this class, creating it if is has never
  5452. * been created before.
  5453. */ static getOrCreateInstance() {
  5454. return null === ai && (ai = new ci), ai;
  5455. }
  5456. /**
  5457. * Registers a callback to be notified when an existence filter mismatch
  5458. * occurs in the Watch listen stream.
  5459. *
  5460. * The relative order in which callbacks are notified is unspecified; do not
  5461. * rely on any particular ordering. If a given callback is registered multiple
  5462. * times then it will be notified multiple times, once per registration.
  5463. *
  5464. * @param callback the callback to invoke upon existence filter mismatch.
  5465. *
  5466. * @return a function that, when called, unregisters the given callback; only
  5467. * the first invocation of the returned function does anything; all subsequent
  5468. * invocations do nothing.
  5469. */ onExistenceFilterMismatch(t) {
  5470. const e = Symbol();
  5471. return this.onExistenceFilterMismatchCallbacks.set(e, t), () => this.onExistenceFilterMismatchCallbacks.delete(e);
  5472. }
  5473. /**
  5474. * Invokes all currently-registered `onExistenceFilterMismatch` callbacks.
  5475. * @param info Information about the existence filter mismatch.
  5476. */ notifyOnExistenceFilterMismatch(t) {
  5477. this.onExistenceFilterMismatchCallbacks.forEach((e => e(t)));
  5478. }
  5479. }
  5480. /** The global singleton instance of `TestingHooks`. */ let ai = null;
  5481. /**
  5482. * @license
  5483. * Copyright 2023 Google LLC
  5484. *
  5485. * Licensed under the Apache License, Version 2.0 (the "License");
  5486. * you may not use this file except in compliance with the License.
  5487. * You may obtain a copy of the License at
  5488. *
  5489. * http://www.apache.org/licenses/LICENSE-2.0
  5490. *
  5491. * Unless required by applicable law or agreed to in writing, software
  5492. * distributed under the License is distributed on an "AS IS" BASIS,
  5493. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5494. * See the License for the specific language governing permissions and
  5495. * limitations under the License.
  5496. */
  5497. /**
  5498. * An instance of the Platform's 'TextEncoder' implementation.
  5499. */ function hi() {
  5500. return new TextEncoder;
  5501. }
  5502. /**
  5503. * An instance of the Platform's 'TextDecoder' implementation.
  5504. */
  5505. /**
  5506. * @license
  5507. * Copyright 2022 Google LLC
  5508. *
  5509. * Licensed under the Apache License, Version 2.0 (the "License");
  5510. * you may not use this file except in compliance with the License.
  5511. * You may obtain a copy of the License at
  5512. *
  5513. * http://www.apache.org/licenses/LICENSE-2.0
  5514. *
  5515. * Unless required by applicable law or agreed to in writing, software
  5516. * distributed under the License is distributed on an "AS IS" BASIS,
  5517. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5518. * See the License for the specific language governing permissions and
  5519. * limitations under the License.
  5520. */
  5521. const li = new webchannelWrapper.Integer([ 4294967295, 4294967295 ], 0);
  5522. // Hash a string using md5 hashing algorithm.
  5523. function fi(t) {
  5524. const e = hi().encode(t), n = new webchannelWrapper.Md5;
  5525. return n.update(e), new Uint8Array(n.digest());
  5526. }
  5527. // Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using
  5528. // 2’s complement using little endian.
  5529. function di(t) {
  5530. const e = new DataView(t.buffer), n = e.getUint32(0, /* littleEndian= */ !0), s = e.getUint32(4, /* littleEndian= */ !0), i = e.getUint32(8, /* littleEndian= */ !0), r = e.getUint32(12, /* littleEndian= */ !0);
  5531. return [ new webchannelWrapper.Integer([ n, s ], 0), new webchannelWrapper.Integer([ i, r ], 0) ];
  5532. }
  5533. class wi {
  5534. constructor(t, e, n) {
  5535. if (this.bitmap = t, this.padding = e, this.hashCount = n, e < 0 || e >= 8) throw new _i(`Invalid padding: ${e}`);
  5536. if (n < 0) throw new _i(`Invalid hash count: ${n}`);
  5537. if (t.length > 0 && 0 === this.hashCount)
  5538. // Only empty bloom filter can have 0 hash count.
  5539. throw new _i(`Invalid hash count: ${n}`);
  5540. if (0 === t.length && 0 !== e)
  5541. // Empty bloom filter should have 0 padding.
  5542. throw new _i(`Invalid padding when bitmap length is 0: ${e}`);
  5543. this.It = 8 * t.length - e,
  5544. // Set the bit count in Integer to avoid repetition in mightContain().
  5545. this.Tt = webchannelWrapper.Integer.fromNumber(this.It);
  5546. }
  5547. // Calculate the ith hash value based on the hashed 64bit integers,
  5548. // and calculate its corresponding bit index in the bitmap to be checked.
  5549. Et(t, e, n) {
  5550. // Calculate hashed value h(i) = h1 + (i * h2).
  5551. let s = t.add(e.multiply(webchannelWrapper.Integer.fromNumber(n)));
  5552. // Wrap if hash value overflow 64bit.
  5553. return 1 === s.compare(li) && (s = new webchannelWrapper.Integer([ s.getBits(0), s.getBits(1) ], 0)),
  5554. s.modulo(this.Tt).toNumber();
  5555. }
  5556. // Return whether the bit on the given index in the bitmap is set to 1.
  5557. At(t) {
  5558. return 0 != (this.bitmap[Math.floor(t / 8)] & 1 << t % 8);
  5559. }
  5560. vt(t) {
  5561. // Empty bitmap should always return false on membership check.
  5562. if (0 === this.It) return !1;
  5563. const e = fi(t), [n, s] = di(e);
  5564. for (let t = 0; t < this.hashCount; t++) {
  5565. const e = this.Et(n, s, t);
  5566. if (!this.At(e)) return !1;
  5567. }
  5568. return !0;
  5569. }
  5570. /** Create bloom filter for testing purposes only. */ static create(t, e, n) {
  5571. const s = t % 8 == 0 ? 0 : 8 - t % 8, i = new Uint8Array(Math.ceil(t / 8)), r = new wi(i, s, e);
  5572. return n.forEach((t => r.insert(t))), r;
  5573. }
  5574. insert(t) {
  5575. if (0 === this.It) return;
  5576. const e = fi(t), [n, s] = di(e);
  5577. for (let t = 0; t < this.hashCount; t++) {
  5578. const e = this.Et(n, s, t);
  5579. this.Rt(e);
  5580. }
  5581. }
  5582. Rt(t) {
  5583. const e = Math.floor(t / 8), n = t % 8;
  5584. this.bitmap[e] |= 1 << n;
  5585. }
  5586. }
  5587. class _i extends Error {
  5588. constructor() {
  5589. super(...arguments), this.name = "BloomFilterError";
  5590. }
  5591. }
  5592. /**
  5593. * @license
  5594. * Copyright 2017 Google LLC
  5595. *
  5596. * Licensed under the Apache License, Version 2.0 (the "License");
  5597. * you may not use this file except in compliance with the License.
  5598. * You may obtain a copy of the License at
  5599. *
  5600. * http://www.apache.org/licenses/LICENSE-2.0
  5601. *
  5602. * Unless required by applicable law or agreed to in writing, software
  5603. * distributed under the License is distributed on an "AS IS" BASIS,
  5604. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5605. * See the License for the specific language governing permissions and
  5606. * limitations under the License.
  5607. */
  5608. /**
  5609. * An event from the RemoteStore. It is split into targetChanges (changes to the
  5610. * state or the set of documents in our watched targets) and documentUpdates
  5611. * (changes to the actual documents).
  5612. */ class mi {
  5613. constructor(
  5614. /**
  5615. * The snapshot version this event brings us up to, or MIN if not set.
  5616. */
  5617. t,
  5618. /**
  5619. * A map from target to changes to the target. See TargetChange.
  5620. */
  5621. e,
  5622. /**
  5623. * A map of targets that is known to be inconsistent, and the purpose for
  5624. * re-listening. Listens for these targets should be re-established without
  5625. * resume tokens.
  5626. */
  5627. n,
  5628. /**
  5629. * A set of which documents have changed or been deleted, along with the
  5630. * doc's new values (if not deleted).
  5631. */
  5632. s,
  5633. /**
  5634. * A set of which document updates are due only to limbo resolution targets.
  5635. */
  5636. i) {
  5637. this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = s,
  5638. this.resolvedLimboDocuments = i;
  5639. }
  5640. /**
  5641. * HACK: Views require RemoteEvents in order to determine whether the view is
  5642. * CURRENT, but secondary tabs don't receive remote events. So this method is
  5643. * used to create a synthesized RemoteEvent that can be used to apply a
  5644. * CURRENT status change to a View, for queries executed in a different tab.
  5645. */
  5646. // PORTING NOTE: Multi-tab only
  5647. static createSynthesizedRemoteEventForCurrentChange(t, e, n) {
  5648. const s = new Map;
  5649. return s.set(t, gi.createSynthesizedTargetChangeForCurrentChange(t, e, n)), new mi(rt.min(), s, new pe(et), cs(), gs());
  5650. }
  5651. }
  5652. /**
  5653. * A TargetChange specifies the set of changes for a specific target as part of
  5654. * a RemoteEvent. These changes track which documents are added, modified or
  5655. * removed, as well as the target's resume token and whether the target is
  5656. * marked CURRENT.
  5657. * The actual changes *to* documents are not part of the TargetChange since
  5658. * documents may be part of multiple targets.
  5659. */ class gi {
  5660. constructor(
  5661. /**
  5662. * An opaque, server-assigned token that allows watching a query to be resumed
  5663. * after disconnecting without retransmitting all the data that matches the
  5664. * query. The resume token essentially identifies a point in time from which
  5665. * the server should resume sending results.
  5666. */
  5667. t,
  5668. /**
  5669. * The "current" (synced) status of this target. Note that "current"
  5670. * has special meaning in the RPC protocol that implies that a target is
  5671. * both up-to-date and consistent with the rest of the watch stream.
  5672. */
  5673. e,
  5674. /**
  5675. * The set of documents that were newly assigned to this target as part of
  5676. * this remote event.
  5677. */
  5678. n,
  5679. /**
  5680. * The set of documents that were already assigned to this target but received
  5681. * an update during this remote event.
  5682. */
  5683. s,
  5684. /**
  5685. * The set of documents that were removed from this target as part of this
  5686. * remote event.
  5687. */
  5688. i) {
  5689. this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = s,
  5690. this.removedDocuments = i;
  5691. }
  5692. /**
  5693. * This method is used to create a synthesized TargetChanges that can be used to
  5694. * apply a CURRENT status change to a View (for queries executed in a different
  5695. * tab) or for new queries (to raise snapshots with correct CURRENT status).
  5696. */ static createSynthesizedTargetChangeForCurrentChange(t, e, n) {
  5697. return new gi(n, e, gs(), gs(), gs());
  5698. }
  5699. }
  5700. /**
  5701. * @license
  5702. * Copyright 2017 Google LLC
  5703. *
  5704. * Licensed under the Apache License, Version 2.0 (the "License");
  5705. * you may not use this file except in compliance with the License.
  5706. * You may obtain a copy of the License at
  5707. *
  5708. * http://www.apache.org/licenses/LICENSE-2.0
  5709. *
  5710. * Unless required by applicable law or agreed to in writing, software
  5711. * distributed under the License is distributed on an "AS IS" BASIS,
  5712. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5713. * See the License for the specific language governing permissions and
  5714. * limitations under the License.
  5715. */
  5716. /**
  5717. * Represents a changed document and a list of target ids to which this change
  5718. * applies.
  5719. *
  5720. * If document has been deleted NoDocument will be provided.
  5721. */ class yi {
  5722. constructor(
  5723. /** The new document applies to all of these targets. */
  5724. t,
  5725. /** The new document is removed from all of these targets. */
  5726. e,
  5727. /** The key of the document for this change. */
  5728. n,
  5729. /**
  5730. * The new document or NoDocument if it was deleted. Is null if the
  5731. * document went out of view without the server sending a new document.
  5732. */
  5733. s) {
  5734. this.Pt = t, this.removedTargetIds = e, this.key = n, this.bt = s;
  5735. }
  5736. }
  5737. class pi {
  5738. constructor(t, e) {
  5739. this.targetId = t, this.Vt = e;
  5740. }
  5741. }
  5742. class Ii {
  5743. constructor(
  5744. /** What kind of change occurred to the watch target. */
  5745. t,
  5746. /** The target IDs that were added/removed/set. */
  5747. e,
  5748. /**
  5749. * An opaque, server-assigned token that allows watching a target to be
  5750. * resumed after disconnecting without retransmitting all the data that
  5751. * matches the target. The resume token essentially identifies a point in
  5752. * time from which the server should resume sending results.
  5753. */
  5754. n = Ve.EMPTY_BYTE_STRING
  5755. /** An RPC error indicating why the watch failed. */ , s = null) {
  5756. this.state = t, this.targetIds = e, this.resumeToken = n, this.cause = s;
  5757. }
  5758. }
  5759. /** Tracks the internal state of a Watch target. */ class Ti {
  5760. constructor() {
  5761. /**
  5762. * The number of pending responses (adds or removes) that we are waiting on.
  5763. * We only consider targets active that have no pending responses.
  5764. */
  5765. this.St = 0,
  5766. /**
  5767. * Keeps track of the document changes since the last raised snapshot.
  5768. *
  5769. * These changes are continuously updated as we receive document updates and
  5770. * always reflect the current set of changes against the last issued snapshot.
  5771. */
  5772. this.Dt = vi(),
  5773. /** See public getters for explanations of these fields. */
  5774. this.Ct = Ve.EMPTY_BYTE_STRING, this.xt = !1,
  5775. /**
  5776. * Whether this target state should be included in the next snapshot. We
  5777. * initialize to true so that newly-added targets are included in the next
  5778. * RemoteEvent.
  5779. */
  5780. this.Nt = !0;
  5781. }
  5782. /**
  5783. * Whether this target has been marked 'current'.
  5784. *
  5785. * 'Current' has special meaning in the RPC protocol: It implies that the
  5786. * Watch backend has sent us all changes up to the point at which the target
  5787. * was added and that the target is consistent with the rest of the watch
  5788. * stream.
  5789. */ get current() {
  5790. return this.xt;
  5791. }
  5792. /** The last resume token sent to us for this target. */ get resumeToken() {
  5793. return this.Ct;
  5794. }
  5795. /** Whether this target has pending target adds or target removes. */ get kt() {
  5796. return 0 !== this.St;
  5797. }
  5798. /** Whether we have modified any state that should trigger a snapshot. */ get Mt() {
  5799. return this.Nt;
  5800. }
  5801. /**
  5802. * Applies the resume token to the TargetChange, but only when it has a new
  5803. * value. Empty resumeTokens are discarded.
  5804. */ $t(t) {
  5805. t.approximateByteSize() > 0 && (this.Nt = !0, this.Ct = t);
  5806. }
  5807. /**
  5808. * Creates a target change from the current set of changes.
  5809. *
  5810. * To reset the document changes after raising this snapshot, call
  5811. * `clearPendingChanges()`.
  5812. */ Ot() {
  5813. let t = gs(), e = gs(), n = gs();
  5814. return this.Dt.forEach(((s, i) => {
  5815. switch (i) {
  5816. case 0 /* ChangeType.Added */ :
  5817. t = t.add(s);
  5818. break;
  5819. case 2 /* ChangeType.Modified */ :
  5820. e = e.add(s);
  5821. break;
  5822. case 1 /* ChangeType.Removed */ :
  5823. n = n.add(s);
  5824. break;
  5825. default:
  5826. O();
  5827. }
  5828. })), new gi(this.Ct, this.xt, t, e, n);
  5829. }
  5830. /**
  5831. * Resets the document changes and sets `hasPendingChanges` to false.
  5832. */ Ft() {
  5833. this.Nt = !1, this.Dt = vi();
  5834. }
  5835. Bt(t, e) {
  5836. this.Nt = !0, this.Dt = this.Dt.insert(t, e);
  5837. }
  5838. Lt(t) {
  5839. this.Nt = !0, this.Dt = this.Dt.remove(t);
  5840. }
  5841. qt() {
  5842. this.St += 1;
  5843. }
  5844. Ut() {
  5845. this.St -= 1;
  5846. }
  5847. Kt() {
  5848. this.Nt = !0, this.xt = !0;
  5849. }
  5850. }
  5851. /**
  5852. * A helper class to accumulate watch changes into a RemoteEvent.
  5853. */
  5854. class Ei {
  5855. constructor(t) {
  5856. this.Gt = t,
  5857. /** The internal state of all tracked targets. */
  5858. this.Qt = new Map,
  5859. /** Keeps track of the documents to update since the last raised snapshot. */
  5860. this.jt = cs(),
  5861. /** A mapping of document keys to their set of target IDs. */
  5862. this.zt = Ai(),
  5863. /**
  5864. * A map of targets with existence filter mismatches. These targets are
  5865. * known to be inconsistent and their listens needs to be re-established by
  5866. * RemoteStore.
  5867. */
  5868. this.Wt = new pe(et);
  5869. }
  5870. /**
  5871. * Processes and adds the DocumentWatchChange to the current set of changes.
  5872. */ Ht(t) {
  5873. for (const e of t.Pt) t.bt && t.bt.isFoundDocument() ? this.Jt(e, t.bt) : this.Yt(e, t.key, t.bt);
  5874. for (const e of t.removedTargetIds) this.Yt(e, t.key, t.bt);
  5875. }
  5876. /** Processes and adds the WatchTargetChange to the current set of changes. */ Xt(t) {
  5877. this.forEachTarget(t, (e => {
  5878. const n = this.Zt(e);
  5879. switch (t.state) {
  5880. case 0 /* WatchTargetChangeState.NoChange */ :
  5881. this.te(e) && n.$t(t.resumeToken);
  5882. break;
  5883. case 1 /* WatchTargetChangeState.Added */ :
  5884. // We need to decrement the number of pending acks needed from watch
  5885. // for this targetId.
  5886. n.Ut(), n.kt ||
  5887. // We have a freshly added target, so we need to reset any state
  5888. // that we had previously. This can happen e.g. when remove and add
  5889. // back a target for existence filter mismatches.
  5890. n.Ft(), n.$t(t.resumeToken);
  5891. break;
  5892. case 2 /* WatchTargetChangeState.Removed */ :
  5893. // We need to keep track of removed targets to we can post-filter and
  5894. // remove any target changes.
  5895. // We need to decrement the number of pending acks needed from watch
  5896. // for this targetId.
  5897. n.Ut(), n.kt || this.removeTarget(e);
  5898. break;
  5899. case 3 /* WatchTargetChangeState.Current */ :
  5900. this.te(e) && (n.Kt(), n.$t(t.resumeToken));
  5901. break;
  5902. case 4 /* WatchTargetChangeState.Reset */ :
  5903. this.te(e) && (
  5904. // Reset the target and synthesizes removes for all existing
  5905. // documents. The backend will re-add any documents that still
  5906. // match the target before it sends the next global snapshot.
  5907. this.ee(e), n.$t(t.resumeToken));
  5908. break;
  5909. default:
  5910. O();
  5911. }
  5912. }));
  5913. }
  5914. /**
  5915. * Iterates over all targetIds that the watch change applies to: either the
  5916. * targetIds explicitly listed in the change or the targetIds of all currently
  5917. * active targets.
  5918. */ forEachTarget(t, e) {
  5919. t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Qt.forEach(((t, n) => {
  5920. this.te(n) && e(n);
  5921. }));
  5922. }
  5923. /**
  5924. * Handles existence filters and synthesizes deletes for filter mismatches.
  5925. * Targets that are invalidated by filter mismatches are added to
  5926. * `pendingTargetResets`.
  5927. */ ne(t) {
  5928. var e;
  5929. const n = t.targetId, s = t.Vt.count, i = this.se(n);
  5930. if (i) {
  5931. const r = i.target;
  5932. if (Fn(r)) if (0 === s) {
  5933. // The existence filter told us the document does not exist. We deduce
  5934. // that this document does not exist and apply a deleted document to
  5935. // our updates. Without applying this deleted document there might be
  5936. // another query that will raise this document as part of a snapshot
  5937. // until it is resolved, essentially exposing inconsistency between
  5938. // queries.
  5939. const t = new ht(r.path);
  5940. this.Yt(n, t, an.newNoDocument(t, rt.min()));
  5941. } else F(1 === s); else {
  5942. const i = this.ie(n);
  5943. // Existence filter mismatch. Mark the documents as being in limbo, and
  5944. // raise a snapshot with `isFromCache:true`.
  5945. if (i !== s) {
  5946. // Apply bloom filter to identify and mark removed documents.
  5947. const s = this.re(t, i);
  5948. if (0 /* BloomFilterApplicationStatus.Success */ !== s) {
  5949. // If bloom filter application fails, we reset the mapping and
  5950. // trigger re-run of the query.
  5951. this.ee(n);
  5952. const t = 2 /* BloomFilterApplicationStatus.FalsePositive */ === s ? "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ : "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */;
  5953. this.Wt = this.Wt.insert(n, t);
  5954. }
  5955. null === (e = ci.instance) || void 0 === e || e.notifyOnExistenceFilterMismatch(function(t, e, n) {
  5956. var s, i, r, o, u, c;
  5957. const a = {
  5958. localCacheCount: e,
  5959. existenceFilterCount: n.count
  5960. }, h = n.unchangedNames;
  5961. h && (a.bloomFilter = {
  5962. applied: 0 /* BloomFilterApplicationStatus.Success */ === t,
  5963. hashCount: null !== (s = null == h ? void 0 : h.hashCount) && void 0 !== s ? s : 0,
  5964. bitmapLength: null !== (o = null === (r = null === (i = null == h ? void 0 : h.bits) || void 0 === i ? void 0 : i.bitmap) || void 0 === r ? void 0 : r.length) && void 0 !== o ? o : 0,
  5965. padding: null !== (c = null === (u = null == h ? void 0 : h.bits) || void 0 === u ? void 0 : u.padding) && void 0 !== c ? c : 0
  5966. });
  5967. return a;
  5968. }
  5969. /**
  5970. * @license
  5971. * Copyright 2017 Google LLC
  5972. *
  5973. * Licensed under the Apache License, Version 2.0 (the "License");
  5974. * you may not use this file except in compliance with the License.
  5975. * You may obtain a copy of the License at
  5976. *
  5977. * http://www.apache.org/licenses/LICENSE-2.0
  5978. *
  5979. * Unless required by applicable law or agreed to in writing, software
  5980. * distributed under the License is distributed on an "AS IS" BASIS,
  5981. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5982. * See the License for the specific language governing permissions and
  5983. * limitations under the License.
  5984. */ (s, i, t.Vt));
  5985. }
  5986. }
  5987. }
  5988. }
  5989. /**
  5990. * Apply bloom filter to remove the deleted documents, and return the
  5991. * application status.
  5992. */ re(t, e) {
  5993. const {unchangedNames: n, count: s} = t.Vt;
  5994. if (!n || !n.bits) return 1 /* BloomFilterApplicationStatus.Skipped */;
  5995. const {bits: {bitmap: i = "", padding: r = 0}, hashCount: o = 0} = n;
  5996. let u, c;
  5997. try {
  5998. u = xe(i).toUint8Array();
  5999. } catch (t) {
  6000. if (t instanceof Pe) return M("Decoding the base64 bloom filter in existence filter failed (" + t.message + "); ignoring the bloom filter and falling back to full re-query."),
  6001. 1 /* BloomFilterApplicationStatus.Skipped */;
  6002. throw t;
  6003. }
  6004. try {
  6005. // BloomFilter throws error if the inputs are invalid.
  6006. c = new wi(u, r, o);
  6007. } catch (t) {
  6008. return M(t instanceof _i ? "BloomFilter error: " : "Applying bloom filter failed: ", t),
  6009. 1 /* BloomFilterApplicationStatus.Skipped */;
  6010. }
  6011. if (0 === c.It) return 1 /* BloomFilterApplicationStatus.Skipped */;
  6012. return s !== e - this.oe(t.targetId, c) ? 2 /* BloomFilterApplicationStatus.FalsePositive */ : 0 /* BloomFilterApplicationStatus.Success */;
  6013. }
  6014. /**
  6015. * Filter out removed documents based on bloom filter membership result and
  6016. * return number of documents removed.
  6017. */ oe(t, e) {
  6018. const n = this.Gt.getRemoteKeysForTarget(t);
  6019. let s = 0;
  6020. return n.forEach((n => {
  6021. const i = this.Gt.ue(), r = `projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;
  6022. e.vt(r) || (this.Yt(t, n, /*updatedDocument=*/ null), s++);
  6023. })), s;
  6024. }
  6025. /**
  6026. * Converts the currently accumulated state into a remote event at the
  6027. * provided snapshot version. Resets the accumulated changes before returning.
  6028. */ ce(t) {
  6029. const e = new Map;
  6030. this.Qt.forEach(((n, s) => {
  6031. const i = this.se(s);
  6032. if (i) {
  6033. if (n.current && Fn(i.target)) {
  6034. // Document queries for document that don't exist can produce an empty
  6035. // result set. To update our local cache, we synthesize a document
  6036. // delete if we have not previously received the document. This
  6037. // resolves the limbo state of the document, removing it from
  6038. // limboDocumentRefs.
  6039. // TODO(dimond): Ideally we would have an explicit lookup target
  6040. // instead resulting in an explicit delete message and we could
  6041. // remove this special logic.
  6042. const e = new ht(i.target.path);
  6043. null !== this.jt.get(e) || this.ae(s, e) || this.Yt(s, e, an.newNoDocument(e, t));
  6044. }
  6045. n.Mt && (e.set(s, n.Ot()), n.Ft());
  6046. }
  6047. }));
  6048. let n = gs();
  6049. // We extract the set of limbo-only document updates as the GC logic
  6050. // special-cases documents that do not appear in the target cache.
  6051. // TODO(gsoltis): Expand on this comment once GC is available in the JS
  6052. // client.
  6053. this.zt.forEach(((t, e) => {
  6054. let s = !0;
  6055. e.forEachWhile((t => {
  6056. const e = this.se(t);
  6057. return !e || "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ === e.purpose || (s = !1,
  6058. !1);
  6059. })), s && (n = n.add(t));
  6060. })), this.jt.forEach(((e, n) => n.setReadTime(t)));
  6061. const s = new mi(t, e, this.Wt, this.jt, n);
  6062. return this.jt = cs(), this.zt = Ai(), this.Wt = new pe(et), s;
  6063. }
  6064. /**
  6065. * Adds the provided document to the internal list of document updates and
  6066. * its document key to the given target's mapping.
  6067. */
  6068. // Visible for testing.
  6069. Jt(t, e) {
  6070. if (!this.te(t)) return;
  6071. const n = this.ae(t, e.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;
  6072. this.Zt(t).Bt(e.key, n), this.jt = this.jt.insert(e.key, e), this.zt = this.zt.insert(e.key, this.he(e.key).add(t));
  6073. }
  6074. /**
  6075. * Removes the provided document from the target mapping. If the
  6076. * document no longer matches the target, but the document's state is still
  6077. * known (e.g. we know that the document was deleted or we received the change
  6078. * that caused the filter mismatch), the new document can be provided
  6079. * to update the remote document cache.
  6080. */
  6081. // Visible for testing.
  6082. Yt(t, e, n) {
  6083. if (!this.te(t)) return;
  6084. const s = this.Zt(t);
  6085. this.ae(t, e) ? s.Bt(e, 1 /* ChangeType.Removed */) :
  6086. // The document may have entered and left the target before we raised a
  6087. // snapshot, so we can just ignore the change.
  6088. s.Lt(e), this.zt = this.zt.insert(e, this.he(e).delete(t)), n && (this.jt = this.jt.insert(e, n));
  6089. }
  6090. removeTarget(t) {
  6091. this.Qt.delete(t);
  6092. }
  6093. /**
  6094. * Returns the current count of documents in the target. This includes both
  6095. * the number of documents that the LocalStore considers to be part of the
  6096. * target as well as any accumulated changes.
  6097. */ ie(t) {
  6098. const e = this.Zt(t).Ot();
  6099. return this.Gt.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;
  6100. }
  6101. /**
  6102. * Increment the number of acks needed from watch before we can consider the
  6103. * server to be 'in-sync' with the client's active targets.
  6104. */ qt(t) {
  6105. this.Zt(t).qt();
  6106. }
  6107. Zt(t) {
  6108. let e = this.Qt.get(t);
  6109. return e || (e = new Ti, this.Qt.set(t, e)), e;
  6110. }
  6111. he(t) {
  6112. let e = this.zt.get(t);
  6113. return e || (e = new Ee(et), this.zt = this.zt.insert(t, e)), e;
  6114. }
  6115. /**
  6116. * Verifies that the user is still interested in this target (by calling
  6117. * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
  6118. * from watch.
  6119. */ te(t) {
  6120. const e = null !== this.se(t);
  6121. return e || N("WatchChangeAggregator", "Detected inactive target", t), e;
  6122. }
  6123. /**
  6124. * Returns the TargetData for an active target (i.e. a target that the user
  6125. * is still interested in that has no outstanding target change requests).
  6126. */ se(t) {
  6127. const e = this.Qt.get(t);
  6128. return e && e.kt ? null : this.Gt.le(t);
  6129. }
  6130. /**
  6131. * Resets the state of a Watch target to its initial state (e.g. sets
  6132. * 'current' to false, clears the resume token and removes its target mapping
  6133. * from all documents).
  6134. */ ee(t) {
  6135. this.Qt.set(t, new Ti);
  6136. this.Gt.getRemoteKeysForTarget(t).forEach((e => {
  6137. this.Yt(t, e, /*updatedDocument=*/ null);
  6138. }));
  6139. }
  6140. /**
  6141. * Returns whether the LocalStore considers the document to be part of the
  6142. * specified target.
  6143. */ ae(t, e) {
  6144. return this.Gt.getRemoteKeysForTarget(t).has(e);
  6145. }
  6146. }
  6147. function Ai() {
  6148. return new pe(ht.comparator);
  6149. }
  6150. function vi() {
  6151. return new pe(ht.comparator);
  6152. }
  6153. const Ri = (() => {
  6154. const t = {
  6155. asc: "ASCENDING",
  6156. desc: "DESCENDING"
  6157. };
  6158. return t;
  6159. })(), Pi = (() => {
  6160. const t = {
  6161. "<": "LESS_THAN",
  6162. "<=": "LESS_THAN_OR_EQUAL",
  6163. ">": "GREATER_THAN",
  6164. ">=": "GREATER_THAN_OR_EQUAL",
  6165. "==": "EQUAL",
  6166. "!=": "NOT_EQUAL",
  6167. "array-contains": "ARRAY_CONTAINS",
  6168. in: "IN",
  6169. "not-in": "NOT_IN",
  6170. "array-contains-any": "ARRAY_CONTAINS_ANY"
  6171. };
  6172. return t;
  6173. })(), bi = (() => {
  6174. const t = {
  6175. and: "AND",
  6176. or: "OR"
  6177. };
  6178. return t;
  6179. })();
  6180. /**
  6181. * This class generates JsonObject values for the Datastore API suitable for
  6182. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  6183. *
  6184. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  6185. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  6186. * format.
  6187. *
  6188. * For a description of the Proto3 JSON format check
  6189. * https://developers.google.com/protocol-buffers/docs/proto3#json
  6190. *
  6191. * TODO(klimt): We can remove the databaseId argument if we keep the full
  6192. * resource name in documents.
  6193. */
  6194. class Vi {
  6195. constructor(t, e) {
  6196. this.databaseId = t, this.useProto3Json = e;
  6197. }
  6198. }
  6199. /**
  6200. * Returns a value for a number (or null) that's appropriate to put into
  6201. * a google.protobuf.Int32Value proto.
  6202. * DO NOT USE THIS FOR ANYTHING ELSE.
  6203. * This method cheats. It's typed as returning "number" because that's what
  6204. * our generated proto interfaces say Int32Value must be. But GRPC actually
  6205. * expects a { value: <number> } struct.
  6206. */
  6207. function Si(t, e) {
  6208. return t.useProto3Json || Ft(e) ? e : {
  6209. value: e
  6210. };
  6211. }
  6212. /**
  6213. * Returns a number (or null) from a google.protobuf.Int32Value proto.
  6214. */
  6215. /**
  6216. * Returns a value for a Date that's appropriate to put into a proto.
  6217. */
  6218. function Di(t, e) {
  6219. if (t.useProto3Json) {
  6220. return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`;
  6221. }
  6222. return {
  6223. seconds: "" + e.seconds,
  6224. nanos: e.nanoseconds
  6225. };
  6226. }
  6227. /**
  6228. * Returns a value for bytes that's appropriate to put in a proto.
  6229. *
  6230. * Visible for testing.
  6231. */
  6232. function Ci(t, e) {
  6233. return t.useProto3Json ? e.toBase64() : e.toUint8Array();
  6234. }
  6235. /**
  6236. * Returns a ByteString based on the proto string value.
  6237. */ function xi(t, e) {
  6238. return Di(t, e.toTimestamp());
  6239. }
  6240. function Ni(t) {
  6241. return F(!!t), rt.fromTimestamp(function(t) {
  6242. const e = De(t);
  6243. return new it(e.seconds, e.nanos);
  6244. }(t));
  6245. }
  6246. function ki(t, e) {
  6247. return function(t) {
  6248. return new ut([ "projects", t.projectId, "databases", t.database ]);
  6249. }(t).child("documents").child(e).canonicalString();
  6250. }
  6251. function Mi(t) {
  6252. const e = ut.fromString(t);
  6253. return F(ur(e)), e;
  6254. }
  6255. function $i(t, e) {
  6256. return ki(t.databaseId, e.path);
  6257. }
  6258. function Oi(t, e) {
  6259. const n = Mi(e);
  6260. if (n.get(1) !== t.databaseId.projectId) throw new U(q.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.databaseId.projectId);
  6261. if (n.get(3) !== t.databaseId.database) throw new U(q.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.databaseId.database);
  6262. return new ht(qi(n));
  6263. }
  6264. function Fi(t, e) {
  6265. return ki(t.databaseId, e);
  6266. }
  6267. function Bi(t) {
  6268. const e = Mi(t);
  6269. // In v1beta1 queries for collections at the root did not have a trailing
  6270. // "/documents". In v1 all resource paths contain "/documents". Preserve the
  6271. // ability to read the v1beta1 form for compatibility with queries persisted
  6272. // in the local target cache.
  6273. return 4 === e.length ? ut.emptyPath() : qi(e);
  6274. }
  6275. function Li(t) {
  6276. return new ut([ "projects", t.databaseId.projectId, "databases", t.databaseId.database ]).canonicalString();
  6277. }
  6278. function qi(t) {
  6279. return F(t.length > 4 && "documents" === t.get(4)), t.popFirst(5);
  6280. }
  6281. /** Creates a Document proto from key and fields (but no create/update time) */ function Ui(t, e, n) {
  6282. return {
  6283. name: $i(t, e),
  6284. fields: n.value.mapValue.fields
  6285. };
  6286. }
  6287. function Ki(t, e, n) {
  6288. const s = Oi(t, e.name), i = Ni(e.updateTime), r = e.createTime ? Ni(e.createTime) : rt.min(), o = new un({
  6289. mapValue: {
  6290. fields: e.fields
  6291. }
  6292. }), u = an.newFoundDocument(s, i, r, o);
  6293. return n && u.setHasCommittedMutations(), n ? u.setHasCommittedMutations() : u;
  6294. }
  6295. function Gi(t, e) {
  6296. return "found" in e ? function(t, e) {
  6297. F(!!e.found), e.found.name, e.found.updateTime;
  6298. const n = Oi(t, e.found.name), s = Ni(e.found.updateTime), i = e.found.createTime ? Ni(e.found.createTime) : rt.min(), r = new un({
  6299. mapValue: {
  6300. fields: e.found.fields
  6301. }
  6302. });
  6303. return an.newFoundDocument(n, s, i, r);
  6304. }(t, e) : "missing" in e ? function(t, e) {
  6305. F(!!e.missing), F(!!e.readTime);
  6306. const n = Oi(t, e.missing), s = Ni(e.readTime);
  6307. return an.newNoDocument(n, s);
  6308. }(t, e) : O();
  6309. }
  6310. function Qi(t, e) {
  6311. let n;
  6312. if ("targetChange" in e) {
  6313. e.targetChange;
  6314. // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
  6315. // if unset
  6316. const s = function(t) {
  6317. return "NO_CHANGE" === t ? 0 /* WatchTargetChangeState.NoChange */ : "ADD" === t ? 1 /* WatchTargetChangeState.Added */ : "REMOVE" === t ? 2 /* WatchTargetChangeState.Removed */ : "CURRENT" === t ? 3 /* WatchTargetChangeState.Current */ : "RESET" === t ? 4 /* WatchTargetChangeState.Reset */ : O();
  6318. }(e.targetChange.targetChangeType || "NO_CHANGE"), i = e.targetChange.targetIds || [], r = function(t, e) {
  6319. return t.useProto3Json ? (F(void 0 === e || "string" == typeof e), Ve.fromBase64String(e || "")) : (F(void 0 === e || e instanceof Uint8Array),
  6320. Ve.fromUint8Array(e || new Uint8Array));
  6321. }(t, e.targetChange.resumeToken), o = e.targetChange.cause, u = o && function(t) {
  6322. const e = void 0 === t.code ? q.UNKNOWN : ui(t.code);
  6323. return new U(e, t.message || "");
  6324. }(o);
  6325. n = new Ii(s, i, r, u || null);
  6326. } else if ("documentChange" in e) {
  6327. e.documentChange;
  6328. const s = e.documentChange;
  6329. s.document, s.document.name, s.document.updateTime;
  6330. const i = Oi(t, s.document.name), r = Ni(s.document.updateTime), o = s.document.createTime ? Ni(s.document.createTime) : rt.min(), u = new un({
  6331. mapValue: {
  6332. fields: s.document.fields
  6333. }
  6334. }), c = an.newFoundDocument(i, r, o, u), a = s.targetIds || [], h = s.removedTargetIds || [];
  6335. n = new yi(a, h, c.key, c);
  6336. } else if ("documentDelete" in e) {
  6337. e.documentDelete;
  6338. const s = e.documentDelete;
  6339. s.document;
  6340. const i = Oi(t, s.document), r = s.readTime ? Ni(s.readTime) : rt.min(), o = an.newNoDocument(i, r), u = s.removedTargetIds || [];
  6341. n = new yi([], u, o.key, o);
  6342. } else if ("documentRemove" in e) {
  6343. e.documentRemove;
  6344. const s = e.documentRemove;
  6345. s.document;
  6346. const i = Oi(t, s.document), r = s.removedTargetIds || [];
  6347. n = new yi([], r, i, null);
  6348. } else {
  6349. if (!("filter" in e)) return O();
  6350. {
  6351. e.filter;
  6352. const t = e.filter;
  6353. t.targetId;
  6354. const {count: s = 0, unchangedNames: i} = t, r = new si(s, i), o = t.targetId;
  6355. n = new pi(o, r);
  6356. }
  6357. }
  6358. return n;
  6359. }
  6360. function ji(t, e) {
  6361. let n;
  6362. if (e instanceof js) n = {
  6363. update: Ui(t, e.key, e.value)
  6364. }; else if (e instanceof Ys) n = {
  6365. delete: $i(t, e.key)
  6366. }; else if (e instanceof zs) n = {
  6367. update: Ui(t, e.key, e.data),
  6368. updateMask: or(e.fieldMask)
  6369. }; else {
  6370. if (!(e instanceof Xs)) return O();
  6371. n = {
  6372. verify: $i(t, e.key)
  6373. };
  6374. }
  6375. return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {
  6376. const n = e.transform;
  6377. if (n instanceof bs) return {
  6378. fieldPath: e.field.canonicalString(),
  6379. setToServerValue: "REQUEST_TIME"
  6380. };
  6381. if (n instanceof Vs) return {
  6382. fieldPath: e.field.canonicalString(),
  6383. appendMissingElements: {
  6384. values: n.elements
  6385. }
  6386. };
  6387. if (n instanceof Ds) return {
  6388. fieldPath: e.field.canonicalString(),
  6389. removeAllFromArray: {
  6390. values: n.elements
  6391. }
  6392. };
  6393. if (n instanceof xs) return {
  6394. fieldPath: e.field.canonicalString(),
  6395. increment: n.gt
  6396. };
  6397. throw O();
  6398. }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) {
  6399. return void 0 !== e.updateTime ? {
  6400. updateTime: xi(t, e.updateTime)
  6401. } : void 0 !== e.exists ? {
  6402. exists: e.exists
  6403. } : O();
  6404. }(t, e.precondition)), n;
  6405. }
  6406. function zi(t, e) {
  6407. const n = e.currentDocument ? function(t) {
  6408. return void 0 !== t.updateTime ? Fs.updateTime(Ni(t.updateTime)) : void 0 !== t.exists ? Fs.exists(t.exists) : Fs.none();
  6409. }(e.currentDocument) : Fs.none(), s = e.updateTransforms ? e.updateTransforms.map((e => function(t, e) {
  6410. let n = null;
  6411. if ("setToServerValue" in e) F("REQUEST_TIME" === e.setToServerValue), n = new bs; else if ("appendMissingElements" in e) {
  6412. const t = e.appendMissingElements.values || [];
  6413. n = new Vs(t);
  6414. } else if ("removeAllFromArray" in e) {
  6415. const t = e.removeAllFromArray.values || [];
  6416. n = new Ds(t);
  6417. } else "increment" in e ? n = new xs(t, e.increment) : O();
  6418. const s = at.fromServerFormat(e.fieldPath);
  6419. return new Ms(s, n);
  6420. }(t, e))) : [];
  6421. if (e.update) {
  6422. e.update.name;
  6423. const i = Oi(t, e.update.name), r = new un({
  6424. mapValue: {
  6425. fields: e.update.fields
  6426. }
  6427. });
  6428. if (e.updateMask) {
  6429. const t = function(t) {
  6430. const e = t.fieldPaths || [];
  6431. return new Re(e.map((t => at.fromServerFormat(t))));
  6432. }(e.updateMask);
  6433. return new zs(i, r, t, n, s);
  6434. }
  6435. return new js(i, r, n, s);
  6436. }
  6437. if (e.delete) {
  6438. const s = Oi(t, e.delete);
  6439. return new Ys(s, n);
  6440. }
  6441. if (e.verify) {
  6442. const s = Oi(t, e.verify);
  6443. return new Xs(s, n);
  6444. }
  6445. return O();
  6446. }
  6447. function Wi(t, e) {
  6448. return t && t.length > 0 ? (F(void 0 !== e), t.map((t => function(t, e) {
  6449. // NOTE: Deletes don't have an updateTime.
  6450. let n = t.updateTime ? Ni(t.updateTime) : Ni(e);
  6451. return n.isEqual(rt.min()) && (
  6452. // The Firestore Emulator currently returns an update time of 0 for
  6453. // deletes of non-existing documents (rather than null). This breaks the
  6454. // test "get deleted doc while offline with source=cache" as NoDocuments
  6455. // with version 0 are filtered by IndexedDb's RemoteDocumentCache.
  6456. // TODO(#2149): Remove this when Emulator is fixed
  6457. n = Ni(e)), new Os(n, t.transformResults || []);
  6458. }(t, e)))) : [];
  6459. }
  6460. function Hi(t, e) {
  6461. return {
  6462. documents: [ Fi(t, e.path) ]
  6463. };
  6464. }
  6465. function Ji(t, e) {
  6466. // Dissect the path into parent, collectionId, and optional key filter.
  6467. const n = {
  6468. structuredQuery: {}
  6469. }, s = e.path;
  6470. null !== e.collectionGroup ? (n.parent = Fi(t, s), n.structuredQuery.from = [ {
  6471. collectionId: e.collectionGroup,
  6472. allDescendants: !0
  6473. } ]) : (n.parent = Fi(t, s.popLast()), n.structuredQuery.from = [ {
  6474. collectionId: s.lastSegment()
  6475. } ]);
  6476. const i = function(t) {
  6477. if (0 === t.length) return;
  6478. return rr(gn.create(t, "and" /* CompositeOperator.AND */));
  6479. }(e.filters);
  6480. i && (n.structuredQuery.where = i);
  6481. const r = function(t) {
  6482. if (0 === t.length) return;
  6483. return t.map((t =>
  6484. // visible for testing
  6485. function(t) {
  6486. return {
  6487. field: sr(t.field),
  6488. direction: tr(t.dir)
  6489. };
  6490. }(t)));
  6491. }(e.orderBy);
  6492. r && (n.structuredQuery.orderBy = r);
  6493. const o = Si(t, e.limit);
  6494. var u;
  6495. return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = {
  6496. before: (u = e.startAt).inclusive,
  6497. values: u.position
  6498. }), e.endAt && (n.structuredQuery.endAt = function(t) {
  6499. return {
  6500. before: !t.inclusive,
  6501. values: t.position
  6502. };
  6503. }(e.endAt)), n;
  6504. }
  6505. function Yi(t) {
  6506. let e = Bi(t.parent);
  6507. const n = t.structuredQuery, s = n.from ? n.from.length : 0;
  6508. let i = null;
  6509. if (s > 0) {
  6510. F(1 === s);
  6511. const t = n.from[0];
  6512. t.allDescendants ? i = t.collectionId : e = e.child(t.collectionId);
  6513. }
  6514. let r = [];
  6515. n.where && (r = function(t) {
  6516. const e = Zi(t);
  6517. if (e instanceof gn && In(e)) return e.getFilters();
  6518. return [ e ];
  6519. }(n.where));
  6520. let o = [];
  6521. n.orderBy && (o = n.orderBy.map((t => function(t) {
  6522. return new dn(ir(t.field),
  6523. // visible for testing
  6524. function(t) {
  6525. switch (t) {
  6526. case "ASCENDING":
  6527. return "asc" /* Direction.ASCENDING */;
  6528. case "DESCENDING":
  6529. return "desc" /* Direction.DESCENDING */;
  6530. default:
  6531. return;
  6532. }
  6533. }
  6534. // visible for testing
  6535. (t.direction));
  6536. }
  6537. // visible for testing
  6538. (t))));
  6539. let u = null;
  6540. n.limit && (u = function(t) {
  6541. let e;
  6542. return e = "object" == typeof t ? t.value : t, Ft(e) ? null : e;
  6543. }(n.limit));
  6544. let c = null;
  6545. n.startAt && (c = function(t) {
  6546. const e = !!t.before, n = t.values || [];
  6547. return new hn(n, e);
  6548. }(n.startAt));
  6549. let a = null;
  6550. return n.endAt && (a = function(t) {
  6551. const e = !t.before, n = t.values || [];
  6552. return new hn(n, e);
  6553. }
  6554. // visible for testing
  6555. (n.endAt)), Kn(e, i, o, r, u, "F" /* LimitType.First */ , c, a);
  6556. }
  6557. function Xi(t, e) {
  6558. const n = function(t) {
  6559. switch (t) {
  6560. case "TargetPurposeListen" /* TargetPurpose.Listen */ :
  6561. return null;
  6562. case "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */ :
  6563. return "existence-filter-mismatch";
  6564. case "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ :
  6565. return "existence-filter-mismatch-bloom";
  6566. case "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ :
  6567. return "limbo-document";
  6568. default:
  6569. return O();
  6570. }
  6571. }(e.purpose);
  6572. return null == n ? null : {
  6573. "goog-listen-tags": n
  6574. };
  6575. }
  6576. function Zi(t) {
  6577. return void 0 !== t.unaryFilter ? function(t) {
  6578. switch (t.unaryFilter.op) {
  6579. case "IS_NAN":
  6580. const e = ir(t.unaryFilter.field);
  6581. return mn.create(e, "==" /* Operator.EQUAL */ , {
  6582. doubleValue: NaN
  6583. });
  6584. case "IS_NULL":
  6585. const n = ir(t.unaryFilter.field);
  6586. return mn.create(n, "==" /* Operator.EQUAL */ , {
  6587. nullValue: "NULL_VALUE"
  6588. });
  6589. case "IS_NOT_NAN":
  6590. const s = ir(t.unaryFilter.field);
  6591. return mn.create(s, "!=" /* Operator.NOT_EQUAL */ , {
  6592. doubleValue: NaN
  6593. });
  6594. case "IS_NOT_NULL":
  6595. const i = ir(t.unaryFilter.field);
  6596. return mn.create(i, "!=" /* Operator.NOT_EQUAL */ , {
  6597. nullValue: "NULL_VALUE"
  6598. });
  6599. default:
  6600. return O();
  6601. }
  6602. }(t) : void 0 !== t.fieldFilter ? function(t) {
  6603. return mn.create(ir(t.fieldFilter.field), function(t) {
  6604. switch (t) {
  6605. case "EQUAL":
  6606. return "==" /* Operator.EQUAL */;
  6607. case "NOT_EQUAL":
  6608. return "!=" /* Operator.NOT_EQUAL */;
  6609. case "GREATER_THAN":
  6610. return ">" /* Operator.GREATER_THAN */;
  6611. case "GREATER_THAN_OR_EQUAL":
  6612. return ">=" /* Operator.GREATER_THAN_OR_EQUAL */;
  6613. case "LESS_THAN":
  6614. return "<" /* Operator.LESS_THAN */;
  6615. case "LESS_THAN_OR_EQUAL":
  6616. return "<=" /* Operator.LESS_THAN_OR_EQUAL */;
  6617. case "ARRAY_CONTAINS":
  6618. return "array-contains" /* Operator.ARRAY_CONTAINS */;
  6619. case "IN":
  6620. return "in" /* Operator.IN */;
  6621. case "NOT_IN":
  6622. return "not-in" /* Operator.NOT_IN */;
  6623. case "ARRAY_CONTAINS_ANY":
  6624. return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */;
  6625. default:
  6626. return O();
  6627. }
  6628. }(t.fieldFilter.op), t.fieldFilter.value);
  6629. }(t) : void 0 !== t.compositeFilter ? function(t) {
  6630. return gn.create(t.compositeFilter.filters.map((t => Zi(t))), function(t) {
  6631. switch (t) {
  6632. case "AND":
  6633. return "and" /* CompositeOperator.AND */;
  6634. case "OR":
  6635. return "or" /* CompositeOperator.OR */;
  6636. default:
  6637. return O();
  6638. }
  6639. }(t.compositeFilter.op));
  6640. }(t) : O();
  6641. }
  6642. function tr(t) {
  6643. return Ri[t];
  6644. }
  6645. function er(t) {
  6646. return Pi[t];
  6647. }
  6648. function nr(t) {
  6649. return bi[t];
  6650. }
  6651. function sr(t) {
  6652. return {
  6653. fieldPath: t.canonicalString()
  6654. };
  6655. }
  6656. function ir(t) {
  6657. return at.fromServerFormat(t.fieldPath);
  6658. }
  6659. function rr(t) {
  6660. return t instanceof mn ? function(t) {
  6661. if ("==" /* Operator.EQUAL */ === t.op) {
  6662. if (Xe(t.value)) return {
  6663. unaryFilter: {
  6664. field: sr(t.field),
  6665. op: "IS_NAN"
  6666. }
  6667. };
  6668. if (Ye(t.value)) return {
  6669. unaryFilter: {
  6670. field: sr(t.field),
  6671. op: "IS_NULL"
  6672. }
  6673. };
  6674. } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) {
  6675. if (Xe(t.value)) return {
  6676. unaryFilter: {
  6677. field: sr(t.field),
  6678. op: "IS_NOT_NAN"
  6679. }
  6680. };
  6681. if (Ye(t.value)) return {
  6682. unaryFilter: {
  6683. field: sr(t.field),
  6684. op: "IS_NOT_NULL"
  6685. }
  6686. };
  6687. }
  6688. return {
  6689. fieldFilter: {
  6690. field: sr(t.field),
  6691. op: er(t.op),
  6692. value: t.value
  6693. }
  6694. };
  6695. }(t) : t instanceof gn ? function(t) {
  6696. const e = t.getFilters().map((t => rr(t)));
  6697. if (1 === e.length) return e[0];
  6698. return {
  6699. compositeFilter: {
  6700. op: nr(t.op),
  6701. filters: e
  6702. }
  6703. };
  6704. }(t) : O();
  6705. }
  6706. function or(t) {
  6707. const e = [];
  6708. return t.fields.forEach((t => e.push(t.canonicalString()))), {
  6709. fieldPaths: e
  6710. };
  6711. }
  6712. function ur(t) {
  6713. // Resource names have at least 4 components (project ID, database ID)
  6714. return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2);
  6715. }
  6716. /**
  6717. * @license
  6718. * Copyright 2017 Google LLC
  6719. *
  6720. * Licensed under the Apache License, Version 2.0 (the "License");
  6721. * you may not use this file except in compliance with the License.
  6722. * You may obtain a copy of the License at
  6723. *
  6724. * http://www.apache.org/licenses/LICENSE-2.0
  6725. *
  6726. * Unless required by applicable law or agreed to in writing, software
  6727. * distributed under the License is distributed on an "AS IS" BASIS,
  6728. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6729. * See the License for the specific language governing permissions and
  6730. * limitations under the License.
  6731. */
  6732. /**
  6733. * An immutable set of metadata that the local store tracks for each target.
  6734. */ class cr {
  6735. constructor(
  6736. /** The target being listened to. */
  6737. t,
  6738. /**
  6739. * The target ID to which the target corresponds; Assigned by the
  6740. * LocalStore for user listens and by the SyncEngine for limbo watches.
  6741. */
  6742. e,
  6743. /** The purpose of the target. */
  6744. n,
  6745. /**
  6746. * The sequence number of the last transaction during which this target data
  6747. * was modified.
  6748. */
  6749. s,
  6750. /** The latest snapshot version seen for this target. */
  6751. i = rt.min()
  6752. /**
  6753. * The maximum snapshot version at which the associated view
  6754. * contained no limbo documents.
  6755. */ , r = rt.min()
  6756. /**
  6757. * An opaque, server-assigned token that allows watching a target to be
  6758. * resumed after disconnecting without retransmitting all the data that
  6759. * matches the target. The resume token essentially identifies a point in
  6760. * time from which the server should resume sending results.
  6761. */ , o = Ve.EMPTY_BYTE_STRING
  6762. /**
  6763. * The number of documents that last matched the query at the resume token or
  6764. * read time. Documents are counted only when making a listen request with
  6765. * resume token or read time, otherwise, keep it null.
  6766. */ , u = null) {
  6767. this.target = t, this.targetId = e, this.purpose = n, this.sequenceNumber = s, this.snapshotVersion = i,
  6768. this.lastLimboFreeSnapshotVersion = r, this.resumeToken = o, this.expectedCount = u;
  6769. }
  6770. /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(t) {
  6771. return new cr(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount);
  6772. }
  6773. /**
  6774. * Creates a new target data instance with an updated resume token and
  6775. * snapshot version.
  6776. */ withResumeToken(t, e) {
  6777. return new cr(this.target, this.targetId, this.purpose, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t,
  6778. /* expectedCount= */ null);
  6779. }
  6780. /**
  6781. * Creates a new target data instance with an updated expected count.
  6782. */ withExpectedCount(t) {
  6783. return new cr(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, t);
  6784. }
  6785. /**
  6786. * Creates a new target data instance with an updated last limbo free
  6787. * snapshot version number.
  6788. */ withLastLimboFreeSnapshotVersion(t) {
  6789. return new cr(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, t, this.resumeToken, this.expectedCount);
  6790. }
  6791. }
  6792. /**
  6793. * @license
  6794. * Copyright 2017 Google LLC
  6795. *
  6796. * Licensed under the Apache License, Version 2.0 (the "License");
  6797. * you may not use this file except in compliance with the License.
  6798. * You may obtain a copy of the License at
  6799. *
  6800. * http://www.apache.org/licenses/LICENSE-2.0
  6801. *
  6802. * Unless required by applicable law or agreed to in writing, software
  6803. * distributed under the License is distributed on an "AS IS" BASIS,
  6804. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6805. * See the License for the specific language governing permissions and
  6806. * limitations under the License.
  6807. */
  6808. /** Serializer for values stored in the LocalStore. */ class ar {
  6809. constructor(t) {
  6810. this.fe = t;
  6811. }
  6812. }
  6813. /** Decodes a remote document from storage locally to a Document. */ function hr(t, e) {
  6814. let n;
  6815. if (e.document) n = Ki(t.fe, e.document, !!e.hasCommittedMutations); else if (e.noDocument) {
  6816. const t = ht.fromSegments(e.noDocument.path), s = wr(e.noDocument.readTime);
  6817. n = an.newNoDocument(t, s), e.hasCommittedMutations && n.setHasCommittedMutations();
  6818. } else {
  6819. if (!e.unknownDocument) return O();
  6820. {
  6821. const t = ht.fromSegments(e.unknownDocument.path), s = wr(e.unknownDocument.version);
  6822. n = an.newUnknownDocument(t, s);
  6823. }
  6824. }
  6825. return e.readTime && n.setReadTime(function(t) {
  6826. const e = new it(t[0], t[1]);
  6827. return rt.fromTimestamp(e);
  6828. }(e.readTime)), n;
  6829. }
  6830. /** Encodes a document for storage locally. */ function lr(t, e) {
  6831. const n = e.key, s = {
  6832. prefixPath: n.getCollectionPath().popLast().toArray(),
  6833. collectionGroup: n.collectionGroup,
  6834. documentId: n.path.lastSegment(),
  6835. readTime: fr(e.readTime),
  6836. hasCommittedMutations: e.hasCommittedMutations
  6837. };
  6838. if (e.isFoundDocument()) s.document = function(t, e) {
  6839. return {
  6840. name: $i(t, e.key),
  6841. fields: e.data.value.mapValue.fields,
  6842. updateTime: Di(t, e.version.toTimestamp()),
  6843. createTime: Di(t, e.createTime.toTimestamp())
  6844. };
  6845. }(t.fe, e); else if (e.isNoDocument()) s.noDocument = {
  6846. path: n.path.toArray(),
  6847. readTime: dr(e.version)
  6848. }; else {
  6849. if (!e.isUnknownDocument()) return O();
  6850. s.unknownDocument = {
  6851. path: n.path.toArray(),
  6852. version: dr(e.version)
  6853. };
  6854. }
  6855. return s;
  6856. }
  6857. function fr(t) {
  6858. const e = t.toTimestamp();
  6859. return [ e.seconds, e.nanoseconds ];
  6860. }
  6861. function dr(t) {
  6862. const e = t.toTimestamp();
  6863. return {
  6864. seconds: e.seconds,
  6865. nanoseconds: e.nanoseconds
  6866. };
  6867. }
  6868. function wr(t) {
  6869. const e = new it(t.seconds, t.nanoseconds);
  6870. return rt.fromTimestamp(e);
  6871. }
  6872. /** Encodes a batch of mutations into a DbMutationBatch for local storage. */
  6873. /** Decodes a DbMutationBatch into a MutationBatch */
  6874. function _r(t, e) {
  6875. const n = (e.baseMutations || []).map((e => zi(t.fe, e)));
  6876. // Squash old transform mutations into existing patch or set mutations.
  6877. // The replacement of representing `transforms` with `update_transforms`
  6878. // on the SDK means that old `transform` mutations stored in IndexedDB need
  6879. // to be updated to `update_transforms`.
  6880. // TODO(b/174608374): Remove this code once we perform a schema migration.
  6881. for (let t = 0; t < e.mutations.length - 1; ++t) {
  6882. const n = e.mutations[t];
  6883. if (t + 1 < e.mutations.length && void 0 !== e.mutations[t + 1].transform) {
  6884. const s = e.mutations[t + 1];
  6885. n.updateTransforms = s.transform.fieldTransforms, e.mutations.splice(t + 1, 1),
  6886. ++t;
  6887. }
  6888. }
  6889. const s = e.mutations.map((e => zi(t.fe, e))), i = it.fromMillis(e.localWriteTimeMs);
  6890. return new Zs(e.batchId, i, n, s);
  6891. }
  6892. /** Decodes a DbTarget into TargetData */ function mr(t) {
  6893. const e = wr(t.readTime), n = void 0 !== t.lastLimboFreeSnapshotVersion ? wr(t.lastLimboFreeSnapshotVersion) : rt.min();
  6894. let s;
  6895. var i;
  6896. return void 0 !== t.query.documents ? (F(1 === (i = t.query).documents.length),
  6897. s = Jn(Gn(Bi(i.documents[0])))) : s = function(t) {
  6898. return Jn(Yi(t));
  6899. }(t.query), new cr(s, t.targetId, "TargetPurposeListen" /* TargetPurpose.Listen */ , t.lastListenSequenceNumber, e, n, Ve.fromBase64String(t.resumeToken));
  6900. }
  6901. /** Encodes TargetData into a DbTarget for storage locally. */ function gr(t, e) {
  6902. const n = dr(e.snapshotVersion), s = dr(e.lastLimboFreeSnapshotVersion);
  6903. let i;
  6904. i = Fn(e.target) ? Hi(t.fe, e.target) : Ji(t.fe, e.target);
  6905. // We can't store the resumeToken as a ByteString in IndexedDb, so we
  6906. // convert it to a base64 string for storage.
  6907. const r = e.resumeToken.toBase64();
  6908. // lastListenSequenceNumber is always 0 until we do real GC.
  6909. return {
  6910. targetId: e.targetId,
  6911. canonicalId: $n(e.target),
  6912. readTime: n,
  6913. resumeToken: r,
  6914. lastListenSequenceNumber: e.sequenceNumber,
  6915. lastLimboFreeSnapshotVersion: s,
  6916. query: i
  6917. };
  6918. }
  6919. /**
  6920. * A helper function for figuring out what kind of query has been stored.
  6921. */
  6922. /**
  6923. * Encodes a `BundledQuery` from bundle proto to a Query object.
  6924. *
  6925. * This reconstructs the original query used to build the bundle being loaded,
  6926. * including features exists only in SDKs (for example: limit-to-last).
  6927. */
  6928. function yr(t) {
  6929. const e = Yi({
  6930. parent: t.parent,
  6931. structuredQuery: t.structuredQuery
  6932. });
  6933. return "LAST" === t.limitType ? Xn(e, e.limit, "L" /* LimitType.Last */) : e;
  6934. }
  6935. /** Encodes a NamedQuery proto object to a NamedQuery model object. */
  6936. /** Encodes a DbDocumentOverlay object to an Overlay model object. */
  6937. function pr(t, e) {
  6938. return new ei(e.largestBatchId, zi(t.fe, e.overlayMutation));
  6939. }
  6940. /** Decodes an Overlay model object into a DbDocumentOverlay object. */
  6941. /**
  6942. * Returns the DbDocumentOverlayKey corresponding to the given user and
  6943. * document key.
  6944. */
  6945. function Ir(t, e) {
  6946. const n = e.path.lastSegment();
  6947. return [ t, qt(e.path.popLast()), n ];
  6948. }
  6949. function Tr(t, e, n, s) {
  6950. return {
  6951. indexId: t,
  6952. uid: e.uid || "",
  6953. sequenceNumber: n,
  6954. readTime: dr(s.readTime),
  6955. documentKey: qt(s.documentKey.path),
  6956. largestBatchId: s.largestBatchId
  6957. };
  6958. }
  6959. /**
  6960. * @license
  6961. * Copyright 2020 Google LLC
  6962. *
  6963. * Licensed under the Apache License, Version 2.0 (the "License");
  6964. * you may not use this file except in compliance with the License.
  6965. * You may obtain a copy of the License at
  6966. *
  6967. * http://www.apache.org/licenses/LICENSE-2.0
  6968. *
  6969. * Unless required by applicable law or agreed to in writing, software
  6970. * distributed under the License is distributed on an "AS IS" BASIS,
  6971. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6972. * See the License for the specific language governing permissions and
  6973. * limitations under the License.
  6974. */ class Er {
  6975. getBundleMetadata(t, e) {
  6976. return Ar(t).get(e).next((t => {
  6977. if (t) return {
  6978. id: (e = t).bundleId,
  6979. createTime: wr(e.createTime),
  6980. version: e.version
  6981. };
  6982. /** Encodes a DbBundle to a BundleMetadata object. */
  6983. var e;
  6984. /** Encodes a BundleMetadata to a DbBundle. */ }));
  6985. }
  6986. saveBundleMetadata(t, e) {
  6987. return Ar(t).put({
  6988. bundleId: (n = e).id,
  6989. createTime: dr(Ni(n.createTime)),
  6990. version: n.version
  6991. });
  6992. var n;
  6993. /** Encodes a DbNamedQuery to a NamedQuery. */ }
  6994. getNamedQuery(t, e) {
  6995. return vr(t).get(e).next((t => {
  6996. if (t) return {
  6997. name: (e = t).name,
  6998. query: yr(e.bundledQuery),
  6999. readTime: wr(e.readTime)
  7000. };
  7001. var e;
  7002. /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ }));
  7003. }
  7004. saveNamedQuery(t, e) {
  7005. return vr(t).put(function(t) {
  7006. return {
  7007. name: t.name,
  7008. readTime: dr(Ni(t.readTime)),
  7009. bundledQuery: t.bundledQuery
  7010. };
  7011. }(e));
  7012. }
  7013. }
  7014. /**
  7015. * Helper to get a typed SimpleDbStore for the bundles object store.
  7016. */ function Ar(t) {
  7017. return _e(t, "bundles");
  7018. }
  7019. /**
  7020. * Helper to get a typed SimpleDbStore for the namedQueries object store.
  7021. */ function vr(t) {
  7022. return _e(t, "namedQueries");
  7023. }
  7024. /**
  7025. * @license
  7026. * Copyright 2022 Google LLC
  7027. *
  7028. * Licensed under the Apache License, Version 2.0 (the "License");
  7029. * you may not use this file except in compliance with the License.
  7030. * You may obtain a copy of the License at
  7031. *
  7032. * http://www.apache.org/licenses/LICENSE-2.0
  7033. *
  7034. * Unless required by applicable law or agreed to in writing, software
  7035. * distributed under the License is distributed on an "AS IS" BASIS,
  7036. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7037. * See the License for the specific language governing permissions and
  7038. * limitations under the License.
  7039. */
  7040. /**
  7041. * Implementation of DocumentOverlayCache using IndexedDb.
  7042. */ class Rr {
  7043. /**
  7044. * @param serializer - The document serializer.
  7045. * @param userId - The userId for which we are accessing overlays.
  7046. */
  7047. constructor(t, e) {
  7048. this.serializer = t, this.userId = e;
  7049. }
  7050. static de(t, e) {
  7051. const n = e.uid || "";
  7052. return new Rr(t, n);
  7053. }
  7054. getOverlay(t, e) {
  7055. return Pr(t).get(Ir(this.userId, e)).next((t => t ? pr(this.serializer, t) : null));
  7056. }
  7057. getOverlays(t, e) {
  7058. const n = fs();
  7059. return Rt.forEach(e, (e => this.getOverlay(t, e).next((t => {
  7060. null !== t && n.set(e, t);
  7061. })))).next((() => n));
  7062. }
  7063. saveOverlays(t, e, n) {
  7064. const s = [];
  7065. return n.forEach(((n, i) => {
  7066. const r = new ei(e, i);
  7067. s.push(this.we(t, r));
  7068. })), Rt.waitFor(s);
  7069. }
  7070. removeOverlaysForBatchId(t, e, n) {
  7071. const s = new Set;
  7072. // Get the set of unique collection paths.
  7073. e.forEach((t => s.add(qt(t.getCollectionPath()))));
  7074. const i = [];
  7075. return s.forEach((e => {
  7076. const s = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, n + 1 ],
  7077. /*lowerOpen=*/ !1,
  7078. /*upperOpen=*/ !0);
  7079. i.push(Pr(t).J("collectionPathOverlayIndex", s));
  7080. })), Rt.waitFor(i);
  7081. }
  7082. getOverlaysForCollection(t, e, n) {
  7083. const s = fs(), i = qt(e), r = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ],
  7084. /*lowerOpen=*/ !0);
  7085. return Pr(t).j("collectionPathOverlayIndex", r).next((t => {
  7086. for (const e of t) {
  7087. const t = pr(this.serializer, e);
  7088. s.set(t.getKey(), t);
  7089. }
  7090. return s;
  7091. }));
  7092. }
  7093. getOverlaysForCollectionGroup(t, e, n, s) {
  7094. const i = fs();
  7095. let r;
  7096. // We want batch IDs larger than `sinceBatchId`, and so the lower bound
  7097. // is not inclusive.
  7098. const o = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, Number.POSITIVE_INFINITY ],
  7099. /*lowerOpen=*/ !0);
  7100. return Pr(t).X({
  7101. index: "collectionGroupOverlayIndex",
  7102. range: o
  7103. }, ((t, e, n) => {
  7104. // We do not want to return partial batch overlays, even if the size
  7105. // of the result set exceeds the given `count` argument. Therefore, we
  7106. // continue to aggregate results even after the result size exceeds
  7107. // `count` if there are more overlays from the `currentBatchId`.
  7108. const o = pr(this.serializer, e);
  7109. i.size() < s || o.largestBatchId === r ? (i.set(o.getKey(), o), r = o.largestBatchId) : n.done();
  7110. })).next((() => i));
  7111. }
  7112. we(t, e) {
  7113. return Pr(t).put(function(t, e, n) {
  7114. const [s, i, r] = Ir(e, n.mutation.key);
  7115. return {
  7116. userId: e,
  7117. collectionPath: i,
  7118. documentId: r,
  7119. collectionGroup: n.mutation.key.getCollectionGroup(),
  7120. largestBatchId: n.largestBatchId,
  7121. overlayMutation: ji(t.fe, n.mutation)
  7122. };
  7123. }(this.serializer, this.userId, e));
  7124. }
  7125. }
  7126. /**
  7127. * Helper to get a typed SimpleDbStore for the document overlay object store.
  7128. */ function Pr(t) {
  7129. return _e(t, "documentOverlays");
  7130. }
  7131. /**
  7132. * @license
  7133. * Copyright 2021 Google LLC
  7134. *
  7135. * Licensed under the Apache License, Version 2.0 (the "License");
  7136. * you may not use this file except in compliance with the License.
  7137. * You may obtain a copy of the License at
  7138. *
  7139. * http://www.apache.org/licenses/LICENSE-2.0
  7140. *
  7141. * Unless required by applicable law or agreed to in writing, software
  7142. * distributed under the License is distributed on an "AS IS" BASIS,
  7143. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7144. * See the License for the specific language governing permissions and
  7145. * limitations under the License.
  7146. */
  7147. // Note: This code is copied from the backend. Code that is not used by
  7148. // Firestore was removed.
  7149. /** Firestore index value writer. */
  7150. class br {
  7151. constructor() {}
  7152. // The write methods below short-circuit writing terminators for values
  7153. // containing a (terminating) truncated value.
  7154. // As an example, consider the resulting encoding for:
  7155. // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM)
  7156. // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC)
  7157. // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC)
  7158. /** Writes an index value. */
  7159. _e(t, e) {
  7160. this.me(t, e),
  7161. // Write separator to split index values
  7162. // (see go/firestore-storage-format#encodings).
  7163. e.ge();
  7164. }
  7165. me(t, e) {
  7166. if ("nullValue" in t) this.ye(e, 5); else if ("booleanValue" in t) this.ye(e, 10),
  7167. e.pe(t.booleanValue ? 1 : 0); else if ("integerValue" in t) this.ye(e, 15), e.pe(Ce(t.integerValue)); else if ("doubleValue" in t) {
  7168. const n = Ce(t.doubleValue);
  7169. isNaN(n) ? this.ye(e, 13) : (this.ye(e, 15), Bt(n) ?
  7170. // -0.0, 0 and 0.0 are all considered the same
  7171. e.pe(0) : e.pe(n));
  7172. } else if ("timestampValue" in t) {
  7173. const n = t.timestampValue;
  7174. this.ye(e, 20), "string" == typeof n ? e.Ie(n) : (e.Ie(`${n.seconds || ""}`), e.pe(n.nanos || 0));
  7175. } else if ("stringValue" in t) this.Te(t.stringValue, e), this.Ee(e); else if ("bytesValue" in t) this.ye(e, 30),
  7176. e.Ae(xe(t.bytesValue)), this.Ee(e); else if ("referenceValue" in t) this.ve(t.referenceValue, e); else if ("geoPointValue" in t) {
  7177. const n = t.geoPointValue;
  7178. this.ye(e, 45), e.pe(n.latitude || 0), e.pe(n.longitude || 0);
  7179. } else "mapValue" in t ? en(t) ? this.ye(e, Number.MAX_SAFE_INTEGER) : (this.Re(t.mapValue, e),
  7180. this.Ee(e)) : "arrayValue" in t ? (this.Pe(t.arrayValue, e), this.Ee(e)) : O();
  7181. }
  7182. Te(t, e) {
  7183. this.ye(e, 25), this.be(t, e);
  7184. }
  7185. be(t, e) {
  7186. e.Ie(t);
  7187. }
  7188. Re(t, e) {
  7189. const n = t.fields || {};
  7190. this.ye(e, 55);
  7191. for (const t of Object.keys(n)) this.Te(t, e), this.me(n[t], e);
  7192. }
  7193. Pe(t, e) {
  7194. const n = t.values || [];
  7195. this.ye(e, 50);
  7196. for (const t of n) this.me(t, e);
  7197. }
  7198. ve(t, e) {
  7199. this.ye(e, 37);
  7200. ht.fromName(t).path.forEach((t => {
  7201. this.ye(e, 60), this.be(t, e);
  7202. }));
  7203. }
  7204. ye(t, e) {
  7205. t.pe(e);
  7206. }
  7207. Ee(t) {
  7208. // While the SDK does not implement truncation, the truncation marker is
  7209. // used to terminate all variable length values (which are strings, bytes,
  7210. // references, arrays and maps).
  7211. t.pe(2);
  7212. }
  7213. }
  7214. br.Ve = new br;
  7215. /**
  7216. * Counts the number of zeros in a byte.
  7217. *
  7218. * Visible for testing.
  7219. */
  7220. function Vr(t) {
  7221. if (0 === t) return 8;
  7222. let e = 0;
  7223. return t >> 4 == 0 && (
  7224. // Test if the first four bits are zero.
  7225. e += 4, t <<= 4), t >> 6 == 0 && (
  7226. // Test if the first two (or next two) bits are zero.
  7227. e += 2, t <<= 2), t >> 7 == 0 && (
  7228. // Test if the remaining bit is zero.
  7229. e += 1), e;
  7230. }
  7231. /** Counts the number of leading zeros in the given byte array. */
  7232. /**
  7233. * Returns the number of bytes required to store "value". Leading zero bytes
  7234. * are skipped.
  7235. */
  7236. function Sr(t) {
  7237. // This is just the number of bytes for the unsigned representation of the number.
  7238. const e = 64 - function(t) {
  7239. let e = 0;
  7240. for (let n = 0; n < 8; ++n) {
  7241. const s = Vr(255 & t[n]);
  7242. if (e += s, 8 !== s) break;
  7243. }
  7244. return e;
  7245. }(t);
  7246. return Math.ceil(e / 8);
  7247. }
  7248. /**
  7249. * OrderedCodeWriter is a minimal-allocation implementation of the writing
  7250. * behavior defined by the backend.
  7251. *
  7252. * The code is ported from its Java counterpart.
  7253. */ class Dr {
  7254. constructor() {
  7255. this.buffer = new Uint8Array(1024), this.position = 0;
  7256. }
  7257. Se(t) {
  7258. const e = t[Symbol.iterator]();
  7259. let n = e.next();
  7260. for (;!n.done; ) this.De(n.value), n = e.next();
  7261. this.Ce();
  7262. }
  7263. xe(t) {
  7264. const e = t[Symbol.iterator]();
  7265. let n = e.next();
  7266. for (;!n.done; ) this.Ne(n.value), n = e.next();
  7267. this.ke();
  7268. }
  7269. /** Writes utf8 bytes into this byte sequence, ascending. */ Me(t) {
  7270. for (const e of t) {
  7271. const t = e.charCodeAt(0);
  7272. if (t < 128) this.De(t); else if (t < 2048) this.De(960 | t >>> 6), this.De(128 | 63 & t); else if (e < "\ud800" || "\udbff" < e) this.De(480 | t >>> 12),
  7273. this.De(128 | 63 & t >>> 6), this.De(128 | 63 & t); else {
  7274. const t = e.codePointAt(0);
  7275. this.De(240 | t >>> 18), this.De(128 | 63 & t >>> 12), this.De(128 | 63 & t >>> 6),
  7276. this.De(128 | 63 & t);
  7277. }
  7278. }
  7279. this.Ce();
  7280. }
  7281. /** Writes utf8 bytes into this byte sequence, descending */ $e(t) {
  7282. for (const e of t) {
  7283. const t = e.charCodeAt(0);
  7284. if (t < 128) this.Ne(t); else if (t < 2048) this.Ne(960 | t >>> 6), this.Ne(128 | 63 & t); else if (e < "\ud800" || "\udbff" < e) this.Ne(480 | t >>> 12),
  7285. this.Ne(128 | 63 & t >>> 6), this.Ne(128 | 63 & t); else {
  7286. const t = e.codePointAt(0);
  7287. this.Ne(240 | t >>> 18), this.Ne(128 | 63 & t >>> 12), this.Ne(128 | 63 & t >>> 6),
  7288. this.Ne(128 | 63 & t);
  7289. }
  7290. }
  7291. this.ke();
  7292. }
  7293. Oe(t) {
  7294. // Values are encoded with a single byte length prefix, followed by the
  7295. // actual value in big-endian format with leading 0 bytes dropped.
  7296. const e = this.Fe(t), n = Sr(e);
  7297. this.Be(1 + n), this.buffer[this.position++] = 255 & n;
  7298. // Write the length
  7299. for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = 255 & e[t];
  7300. }
  7301. Le(t) {
  7302. // Values are encoded with a single byte length prefix, followed by the
  7303. // inverted value in big-endian format with leading 0 bytes dropped.
  7304. const e = this.Fe(t), n = Sr(e);
  7305. this.Be(1 + n), this.buffer[this.position++] = ~(255 & n);
  7306. // Write the length
  7307. for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = ~(255 & e[t]);
  7308. }
  7309. /**
  7310. * Writes the "infinity" byte sequence that sorts after all other byte
  7311. * sequences written in ascending order.
  7312. */ qe() {
  7313. this.Ue(255), this.Ue(255);
  7314. }
  7315. /**
  7316. * Writes the "infinity" byte sequence that sorts before all other byte
  7317. * sequences written in descending order.
  7318. */ Ke() {
  7319. this.Ge(255), this.Ge(255);
  7320. }
  7321. /**
  7322. * Resets the buffer such that it is the same as when it was newly
  7323. * constructed.
  7324. */ reset() {
  7325. this.position = 0;
  7326. }
  7327. seed(t) {
  7328. this.Be(t.length), this.buffer.set(t, this.position), this.position += t.length;
  7329. }
  7330. /** Makes a copy of the encoded bytes in this buffer. */ Qe() {
  7331. return this.buffer.slice(0, this.position);
  7332. }
  7333. /**
  7334. * Encodes `val` into an encoding so that the order matches the IEEE 754
  7335. * floating-point comparison results with the following exceptions:
  7336. * -0.0 < 0.0
  7337. * all non-NaN < NaN
  7338. * NaN = NaN
  7339. */ Fe(t) {
  7340. const e =
  7341. /** Converts a JavaScript number to a byte array (using big endian encoding). */
  7342. function(t) {
  7343. const e = new DataView(new ArrayBuffer(8));
  7344. return e.setFloat64(0, t, /* littleEndian= */ !1), new Uint8Array(e.buffer);
  7345. }(t), n = 0 != (128 & e[0]);
  7346. // Check if the first bit is set. We use a bit mask since value[0] is
  7347. // encoded as a number from 0 to 255.
  7348. // Revert the two complement to get natural ordering
  7349. e[0] ^= n ? 255 : 128;
  7350. for (let t = 1; t < e.length; ++t) e[t] ^= n ? 255 : 0;
  7351. return e;
  7352. }
  7353. /** Writes a single byte ascending to the buffer. */ De(t) {
  7354. const e = 255 & t;
  7355. 0 === e ? (this.Ue(0), this.Ue(255)) : 255 === e ? (this.Ue(255), this.Ue(0)) : this.Ue(e);
  7356. }
  7357. /** Writes a single byte descending to the buffer. */ Ne(t) {
  7358. const e = 255 & t;
  7359. 0 === e ? (this.Ge(0), this.Ge(255)) : 255 === e ? (this.Ge(255), this.Ge(0)) : this.Ge(t);
  7360. }
  7361. Ce() {
  7362. this.Ue(0), this.Ue(1);
  7363. }
  7364. ke() {
  7365. this.Ge(0), this.Ge(1);
  7366. }
  7367. Ue(t) {
  7368. this.Be(1), this.buffer[this.position++] = t;
  7369. }
  7370. Ge(t) {
  7371. this.Be(1), this.buffer[this.position++] = ~t;
  7372. }
  7373. Be(t) {
  7374. const e = t + this.position;
  7375. if (e <= this.buffer.length) return;
  7376. // Try doubling.
  7377. let n = 2 * this.buffer.length;
  7378. // Still not big enough? Just allocate the right size.
  7379. n < e && (n = e);
  7380. // Create the new buffer.
  7381. const s = new Uint8Array(n);
  7382. s.set(this.buffer), // copy old data
  7383. this.buffer = s;
  7384. }
  7385. }
  7386. class Cr {
  7387. constructor(t) {
  7388. this.je = t;
  7389. }
  7390. Ae(t) {
  7391. this.je.Se(t);
  7392. }
  7393. Ie(t) {
  7394. this.je.Me(t);
  7395. }
  7396. pe(t) {
  7397. this.je.Oe(t);
  7398. }
  7399. ge() {
  7400. this.je.qe();
  7401. }
  7402. }
  7403. class xr {
  7404. constructor(t) {
  7405. this.je = t;
  7406. }
  7407. Ae(t) {
  7408. this.je.xe(t);
  7409. }
  7410. Ie(t) {
  7411. this.je.$e(t);
  7412. }
  7413. pe(t) {
  7414. this.je.Le(t);
  7415. }
  7416. ge() {
  7417. this.je.Ke();
  7418. }
  7419. }
  7420. /**
  7421. * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the
  7422. * actual encoding.
  7423. */ class Nr {
  7424. constructor() {
  7425. this.je = new Dr, this.ze = new Cr(this.je), this.We = new xr(this.je);
  7426. }
  7427. seed(t) {
  7428. this.je.seed(t);
  7429. }
  7430. He(t) {
  7431. return 0 /* IndexKind.ASCENDING */ === t ? this.ze : this.We;
  7432. }
  7433. Qe() {
  7434. return this.je.Qe();
  7435. }
  7436. reset() {
  7437. this.je.reset();
  7438. }
  7439. }
  7440. /**
  7441. * @license
  7442. * Copyright 2022 Google LLC
  7443. *
  7444. * Licensed under the Apache License, Version 2.0 (the "License");
  7445. * you may not use this file except in compliance with the License.
  7446. * You may obtain a copy of the License at
  7447. *
  7448. * http://www.apache.org/licenses/LICENSE-2.0
  7449. *
  7450. * Unless required by applicable law or agreed to in writing, software
  7451. * distributed under the License is distributed on an "AS IS" BASIS,
  7452. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7453. * See the License for the specific language governing permissions and
  7454. * limitations under the License.
  7455. */
  7456. /** Represents an index entry saved by the SDK in persisted storage. */ class kr {
  7457. constructor(t, e, n, s) {
  7458. this.indexId = t, this.documentKey = e, this.arrayValue = n, this.directionalValue = s;
  7459. }
  7460. /**
  7461. * Returns an IndexEntry entry that sorts immediately after the current
  7462. * directional value.
  7463. */ Je() {
  7464. const t = this.directionalValue.length, e = 0 === t || 255 === this.directionalValue[t - 1] ? t + 1 : t, n = new Uint8Array(e);
  7465. return n.set(this.directionalValue, 0), e !== t ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1],
  7466. new kr(this.indexId, this.documentKey, this.arrayValue, n);
  7467. }
  7468. }
  7469. function Mr(t, e) {
  7470. let n = t.indexId - e.indexId;
  7471. return 0 !== n ? n : (n = $r(t.arrayValue, e.arrayValue), 0 !== n ? n : (n = $r(t.directionalValue, e.directionalValue),
  7472. 0 !== n ? n : ht.comparator(t.documentKey, e.documentKey)));
  7473. }
  7474. function $r(t, e) {
  7475. for (let n = 0; n < t.length && n < e.length; ++n) {
  7476. const s = t[n] - e[n];
  7477. if (0 !== s) return s;
  7478. }
  7479. return t.length - e.length;
  7480. }
  7481. /**
  7482. * @license
  7483. * Copyright 2022 Google LLC
  7484. *
  7485. * Licensed under the Apache License, Version 2.0 (the "License");
  7486. * you may not use this file except in compliance with the License.
  7487. * You may obtain a copy of the License at
  7488. *
  7489. * http://www.apache.org/licenses/LICENSE-2.0
  7490. *
  7491. * Unless required by applicable law or agreed to in writing, software
  7492. * distributed under the License is distributed on an "AS IS" BASIS,
  7493. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7494. * See the License for the specific language governing permissions and
  7495. * limitations under the License.
  7496. */
  7497. /**
  7498. * A light query planner for Firestore.
  7499. *
  7500. * This class matches a `FieldIndex` against a Firestore Query `Target`. It
  7501. * determines whether a given index can be used to serve the specified target.
  7502. *
  7503. * The following table showcases some possible index configurations:
  7504. *
  7505. * Query | Index
  7506. * -----------------------------------------------------------------------------
  7507. * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC
  7508. * where('a', '==', 'a').where('b', '==', 'b') | a ASC
  7509. * where('a', '==', 'a').where('b', '==', 'b') | b DESC
  7510. * where('a', '>=', 'a').orderBy('a') | a ASC
  7511. * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC
  7512. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC
  7513. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC
  7514. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING
  7515. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS
  7516. */ class Or {
  7517. constructor(t) {
  7518. this.collectionId = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(),
  7519. this.Ye = t.orderBy, this.Xe = [];
  7520. for (const e of t.filters) {
  7521. const t = e;
  7522. t.isInequality() ? this.Ze = t : this.Xe.push(t);
  7523. }
  7524. }
  7525. /**
  7526. * Returns whether the index can be used to serve the TargetIndexMatcher's
  7527. * target.
  7528. *
  7529. * An index is considered capable of serving the target when:
  7530. * - The target uses all index segments for its filters and orderBy clauses.
  7531. * The target can have additional filter and orderBy clauses, but not
  7532. * fewer.
  7533. * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also
  7534. * have a corresponding `CONTAINS` segment.
  7535. * - All directional index segments can be mapped to the target as a series of
  7536. * equality filters, a single inequality filter and a series of orderBy
  7537. * clauses.
  7538. * - The segments that represent the equality filters may appear out of order.
  7539. * - The optional segment for the inequality filter must appear after all
  7540. * equality segments.
  7541. * - The segments that represent that orderBy clause of the target must appear
  7542. * in order after all equality and inequality segments. Single orderBy
  7543. * clauses cannot be skipped, but a continuous orderBy suffix may be
  7544. * omitted.
  7545. */ tn(t) {
  7546. F(t.collectionGroup === this.collectionId);
  7547. // If there is an array element, find a matching filter.
  7548. const e = ft(t);
  7549. if (void 0 !== e && !this.en(e)) return !1;
  7550. const n = dt(t);
  7551. let s = new Set, i = 0, r = 0;
  7552. // Process all equalities first. Equalities can appear out of order.
  7553. for (;i < n.length && this.en(n[i]); ++i) s = s.add(n[i].fieldPath.canonicalString());
  7554. // If we already have processed all segments, all segments are used to serve
  7555. // the equality filters and we do not need to map any segments to the
  7556. // target's inequality and orderBy clauses.
  7557. if (i === n.length) return !0;
  7558. if (void 0 !== this.Ze) {
  7559. // If there is an inequality filter and the field was not in one of the
  7560. // equality filters above, the next segment must match both the filter
  7561. // and the first orderBy clause.
  7562. if (!s.has(this.Ze.field.canonicalString())) {
  7563. const t = n[i];
  7564. if (!this.nn(this.Ze, t) || !this.sn(this.Ye[r++], t)) return !1;
  7565. }
  7566. ++i;
  7567. }
  7568. // All remaining segments need to represent the prefix of the target's
  7569. // orderBy.
  7570. for (;i < n.length; ++i) {
  7571. const t = n[i];
  7572. if (r >= this.Ye.length || !this.sn(this.Ye[r++], t)) return !1;
  7573. }
  7574. return !0;
  7575. }
  7576. en(t) {
  7577. for (const e of this.Xe) if (this.nn(e, t)) return !0;
  7578. return !1;
  7579. }
  7580. nn(t, e) {
  7581. if (void 0 === t || !t.field.isEqual(e.fieldPath)) return !1;
  7582. const n = "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op;
  7583. return 2 /* IndexKind.CONTAINS */ === e.kind === n;
  7584. }
  7585. sn(t, e) {
  7586. return !!t.field.isEqual(e.fieldPath) && (0 /* IndexKind.ASCENDING */ === e.kind && "asc" /* Direction.ASCENDING */ === t.dir || 1 /* IndexKind.DESCENDING */ === e.kind && "desc" /* Direction.DESCENDING */ === t.dir);
  7587. }
  7588. }
  7589. /**
  7590. * @license
  7591. * Copyright 2022 Google LLC
  7592. *
  7593. * Licensed under the Apache License, Version 2.0 (the "License");
  7594. * you may not use this file except in compliance with the License.
  7595. * You may obtain a copy of the License at
  7596. *
  7597. * http://www.apache.org/licenses/LICENSE-2.0
  7598. *
  7599. * Unless required by applicable law or agreed to in writing, software
  7600. * distributed under the License is distributed on an "AS IS" BASIS,
  7601. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7602. * See the License for the specific language governing permissions and
  7603. * limitations under the License.
  7604. */
  7605. /**
  7606. * Provides utility functions that help with boolean logic transformations needed for handling
  7607. * complex filters used in queries.
  7608. */
  7609. /**
  7610. * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in
  7611. * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given
  7612. * input into a disjunction of equality filters and returns the expanded filter.
  7613. */ function Fr(t) {
  7614. var e, n;
  7615. if (F(t instanceof mn || t instanceof gn), t instanceof mn) {
  7616. if (t instanceof Cn) {
  7617. const s = (null === (n = null === (e = t.value.arrayValue) || void 0 === e ? void 0 : e.values) || void 0 === n ? void 0 : n.map((e => mn.create(t.field, "==" /* Operator.EQUAL */ , e)))) || [];
  7618. return gn.create(s, "or" /* CompositeOperator.OR */);
  7619. }
  7620. // We have reached other kinds of field filters.
  7621. return t;
  7622. }
  7623. // We have a composite filter.
  7624. const s = t.filters.map((t => Fr(t)));
  7625. return gn.create(s, t.op);
  7626. }
  7627. /**
  7628. * Given a composite filter, returns the list of terms in its disjunctive normal form.
  7629. *
  7630. * <p>Each element in the return value is one term of the resulting DNF. For instance: For the
  7631. * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list
  7632. * with two elements: a composite filter that performs (A && C), and a composite filter that
  7633. * performs (B && C).
  7634. *
  7635. * @param filter the composite filter to calculate DNF transform for.
  7636. * @return the terms in the DNF transform.
  7637. */ function Br(t) {
  7638. if (0 === t.getFilters().length) return [];
  7639. const e = Kr(Fr(t));
  7640. return F(Ur(e)), Lr(e) || qr(e) ? [ e ] : e.getFilters();
  7641. }
  7642. /** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function Lr(t) {
  7643. return t instanceof mn;
  7644. }
  7645. /**
  7646. * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10
  7647. * && b == 20)
  7648. */ function qr(t) {
  7649. return t instanceof gn && In(t);
  7650. }
  7651. /**
  7652. * Returns whether or not the given filter is in disjunctive normal form (DNF).
  7653. *
  7654. * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical
  7655. * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.
  7656. *
  7657. * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form
  7658. */ function Ur(t) {
  7659. return Lr(t) || qr(t) ||
  7660. /**
  7661. * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and
  7662. * field filters. e.g. (a == 10) || (b==20 && c==30)
  7663. */
  7664. function(t) {
  7665. if (t instanceof gn && pn(t)) {
  7666. for (const e of t.getFilters()) if (!Lr(e) && !qr(e)) return !1;
  7667. return !0;
  7668. }
  7669. return !1;
  7670. }(t);
  7671. }
  7672. function Kr(t) {
  7673. if (F(t instanceof mn || t instanceof gn), t instanceof mn) return t;
  7674. if (1 === t.filters.length) return Kr(t.filters[0]);
  7675. // Compute DNF for each of the subfilters first
  7676. const e = t.filters.map((t => Kr(t)));
  7677. let n = gn.create(e, t.op);
  7678. return n = jr(n), Ur(n) ? n : (F(n instanceof gn), F(yn(n)), F(n.filters.length > 1),
  7679. n.filters.reduce(((t, e) => Gr(t, e))));
  7680. }
  7681. function Gr(t, e) {
  7682. let n;
  7683. return F(t instanceof mn || t instanceof gn), F(e instanceof mn || e instanceof gn),
  7684. // FieldFilter FieldFilter
  7685. n = t instanceof mn ? e instanceof mn ? function(t, e) {
  7686. // Conjunction distribution for two field filters is the conjunction of them.
  7687. return gn.create([ t, e ], "and" /* CompositeOperator.AND */);
  7688. }(t, e) : Qr(t, e) : e instanceof mn ? Qr(e, t) : function(t, e) {
  7689. // There are four cases:
  7690. // (A & B) & (C & D) --> (A & B & C & D)
  7691. // (A & B) & (C | D) --> (A & B & C) | (A & B & D)
  7692. // (A | B) & (C & D) --> (C & D & A) | (C & D & B)
  7693. // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)
  7694. // Case 1 is a merge.
  7695. if (F(t.filters.length > 0 && e.filters.length > 0), yn(t) && yn(e)) return vn(t, e.getFilters());
  7696. // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases
  7697. // we should take each element of the disjunction and distribute it over the other side, and
  7698. // return the disjunction of the distribution results.
  7699. const n = pn(t) ? t : e, s = pn(t) ? e : t, i = n.filters.map((t => Gr(t, s)));
  7700. return gn.create(i, "or" /* CompositeOperator.OR */);
  7701. }(t, e), jr(n);
  7702. }
  7703. function Qr(t, e) {
  7704. // There are two cases:
  7705. // A & (B & C) --> (A & B & C)
  7706. // A & (B | C) --> (A & B) | (A & C)
  7707. if (yn(e))
  7708. // Case 1
  7709. return vn(e, t.getFilters());
  7710. {
  7711. // Case 2
  7712. const n = e.filters.map((e => Gr(t, e)));
  7713. return gn.create(n, "or" /* CompositeOperator.OR */);
  7714. }
  7715. }
  7716. /**
  7717. * Applies the associativity property to the given filter and returns the resulting filter.
  7718. *
  7719. * <ul>
  7720. * <li>A | (B | C) == (A | B) | C == (A | B | C)
  7721. * <li>A & (B & C) == (A & B) & C == (A & B & C)
  7722. * </ul>
  7723. *
  7724. * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic
  7725. */ function jr(t) {
  7726. if (F(t instanceof mn || t instanceof gn), t instanceof mn) return t;
  7727. const e = t.getFilters();
  7728. // If the composite filter only contains 1 filter, apply associativity to it.
  7729. if (1 === e.length) return jr(e[0]);
  7730. // Associativity applied to a flat composite filter results is itself.
  7731. if (Tn(t)) return t;
  7732. // First apply associativity to all subfilters. This will in turn recursively apply
  7733. // associativity to all nested composite filters and field filters.
  7734. const n = e.map((t => jr(t))), s = [];
  7735. // For composite subfilters that perform the same kind of logical operation as `compositeFilter`
  7736. // take out their filters and add them to `compositeFilter`. For example:
  7737. // compositeFilter = (A | (B | C | D))
  7738. // compositeSubfilter = (B | C | D)
  7739. // Result: (A | B | C | D)
  7740. // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been
  7741. // added to the top-level "compositeFilter".
  7742. return n.forEach((e => {
  7743. e instanceof mn ? s.push(e) : e instanceof gn && (e.op === t.op ?
  7744. // compositeFilter: (A | (B | C))
  7745. // compositeSubfilter: (B | C)
  7746. // Result: (A | B | C)
  7747. s.push(...e.filters) :
  7748. // compositeFilter: (A | (B & C))
  7749. // compositeSubfilter: (B & C)
  7750. // Result: (A | (B & C))
  7751. s.push(e));
  7752. })), 1 === s.length ? s[0] : gn.create(s, t.op);
  7753. }
  7754. /**
  7755. * @license
  7756. * Copyright 2019 Google LLC
  7757. *
  7758. * Licensed under the Apache License, Version 2.0 (the "License");
  7759. * you may not use this file except in compliance with the License.
  7760. * You may obtain a copy of the License at
  7761. *
  7762. * http://www.apache.org/licenses/LICENSE-2.0
  7763. *
  7764. * Unless required by applicable law or agreed to in writing, software
  7765. * distributed under the License is distributed on an "AS IS" BASIS,
  7766. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7767. * See the License for the specific language governing permissions and
  7768. * limitations under the License.
  7769. */
  7770. /**
  7771. * An in-memory implementation of IndexManager.
  7772. */ class zr {
  7773. constructor() {
  7774. this.rn = new Wr;
  7775. }
  7776. addToCollectionParentIndex(t, e) {
  7777. return this.rn.add(e), Rt.resolve();
  7778. }
  7779. getCollectionParents(t, e) {
  7780. return Rt.resolve(this.rn.getEntries(e));
  7781. }
  7782. addFieldIndex(t, e) {
  7783. // Field indices are not supported with memory persistence.
  7784. return Rt.resolve();
  7785. }
  7786. deleteFieldIndex(t, e) {
  7787. // Field indices are not supported with memory persistence.
  7788. return Rt.resolve();
  7789. }
  7790. getDocumentsMatchingTarget(t, e) {
  7791. // Field indices are not supported with memory persistence.
  7792. return Rt.resolve(null);
  7793. }
  7794. getIndexType(t, e) {
  7795. // Field indices are not supported with memory persistence.
  7796. return Rt.resolve(0 /* IndexType.NONE */);
  7797. }
  7798. getFieldIndexes(t, e) {
  7799. // Field indices are not supported with memory persistence.
  7800. return Rt.resolve([]);
  7801. }
  7802. getNextCollectionGroupToUpdate(t) {
  7803. // Field indices are not supported with memory persistence.
  7804. return Rt.resolve(null);
  7805. }
  7806. getMinOffset(t, e) {
  7807. return Rt.resolve(It.min());
  7808. }
  7809. getMinOffsetFromCollectionGroup(t, e) {
  7810. return Rt.resolve(It.min());
  7811. }
  7812. updateCollectionGroup(t, e, n) {
  7813. // Field indices are not supported with memory persistence.
  7814. return Rt.resolve();
  7815. }
  7816. updateIndexEntries(t, e) {
  7817. // Field indices are not supported with memory persistence.
  7818. return Rt.resolve();
  7819. }
  7820. }
  7821. /**
  7822. * Internal implementation of the collection-parent index exposed by MemoryIndexManager.
  7823. * Also used for in-memory caching by IndexedDbIndexManager and initial index population
  7824. * in indexeddb_schema.ts
  7825. */ class Wr {
  7826. constructor() {
  7827. this.index = {};
  7828. }
  7829. // Returns false if the entry already existed.
  7830. add(t) {
  7831. const e = t.lastSegment(), n = t.popLast(), s = this.index[e] || new Ee(ut.comparator), i = !s.has(n);
  7832. return this.index[e] = s.add(n), i;
  7833. }
  7834. has(t) {
  7835. const e = t.lastSegment(), n = t.popLast(), s = this.index[e];
  7836. return s && s.has(n);
  7837. }
  7838. getEntries(t) {
  7839. return (this.index[t] || new Ee(ut.comparator)).toArray();
  7840. }
  7841. }
  7842. /**
  7843. * @license
  7844. * Copyright 2019 Google LLC
  7845. *
  7846. * Licensed under the Apache License, Version 2.0 (the "License");
  7847. * you may not use this file except in compliance with the License.
  7848. * You may obtain a copy of the License at
  7849. *
  7850. * http://www.apache.org/licenses/LICENSE-2.0
  7851. *
  7852. * Unless required by applicable law or agreed to in writing, software
  7853. * distributed under the License is distributed on an "AS IS" BASIS,
  7854. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7855. * See the License for the specific language governing permissions and
  7856. * limitations under the License.
  7857. */ const Hr = new Uint8Array(0);
  7858. /**
  7859. * A persisted implementation of IndexManager.
  7860. *
  7861. * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index
  7862. * data as it supports multi-tab access.
  7863. */
  7864. class Jr {
  7865. constructor(t, e) {
  7866. this.user = t, this.databaseId = e,
  7867. /**
  7868. * An in-memory copy of the index entries we've already written since the SDK
  7869. * launched. Used to avoid re-writing the same entry repeatedly.
  7870. *
  7871. * This is *NOT* a complete cache of what's in persistence and so can never be
  7872. * used to satisfy reads.
  7873. */
  7874. this.on = new Wr,
  7875. /**
  7876. * Maps from a target to its equivalent list of sub-targets. Each sub-target
  7877. * contains only one term from the target's disjunctive normal form (DNF).
  7878. */
  7879. this.un = new os((t => $n(t)), ((t, e) => On(t, e))), this.uid = t.uid || "";
  7880. }
  7881. /**
  7882. * Adds a new entry to the collection parent index.
  7883. *
  7884. * Repeated calls for the same collectionPath should be avoided within a
  7885. * transaction as IndexedDbIndexManager only caches writes once a transaction
  7886. * has been committed.
  7887. */ addToCollectionParentIndex(t, e) {
  7888. if (!this.on.has(e)) {
  7889. const n = e.lastSegment(), s = e.popLast();
  7890. t.addOnCommittedListener((() => {
  7891. // Add the collection to the in memory cache only if the transaction was
  7892. // successfully committed.
  7893. this.on.add(e);
  7894. }));
  7895. const i = {
  7896. collectionId: n,
  7897. parent: qt(s)
  7898. };
  7899. return Yr(t).put(i);
  7900. }
  7901. return Rt.resolve();
  7902. }
  7903. getCollectionParents(t, e) {
  7904. const n = [], s = IDBKeyRange.bound([ e, "" ], [ st(e), "" ],
  7905. /*lowerOpen=*/ !1,
  7906. /*upperOpen=*/ !0);
  7907. return Yr(t).j(s).next((t => {
  7908. for (const s of t) {
  7909. // This collectionId guard shouldn't be necessary (and isn't as long
  7910. // as we're running in a real browser), but there's a bug in
  7911. // indexeddbshim that breaks our range in our tests running in node:
  7912. // https://github.com/axemclion/IndexedDBShim/issues/334
  7913. if (s.collectionId !== e) break;
  7914. n.push(Gt(s.parent));
  7915. }
  7916. return n;
  7917. }));
  7918. }
  7919. addFieldIndex(t, e) {
  7920. // TODO(indexing): Verify that the auto-incrementing index ID works in
  7921. // Safari & Firefox.
  7922. const n = Zr(t), s = function(t) {
  7923. return {
  7924. indexId: t.indexId,
  7925. collectionGroup: t.collectionGroup,
  7926. fields: t.fields.map((t => [ t.fieldPath.canonicalString(), t.kind ]))
  7927. };
  7928. }(e);
  7929. delete s.indexId;
  7930. // `indexId` is auto-populated by IndexedDb
  7931. const i = n.add(s);
  7932. if (e.indexState) {
  7933. const n = to(t);
  7934. return i.next((t => {
  7935. n.put(Tr(t, this.user, e.indexState.sequenceNumber, e.indexState.offset));
  7936. }));
  7937. }
  7938. return i.next();
  7939. }
  7940. deleteFieldIndex(t, e) {
  7941. const n = Zr(t), s = to(t), i = Xr(t);
  7942. return n.delete(e.indexId).next((() => s.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7943. /*lowerOpen=*/ !1,
  7944. /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7945. /*lowerOpen=*/ !1,
  7946. /*upperOpen=*/ !0))));
  7947. }
  7948. getDocumentsMatchingTarget(t, e) {
  7949. const n = Xr(t);
  7950. let s = !0;
  7951. const i = new Map;
  7952. return Rt.forEach(this.cn(e), (e => this.an(t, e).next((t => {
  7953. s && (s = !!t), i.set(e, t);
  7954. })))).next((() => {
  7955. if (s) {
  7956. let t = gs();
  7957. const s = [];
  7958. return Rt.forEach(i, ((i, r) => {
  7959. var o;
  7960. N("IndexedDbIndexManager", `Using index ${o = i, `id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map((t => `${t.fieldPath}:${t.kind}`)).join(",")}`} to execute ${$n(e)}`);
  7961. const u = function(t, e) {
  7962. const n = ft(e);
  7963. if (void 0 === n) return null;
  7964. for (const e of Bn(t, n.fieldPath)) switch (e.op) {
  7965. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  7966. return e.value.arrayValue.values || [];
  7967. case "array-contains" /* Operator.ARRAY_CONTAINS */ :
  7968. return [ e.value ];
  7969. // Remaining filters are not array filters.
  7970. }
  7971. return null;
  7972. }
  7973. /**
  7974. * Returns the list of values that are used in != or NOT_IN filters. Returns
  7975. * `null` if there are no such filters.
  7976. */ (r, i), c = function(t, e) {
  7977. const n = new Map;
  7978. for (const s of dt(e)) for (const e of Bn(t, s.fieldPath)) switch (e.op) {
  7979. case "==" /* Operator.EQUAL */ :
  7980. case "in" /* Operator.IN */ :
  7981. // Encode equality prefix, which is encoded in the index value before
  7982. // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
  7983. // `value != 'ab'`).
  7984. n.set(s.fieldPath.canonicalString(), e.value);
  7985. break;
  7986. case "not-in" /* Operator.NOT_IN */ :
  7987. case "!=" /* Operator.NOT_EQUAL */ :
  7988. // NotIn/NotEqual is always a suffix. There cannot be any remaining
  7989. // segments and hence we can return early here.
  7990. return n.set(s.fieldPath.canonicalString(), e.value), Array.from(n.values());
  7991. // Remaining filters cannot be used as notIn bounds.
  7992. }
  7993. return null;
  7994. }
  7995. /**
  7996. * Returns a lower bound of field values that can be used as a starting point to
  7997. * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound
  7998. * exists.
  7999. */ (r, i), a = function(t, e) {
  8000. const n = [];
  8001. let s = !0;
  8002. // For each segment, retrieve a lower bound if there is a suitable filter or
  8003. // startAt.
  8004. for (const i of dt(e)) {
  8005. const e = 0 /* IndexKind.ASCENDING */ === i.kind ? Ln(t, i.fieldPath, t.startAt) : qn(t, i.fieldPath, t.startAt);
  8006. n.push(e.value), s && (s = e.inclusive);
  8007. }
  8008. return new hn(n, s);
  8009. }
  8010. /**
  8011. * Returns an upper bound of field values that can be used as an ending point
  8012. * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no
  8013. * upper bound exists.
  8014. */ (r, i), h = function(t, e) {
  8015. const n = [];
  8016. let s = !0;
  8017. // For each segment, retrieve an upper bound if there is a suitable filter or
  8018. // endAt.
  8019. for (const i of dt(e)) {
  8020. const e = 0 /* IndexKind.ASCENDING */ === i.kind ? qn(t, i.fieldPath, t.endAt) : Ln(t, i.fieldPath, t.endAt);
  8021. n.push(e.value), s && (s = e.inclusive);
  8022. }
  8023. return new hn(n, s);
  8024. }(r, i), l = this.hn(i, r, a), f = this.hn(i, r, h), d = this.ln(i, r, c), w = this.fn(i.indexId, u, l, a.inclusive, f, h.inclusive, d);
  8025. return Rt.forEach(w, (i => n.H(i, e.limit).next((e => {
  8026. e.forEach((e => {
  8027. const n = ht.fromSegments(e.documentKey);
  8028. t.has(n) || (t = t.add(n), s.push(n));
  8029. }));
  8030. }))));
  8031. })).next((() => s));
  8032. }
  8033. return Rt.resolve(null);
  8034. }));
  8035. }
  8036. cn(t) {
  8037. let e = this.un.get(t);
  8038. if (e) return e;
  8039. if (0 === t.filters.length) e = [ t ]; else {
  8040. e = Br(gn.create(t.filters, "and" /* CompositeOperator.AND */)).map((e => Mn(t.path, t.collectionGroup, t.orderBy, e.getFilters(), t.limit, t.startAt, t.endAt)));
  8041. }
  8042. return this.un.set(t, e), e;
  8043. }
  8044. /**
  8045. * Constructs a key range query on `DbIndexEntryStore` that unions all
  8046. * bounds.
  8047. */ fn(t, e, n, s, i, r, o) {
  8048. // The number of total index scans we union together. This is similar to a
  8049. // distributed normal form, but adapted for array values. We create a single
  8050. // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter
  8051. // combined with the values from the query bounds.
  8052. const u = (null != e ? e.length : 1) * Math.max(n.length, i.length), c = u / (null != e ? e.length : 1), a = [];
  8053. for (let h = 0; h < u; ++h) {
  8054. const u = e ? this.dn(e[h / c]) : Hr, l = this.wn(t, u, n[h % c], s), f = this._n(t, u, i[h % c], r), d = o.map((e => this.wn(t, u, e,
  8055. /* inclusive= */ !0)));
  8056. a.push(...this.createRange(l, f, d));
  8057. }
  8058. return a;
  8059. }
  8060. /** Generates the lower bound for `arrayValue` and `directionalValue`. */ wn(t, e, n, s) {
  8061. const i = new kr(t, ht.empty(), e, n);
  8062. return s ? i : i.Je();
  8063. }
  8064. /** Generates the upper bound for `arrayValue` and `directionalValue`. */ _n(t, e, n, s) {
  8065. const i = new kr(t, ht.empty(), e, n);
  8066. return s ? i.Je() : i;
  8067. }
  8068. an(t, e) {
  8069. const n = new Or(e), s = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment();
  8070. return this.getFieldIndexes(t, s).next((t => {
  8071. // Return the index with the most number of segments.
  8072. let e = null;
  8073. for (const s of t) {
  8074. n.tn(s) && (!e || s.fields.length > e.fields.length) && (e = s);
  8075. }
  8076. return e;
  8077. }));
  8078. }
  8079. getIndexType(t, e) {
  8080. let n = 2 /* IndexType.FULL */;
  8081. const s = this.cn(e);
  8082. return Rt.forEach(s, (e => this.an(t, e).next((t => {
  8083. t ? 0 /* IndexType.NONE */ !== n && t.fields.length < function(t) {
  8084. let e = new Ee(at.comparator), n = !1;
  8085. for (const s of t.filters) for (const t of s.getFlattenedFilters())
  8086. // __name__ is not an explicit segment of any index, so we don't need to
  8087. // count it.
  8088. t.field.isKeyField() || (
  8089. // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
  8090. // For instance, it is possible to have an index for "a ARRAY a ASC". Even
  8091. // though these are on the same field, they should be counted as two
  8092. // separate segments in an index.
  8093. "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op ? n = !0 : e = e.add(t.field));
  8094. for (const n of t.orderBy)
  8095. // __name__ is not an explicit segment of any index, so we don't need to
  8096. // count it.
  8097. n.field.isKeyField() || (e = e.add(n.field));
  8098. return e.size + (n ? 1 : 0);
  8099. }(e) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;
  8100. })))).next((() =>
  8101. // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider
  8102. // OR queries that have a `limit` to have a partial index. For such queries we perform sorting
  8103. // and apply the limit in memory as a post-processing step.
  8104. function(t) {
  8105. return null !== t.limit;
  8106. }(e) && s.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));
  8107. }
  8108. /**
  8109. * Returns the byte encoded form of the directional values in the field index.
  8110. * Returns `null` if the document does not have all fields specified in the
  8111. * index.
  8112. */ mn(t, e) {
  8113. const n = new Nr;
  8114. for (const s of dt(t)) {
  8115. const t = e.data.field(s.fieldPath);
  8116. if (null == t) return null;
  8117. const i = n.He(s.kind);
  8118. br.Ve._e(t, i);
  8119. }
  8120. return n.Qe();
  8121. }
  8122. /** Encodes a single value to the ascending index format. */ dn(t) {
  8123. const e = new Nr;
  8124. return br.Ve._e(t, e.He(0 /* IndexKind.ASCENDING */)), e.Qe();
  8125. }
  8126. /**
  8127. * Returns an encoded form of the document key that sorts based on the key
  8128. * ordering of the field index.
  8129. */ gn(t, e) {
  8130. const n = new Nr;
  8131. return br.Ve._e(We(this.databaseId, e), n.He(function(t) {
  8132. const e = dt(t);
  8133. return 0 === e.length ? 0 /* IndexKind.ASCENDING */ : e[e.length - 1].kind;
  8134. }(t))), n.Qe();
  8135. }
  8136. /**
  8137. * Encodes the given field values according to the specification in `target`.
  8138. * For IN queries, a list of possible values is returned.
  8139. */ ln(t, e, n) {
  8140. if (null === n) return [];
  8141. let s = [];
  8142. s.push(new Nr);
  8143. let i = 0;
  8144. for (const r of dt(t)) {
  8145. const t = n[i++];
  8146. for (const n of s) if (this.yn(e, r.fieldPath) && Je(t)) s = this.pn(s, r, t); else {
  8147. const e = n.He(r.kind);
  8148. br.Ve._e(t, e);
  8149. }
  8150. }
  8151. return this.In(s);
  8152. }
  8153. /**
  8154. * Encodes the given bounds according to the specification in `target`. For IN
  8155. * queries, a list of possible values is returned.
  8156. */ hn(t, e, n) {
  8157. return this.ln(t, e, n.position);
  8158. }
  8159. /** Returns the byte representation for the provided encoders. */ In(t) {
  8160. const e = [];
  8161. for (let n = 0; n < t.length; ++n) e[n] = t[n].Qe();
  8162. return e;
  8163. }
  8164. /**
  8165. * Creates a separate encoder for each element of an array.
  8166. *
  8167. * The method appends each value to all existing encoders (e.g. filter("a",
  8168. * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A
  8169. * list of new encoders is returned.
  8170. */ pn(t, e, n) {
  8171. const s = [ ...t ], i = [];
  8172. for (const t of n.arrayValue.values || []) for (const n of s) {
  8173. const s = new Nr;
  8174. s.seed(n.Qe()), br.Ve._e(t, s.He(e.kind)), i.push(s);
  8175. }
  8176. return i;
  8177. }
  8178. yn(t, e) {
  8179. return !!t.filters.find((t => t instanceof mn && t.field.isEqual(e) && ("in" /* Operator.IN */ === t.op || "not-in" /* Operator.NOT_IN */ === t.op)));
  8180. }
  8181. getFieldIndexes(t, e) {
  8182. const n = Zr(t), s = to(t);
  8183. return (e ? n.j("collectionGroupIndex", IDBKeyRange.bound(e, e)) : n.j()).next((t => {
  8184. const e = [];
  8185. return Rt.forEach(t, (t => s.get([ t.indexId, this.uid ]).next((n => {
  8186. e.push(function(t, e) {
  8187. const n = e ? new gt(e.sequenceNumber, new It(wr(e.readTime), new ht(Gt(e.documentKey)), e.largestBatchId)) : gt.empty(), s = t.fields.map((([t, e]) => new _t(at.fromServerFormat(t), e)));
  8188. return new lt(t.indexId, t.collectionGroup, s, n);
  8189. }(t, n));
  8190. })))).next((() => e));
  8191. }));
  8192. }
  8193. getNextCollectionGroupToUpdate(t) {
  8194. return this.getFieldIndexes(t).next((t => 0 === t.length ? null : (t.sort(((t, e) => {
  8195. const n = t.indexState.sequenceNumber - e.indexState.sequenceNumber;
  8196. return 0 !== n ? n : et(t.collectionGroup, e.collectionGroup);
  8197. })), t[0].collectionGroup)));
  8198. }
  8199. updateCollectionGroup(t, e, n) {
  8200. const s = Zr(t), i = to(t);
  8201. return this.Tn(t).next((t => s.j("collectionGroupIndex", IDBKeyRange.bound(e, e)).next((e => Rt.forEach(e, (e => i.put(Tr(e.indexId, this.user, t, n))))))));
  8202. }
  8203. updateIndexEntries(t, e) {
  8204. // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as
  8205. // it could be used across different IndexedDB transactions. As any cached
  8206. // data might be invalidated by other multi-tab clients, we can only trust
  8207. // data within a single IndexedDB transaction. We therefore add a cache
  8208. // here.
  8209. const n = new Map;
  8210. return Rt.forEach(e, ((e, s) => {
  8211. const i = n.get(e.collectionGroup);
  8212. return (i ? Rt.resolve(i) : this.getFieldIndexes(t, e.collectionGroup)).next((i => (n.set(e.collectionGroup, i),
  8213. Rt.forEach(i, (n => this.En(t, e, n).next((e => {
  8214. const i = this.An(s, n);
  8215. return e.isEqual(i) ? Rt.resolve() : this.vn(t, s, n, e, i);
  8216. })))))));
  8217. }));
  8218. }
  8219. Rn(t, e, n, s) {
  8220. return Xr(t).put({
  8221. indexId: s.indexId,
  8222. uid: this.uid,
  8223. arrayValue: s.arrayValue,
  8224. directionalValue: s.directionalValue,
  8225. orderedDocumentKey: this.gn(n, e.key),
  8226. documentKey: e.key.path.toArray()
  8227. });
  8228. }
  8229. Pn(t, e, n, s) {
  8230. return Xr(t).delete([ s.indexId, this.uid, s.arrayValue, s.directionalValue, this.gn(n, e.key), e.key.path.toArray() ]);
  8231. }
  8232. En(t, e, n) {
  8233. const s = Xr(t);
  8234. let i = new Ee(Mr);
  8235. return s.X({
  8236. index: "documentKeyIndex",
  8237. range: IDBKeyRange.only([ n.indexId, this.uid, this.gn(n, e) ])
  8238. }, ((t, s) => {
  8239. i = i.add(new kr(n.indexId, e, s.arrayValue, s.directionalValue));
  8240. })).next((() => i));
  8241. }
  8242. /** Creates the index entries for the given document. */ An(t, e) {
  8243. let n = new Ee(Mr);
  8244. const s = this.mn(e, t);
  8245. if (null == s) return n;
  8246. const i = ft(e);
  8247. if (null != i) {
  8248. const r = t.data.field(i.fieldPath);
  8249. if (Je(r)) for (const i of r.arrayValue.values || []) n = n.add(new kr(e.indexId, t.key, this.dn(i), s));
  8250. } else n = n.add(new kr(e.indexId, t.key, Hr, s));
  8251. return n;
  8252. }
  8253. /**
  8254. * Updates the index entries for the provided document by deleting entries
  8255. * that are no longer referenced in `newEntries` and adding all newly added
  8256. * entries.
  8257. */ vn(t, e, n, s, i) {
  8258. N("IndexedDbIndexManager", "Updating index entries for document '%s'", e.key);
  8259. const r = [];
  8260. return function(t, e, n, s, i) {
  8261. const r = t.getIterator(), o = e.getIterator();
  8262. let u = ve(r), c = ve(o);
  8263. // Walk through the two sets at the same time, using the ordering defined by
  8264. // `comparator`.
  8265. for (;u || c; ) {
  8266. let t = !1, e = !1;
  8267. if (u && c) {
  8268. const s = n(u, c);
  8269. s < 0 ?
  8270. // The element was removed if the next element in our ordered
  8271. // walkthrough is only in `before`.
  8272. e = !0 : s > 0 && (
  8273. // The element was added if the next element in our ordered walkthrough
  8274. // is only in `after`.
  8275. t = !0);
  8276. } else null != u ? e = !0 : t = !0;
  8277. t ? (s(c), c = ve(o)) : e ? (i(u), u = ve(r)) : (u = ve(r), c = ve(o));
  8278. }
  8279. }(s, i, Mr, (
  8280. /* onAdd= */ s => {
  8281. r.push(this.Rn(t, e, n, s));
  8282. }), (
  8283. /* onRemove= */ s => {
  8284. r.push(this.Pn(t, e, n, s));
  8285. })), Rt.waitFor(r);
  8286. }
  8287. Tn(t) {
  8288. let e = 1;
  8289. return to(t).X({
  8290. index: "sequenceNumberIndex",
  8291. reverse: !0,
  8292. range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])
  8293. }, ((t, n, s) => {
  8294. s.done(), e = n.sequenceNumber + 1;
  8295. })).next((() => e));
  8296. }
  8297. /**
  8298. * Returns a new set of IDB ranges that splits the existing range and excludes
  8299. * any values that match the `notInValue` from these ranges. As an example,
  8300. * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.
  8301. */ createRange(t, e, n) {
  8302. // The notIn values need to be sorted and unique so that we can return a
  8303. // sorted set of non-overlapping ranges.
  8304. n = n.sort(((t, e) => Mr(t, e))).filter(((t, e, n) => !e || 0 !== Mr(t, n[e - 1])));
  8305. const s = [];
  8306. s.push(t);
  8307. for (const i of n) {
  8308. const n = Mr(i, t), r = Mr(i, e);
  8309. if (0 === n)
  8310. // `notInValue` is the lower bound. We therefore need to raise the bound
  8311. // to the next value.
  8312. s[0] = t.Je(); else if (n > 0 && r < 0)
  8313. // `notInValue` is in the middle of the range
  8314. s.push(i), s.push(i.Je()); else if (r > 0)
  8315. // `notInValue` (and all following values) are out of the range
  8316. break;
  8317. }
  8318. s.push(e);
  8319. const i = [];
  8320. for (let t = 0; t < s.length; t += 2) {
  8321. // If we encounter two bounds that will create an unmatchable key range,
  8322. // then we return an empty set of key ranges.
  8323. if (this.bn(s[t], s[t + 1])) return [];
  8324. const e = [ s[t].indexId, this.uid, s[t].arrayValue, s[t].directionalValue, Hr, [] ], n = [ s[t + 1].indexId, this.uid, s[t + 1].arrayValue, s[t + 1].directionalValue, Hr, [] ];
  8325. i.push(IDBKeyRange.bound(e, n));
  8326. }
  8327. return i;
  8328. }
  8329. bn(t, e) {
  8330. // If lower bound is greater than the upper bound, then the key
  8331. // range can never be matched.
  8332. return Mr(t, e) > 0;
  8333. }
  8334. getMinOffsetFromCollectionGroup(t, e) {
  8335. return this.getFieldIndexes(t, e).next(eo);
  8336. }
  8337. getMinOffset(t, e) {
  8338. return Rt.mapArray(this.cn(e), (e => this.an(t, e).next((t => t || O())))).next(eo);
  8339. }
  8340. }
  8341. /**
  8342. * Helper to get a typed SimpleDbStore for the collectionParents
  8343. * document store.
  8344. */ function Yr(t) {
  8345. return _e(t, "collectionParents");
  8346. }
  8347. /**
  8348. * Helper to get a typed SimpleDbStore for the index entry object store.
  8349. */ function Xr(t) {
  8350. return _e(t, "indexEntries");
  8351. }
  8352. /**
  8353. * Helper to get a typed SimpleDbStore for the index configuration object store.
  8354. */ function Zr(t) {
  8355. return _e(t, "indexConfiguration");
  8356. }
  8357. /**
  8358. * Helper to get a typed SimpleDbStore for the index state object store.
  8359. */ function to(t) {
  8360. return _e(t, "indexState");
  8361. }
  8362. function eo(t) {
  8363. F(0 !== t.length);
  8364. let e = t[0].indexState.offset, n = e.largestBatchId;
  8365. for (let s = 1; s < t.length; s++) {
  8366. const i = t[s].indexState.offset;
  8367. Tt(i, e) < 0 && (e = i), n < i.largestBatchId && (n = i.largestBatchId);
  8368. }
  8369. return new It(e.readTime, e.documentKey, n);
  8370. }
  8371. /**
  8372. * @license
  8373. * Copyright 2018 Google LLC
  8374. *
  8375. * Licensed under the Apache License, Version 2.0 (the "License");
  8376. * you may not use this file except in compliance with the License.
  8377. * You may obtain a copy of the License at
  8378. *
  8379. * http://www.apache.org/licenses/LICENSE-2.0
  8380. *
  8381. * Unless required by applicable law or agreed to in writing, software
  8382. * distributed under the License is distributed on an "AS IS" BASIS,
  8383. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8384. * See the License for the specific language governing permissions and
  8385. * limitations under the License.
  8386. */ const no = {
  8387. didRun: !1,
  8388. sequenceNumbersCollected: 0,
  8389. targetsRemoved: 0,
  8390. documentsRemoved: 0
  8391. };
  8392. class so {
  8393. constructor(
  8394. // When we attempt to collect, we will only do so if the cache size is greater than this
  8395. // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.
  8396. t,
  8397. // The percentage of sequence numbers that we will attempt to collect
  8398. e,
  8399. // A cap on the total number of sequence numbers that will be collected. This prevents
  8400. // us from collecting a huge number of sequence numbers if the cache has grown very large.
  8401. n) {
  8402. this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;
  8403. }
  8404. static withCacheSize(t) {
  8405. return new so(t, so.DEFAULT_COLLECTION_PERCENTILE, so.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);
  8406. }
  8407. }
  8408. /**
  8409. * @license
  8410. * Copyright 2020 Google LLC
  8411. *
  8412. * Licensed under the Apache License, Version 2.0 (the "License");
  8413. * you may not use this file except in compliance with the License.
  8414. * You may obtain a copy of the License at
  8415. *
  8416. * http://www.apache.org/licenses/LICENSE-2.0
  8417. *
  8418. * Unless required by applicable law or agreed to in writing, software
  8419. * distributed under the License is distributed on an "AS IS" BASIS,
  8420. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8421. * See the License for the specific language governing permissions and
  8422. * limitations under the License.
  8423. */
  8424. /**
  8425. * Delete a mutation batch and the associated document mutations.
  8426. * @returns A PersistencePromise of the document mutations that were removed.
  8427. */
  8428. function io(t, e, n) {
  8429. const s = t.store("mutations"), i = t.store("documentMutations"), r = [], o = IDBKeyRange.only(n.batchId);
  8430. let u = 0;
  8431. const c = s.X({
  8432. range: o
  8433. }, ((t, e, n) => (u++, n.delete())));
  8434. r.push(c.next((() => {
  8435. F(1 === u);
  8436. })));
  8437. const a = [];
  8438. for (const t of n.mutations) {
  8439. const s = zt(e, t.key.path, n.batchId);
  8440. r.push(i.delete(s)), a.push(t.key);
  8441. }
  8442. return Rt.waitFor(r).next((() => a));
  8443. }
  8444. /**
  8445. * Returns an approximate size for the given document.
  8446. */ function ro(t) {
  8447. if (!t) return 0;
  8448. let e;
  8449. if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {
  8450. if (!t.noDocument) throw O();
  8451. e = t.noDocument;
  8452. }
  8453. return JSON.stringify(e).length;
  8454. }
  8455. /**
  8456. * @license
  8457. * Copyright 2017 Google LLC
  8458. *
  8459. * Licensed under the Apache License, Version 2.0 (the "License");
  8460. * you may not use this file except in compliance with the License.
  8461. * You may obtain a copy of the License at
  8462. *
  8463. * http://www.apache.org/licenses/LICENSE-2.0
  8464. *
  8465. * Unless required by applicable law or agreed to in writing, software
  8466. * distributed under the License is distributed on an "AS IS" BASIS,
  8467. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8468. * See the License for the specific language governing permissions and
  8469. * limitations under the License.
  8470. */
  8471. /** A mutation queue for a specific user, backed by IndexedDB. */ so.DEFAULT_COLLECTION_PERCENTILE = 10,
  8472. so.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, so.DEFAULT = new so(41943040, so.DEFAULT_COLLECTION_PERCENTILE, so.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),
  8473. so.DISABLED = new so(-1, 0, 0);
  8474. class oo {
  8475. constructor(
  8476. /**
  8477. * The normalized userId (e.g. null UID => "" userId) used to store /
  8478. * retrieve mutations.
  8479. */
  8480. t, e, n, s) {
  8481. this.userId = t, this.serializer = e, this.indexManager = n, this.referenceDelegate = s,
  8482. /**
  8483. * Caches the document keys for pending mutation batches. If the mutation
  8484. * has been removed from IndexedDb, the cached value may continue to
  8485. * be used to retrieve the batch's document keys. To remove a cached value
  8486. * locally, `removeCachedMutationKeys()` should be invoked either directly
  8487. * or through `removeMutationBatches()`.
  8488. *
  8489. * With multi-tab, when the primary client acknowledges or rejects a mutation,
  8490. * this cache is used by secondary clients to invalidate the local
  8491. * view of the documents that were previously affected by the mutation.
  8492. */
  8493. // PORTING NOTE: Multi-tab only.
  8494. this.Vn = {};
  8495. }
  8496. /**
  8497. * Creates a new mutation queue for the given user.
  8498. * @param user - The user for which to create a mutation queue.
  8499. * @param serializer - The serializer to use when persisting to IndexedDb.
  8500. */ static de(t, e, n, s) {
  8501. // TODO(mcg): Figure out what constraints there are on userIDs
  8502. // In particular, are there any reserved characters? are empty ids allowed?
  8503. // For the moment store these together in the same mutations table assuming
  8504. // that empty userIDs aren't allowed.
  8505. F("" !== t.uid);
  8506. const i = t.isAuthenticated() ? t.uid : "";
  8507. return new oo(i, e, n, s);
  8508. }
  8509. checkEmpty(t) {
  8510. let e = !0;
  8511. const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8512. return co(t).X({
  8513. index: "userMutationsIndex",
  8514. range: n
  8515. }, ((t, n, s) => {
  8516. e = !1, s.done();
  8517. })).next((() => e));
  8518. }
  8519. addMutationBatch(t, e, n, s) {
  8520. const i = ao(t), r = co(t);
  8521. // The IndexedDb implementation in Chrome (and Firefox) does not handle
  8522. // compound indices that include auto-generated keys correctly. To ensure
  8523. // that the index entry is added correctly in all browsers, we perform two
  8524. // writes: The first write is used to retrieve the next auto-generated Batch
  8525. // ID, and the second write populates the index and stores the actual
  8526. // mutation batch.
  8527. // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972
  8528. // We write an empty object to obtain key
  8529. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8530. return r.add({}).next((o => {
  8531. F("number" == typeof o);
  8532. const u = new Zs(o, e, n, s), c = function(t, e, n) {
  8533. const s = n.baseMutations.map((e => ji(t.fe, e))), i = n.mutations.map((e => ji(t.fe, e)));
  8534. return {
  8535. userId: e,
  8536. batchId: n.batchId,
  8537. localWriteTimeMs: n.localWriteTime.toMillis(),
  8538. baseMutations: s,
  8539. mutations: i
  8540. };
  8541. }(this.serializer, this.userId, u), a = [];
  8542. let h = new Ee(((t, e) => et(t.canonicalString(), e.canonicalString())));
  8543. for (const t of s) {
  8544. const e = zt(this.userId, t.key.path, o);
  8545. h = h.add(t.key.path.popLast()), a.push(r.put(c)), a.push(i.put(e, Wt));
  8546. }
  8547. return h.forEach((e => {
  8548. a.push(this.indexManager.addToCollectionParentIndex(t, e));
  8549. })), t.addOnCommittedListener((() => {
  8550. this.Vn[o] = u.keys();
  8551. })), Rt.waitFor(a).next((() => u));
  8552. }));
  8553. }
  8554. lookupMutationBatch(t, e) {
  8555. return co(t).get(e).next((t => t ? (F(t.userId === this.userId), _r(this.serializer, t)) : null));
  8556. }
  8557. /**
  8558. * Returns the document keys for the mutation batch with the given batchId.
  8559. * For primary clients, this method returns `null` after
  8560. * `removeMutationBatches()` has been called. Secondary clients return a
  8561. * cached result until `removeCachedMutationKeys()` is invoked.
  8562. */
  8563. // PORTING NOTE: Multi-tab only.
  8564. Sn(t, e) {
  8565. return this.Vn[e] ? Rt.resolve(this.Vn[e]) : this.lookupMutationBatch(t, e).next((t => {
  8566. if (t) {
  8567. const n = t.keys();
  8568. return this.Vn[e] = n, n;
  8569. }
  8570. return null;
  8571. }));
  8572. }
  8573. getNextMutationBatchAfterBatchId(t, e) {
  8574. const n = e + 1, s = IDBKeyRange.lowerBound([ this.userId, n ]);
  8575. let i = null;
  8576. return co(t).X({
  8577. index: "userMutationsIndex",
  8578. range: s
  8579. }, ((t, e, s) => {
  8580. e.userId === this.userId && (F(e.batchId >= n), i = _r(this.serializer, e)), s.done();
  8581. })).next((() => i));
  8582. }
  8583. getHighestUnacknowledgedBatchId(t) {
  8584. const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);
  8585. let n = -1;
  8586. return co(t).X({
  8587. index: "userMutationsIndex",
  8588. range: e,
  8589. reverse: !0
  8590. }, ((t, e, s) => {
  8591. n = e.batchId, s.done();
  8592. })).next((() => n));
  8593. }
  8594. getAllMutationBatches(t) {
  8595. const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8596. return co(t).j("userMutationsIndex", e).next((t => t.map((t => _r(this.serializer, t)))));
  8597. }
  8598. getAllMutationBatchesAffectingDocumentKey(t, e) {
  8599. // Scan the document-mutation index starting with a prefix starting with
  8600. // the given documentKey.
  8601. const n = jt(this.userId, e.path), s = IDBKeyRange.lowerBound(n), i = [];
  8602. return ao(t).X({
  8603. range: s
  8604. }, ((n, s, r) => {
  8605. const [o, u, c] = n, a = Gt(u);
  8606. // Only consider rows matching exactly the specific key of
  8607. // interest. Note that because we order by path first, and we
  8608. // order terminators before path separators, we'll encounter all
  8609. // the index rows for documentKey contiguously. In particular, all
  8610. // the rows for documentKey will occur before any rows for
  8611. // documents nested in a subcollection beneath documentKey so we
  8612. // can stop as soon as we hit any such row.
  8613. if (o === this.userId && e.path.isEqual(a))
  8614. // Look up the mutation batch in the store.
  8615. return co(t).get(c).next((t => {
  8616. if (!t) throw O();
  8617. F(t.userId === this.userId), i.push(_r(this.serializer, t));
  8618. }));
  8619. r.done();
  8620. })).next((() => i));
  8621. }
  8622. getAllMutationBatchesAffectingDocumentKeys(t, e) {
  8623. let n = new Ee(et);
  8624. const s = [];
  8625. return e.forEach((e => {
  8626. const i = jt(this.userId, e.path), r = IDBKeyRange.lowerBound(i), o = ao(t).X({
  8627. range: r
  8628. }, ((t, s, i) => {
  8629. const [r, o, u] = t, c = Gt(o);
  8630. // Only consider rows matching exactly the specific key of
  8631. // interest. Note that because we order by path first, and we
  8632. // order terminators before path separators, we'll encounter all
  8633. // the index rows for documentKey contiguously. In particular, all
  8634. // the rows for documentKey will occur before any rows for
  8635. // documents nested in a subcollection beneath documentKey so we
  8636. // can stop as soon as we hit any such row.
  8637. r === this.userId && e.path.isEqual(c) ? n = n.add(u) : i.done();
  8638. }));
  8639. s.push(o);
  8640. })), Rt.waitFor(s).next((() => this.Dn(t, n)));
  8641. }
  8642. getAllMutationBatchesAffectingQuery(t, e) {
  8643. const n = e.path, s = n.length + 1, i = jt(this.userId, n), r = IDBKeyRange.lowerBound(i);
  8644. // Collect up unique batchIDs encountered during a scan of the index. Use a
  8645. // SortedSet to accumulate batch IDs so they can be traversed in order in a
  8646. // scan of the main table.
  8647. let o = new Ee(et);
  8648. return ao(t).X({
  8649. range: r
  8650. }, ((t, e, i) => {
  8651. const [r, u, c] = t, a = Gt(u);
  8652. r === this.userId && n.isPrefixOf(a) ?
  8653. // Rows with document keys more than one segment longer than the
  8654. // query path can't be matches. For example, a query on 'rooms'
  8655. // can't match the document /rooms/abc/messages/xyx.
  8656. // TODO(mcg): we'll need a different scanner when we implement
  8657. // ancestor queries.
  8658. a.length === s && (o = o.add(c)) : i.done();
  8659. })).next((() => this.Dn(t, o)));
  8660. }
  8661. Dn(t, e) {
  8662. const n = [], s = [];
  8663. // TODO(rockwood): Implement this using iterate.
  8664. return e.forEach((e => {
  8665. s.push(co(t).get(e).next((t => {
  8666. if (null === t) throw O();
  8667. F(t.userId === this.userId), n.push(_r(this.serializer, t));
  8668. })));
  8669. })), Rt.waitFor(s).next((() => n));
  8670. }
  8671. removeMutationBatch(t, e) {
  8672. return io(t.ht, this.userId, e).next((n => (t.addOnCommittedListener((() => {
  8673. this.Cn(e.batchId);
  8674. })), Rt.forEach(n, (e => this.referenceDelegate.markPotentiallyOrphaned(t, e))))));
  8675. }
  8676. /**
  8677. * Clears the cached keys for a mutation batch. This method should be
  8678. * called by secondary clients after they process mutation updates.
  8679. *
  8680. * Note that this method does not have to be called from primary clients as
  8681. * the corresponding cache entries are cleared when an acknowledged or
  8682. * rejected batch is removed from the mutation queue.
  8683. */
  8684. // PORTING NOTE: Multi-tab only
  8685. Cn(t) {
  8686. delete this.Vn[t];
  8687. }
  8688. performConsistencyCheck(t) {
  8689. return this.checkEmpty(t).next((e => {
  8690. if (!e) return Rt.resolve();
  8691. // Verify that there are no entries in the documentMutations index if
  8692. // the queue is empty.
  8693. const n = IDBKeyRange.lowerBound([ this.userId ]);
  8694. const s = [];
  8695. return ao(t).X({
  8696. range: n
  8697. }, ((t, e, n) => {
  8698. if (t[0] === this.userId) {
  8699. const e = Gt(t[1]);
  8700. s.push(e);
  8701. } else n.done();
  8702. })).next((() => {
  8703. F(0 === s.length);
  8704. }));
  8705. }));
  8706. }
  8707. containsKey(t, e) {
  8708. return uo(t, this.userId, e);
  8709. }
  8710. // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
  8711. /** Returns the mutation queue's metadata from IndexedDb. */
  8712. xn(t) {
  8713. return ho(t).get(this.userId).next((t => t || {
  8714. userId: this.userId,
  8715. lastAcknowledgedBatchId: -1,
  8716. lastStreamToken: ""
  8717. }));
  8718. }
  8719. }
  8720. /**
  8721. * @returns true if the mutation queue for the given user contains a pending
  8722. * mutation for the given key.
  8723. */ function uo(t, e, n) {
  8724. const s = jt(e, n.path), i = s[1], r = IDBKeyRange.lowerBound(s);
  8725. let o = !1;
  8726. return ao(t).X({
  8727. range: r,
  8728. Y: !0
  8729. }, ((t, n, s) => {
  8730. const [r, u, /*batchID*/ c] = t;
  8731. r === e && u === i && (o = !0), s.done();
  8732. })).next((() => o));
  8733. }
  8734. /** Returns true if any mutation queue contains the given document. */
  8735. /**
  8736. * Helper to get a typed SimpleDbStore for the mutations object store.
  8737. */
  8738. function co(t) {
  8739. return _e(t, "mutations");
  8740. }
  8741. /**
  8742. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8743. */ function ao(t) {
  8744. return _e(t, "documentMutations");
  8745. }
  8746. /**
  8747. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8748. */ function ho(t) {
  8749. return _e(t, "mutationQueues");
  8750. }
  8751. /**
  8752. * @license
  8753. * Copyright 2017 Google LLC
  8754. *
  8755. * Licensed under the Apache License, Version 2.0 (the "License");
  8756. * you may not use this file except in compliance with the License.
  8757. * You may obtain a copy of the License at
  8758. *
  8759. * http://www.apache.org/licenses/LICENSE-2.0
  8760. *
  8761. * Unless required by applicable law or agreed to in writing, software
  8762. * distributed under the License is distributed on an "AS IS" BASIS,
  8763. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8764. * See the License for the specific language governing permissions and
  8765. * limitations under the License.
  8766. */
  8767. /** Offset to ensure non-overlapping target ids. */
  8768. /**
  8769. * Generates monotonically increasing target IDs for sending targets to the
  8770. * watch stream.
  8771. *
  8772. * The client constructs two generators, one for the target cache, and one for
  8773. * for the sync engine (to generate limbo documents targets). These
  8774. * generators produce non-overlapping IDs (by using even and odd IDs
  8775. * respectively).
  8776. *
  8777. * By separating the target ID space, the query cache can generate target IDs
  8778. * that persist across client restarts, while sync engine can independently
  8779. * generate in-memory target IDs that are transient and can be reused after a
  8780. * restart.
  8781. */
  8782. class lo {
  8783. constructor(t) {
  8784. this.Nn = t;
  8785. }
  8786. next() {
  8787. return this.Nn += 2, this.Nn;
  8788. }
  8789. static kn() {
  8790. // The target cache generator must return '2' in its first call to `next()`
  8791. // as there is no differentiation in the protocol layer between an unset
  8792. // number and the number '0'. If we were to sent a target with target ID
  8793. // '0', the backend would consider it unset and replace it with its own ID.
  8794. return new lo(0);
  8795. }
  8796. static Mn() {
  8797. // Sync engine assigns target IDs for limbo document detection.
  8798. return new lo(-1);
  8799. }
  8800. }
  8801. /**
  8802. * @license
  8803. * Copyright 2017 Google LLC
  8804. *
  8805. * Licensed under the Apache License, Version 2.0 (the "License");
  8806. * you may not use this file except in compliance with the License.
  8807. * You may obtain a copy of the License at
  8808. *
  8809. * http://www.apache.org/licenses/LICENSE-2.0
  8810. *
  8811. * Unless required by applicable law or agreed to in writing, software
  8812. * distributed under the License is distributed on an "AS IS" BASIS,
  8813. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8814. * See the License for the specific language governing permissions and
  8815. * limitations under the License.
  8816. */ class fo {
  8817. constructor(t, e) {
  8818. this.referenceDelegate = t, this.serializer = e;
  8819. }
  8820. // PORTING NOTE: We don't cache global metadata for the target cache, since
  8821. // some of it (in particular `highestTargetId`) can be modified by secondary
  8822. // tabs. We could perhaps be more granular (and e.g. still cache
  8823. // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go
  8824. // to IndexedDb whenever we need to read metadata. We can revisit if it turns
  8825. // out to have a meaningful performance impact.
  8826. allocateTargetId(t) {
  8827. return this.$n(t).next((e => {
  8828. const n = new lo(e.highestTargetId);
  8829. return e.highestTargetId = n.next(), this.On(t, e).next((() => e.highestTargetId));
  8830. }));
  8831. }
  8832. getLastRemoteSnapshotVersion(t) {
  8833. return this.$n(t).next((t => rt.fromTimestamp(new it(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds))));
  8834. }
  8835. getHighestSequenceNumber(t) {
  8836. return this.$n(t).next((t => t.highestListenSequenceNumber));
  8837. }
  8838. setTargetsMetadata(t, e, n) {
  8839. return this.$n(t).next((s => (s.highestListenSequenceNumber = e, n && (s.lastRemoteSnapshotVersion = n.toTimestamp()),
  8840. e > s.highestListenSequenceNumber && (s.highestListenSequenceNumber = e), this.On(t, s))));
  8841. }
  8842. addTargetData(t, e) {
  8843. return this.Fn(t, e).next((() => this.$n(t).next((n => (n.targetCount += 1, this.Bn(e, n),
  8844. this.On(t, n))))));
  8845. }
  8846. updateTargetData(t, e) {
  8847. return this.Fn(t, e);
  8848. }
  8849. removeTargetData(t, e) {
  8850. return this.removeMatchingKeysForTargetId(t, e.targetId).next((() => wo(t).delete(e.targetId))).next((() => this.$n(t))).next((e => (F(e.targetCount > 0),
  8851. e.targetCount -= 1, this.On(t, e))));
  8852. }
  8853. /**
  8854. * Drops any targets with sequence number less than or equal to the upper bound, excepting those
  8855. * present in `activeTargetIds`. Document associations for the removed targets are also removed.
  8856. * Returns the number of targets removed.
  8857. */ removeTargets(t, e, n) {
  8858. let s = 0;
  8859. const i = [];
  8860. return wo(t).X(((r, o) => {
  8861. const u = mr(o);
  8862. u.sequenceNumber <= e && null === n.get(u.targetId) && (s++, i.push(this.removeTargetData(t, u)));
  8863. })).next((() => Rt.waitFor(i))).next((() => s));
  8864. }
  8865. /**
  8866. * Call provided function with each `TargetData` that we have cached.
  8867. */ forEachTarget(t, e) {
  8868. return wo(t).X(((t, n) => {
  8869. const s = mr(n);
  8870. e(s);
  8871. }));
  8872. }
  8873. $n(t) {
  8874. return _o(t).get("targetGlobalKey").next((t => (F(null !== t), t)));
  8875. }
  8876. On(t, e) {
  8877. return _o(t).put("targetGlobalKey", e);
  8878. }
  8879. Fn(t, e) {
  8880. return wo(t).put(gr(this.serializer, e));
  8881. }
  8882. /**
  8883. * In-place updates the provided metadata to account for values in the given
  8884. * TargetData. Saving is done separately. Returns true if there were any
  8885. * changes to the metadata.
  8886. */ Bn(t, e) {
  8887. let n = !1;
  8888. return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0),
  8889. t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber,
  8890. n = !0), n;
  8891. }
  8892. getTargetCount(t) {
  8893. return this.$n(t).next((t => t.targetCount));
  8894. }
  8895. getTargetData(t, e) {
  8896. // Iterating by the canonicalId may yield more than one result because
  8897. // canonicalId values are not required to be unique per target. This query
  8898. // depends on the queryTargets index to be efficient.
  8899. const n = $n(e), s = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);
  8900. let i = null;
  8901. return wo(t).X({
  8902. range: s,
  8903. index: "queryTargetsIndex"
  8904. }, ((t, n, s) => {
  8905. const r = mr(n);
  8906. // After finding a potential match, check that the target is
  8907. // actually equal to the requested target.
  8908. On(e, r.target) && (i = r, s.done());
  8909. })).next((() => i));
  8910. }
  8911. addMatchingKeys(t, e, n) {
  8912. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8913. // IndexedDb.
  8914. const s = [], i = mo(t);
  8915. return e.forEach((e => {
  8916. const r = qt(e.path);
  8917. s.push(i.put({
  8918. targetId: n,
  8919. path: r
  8920. })), s.push(this.referenceDelegate.addReference(t, n, e));
  8921. })), Rt.waitFor(s);
  8922. }
  8923. removeMatchingKeys(t, e, n) {
  8924. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8925. // IndexedDb.
  8926. const s = mo(t);
  8927. return Rt.forEach(e, (e => {
  8928. const i = qt(e.path);
  8929. return Rt.waitFor([ s.delete([ n, i ]), this.referenceDelegate.removeReference(t, n, e) ]);
  8930. }));
  8931. }
  8932. removeMatchingKeysForTargetId(t, e) {
  8933. const n = mo(t), s = IDBKeyRange.bound([ e ], [ e + 1 ],
  8934. /*lowerOpen=*/ !1,
  8935. /*upperOpen=*/ !0);
  8936. return n.delete(s);
  8937. }
  8938. getMatchingKeysForTargetId(t, e) {
  8939. const n = IDBKeyRange.bound([ e ], [ e + 1 ],
  8940. /*lowerOpen=*/ !1,
  8941. /*upperOpen=*/ !0), s = mo(t);
  8942. let i = gs();
  8943. return s.X({
  8944. range: n,
  8945. Y: !0
  8946. }, ((t, e, n) => {
  8947. const s = Gt(t[1]), r = new ht(s);
  8948. i = i.add(r);
  8949. })).next((() => i));
  8950. }
  8951. containsKey(t, e) {
  8952. const n = qt(e.path), s = IDBKeyRange.bound([ n ], [ st(n) ],
  8953. /*lowerOpen=*/ !1,
  8954. /*upperOpen=*/ !0);
  8955. let i = 0;
  8956. return mo(t).X({
  8957. index: "documentTargetsIndex",
  8958. Y: !0,
  8959. range: s
  8960. }, (([t, e], n, s) => {
  8961. // Having a sentinel row for a document does not count as containing that document;
  8962. // For the target cache, containing the document means the document is part of some
  8963. // target.
  8964. 0 !== t && (i++, s.done());
  8965. })).next((() => i > 0));
  8966. }
  8967. /**
  8968. * Looks up a TargetData entry by target ID.
  8969. *
  8970. * @param targetId - The target ID of the TargetData entry to look up.
  8971. * @returns The cached TargetData entry, or null if the cache has no entry for
  8972. * the target.
  8973. */
  8974. // PORTING NOTE: Multi-tab only.
  8975. le(t, e) {
  8976. return wo(t).get(e).next((t => t ? mr(t) : null));
  8977. }
  8978. }
  8979. /**
  8980. * Helper to get a typed SimpleDbStore for the queries object store.
  8981. */ function wo(t) {
  8982. return _e(t, "targets");
  8983. }
  8984. /**
  8985. * Helper to get a typed SimpleDbStore for the target globals object store.
  8986. */ function _o(t) {
  8987. return _e(t, "targetGlobal");
  8988. }
  8989. /**
  8990. * Helper to get a typed SimpleDbStore for the document target object store.
  8991. */ function mo(t) {
  8992. return _e(t, "targetDocuments");
  8993. }
  8994. /**
  8995. * @license
  8996. * Copyright 2020 Google LLC
  8997. *
  8998. * Licensed under the Apache License, Version 2.0 (the "License");
  8999. * you may not use this file except in compliance with the License.
  9000. * You may obtain a copy of the License at
  9001. *
  9002. * http://www.apache.org/licenses/LICENSE-2.0
  9003. *
  9004. * Unless required by applicable law or agreed to in writing, software
  9005. * distributed under the License is distributed on an "AS IS" BASIS,
  9006. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9007. * See the License for the specific language governing permissions and
  9008. * limitations under the License.
  9009. */ function go([t, e], [n, s]) {
  9010. const i = et(t, n);
  9011. return 0 === i ? et(e, s) : i;
  9012. }
  9013. /**
  9014. * Used to calculate the nth sequence number. Keeps a rolling buffer of the
  9015. * lowest n values passed to `addElement`, and finally reports the largest of
  9016. * them in `maxValue`.
  9017. */ class yo {
  9018. constructor(t) {
  9019. this.Ln = t, this.buffer = new Ee(go), this.qn = 0;
  9020. }
  9021. Un() {
  9022. return ++this.qn;
  9023. }
  9024. Kn(t) {
  9025. const e = [ t, this.Un() ];
  9026. if (this.buffer.size < this.Ln) this.buffer = this.buffer.add(e); else {
  9027. const t = this.buffer.last();
  9028. go(e, t) < 0 && (this.buffer = this.buffer.delete(t).add(e));
  9029. }
  9030. }
  9031. get maxValue() {
  9032. // Guaranteed to be non-empty. If we decide we are not collecting any
  9033. // sequence numbers, nthSequenceNumber below short-circuits. If we have
  9034. // decided that we are collecting n sequence numbers, it's because n is some
  9035. // percentage of the existing sequence numbers. That means we should never
  9036. // be in a situation where we are collecting sequence numbers but don't
  9037. // actually have any.
  9038. return this.buffer.last()[0];
  9039. }
  9040. }
  9041. /**
  9042. * This class is responsible for the scheduling of LRU garbage collection. It handles checking
  9043. * whether or not GC is enabled, as well as which delay to use before the next run.
  9044. */ class po {
  9045. constructor(t, e, n) {
  9046. this.garbageCollector = t, this.asyncQueue = e, this.localStore = n, this.Gn = null;
  9047. }
  9048. start() {
  9049. -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Qn(6e4);
  9050. }
  9051. stop() {
  9052. this.Gn && (this.Gn.cancel(), this.Gn = null);
  9053. }
  9054. get started() {
  9055. return null !== this.Gn;
  9056. }
  9057. Qn(t) {
  9058. N("LruGarbageCollector", `Garbage collection scheduled in ${t}ms`), this.Gn = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */ , t, (async () => {
  9059. this.Gn = null;
  9060. try {
  9061. await this.localStore.collectGarbage(this.garbageCollector);
  9062. } catch (t) {
  9063. Dt(t) ? N("LruGarbageCollector", "Ignoring IndexedDB error during garbage collection: ", t) : await vt(t);
  9064. }
  9065. await this.Qn(3e5);
  9066. }));
  9067. }
  9068. }
  9069. /**
  9070. * Implements the steps for LRU garbage collection.
  9071. */ class Io {
  9072. constructor(t, e) {
  9073. this.jn = t, this.params = e;
  9074. }
  9075. calculateTargetCount(t, e) {
  9076. return this.jn.zn(t).next((t => Math.floor(e / 100 * t)));
  9077. }
  9078. nthSequenceNumber(t, e) {
  9079. if (0 === e) return Rt.resolve(Ot.ct);
  9080. const n = new yo(e);
  9081. return this.jn.forEachTarget(t, (t => n.Kn(t.sequenceNumber))).next((() => this.jn.Wn(t, (t => n.Kn(t))))).next((() => n.maxValue));
  9082. }
  9083. removeTargets(t, e, n) {
  9084. return this.jn.removeTargets(t, e, n);
  9085. }
  9086. removeOrphanedDocuments(t, e) {
  9087. return this.jn.removeOrphanedDocuments(t, e);
  9088. }
  9089. collect(t, e) {
  9090. return -1 === this.params.cacheSizeCollectionThreshold ? (N("LruGarbageCollector", "Garbage collection skipped; disabled"),
  9091. Rt.resolve(no)) : this.getCacheSize(t).next((n => n < this.params.cacheSizeCollectionThreshold ? (N("LruGarbageCollector", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),
  9092. no) : this.Hn(t, e)));
  9093. }
  9094. getCacheSize(t) {
  9095. return this.jn.getCacheSize(t);
  9096. }
  9097. Hn(t, e) {
  9098. let n, s, i, r, o, c, a;
  9099. const h = Date.now();
  9100. return this.calculateTargetCount(t, this.params.percentileToCollect).next((e => (
  9101. // Cap at the configured max
  9102. e > this.params.maximumSequenceNumbersToCollect ? (N("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),
  9103. s = this.params.maximumSequenceNumbersToCollect) : s = e, r = Date.now(), this.nthSequenceNumber(t, s)))).next((s => (n = s,
  9104. o = Date.now(), this.removeTargets(t, n, e)))).next((e => (i = e, c = Date.now(),
  9105. this.removeOrphanedDocuments(t, n)))).next((t => {
  9106. if (a = Date.now(), C() <= logger.LogLevel.DEBUG) {
  9107. N("LruGarbageCollector", `LRU Garbage Collection\n\tCounted targets in ${r - h}ms\n\tDetermined least recently used ${s} in ` + (o - r) + "ms\n" + `\tRemoved ${i} targets in ` + (c - o) + "ms\n" + `\tRemoved ${t} documents in ` + (a - c) + "ms\n" + `Total Duration: ${a - h}ms`);
  9108. }
  9109. return Rt.resolve({
  9110. didRun: !0,
  9111. sequenceNumbersCollected: s,
  9112. targetsRemoved: i,
  9113. documentsRemoved: t
  9114. });
  9115. }));
  9116. }
  9117. }
  9118. function To(t, e) {
  9119. return new Io(t, e);
  9120. }
  9121. /**
  9122. * @license
  9123. * Copyright 2020 Google LLC
  9124. *
  9125. * Licensed under the Apache License, Version 2.0 (the "License");
  9126. * you may not use this file except in compliance with the License.
  9127. * You may obtain a copy of the License at
  9128. *
  9129. * http://www.apache.org/licenses/LICENSE-2.0
  9130. *
  9131. * Unless required by applicable law or agreed to in writing, software
  9132. * distributed under the License is distributed on an "AS IS" BASIS,
  9133. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9134. * See the License for the specific language governing permissions and
  9135. * limitations under the License.
  9136. */
  9137. /** Provides LRU functionality for IndexedDB persistence. */ class Eo {
  9138. constructor(t, e) {
  9139. this.db = t, this.garbageCollector = To(this, e);
  9140. }
  9141. zn(t) {
  9142. const e = this.Jn(t);
  9143. return this.db.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));
  9144. }
  9145. Jn(t) {
  9146. let e = 0;
  9147. return this.Wn(t, (t => {
  9148. e++;
  9149. })).next((() => e));
  9150. }
  9151. forEachTarget(t, e) {
  9152. return this.db.getTargetCache().forEachTarget(t, e);
  9153. }
  9154. Wn(t, e) {
  9155. return this.Yn(t, ((t, n) => e(n)));
  9156. }
  9157. addReference(t, e, n) {
  9158. return Ao(t, n);
  9159. }
  9160. removeReference(t, e, n) {
  9161. return Ao(t, n);
  9162. }
  9163. removeTargets(t, e, n) {
  9164. return this.db.getTargetCache().removeTargets(t, e, n);
  9165. }
  9166. markPotentiallyOrphaned(t, e) {
  9167. return Ao(t, e);
  9168. }
  9169. /**
  9170. * Returns true if anything would prevent this document from being garbage
  9171. * collected, given that the document in question is not present in any
  9172. * targets and has a sequence number less than or equal to the upper bound for
  9173. * the collection run.
  9174. */ Xn(t, e) {
  9175. return function(t, e) {
  9176. let n = !1;
  9177. return ho(t).Z((s => uo(t, s, e).next((t => (t && (n = !0), Rt.resolve(!t)))))).next((() => n));
  9178. }(t, e);
  9179. }
  9180. removeOrphanedDocuments(t, e) {
  9181. const n = this.db.getRemoteDocumentCache().newChangeBuffer(), s = [];
  9182. let i = 0;
  9183. return this.Yn(t, ((r, o) => {
  9184. if (o <= e) {
  9185. const e = this.Xn(t, r).next((e => {
  9186. if (!e)
  9187. // Our size accounting requires us to read all documents before
  9188. // removing them.
  9189. return i++, n.getEntry(t, r).next((() => (n.removeEntry(r, rt.min()), mo(t).delete([ 0, qt(r.path) ]))));
  9190. }));
  9191. s.push(e);
  9192. }
  9193. })).next((() => Rt.waitFor(s))).next((() => n.apply(t))).next((() => i));
  9194. }
  9195. removeTarget(t, e) {
  9196. const n = e.withSequenceNumber(t.currentSequenceNumber);
  9197. return this.db.getTargetCache().updateTargetData(t, n);
  9198. }
  9199. updateLimboDocument(t, e) {
  9200. return Ao(t, e);
  9201. }
  9202. /**
  9203. * Call provided function for each document in the cache that is 'orphaned'. Orphaned
  9204. * means not a part of any target, so the only entry in the target-document index for
  9205. * that document will be the sentinel row (targetId 0), which will also have the sequence
  9206. * number for the last time the document was accessed.
  9207. */ Yn(t, e) {
  9208. const n = mo(t);
  9209. let s, i = Ot.ct;
  9210. return n.X({
  9211. index: "documentTargetsIndex"
  9212. }, (([t, n], {path: r, sequenceNumber: o}) => {
  9213. 0 === t ? (
  9214. // if nextToReport is valid, report it, this is a new key so the
  9215. // last one must not be a member of any targets.
  9216. i !== Ot.ct && e(new ht(Gt(s)), i),
  9217. // set nextToReport to be this sequence number. It's the next one we
  9218. // might report, if we don't find any targets for this document.
  9219. // Note that the sequence number must be defined when the targetId
  9220. // is 0.
  9221. i = o, s = r) :
  9222. // set nextToReport to be invalid, we know we don't need to report
  9223. // this one since we found a target for it.
  9224. i = Ot.ct;
  9225. })).next((() => {
  9226. // Since we report sequence numbers after getting to the next key, we
  9227. // need to check if the last key we iterated over was an orphaned
  9228. // document and report it.
  9229. i !== Ot.ct && e(new ht(Gt(s)), i);
  9230. }));
  9231. }
  9232. getCacheSize(t) {
  9233. return this.db.getRemoteDocumentCache().getSize(t);
  9234. }
  9235. }
  9236. function Ao(t, e) {
  9237. return mo(t).put(
  9238. /**
  9239. * @returns A value suitable for writing a sentinel row in the target-document
  9240. * store.
  9241. */
  9242. function(t, e) {
  9243. return {
  9244. targetId: 0,
  9245. path: qt(t.path),
  9246. sequenceNumber: e
  9247. };
  9248. }(e, t.currentSequenceNumber));
  9249. }
  9250. /**
  9251. * @license
  9252. * Copyright 2017 Google LLC
  9253. *
  9254. * Licensed under the Apache License, Version 2.0 (the "License");
  9255. * you may not use this file except in compliance with the License.
  9256. * You may obtain a copy of the License at
  9257. *
  9258. * http://www.apache.org/licenses/LICENSE-2.0
  9259. *
  9260. * Unless required by applicable law or agreed to in writing, software
  9261. * distributed under the License is distributed on an "AS IS" BASIS,
  9262. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9263. * See the License for the specific language governing permissions and
  9264. * limitations under the License.
  9265. */
  9266. /**
  9267. * An in-memory buffer of entries to be written to a RemoteDocumentCache.
  9268. * It can be used to batch up a set of changes to be written to the cache, but
  9269. * additionally supports reading entries back with the `getEntry()` method,
  9270. * falling back to the underlying RemoteDocumentCache if no entry is
  9271. * buffered.
  9272. *
  9273. * Entries added to the cache *must* be read first. This is to facilitate
  9274. * calculating the size delta of the pending changes.
  9275. *
  9276. * PORTING NOTE: This class was implemented then removed from other platforms.
  9277. * If byte-counting ends up being needed on the other platforms, consider
  9278. * porting this class as part of that implementation work.
  9279. */ class vo {
  9280. constructor() {
  9281. // A mapping of document key to the new cache entry that should be written.
  9282. this.changes = new os((t => t.toString()), ((t, e) => t.isEqual(e))), this.changesApplied = !1;
  9283. }
  9284. /**
  9285. * Buffers a `RemoteDocumentCache.addEntry()` call.
  9286. *
  9287. * You can only modify documents that have already been retrieved via
  9288. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  9289. */ addEntry(t) {
  9290. this.assertNotApplied(), this.changes.set(t.key, t);
  9291. }
  9292. /**
  9293. * Buffers a `RemoteDocumentCache.removeEntry()` call.
  9294. *
  9295. * You can only remove documents that have already been retrieved via
  9296. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  9297. */ removeEntry(t, e) {
  9298. this.assertNotApplied(), this.changes.set(t, an.newInvalidDocument(t).setReadTime(e));
  9299. }
  9300. /**
  9301. * Looks up an entry in the cache. The buffered changes will first be checked,
  9302. * and if no buffered change applies, this will forward to
  9303. * `RemoteDocumentCache.getEntry()`.
  9304. *
  9305. * @param transaction - The transaction in which to perform any persistence
  9306. * operations.
  9307. * @param documentKey - The key of the entry to look up.
  9308. * @returns The cached document or an invalid document if we have nothing
  9309. * cached.
  9310. */ getEntry(t, e) {
  9311. this.assertNotApplied();
  9312. const n = this.changes.get(e);
  9313. return void 0 !== n ? Rt.resolve(n) : this.getFromCache(t, e);
  9314. }
  9315. /**
  9316. * Looks up several entries in the cache, forwarding to
  9317. * `RemoteDocumentCache.getEntry()`.
  9318. *
  9319. * @param transaction - The transaction in which to perform any persistence
  9320. * operations.
  9321. * @param documentKeys - The keys of the entries to look up.
  9322. * @returns A map of cached documents, indexed by key. If an entry cannot be
  9323. * found, the corresponding key will be mapped to an invalid document.
  9324. */ getEntries(t, e) {
  9325. return this.getAllFromCache(t, e);
  9326. }
  9327. /**
  9328. * Applies buffered changes to the underlying RemoteDocumentCache, using
  9329. * the provided transaction.
  9330. */ apply(t) {
  9331. return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);
  9332. }
  9333. /** Helper to assert this.changes is not null */ assertNotApplied() {}
  9334. }
  9335. /**
  9336. * @license
  9337. * Copyright 2017 Google LLC
  9338. *
  9339. * Licensed under the Apache License, Version 2.0 (the "License");
  9340. * you may not use this file except in compliance with the License.
  9341. * You may obtain a copy of the License at
  9342. *
  9343. * http://www.apache.org/licenses/LICENSE-2.0
  9344. *
  9345. * Unless required by applicable law or agreed to in writing, software
  9346. * distributed under the License is distributed on an "AS IS" BASIS,
  9347. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9348. * See the License for the specific language governing permissions and
  9349. * limitations under the License.
  9350. */
  9351. /**
  9352. * The RemoteDocumentCache for IndexedDb. To construct, invoke
  9353. * `newIndexedDbRemoteDocumentCache()`.
  9354. */ class Ro {
  9355. constructor(t) {
  9356. this.serializer = t;
  9357. }
  9358. setIndexManager(t) {
  9359. this.indexManager = t;
  9360. }
  9361. /**
  9362. * Adds the supplied entries to the cache.
  9363. *
  9364. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  9365. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9366. */ addEntry(t, e, n) {
  9367. return So(t).put(n);
  9368. }
  9369. /**
  9370. * Removes a document from the cache.
  9371. *
  9372. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  9373. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9374. */ removeEntry(t, e, n) {
  9375. return So(t).delete(
  9376. /**
  9377. * Returns a key that can be used for document lookups via the primary key of
  9378. * the DbRemoteDocument object store.
  9379. */
  9380. function(t, e) {
  9381. const n = t.path.toArray();
  9382. return [
  9383. /* prefix path */ n.slice(0, n.length - 2),
  9384. /* collection id */ n[n.length - 2], fr(e),
  9385. /* document id */ n[n.length - 1] ];
  9386. }
  9387. /**
  9388. * Returns a key that can be used for document lookups on the
  9389. * `DbRemoteDocumentDocumentCollectionGroupIndex` index.
  9390. */ (e, n));
  9391. }
  9392. /**
  9393. * Updates the current cache size.
  9394. *
  9395. * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
  9396. * cache's metadata.
  9397. */ updateMetadata(t, e) {
  9398. return this.getMetadata(t).next((n => (n.byteSize += e, this.Zn(t, n))));
  9399. }
  9400. getEntry(t, e) {
  9401. let n = an.newInvalidDocument(e);
  9402. return So(t).X({
  9403. index: "documentKeyIndex",
  9404. range: IDBKeyRange.only(Do(e))
  9405. }, ((t, s) => {
  9406. n = this.ts(e, s);
  9407. })).next((() => n));
  9408. }
  9409. /**
  9410. * Looks up an entry in the cache.
  9411. *
  9412. * @param documentKey - The key of the entry to look up.
  9413. * @returns The cached document entry and its size.
  9414. */ es(t, e) {
  9415. let n = {
  9416. size: 0,
  9417. document: an.newInvalidDocument(e)
  9418. };
  9419. return So(t).X({
  9420. index: "documentKeyIndex",
  9421. range: IDBKeyRange.only(Do(e))
  9422. }, ((t, s) => {
  9423. n = {
  9424. document: this.ts(e, s),
  9425. size: ro(s)
  9426. };
  9427. })).next((() => n));
  9428. }
  9429. getEntries(t, e) {
  9430. let n = cs();
  9431. return this.ns(t, e, ((t, e) => {
  9432. const s = this.ts(t, e);
  9433. n = n.insert(t, s);
  9434. })).next((() => n));
  9435. }
  9436. /**
  9437. * Looks up several entries in the cache.
  9438. *
  9439. * @param documentKeys - The set of keys entries to look up.
  9440. * @returns A map of documents indexed by key and a map of sizes indexed by
  9441. * key (zero if the document does not exist).
  9442. */ ss(t, e) {
  9443. let n = cs(), s = new pe(ht.comparator);
  9444. return this.ns(t, e, ((t, e) => {
  9445. const i = this.ts(t, e);
  9446. n = n.insert(t, i), s = s.insert(t, ro(e));
  9447. })).next((() => ({
  9448. documents: n,
  9449. rs: s
  9450. })));
  9451. }
  9452. ns(t, e, n) {
  9453. if (e.isEmpty()) return Rt.resolve();
  9454. let s = new Ee(xo);
  9455. e.forEach((t => s = s.add(t)));
  9456. const i = IDBKeyRange.bound(Do(s.first()), Do(s.last())), r = s.getIterator();
  9457. let o = r.getNext();
  9458. return So(t).X({
  9459. index: "documentKeyIndex",
  9460. range: i
  9461. }, ((t, e, s) => {
  9462. const i = ht.fromSegments([ ...e.prefixPath, e.collectionGroup, e.documentId ]);
  9463. // Go through keys not found in cache.
  9464. for (;o && xo(o, i) < 0; ) n(o, null), o = r.getNext();
  9465. o && o.isEqual(i) && (
  9466. // Key found in cache.
  9467. n(o, e), o = r.hasNext() ? r.getNext() : null),
  9468. // Skip to the next key (if there is one).
  9469. o ? s.G(Do(o)) : s.done();
  9470. })).next((() => {
  9471. // The rest of the keys are not in the cache. One case where `iterate`
  9472. // above won't go through them is when the cache is empty.
  9473. for (;o; ) n(o, null), o = r.hasNext() ? r.getNext() : null;
  9474. }));
  9475. }
  9476. getDocumentsMatchingQuery(t, e, n, s) {
  9477. const i = e.path, r = [ i.popLast().toArray(), i.lastSegment(), fr(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment() ], o = [ i.popLast().toArray(), i.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], "" ];
  9478. return So(t).j(IDBKeyRange.bound(r, o, !0)).next((t => {
  9479. let n = cs();
  9480. for (const i of t) {
  9481. const t = this.ts(ht.fromSegments(i.prefixPath.concat(i.collectionGroup, i.documentId)), i);
  9482. t.isFoundDocument() && (ns(e, t) || s.has(t.key)) && (
  9483. // Either the document matches the given query, or it is mutated.
  9484. n = n.insert(t.key, t));
  9485. }
  9486. return n;
  9487. }));
  9488. }
  9489. getAllFromCollectionGroup(t, e, n, s) {
  9490. let i = cs();
  9491. const r = Co(e, n), o = Co(e, It.max());
  9492. return So(t).X({
  9493. index: "collectionGroupIndex",
  9494. range: IDBKeyRange.bound(r, o, !0)
  9495. }, ((t, e, n) => {
  9496. const r = this.ts(ht.fromSegments(e.prefixPath.concat(e.collectionGroup, e.documentId)), e);
  9497. i = i.insert(r.key, r), i.size === s && n.done();
  9498. })).next((() => i));
  9499. }
  9500. newChangeBuffer(t) {
  9501. return new bo(this, !!t && t.trackRemovals);
  9502. }
  9503. getSize(t) {
  9504. return this.getMetadata(t).next((t => t.byteSize));
  9505. }
  9506. getMetadata(t) {
  9507. return Vo(t).get("remoteDocumentGlobalKey").next((t => (F(!!t), t)));
  9508. }
  9509. Zn(t, e) {
  9510. return Vo(t).put("remoteDocumentGlobalKey", e);
  9511. }
  9512. /**
  9513. * Decodes `dbRemoteDoc` and returns the document (or an invalid document if
  9514. * the document corresponds to the format used for sentinel deletes).
  9515. */ ts(t, e) {
  9516. if (e) {
  9517. const t = hr(this.serializer, e);
  9518. // Whether the document is a sentinel removal and should only be used in the
  9519. // `getNewDocumentChanges()`
  9520. if (!(t.isNoDocument() && t.version.isEqual(rt.min()))) return t;
  9521. }
  9522. return an.newInvalidDocument(t);
  9523. }
  9524. }
  9525. /** Creates a new IndexedDbRemoteDocumentCache. */ function Po(t) {
  9526. return new Ro(t);
  9527. }
  9528. /**
  9529. * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.
  9530. *
  9531. * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size
  9532. * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb
  9533. * when we apply the changes.
  9534. */ class bo extends vo {
  9535. /**
  9536. * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.
  9537. * @param trackRemovals - Whether to create sentinel deletes that can be tracked by
  9538. * `getNewDocumentChanges()`.
  9539. */
  9540. constructor(t, e) {
  9541. super(), this.os = t, this.trackRemovals = e,
  9542. // A map of document sizes and read times prior to applying the changes in
  9543. // this buffer.
  9544. this.us = new os((t => t.toString()), ((t, e) => t.isEqual(e)));
  9545. }
  9546. applyChanges(t) {
  9547. const e = [];
  9548. let n = 0, s = new Ee(((t, e) => et(t.canonicalString(), e.canonicalString())));
  9549. return this.changes.forEach(((i, r) => {
  9550. const o = this.us.get(i);
  9551. if (e.push(this.os.removeEntry(t, i, o.readTime)), r.isValidDocument()) {
  9552. const u = lr(this.os.serializer, r);
  9553. s = s.add(i.path.popLast());
  9554. const c = ro(u);
  9555. n += c - o.size, e.push(this.os.addEntry(t, i, u));
  9556. } else if (n -= o.size, this.trackRemovals) {
  9557. // In order to track removals, we store a "sentinel delete" in the
  9558. // RemoteDocumentCache. This entry is represented by a NoDocument
  9559. // with a version of 0 and ignored by `maybeDecodeDocument()` but
  9560. // preserved in `getNewDocumentChanges()`.
  9561. const n = lr(this.os.serializer, r.convertToNoDocument(rt.min()));
  9562. e.push(this.os.addEntry(t, i, n));
  9563. }
  9564. })), s.forEach((n => {
  9565. e.push(this.os.indexManager.addToCollectionParentIndex(t, n));
  9566. })), e.push(this.os.updateMetadata(t, n)), Rt.waitFor(e);
  9567. }
  9568. getFromCache(t, e) {
  9569. // Record the size of everything we load from the cache so we can compute a delta later.
  9570. return this.os.es(t, e).next((t => (this.us.set(e, {
  9571. size: t.size,
  9572. readTime: t.document.readTime
  9573. }), t.document)));
  9574. }
  9575. getAllFromCache(t, e) {
  9576. // Record the size of everything we load from the cache so we can compute
  9577. // a delta later.
  9578. return this.os.ss(t, e).next((({documents: t, rs: e}) => (
  9579. // Note: `getAllFromCache` returns two maps instead of a single map from
  9580. // keys to `DocumentSizeEntry`s. This is to allow returning the
  9581. // `MutableDocumentMap` directly, without a conversion.
  9582. e.forEach(((e, n) => {
  9583. this.us.set(e, {
  9584. size: n,
  9585. readTime: t.get(e).readTime
  9586. });
  9587. })), t)));
  9588. }
  9589. }
  9590. function Vo(t) {
  9591. return _e(t, "remoteDocumentGlobal");
  9592. }
  9593. /**
  9594. * Helper to get a typed SimpleDbStore for the remoteDocuments object store.
  9595. */ function So(t) {
  9596. return _e(t, "remoteDocumentsV14");
  9597. }
  9598. /**
  9599. * Returns a key that can be used for document lookups on the
  9600. * `DbRemoteDocumentDocumentKeyIndex` index.
  9601. */ function Do(t) {
  9602. const e = t.path.toArray();
  9603. return [
  9604. /* prefix path */ e.slice(0, e.length - 2),
  9605. /* collection id */ e[e.length - 2],
  9606. /* document id */ e[e.length - 1] ];
  9607. }
  9608. function Co(t, e) {
  9609. const n = e.documentKey.path.toArray();
  9610. return [
  9611. /* collection id */ t, fr(e.readTime),
  9612. /* prefix path */ n.slice(0, n.length - 2),
  9613. /* document id */ n.length > 0 ? n[n.length - 1] : "" ];
  9614. }
  9615. /**
  9616. * Comparator that compares document keys according to the primary key sorting
  9617. * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
  9618. * and then document ID).
  9619. *
  9620. * Visible for testing.
  9621. */ function xo(t, e) {
  9622. const n = t.path.toArray(), s = e.path.toArray();
  9623. // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
  9624. let i = 0;
  9625. for (let t = 0; t < n.length - 2 && t < s.length - 2; ++t) if (i = et(n[t], s[t]),
  9626. i) return i;
  9627. return i = et(n.length, s.length), i || (i = et(n[n.length - 2], s[s.length - 2]),
  9628. i || et(n[n.length - 1], s[s.length - 1]));
  9629. }
  9630. /**
  9631. * @license
  9632. * Copyright 2017 Google LLC
  9633. *
  9634. * Licensed under the Apache License, Version 2.0 (the "License");
  9635. * you may not use this file except in compliance with the License.
  9636. * You may obtain a copy of the License at
  9637. *
  9638. * http://www.apache.org/licenses/LICENSE-2.0
  9639. *
  9640. * Unless required by applicable law or agreed to in writing, software
  9641. * distributed under the License is distributed on an "AS IS" BASIS,
  9642. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9643. * See the License for the specific language governing permissions and
  9644. * limitations under the License.
  9645. */
  9646. /**
  9647. * Schema Version for the Web client:
  9648. * 1. Initial version including Mutation Queue, Query Cache, and Remote
  9649. * Document Cache
  9650. * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No
  9651. * longer required because migration 3 unconditionally clears it.
  9652. * 3. Dropped and re-created Query Cache to deal with cache corruption related
  9653. * to limbo resolution. Addresses
  9654. * https://github.com/firebase/firebase-ios-sdk/issues/1548
  9655. * 4. Multi-Tab Support.
  9656. * 5. Removal of held write acks.
  9657. * 6. Create document global for tracking document cache size.
  9658. * 7. Ensure every cached document has a sentinel row with a sequence number.
  9659. * 8. Add collection-parent index for Collection Group queries.
  9660. * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than
  9661. * an auto-incrementing ID. This is required for Index-Free queries.
  9662. * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
  9663. * 11. Add bundles and named_queries for bundle support.
  9664. * 12. Add document overlays.
  9665. * 13. Rewrite the keys of the remote document cache to allow for efficient
  9666. * document lookup via `getAll()`.
  9667. * 14. Add overlays.
  9668. * 15. Add indexing support.
  9669. */
  9670. /**
  9671. * @license
  9672. * Copyright 2022 Google LLC
  9673. *
  9674. * Licensed under the Apache License, Version 2.0 (the "License");
  9675. * you may not use this file except in compliance with the License.
  9676. * You may obtain a copy of the License at
  9677. *
  9678. * http://www.apache.org/licenses/LICENSE-2.0
  9679. *
  9680. * Unless required by applicable law or agreed to in writing, software
  9681. * distributed under the License is distributed on an "AS IS" BASIS,
  9682. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9683. * See the License for the specific language governing permissions and
  9684. * limitations under the License.
  9685. */
  9686. /**
  9687. * Represents a local view (overlay) of a document, and the fields that are
  9688. * locally mutated.
  9689. */
  9690. class No {
  9691. constructor(t,
  9692. /**
  9693. * The fields that are locally mutated by patch mutations.
  9694. *
  9695. * If the overlayed document is from set or delete mutations, this is `null`.
  9696. * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
  9697. */
  9698. e) {
  9699. this.overlayedDocument = t, this.mutatedFields = e;
  9700. }
  9701. }
  9702. /**
  9703. * @license
  9704. * Copyright 2017 Google LLC
  9705. *
  9706. * Licensed under the Apache License, Version 2.0 (the "License");
  9707. * you may not use this file except in compliance with the License.
  9708. * You may obtain a copy of the License at
  9709. *
  9710. * http://www.apache.org/licenses/LICENSE-2.0
  9711. *
  9712. * Unless required by applicable law or agreed to in writing, software
  9713. * distributed under the License is distributed on an "AS IS" BASIS,
  9714. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9715. * See the License for the specific language governing permissions and
  9716. * limitations under the License.
  9717. */
  9718. /**
  9719. * A readonly view of the local state of all documents we're tracking (i.e. we
  9720. * have a cached version in remoteDocumentCache or local mutations for the
  9721. * document). The view is computed by applying the mutations in the
  9722. * MutationQueue to the RemoteDocumentCache.
  9723. */ class ko {
  9724. constructor(t, e, n, s) {
  9725. this.remoteDocumentCache = t, this.mutationQueue = e, this.documentOverlayCache = n,
  9726. this.indexManager = s;
  9727. }
  9728. /**
  9729. * Get the local view of the document identified by `key`.
  9730. *
  9731. * @returns Local view of the document or null if we don't have any cached
  9732. * state for it.
  9733. */ getDocument(t, e) {
  9734. let n = null;
  9735. return this.documentOverlayCache.getOverlay(t, e).next((s => (n = s, this.remoteDocumentCache.getEntry(t, e)))).next((t => (null !== n && Ks(n.mutation, t, Re.empty(), it.now()),
  9736. t)));
  9737. }
  9738. /**
  9739. * Gets the local view of the documents identified by `keys`.
  9740. *
  9741. * If we don't have cached state for a document in `keys`, a NoDocument will
  9742. * be stored for that key in the resulting set.
  9743. */ getDocuments(t, e) {
  9744. return this.remoteDocumentCache.getEntries(t, e).next((e => this.getLocalViewOfDocuments(t, e, gs()).next((() => e))));
  9745. }
  9746. /**
  9747. * Similar to `getDocuments`, but creates the local view from the given
  9748. * `baseDocs` without retrieving documents from the local store.
  9749. *
  9750. * @param transaction - The transaction this operation is scoped to.
  9751. * @param docs - The documents to apply local mutations to get the local views.
  9752. * @param existenceStateChanged - The set of document keys whose existence state
  9753. * is changed. This is useful to determine if some documents overlay needs
  9754. * to be recalculated.
  9755. */ getLocalViewOfDocuments(t, e, n = gs()) {
  9756. const s = fs();
  9757. return this.populateOverlays(t, s, e).next((() => this.computeViews(t, e, s, n).next((t => {
  9758. let e = hs();
  9759. return t.forEach(((t, n) => {
  9760. e = e.insert(t, n.overlayedDocument);
  9761. })), e;
  9762. }))));
  9763. }
  9764. /**
  9765. * Gets the overlayed documents for the given document map, which will include
  9766. * the local view of those documents and a `FieldMask` indicating which fields
  9767. * are mutated locally, `null` if overlay is a Set or Delete mutation.
  9768. */ getOverlayedDocuments(t, e) {
  9769. const n = fs();
  9770. return this.populateOverlays(t, n, e).next((() => this.computeViews(t, e, n, gs())));
  9771. }
  9772. /**
  9773. * Fetches the overlays for {@code docs} and adds them to provided overlay map
  9774. * if the map does not already contain an entry for the given document key.
  9775. */ populateOverlays(t, e, n) {
  9776. const s = [];
  9777. return n.forEach((t => {
  9778. e.has(t) || s.push(t);
  9779. })), this.documentOverlayCache.getOverlays(t, s).next((t => {
  9780. t.forEach(((t, n) => {
  9781. e.set(t, n);
  9782. }));
  9783. }));
  9784. }
  9785. /**
  9786. * Computes the local view for the given documents.
  9787. *
  9788. * @param docs - The documents to compute views for. It also has the base
  9789. * version of the documents.
  9790. * @param overlays - The overlays that need to be applied to the given base
  9791. * version of the documents.
  9792. * @param existenceStateChanged - A set of documents whose existence states
  9793. * might have changed. This is used to determine if we need to re-calculate
  9794. * overlays from mutation queues.
  9795. * @return A map represents the local documents view.
  9796. */ computeViews(t, e, n, s) {
  9797. let i = cs();
  9798. const r = ws(), o = ws();
  9799. return e.forEach(((t, e) => {
  9800. const o = n.get(e.key);
  9801. // Recalculate an overlay if the document's existence state changed due to
  9802. // a remote event *and* the overlay is a PatchMutation. This is because
  9803. // document existence state can change if some patch mutation's
  9804. // preconditions are met.
  9805. // NOTE: we recalculate when `overlay` is undefined as well, because there
  9806. // might be a patch mutation whose precondition does not match before the
  9807. // change (hence overlay is undefined), but would now match.
  9808. s.has(e.key) && (void 0 === o || o.mutation instanceof zs) ? i = i.insert(e.key, e) : void 0 !== o ? (r.set(e.key, o.mutation.getFieldMask()),
  9809. Ks(o.mutation, e, o.mutation.getFieldMask(), it.now())) :
  9810. // no overlay exists
  9811. // Using EMPTY to indicate there is no overlay for the document.
  9812. r.set(e.key, Re.empty());
  9813. })), this.recalculateAndSaveOverlays(t, i).next((t => (t.forEach(((t, e) => r.set(t, e))),
  9814. e.forEach(((t, e) => {
  9815. var n;
  9816. return o.set(t, new No(e, null !== (n = r.get(t)) && void 0 !== n ? n : null));
  9817. })), o)));
  9818. }
  9819. recalculateAndSaveOverlays(t, e) {
  9820. const n = ws();
  9821. // A reverse lookup map from batch id to the documents within that batch.
  9822. let s = new pe(((t, e) => t - e)), i = gs();
  9823. return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t, e).next((t => {
  9824. for (const i of t) i.keys().forEach((t => {
  9825. const r = e.get(t);
  9826. if (null === r) return;
  9827. let o = n.get(t) || Re.empty();
  9828. o = i.applyToLocalView(r, o), n.set(t, o);
  9829. const u = (s.get(i.batchId) || gs()).add(t);
  9830. s = s.insert(i.batchId, u);
  9831. }));
  9832. })).next((() => {
  9833. const r = [], o = s.getReverseIterator();
  9834. // Iterate in descending order of batch IDs, and skip documents that are
  9835. // already saved.
  9836. for (;o.hasNext(); ) {
  9837. const s = o.getNext(), u = s.key, c = s.value, a = ds();
  9838. c.forEach((t => {
  9839. if (!i.has(t)) {
  9840. const s = qs(e.get(t), n.get(t));
  9841. null !== s && a.set(t, s), i = i.add(t);
  9842. }
  9843. })), r.push(this.documentOverlayCache.saveOverlays(t, u, a));
  9844. }
  9845. return Rt.waitFor(r);
  9846. })).next((() => n));
  9847. }
  9848. /**
  9849. * Recalculates overlays by reading the documents from remote document cache
  9850. * first, and saves them after they are calculated.
  9851. */ recalculateAndSaveOverlaysForDocumentKeys(t, e) {
  9852. return this.remoteDocumentCache.getEntries(t, e).next((e => this.recalculateAndSaveOverlays(t, e)));
  9853. }
  9854. /**
  9855. * Performs a query against the local view of all documents.
  9856. *
  9857. * @param transaction - The persistence transaction.
  9858. * @param query - The query to match documents against.
  9859. * @param offset - Read time and key to start scanning by (exclusive).
  9860. */ getDocumentsMatchingQuery(t, e, n) {
  9861. /**
  9862. * Returns whether the query matches a single document by path (rather than a
  9863. * collection).
  9864. */
  9865. return function(t) {
  9866. return ht.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  9867. }(e) ? this.getDocumentsMatchingDocumentQuery(t, e.path) : Wn(e) ? this.getDocumentsMatchingCollectionGroupQuery(t, e, n) : this.getDocumentsMatchingCollectionQuery(t, e, n);
  9868. }
  9869. /**
  9870. * Given a collection group, returns the next documents that follow the provided offset, along
  9871. * with an updated batch ID.
  9872. *
  9873. * <p>The documents returned by this method are ordered by remote version from the provided
  9874. * offset. If there are no more remote documents after the provided offset, documents with
  9875. * mutations in order of batch id from the offset are returned. Since all documents in a batch are
  9876. * returned together, the total number of documents returned can exceed {@code count}.
  9877. *
  9878. * @param transaction
  9879. * @param collectionGroup The collection group for the documents.
  9880. * @param offset The offset to index into.
  9881. * @param count The number of documents to return
  9882. * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
  9883. */ getNextDocuments(t, e, n, s) {
  9884. return this.remoteDocumentCache.getAllFromCollectionGroup(t, e, n, s).next((i => {
  9885. const r = s - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(t, e, n.largestBatchId, s - i.size) : Rt.resolve(fs());
  9886. // The callsite will use the largest batch ID together with the latest read time to create
  9887. // a new index offset. Since we only process batch IDs if all remote documents have been read,
  9888. // no overlay will increase the overall read time. This is why we only need to special case
  9889. // the batch id.
  9890. let o = -1, u = i;
  9891. return r.next((e => Rt.forEach(e, ((e, n) => (o < n.largestBatchId && (o = n.largestBatchId),
  9892. i.get(e) ? Rt.resolve() : this.remoteDocumentCache.getEntry(t, e).next((t => {
  9893. u = u.insert(e, t);
  9894. }))))).next((() => this.populateOverlays(t, e, i))).next((() => this.computeViews(t, u, e, gs()))).next((t => ({
  9895. batchId: o,
  9896. changes: ls(t)
  9897. })))));
  9898. }));
  9899. }
  9900. getDocumentsMatchingDocumentQuery(t, e) {
  9901. // Just do a simple document lookup.
  9902. return this.getDocument(t, new ht(e)).next((t => {
  9903. let e = hs();
  9904. return t.isFoundDocument() && (e = e.insert(t.key, t)), e;
  9905. }));
  9906. }
  9907. getDocumentsMatchingCollectionGroupQuery(t, e, n) {
  9908. const s = e.collectionGroup;
  9909. let i = hs();
  9910. return this.indexManager.getCollectionParents(t, s).next((r => Rt.forEach(r, (r => {
  9911. const o = function(t, e) {
  9912. return new Un(e,
  9913. /*collectionGroup=*/ null, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  9914. }(e, r.child(s));
  9915. return this.getDocumentsMatchingCollectionQuery(t, o, n).next((t => {
  9916. t.forEach(((t, e) => {
  9917. i = i.insert(t, e);
  9918. }));
  9919. }));
  9920. })).next((() => i))));
  9921. }
  9922. getDocumentsMatchingCollectionQuery(t, e, n) {
  9923. // Query the remote documents and overlay mutations.
  9924. let s;
  9925. return this.documentOverlayCache.getOverlaysForCollection(t, e.path, n.largestBatchId).next((i => (s = i,
  9926. this.remoteDocumentCache.getDocumentsMatchingQuery(t, e, n, s)))).next((t => {
  9927. // As documents might match the query because of their overlay we need to
  9928. // include documents for all overlays in the initial document set.
  9929. s.forEach(((e, n) => {
  9930. const s = n.getKey();
  9931. null === t.get(s) && (t = t.insert(s, an.newInvalidDocument(s)));
  9932. }));
  9933. // Apply the overlays and match against the query.
  9934. let n = hs();
  9935. return t.forEach(((t, i) => {
  9936. const r = s.get(t);
  9937. void 0 !== r && Ks(r.mutation, i, Re.empty(), it.now()),
  9938. // Finally, insert the documents that still match the query
  9939. ns(e, i) && (n = n.insert(t, i));
  9940. })), n;
  9941. }));
  9942. }
  9943. }
  9944. /**
  9945. * @license
  9946. * Copyright 2020 Google LLC
  9947. *
  9948. * Licensed under the Apache License, Version 2.0 (the "License");
  9949. * you may not use this file except in compliance with the License.
  9950. * You may obtain a copy of the License at
  9951. *
  9952. * http://www.apache.org/licenses/LICENSE-2.0
  9953. *
  9954. * Unless required by applicable law or agreed to in writing, software
  9955. * distributed under the License is distributed on an "AS IS" BASIS,
  9956. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9957. * See the License for the specific language governing permissions and
  9958. * limitations under the License.
  9959. */ class Mo {
  9960. constructor(t) {
  9961. this.serializer = t, this.cs = new Map, this.hs = new Map;
  9962. }
  9963. getBundleMetadata(t, e) {
  9964. return Rt.resolve(this.cs.get(e));
  9965. }
  9966. saveBundleMetadata(t, e) {
  9967. /** Decodes a BundleMetadata proto into a BundleMetadata object. */
  9968. var n;
  9969. return this.cs.set(e.id, {
  9970. id: (n = e).id,
  9971. version: n.version,
  9972. createTime: Ni(n.createTime)
  9973. }), Rt.resolve();
  9974. }
  9975. getNamedQuery(t, e) {
  9976. return Rt.resolve(this.hs.get(e));
  9977. }
  9978. saveNamedQuery(t, e) {
  9979. return this.hs.set(e.name, function(t) {
  9980. return {
  9981. name: t.name,
  9982. query: yr(t.bundledQuery),
  9983. readTime: Ni(t.readTime)
  9984. };
  9985. }(e)), Rt.resolve();
  9986. }
  9987. }
  9988. /**
  9989. * @license
  9990. * Copyright 2022 Google LLC
  9991. *
  9992. * Licensed under the Apache License, Version 2.0 (the "License");
  9993. * you may not use this file except in compliance with the License.
  9994. * You may obtain a copy of the License at
  9995. *
  9996. * http://www.apache.org/licenses/LICENSE-2.0
  9997. *
  9998. * Unless required by applicable law or agreed to in writing, software
  9999. * distributed under the License is distributed on an "AS IS" BASIS,
  10000. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10001. * See the License for the specific language governing permissions and
  10002. * limitations under the License.
  10003. */
  10004. /**
  10005. * An in-memory implementation of DocumentOverlayCache.
  10006. */ class $o {
  10007. constructor() {
  10008. // A map sorted by DocumentKey, whose value is a pair of the largest batch id
  10009. // for the overlay and the overlay itself.
  10010. this.overlays = new pe(ht.comparator), this.ls = new Map;
  10011. }
  10012. getOverlay(t, e) {
  10013. return Rt.resolve(this.overlays.get(e));
  10014. }
  10015. getOverlays(t, e) {
  10016. const n = fs();
  10017. return Rt.forEach(e, (e => this.getOverlay(t, e).next((t => {
  10018. null !== t && n.set(e, t);
  10019. })))).next((() => n));
  10020. }
  10021. saveOverlays(t, e, n) {
  10022. return n.forEach(((n, s) => {
  10023. this.we(t, e, s);
  10024. })), Rt.resolve();
  10025. }
  10026. removeOverlaysForBatchId(t, e, n) {
  10027. const s = this.ls.get(n);
  10028. return void 0 !== s && (s.forEach((t => this.overlays = this.overlays.remove(t))),
  10029. this.ls.delete(n)), Rt.resolve();
  10030. }
  10031. getOverlaysForCollection(t, e, n) {
  10032. const s = fs(), i = e.length + 1, r = new ht(e.child("")), o = this.overlays.getIteratorFrom(r);
  10033. for (;o.hasNext(); ) {
  10034. const t = o.getNext().value, r = t.getKey();
  10035. if (!e.isPrefixOf(r.path)) break;
  10036. // Documents from sub-collections
  10037. r.path.length === i && (t.largestBatchId > n && s.set(t.getKey(), t));
  10038. }
  10039. return Rt.resolve(s);
  10040. }
  10041. getOverlaysForCollectionGroup(t, e, n, s) {
  10042. let i = new pe(((t, e) => t - e));
  10043. const r = this.overlays.getIterator();
  10044. for (;r.hasNext(); ) {
  10045. const t = r.getNext().value;
  10046. if (t.getKey().getCollectionGroup() === e && t.largestBatchId > n) {
  10047. let e = i.get(t.largestBatchId);
  10048. null === e && (e = fs(), i = i.insert(t.largestBatchId, e)), e.set(t.getKey(), t);
  10049. }
  10050. }
  10051. const o = fs(), u = i.getIterator();
  10052. for (;u.hasNext(); ) {
  10053. if (u.getNext().value.forEach(((t, e) => o.set(t, e))), o.size() >= s) break;
  10054. }
  10055. return Rt.resolve(o);
  10056. }
  10057. we(t, e, n) {
  10058. // Remove the association of the overlay to its batch id.
  10059. const s = this.overlays.get(n.key);
  10060. if (null !== s) {
  10061. const t = this.ls.get(s.largestBatchId).delete(n.key);
  10062. this.ls.set(s.largestBatchId, t);
  10063. }
  10064. this.overlays = this.overlays.insert(n.key, new ei(e, n));
  10065. // Create the association of this overlay to the given largestBatchId.
  10066. let i = this.ls.get(e);
  10067. void 0 === i && (i = gs(), this.ls.set(e, i)), this.ls.set(e, i.add(n.key));
  10068. }
  10069. }
  10070. /**
  10071. * @license
  10072. * Copyright 2017 Google LLC
  10073. *
  10074. * Licensed under the Apache License, Version 2.0 (the "License");
  10075. * you may not use this file except in compliance with the License.
  10076. * You may obtain a copy of the License at
  10077. *
  10078. * http://www.apache.org/licenses/LICENSE-2.0
  10079. *
  10080. * Unless required by applicable law or agreed to in writing, software
  10081. * distributed under the License is distributed on an "AS IS" BASIS,
  10082. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10083. * See the License for the specific language governing permissions and
  10084. * limitations under the License.
  10085. */
  10086. /**
  10087. * A collection of references to a document from some kind of numbered entity
  10088. * (either a target ID or batch ID). As references are added to or removed from
  10089. * the set corresponding events are emitted to a registered garbage collector.
  10090. *
  10091. * Each reference is represented by a DocumentReference object. Each of them
  10092. * contains enough information to uniquely identify the reference. They are all
  10093. * stored primarily in a set sorted by key. A document is considered garbage if
  10094. * there's no references in that set (this can be efficiently checked thanks to
  10095. * sorting by key).
  10096. *
  10097. * ReferenceSet also keeps a secondary set that contains references sorted by
  10098. * IDs. This one is used to efficiently implement removal of all references by
  10099. * some target ID.
  10100. */ class Oo {
  10101. constructor() {
  10102. // A set of outstanding references to a document sorted by key.
  10103. this.fs = new Ee(Fo.ds),
  10104. // A set of outstanding references to a document sorted by target id.
  10105. this.ws = new Ee(Fo._s);
  10106. }
  10107. /** Returns true if the reference set contains no references. */ isEmpty() {
  10108. return this.fs.isEmpty();
  10109. }
  10110. /** Adds a reference to the given document key for the given ID. */ addReference(t, e) {
  10111. const n = new Fo(t, e);
  10112. this.fs = this.fs.add(n), this.ws = this.ws.add(n);
  10113. }
  10114. /** Add references to the given document keys for the given ID. */ gs(t, e) {
  10115. t.forEach((t => this.addReference(t, e)));
  10116. }
  10117. /**
  10118. * Removes a reference to the given document key for the given
  10119. * ID.
  10120. */ removeReference(t, e) {
  10121. this.ys(new Fo(t, e));
  10122. }
  10123. ps(t, e) {
  10124. t.forEach((t => this.removeReference(t, e)));
  10125. }
  10126. /**
  10127. * Clears all references with a given ID. Calls removeRef() for each key
  10128. * removed.
  10129. */ Is(t) {
  10130. const e = new ht(new ut([])), n = new Fo(e, t), s = new Fo(e, t + 1), i = [];
  10131. return this.ws.forEachInRange([ n, s ], (t => {
  10132. this.ys(t), i.push(t.key);
  10133. })), i;
  10134. }
  10135. Ts() {
  10136. this.fs.forEach((t => this.ys(t)));
  10137. }
  10138. ys(t) {
  10139. this.fs = this.fs.delete(t), this.ws = this.ws.delete(t);
  10140. }
  10141. Es(t) {
  10142. const e = new ht(new ut([])), n = new Fo(e, t), s = new Fo(e, t + 1);
  10143. let i = gs();
  10144. return this.ws.forEachInRange([ n, s ], (t => {
  10145. i = i.add(t.key);
  10146. })), i;
  10147. }
  10148. containsKey(t) {
  10149. const e = new Fo(t, 0), n = this.fs.firstAfterOrEqual(e);
  10150. return null !== n && t.isEqual(n.key);
  10151. }
  10152. }
  10153. class Fo {
  10154. constructor(t, e) {
  10155. this.key = t, this.As = e;
  10156. }
  10157. /** Compare by key then by ID */ static ds(t, e) {
  10158. return ht.comparator(t.key, e.key) || et(t.As, e.As);
  10159. }
  10160. /** Compare by ID then by key */ static _s(t, e) {
  10161. return et(t.As, e.As) || ht.comparator(t.key, e.key);
  10162. }
  10163. }
  10164. /**
  10165. * @license
  10166. * Copyright 2017 Google LLC
  10167. *
  10168. * Licensed under the Apache License, Version 2.0 (the "License");
  10169. * you may not use this file except in compliance with the License.
  10170. * You may obtain a copy of the License at
  10171. *
  10172. * http://www.apache.org/licenses/LICENSE-2.0
  10173. *
  10174. * Unless required by applicable law or agreed to in writing, software
  10175. * distributed under the License is distributed on an "AS IS" BASIS,
  10176. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10177. * See the License for the specific language governing permissions and
  10178. * limitations under the License.
  10179. */ class Bo {
  10180. constructor(t, e) {
  10181. this.indexManager = t, this.referenceDelegate = e,
  10182. /**
  10183. * The set of all mutations that have been sent but not yet been applied to
  10184. * the backend.
  10185. */
  10186. this.mutationQueue = [],
  10187. /** Next value to use when assigning sequential IDs to each mutation batch. */
  10188. this.vs = 1,
  10189. /** An ordered mapping between documents and the mutations batch IDs. */
  10190. this.Rs = new Ee(Fo.ds);
  10191. }
  10192. checkEmpty(t) {
  10193. return Rt.resolve(0 === this.mutationQueue.length);
  10194. }
  10195. addMutationBatch(t, e, n, s) {
  10196. const i = this.vs;
  10197. this.vs++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];
  10198. const r = new Zs(i, e, n, s);
  10199. this.mutationQueue.push(r);
  10200. // Track references by document key and index collection parents.
  10201. for (const e of s) this.Rs = this.Rs.add(new Fo(e.key, i)), this.indexManager.addToCollectionParentIndex(t, e.key.path.popLast());
  10202. return Rt.resolve(r);
  10203. }
  10204. lookupMutationBatch(t, e) {
  10205. return Rt.resolve(this.Ps(e));
  10206. }
  10207. getNextMutationBatchAfterBatchId(t, e) {
  10208. const n = e + 1, s = this.bs(n), i = s < 0 ? 0 : s;
  10209. // The requested batchId may still be out of range so normalize it to the
  10210. // start of the queue.
  10211. return Rt.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);
  10212. }
  10213. getHighestUnacknowledgedBatchId() {
  10214. return Rt.resolve(0 === this.mutationQueue.length ? -1 : this.vs - 1);
  10215. }
  10216. getAllMutationBatches(t) {
  10217. return Rt.resolve(this.mutationQueue.slice());
  10218. }
  10219. getAllMutationBatchesAffectingDocumentKey(t, e) {
  10220. const n = new Fo(e, 0), s = new Fo(e, Number.POSITIVE_INFINITY), i = [];
  10221. return this.Rs.forEachInRange([ n, s ], (t => {
  10222. const e = this.Ps(t.As);
  10223. i.push(e);
  10224. })), Rt.resolve(i);
  10225. }
  10226. getAllMutationBatchesAffectingDocumentKeys(t, e) {
  10227. let n = new Ee(et);
  10228. return e.forEach((t => {
  10229. const e = new Fo(t, 0), s = new Fo(t, Number.POSITIVE_INFINITY);
  10230. this.Rs.forEachInRange([ e, s ], (t => {
  10231. n = n.add(t.As);
  10232. }));
  10233. })), Rt.resolve(this.Vs(n));
  10234. }
  10235. getAllMutationBatchesAffectingQuery(t, e) {
  10236. // Use the query path as a prefix for testing if a document matches the
  10237. // query.
  10238. const n = e.path, s = n.length + 1;
  10239. // Construct a document reference for actually scanning the index. Unlike
  10240. // the prefix the document key in this reference must have an even number of
  10241. // segments. The empty segment can be used a suffix of the query path
  10242. // because it precedes all other segments in an ordered traversal.
  10243. let i = n;
  10244. ht.isDocumentKey(i) || (i = i.child(""));
  10245. const r = new Fo(new ht(i), 0);
  10246. // Find unique batchIDs referenced by all documents potentially matching the
  10247. // query.
  10248. let o = new Ee(et);
  10249. return this.Rs.forEachWhile((t => {
  10250. const e = t.key.path;
  10251. return !!n.isPrefixOf(e) && (
  10252. // Rows with document keys more than one segment longer than the query
  10253. // path can't be matches. For example, a query on 'rooms' can't match
  10254. // the document /rooms/abc/messages/xyx.
  10255. // TODO(mcg): we'll need a different scanner when we implement
  10256. // ancestor queries.
  10257. e.length === s && (o = o.add(t.As)), !0);
  10258. }), r), Rt.resolve(this.Vs(o));
  10259. }
  10260. Vs(t) {
  10261. // Construct an array of matching batches, sorted by batchID to ensure that
  10262. // multiple mutations affecting the same document key are applied in order.
  10263. const e = [];
  10264. return t.forEach((t => {
  10265. const n = this.Ps(t);
  10266. null !== n && e.push(n);
  10267. })), e;
  10268. }
  10269. removeMutationBatch(t, e) {
  10270. F(0 === this.Ss(e.batchId, "removed")), this.mutationQueue.shift();
  10271. let n = this.Rs;
  10272. return Rt.forEach(e.mutations, (s => {
  10273. const i = new Fo(s.key, e.batchId);
  10274. return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(t, s.key);
  10275. })).next((() => {
  10276. this.Rs = n;
  10277. }));
  10278. }
  10279. Cn(t) {
  10280. // No-op since the memory mutation queue does not maintain a separate cache.
  10281. }
  10282. containsKey(t, e) {
  10283. const n = new Fo(e, 0), s = this.Rs.firstAfterOrEqual(n);
  10284. return Rt.resolve(e.isEqual(s && s.key));
  10285. }
  10286. performConsistencyCheck(t) {
  10287. return this.mutationQueue.length, Rt.resolve();
  10288. }
  10289. /**
  10290. * Finds the index of the given batchId in the mutation queue and asserts that
  10291. * the resulting index is within the bounds of the queue.
  10292. *
  10293. * @param batchId - The batchId to search for
  10294. * @param action - A description of what the caller is doing, phrased in passive
  10295. * form (e.g. "acknowledged" in a routine that acknowledges batches).
  10296. */ Ss(t, e) {
  10297. return this.bs(t);
  10298. }
  10299. /**
  10300. * Finds the index of the given batchId in the mutation queue. This operation
  10301. * is O(1).
  10302. *
  10303. * @returns The computed index of the batch with the given batchId, based on
  10304. * the state of the queue. Note this index can be negative if the requested
  10305. * batchId has already been remvoed from the queue or past the end of the
  10306. * queue if the batchId is larger than the last added batch.
  10307. */ bs(t) {
  10308. if (0 === this.mutationQueue.length)
  10309. // As an index this is past the end of the queue
  10310. return 0;
  10311. // Examine the front of the queue to figure out the difference between the
  10312. // batchId and indexes in the array. Note that since the queue is ordered
  10313. // by batchId, if the first batch has a larger batchId then the requested
  10314. // batchId doesn't exist in the queue.
  10315. return t - this.mutationQueue[0].batchId;
  10316. }
  10317. /**
  10318. * A version of lookupMutationBatch that doesn't return a promise, this makes
  10319. * other functions that uses this code easier to read and more efficent.
  10320. */ Ps(t) {
  10321. const e = this.bs(t);
  10322. if (e < 0 || e >= this.mutationQueue.length) return null;
  10323. return this.mutationQueue[e];
  10324. }
  10325. }
  10326. /**
  10327. * @license
  10328. * Copyright 2017 Google LLC
  10329. *
  10330. * Licensed under the Apache License, Version 2.0 (the "License");
  10331. * you may not use this file except in compliance with the License.
  10332. * You may obtain a copy of the License at
  10333. *
  10334. * http://www.apache.org/licenses/LICENSE-2.0
  10335. *
  10336. * Unless required by applicable law or agreed to in writing, software
  10337. * distributed under the License is distributed on an "AS IS" BASIS,
  10338. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10339. * See the License for the specific language governing permissions and
  10340. * limitations under the License.
  10341. */
  10342. /**
  10343. * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke
  10344. * `newMemoryRemoteDocumentCache()`.
  10345. */
  10346. class Lo {
  10347. /**
  10348. * @param sizer - Used to assess the size of a document. For eager GC, this is
  10349. * expected to just return 0 to avoid unnecessarily doing the work of
  10350. * calculating the size.
  10351. */
  10352. constructor(t) {
  10353. this.Ds = t,
  10354. /** Underlying cache of documents and their read times. */
  10355. this.docs = new pe(ht.comparator),
  10356. /** Size of all cached documents. */
  10357. this.size = 0;
  10358. }
  10359. setIndexManager(t) {
  10360. this.indexManager = t;
  10361. }
  10362. /**
  10363. * Adds the supplied entry to the cache and updates the cache size as appropriate.
  10364. *
  10365. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  10366. * returned by `newChangeBuffer()`.
  10367. */ addEntry(t, e) {
  10368. const n = e.key, s = this.docs.get(n), i = s ? s.size : 0, r = this.Ds(e);
  10369. return this.docs = this.docs.insert(n, {
  10370. document: e.mutableCopy(),
  10371. size: r
  10372. }), this.size += r - i, this.indexManager.addToCollectionParentIndex(t, n.path.popLast());
  10373. }
  10374. /**
  10375. * Removes the specified entry from the cache and updates the cache size as appropriate.
  10376. *
  10377. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  10378. * returned by `newChangeBuffer()`.
  10379. */ removeEntry(t) {
  10380. const e = this.docs.get(t);
  10381. e && (this.docs = this.docs.remove(t), this.size -= e.size);
  10382. }
  10383. getEntry(t, e) {
  10384. const n = this.docs.get(e);
  10385. return Rt.resolve(n ? n.document.mutableCopy() : an.newInvalidDocument(e));
  10386. }
  10387. getEntries(t, e) {
  10388. let n = cs();
  10389. return e.forEach((t => {
  10390. const e = this.docs.get(t);
  10391. n = n.insert(t, e ? e.document.mutableCopy() : an.newInvalidDocument(t));
  10392. })), Rt.resolve(n);
  10393. }
  10394. getDocumentsMatchingQuery(t, e, n, s) {
  10395. let i = cs();
  10396. // Documents are ordered by key, so we can use a prefix scan to narrow down
  10397. // the documents we need to match the query against.
  10398. const r = e.path, o = new ht(r.child("")), u = this.docs.getIteratorFrom(o);
  10399. for (;u.hasNext(); ) {
  10400. const {key: t, value: {document: o}} = u.getNext();
  10401. if (!r.isPrefixOf(t.path)) break;
  10402. t.path.length > r.length + 1 || (Tt(pt(o), n) <= 0 || (s.has(o.key) || ns(e, o)) && (i = i.insert(o.key, o.mutableCopy())));
  10403. }
  10404. return Rt.resolve(i);
  10405. }
  10406. getAllFromCollectionGroup(t, e, n, s) {
  10407. // This method should only be called from the IndexBackfiller if persistence
  10408. // is enabled.
  10409. O();
  10410. }
  10411. Cs(t, e) {
  10412. return Rt.forEach(this.docs, (t => e(t)));
  10413. }
  10414. newChangeBuffer(t) {
  10415. // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
  10416. // a separate changelog and does not need special handling for removals.
  10417. return new qo(this);
  10418. }
  10419. getSize(t) {
  10420. return Rt.resolve(this.size);
  10421. }
  10422. }
  10423. /**
  10424. * Creates a new memory-only RemoteDocumentCache.
  10425. *
  10426. * @param sizer - Used to assess the size of a document. For eager GC, this is
  10427. * expected to just return 0 to avoid unnecessarily doing the work of
  10428. * calculating the size.
  10429. */
  10430. /**
  10431. * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.
  10432. */
  10433. class qo extends vo {
  10434. constructor(t) {
  10435. super(), this.os = t;
  10436. }
  10437. applyChanges(t) {
  10438. const e = [];
  10439. return this.changes.forEach(((n, s) => {
  10440. s.isValidDocument() ? e.push(this.os.addEntry(t, s)) : this.os.removeEntry(n);
  10441. })), Rt.waitFor(e);
  10442. }
  10443. getFromCache(t, e) {
  10444. return this.os.getEntry(t, e);
  10445. }
  10446. getAllFromCache(t, e) {
  10447. return this.os.getEntries(t, e);
  10448. }
  10449. }
  10450. /**
  10451. * @license
  10452. * Copyright 2017 Google LLC
  10453. *
  10454. * Licensed under the Apache License, Version 2.0 (the "License");
  10455. * you may not use this file except in compliance with the License.
  10456. * You may obtain a copy of the License at
  10457. *
  10458. * http://www.apache.org/licenses/LICENSE-2.0
  10459. *
  10460. * Unless required by applicable law or agreed to in writing, software
  10461. * distributed under the License is distributed on an "AS IS" BASIS,
  10462. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10463. * See the License for the specific language governing permissions and
  10464. * limitations under the License.
  10465. */ class Uo {
  10466. constructor(t) {
  10467. this.persistence = t,
  10468. /**
  10469. * Maps a target to the data about that target
  10470. */
  10471. this.xs = new os((t => $n(t)), On),
  10472. /** The last received snapshot version. */
  10473. this.lastRemoteSnapshotVersion = rt.min(),
  10474. /** The highest numbered target ID encountered. */
  10475. this.highestTargetId = 0,
  10476. /** The highest sequence number encountered. */
  10477. this.Ns = 0,
  10478. /**
  10479. * A ordered bidirectional mapping between documents and the remote target
  10480. * IDs.
  10481. */
  10482. this.ks = new Oo, this.targetCount = 0, this.Ms = lo.kn();
  10483. }
  10484. forEachTarget(t, e) {
  10485. return this.xs.forEach(((t, n) => e(n))), Rt.resolve();
  10486. }
  10487. getLastRemoteSnapshotVersion(t) {
  10488. return Rt.resolve(this.lastRemoteSnapshotVersion);
  10489. }
  10490. getHighestSequenceNumber(t) {
  10491. return Rt.resolve(this.Ns);
  10492. }
  10493. allocateTargetId(t) {
  10494. return this.highestTargetId = this.Ms.next(), Rt.resolve(this.highestTargetId);
  10495. }
  10496. setTargetsMetadata(t, e, n) {
  10497. return n && (this.lastRemoteSnapshotVersion = n), e > this.Ns && (this.Ns = e),
  10498. Rt.resolve();
  10499. }
  10500. Fn(t) {
  10501. this.xs.set(t.target, t);
  10502. const e = t.targetId;
  10503. e > this.highestTargetId && (this.Ms = new lo(e), this.highestTargetId = e), t.sequenceNumber > this.Ns && (this.Ns = t.sequenceNumber);
  10504. }
  10505. addTargetData(t, e) {
  10506. return this.Fn(e), this.targetCount += 1, Rt.resolve();
  10507. }
  10508. updateTargetData(t, e) {
  10509. return this.Fn(e), Rt.resolve();
  10510. }
  10511. removeTargetData(t, e) {
  10512. return this.xs.delete(e.target), this.ks.Is(e.targetId), this.targetCount -= 1,
  10513. Rt.resolve();
  10514. }
  10515. removeTargets(t, e, n) {
  10516. let s = 0;
  10517. const i = [];
  10518. return this.xs.forEach(((r, o) => {
  10519. o.sequenceNumber <= e && null === n.get(o.targetId) && (this.xs.delete(r), i.push(this.removeMatchingKeysForTargetId(t, o.targetId)),
  10520. s++);
  10521. })), Rt.waitFor(i).next((() => s));
  10522. }
  10523. getTargetCount(t) {
  10524. return Rt.resolve(this.targetCount);
  10525. }
  10526. getTargetData(t, e) {
  10527. const n = this.xs.get(e) || null;
  10528. return Rt.resolve(n);
  10529. }
  10530. addMatchingKeys(t, e, n) {
  10531. return this.ks.gs(e, n), Rt.resolve();
  10532. }
  10533. removeMatchingKeys(t, e, n) {
  10534. this.ks.ps(e, n);
  10535. const s = this.persistence.referenceDelegate, i = [];
  10536. return s && e.forEach((e => {
  10537. i.push(s.markPotentiallyOrphaned(t, e));
  10538. })), Rt.waitFor(i);
  10539. }
  10540. removeMatchingKeysForTargetId(t, e) {
  10541. return this.ks.Is(e), Rt.resolve();
  10542. }
  10543. getMatchingKeysForTargetId(t, e) {
  10544. const n = this.ks.Es(e);
  10545. return Rt.resolve(n);
  10546. }
  10547. containsKey(t, e) {
  10548. return Rt.resolve(this.ks.containsKey(e));
  10549. }
  10550. }
  10551. /**
  10552. * @license
  10553. * Copyright 2017 Google LLC
  10554. *
  10555. * Licensed under the Apache License, Version 2.0 (the "License");
  10556. * you may not use this file except in compliance with the License.
  10557. * You may obtain a copy of the License at
  10558. *
  10559. * http://www.apache.org/licenses/LICENSE-2.0
  10560. *
  10561. * Unless required by applicable law or agreed to in writing, software
  10562. * distributed under the License is distributed on an "AS IS" BASIS,
  10563. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10564. * See the License for the specific language governing permissions and
  10565. * limitations under the License.
  10566. */
  10567. /**
  10568. * A memory-backed instance of Persistence. Data is stored only in RAM and
  10569. * not persisted across sessions.
  10570. */
  10571. class Ko {
  10572. /**
  10573. * The constructor accepts a factory for creating a reference delegate. This
  10574. * allows both the delegate and this instance to have strong references to
  10575. * each other without having nullable fields that would then need to be
  10576. * checked or asserted on every access.
  10577. */
  10578. constructor(t, e) {
  10579. this.$s = {}, this.overlays = {}, this.Os = new Ot(0), this.Fs = !1, this.Fs = !0,
  10580. this.referenceDelegate = t(this), this.Bs = new Uo(this);
  10581. this.indexManager = new zr, this.remoteDocumentCache = function(t) {
  10582. return new Lo(t);
  10583. }((t => this.referenceDelegate.Ls(t))), this.serializer = new ar(e), this.qs = new Mo(this.serializer);
  10584. }
  10585. start() {
  10586. return Promise.resolve();
  10587. }
  10588. shutdown() {
  10589. // No durable state to ensure is closed on shutdown.
  10590. return this.Fs = !1, Promise.resolve();
  10591. }
  10592. get started() {
  10593. return this.Fs;
  10594. }
  10595. setDatabaseDeletedListener() {
  10596. // No op.
  10597. }
  10598. setNetworkEnabled() {
  10599. // No op.
  10600. }
  10601. getIndexManager(t) {
  10602. // We do not currently support indices for memory persistence, so we can
  10603. // return the same shared instance of the memory index manager.
  10604. return this.indexManager;
  10605. }
  10606. getDocumentOverlayCache(t) {
  10607. let e = this.overlays[t.toKey()];
  10608. return e || (e = new $o, this.overlays[t.toKey()] = e), e;
  10609. }
  10610. getMutationQueue(t, e) {
  10611. let n = this.$s[t.toKey()];
  10612. return n || (n = new Bo(e, this.referenceDelegate), this.$s[t.toKey()] = n), n;
  10613. }
  10614. getTargetCache() {
  10615. return this.Bs;
  10616. }
  10617. getRemoteDocumentCache() {
  10618. return this.remoteDocumentCache;
  10619. }
  10620. getBundleCache() {
  10621. return this.qs;
  10622. }
  10623. runTransaction(t, e, n) {
  10624. N("MemoryPersistence", "Starting transaction:", t);
  10625. const s = new Go(this.Os.next());
  10626. return this.referenceDelegate.Us(), n(s).next((t => this.referenceDelegate.Ks(s).next((() => t)))).toPromise().then((t => (s.raiseOnCommittedEvent(),
  10627. t)));
  10628. }
  10629. Gs(t, e) {
  10630. return Rt.or(Object.values(this.$s).map((n => () => n.containsKey(t, e))));
  10631. }
  10632. }
  10633. /**
  10634. * Memory persistence is not actually transactional, but future implementations
  10635. * may have transaction-scoped state.
  10636. */ class Go extends At {
  10637. constructor(t) {
  10638. super(), this.currentSequenceNumber = t;
  10639. }
  10640. }
  10641. class Qo {
  10642. constructor(t) {
  10643. this.persistence = t,
  10644. /** Tracks all documents that are active in Query views. */
  10645. this.Qs = new Oo,
  10646. /** The list of documents that are potentially GCed after each transaction. */
  10647. this.js = null;
  10648. }
  10649. static zs(t) {
  10650. return new Qo(t);
  10651. }
  10652. get Ws() {
  10653. if (this.js) return this.js;
  10654. throw O();
  10655. }
  10656. addReference(t, e, n) {
  10657. return this.Qs.addReference(n, e), this.Ws.delete(n.toString()), Rt.resolve();
  10658. }
  10659. removeReference(t, e, n) {
  10660. return this.Qs.removeReference(n, e), this.Ws.add(n.toString()), Rt.resolve();
  10661. }
  10662. markPotentiallyOrphaned(t, e) {
  10663. return this.Ws.add(e.toString()), Rt.resolve();
  10664. }
  10665. removeTarget(t, e) {
  10666. this.Qs.Is(e.targetId).forEach((t => this.Ws.add(t.toString())));
  10667. const n = this.persistence.getTargetCache();
  10668. return n.getMatchingKeysForTargetId(t, e.targetId).next((t => {
  10669. t.forEach((t => this.Ws.add(t.toString())));
  10670. })).next((() => n.removeTargetData(t, e)));
  10671. }
  10672. Us() {
  10673. this.js = new Set;
  10674. }
  10675. Ks(t) {
  10676. // Remove newly orphaned documents.
  10677. const e = this.persistence.getRemoteDocumentCache().newChangeBuffer();
  10678. return Rt.forEach(this.Ws, (n => {
  10679. const s = ht.fromPath(n);
  10680. return this.Hs(t, s).next((t => {
  10681. t || e.removeEntry(s, rt.min());
  10682. }));
  10683. })).next((() => (this.js = null, e.apply(t))));
  10684. }
  10685. updateLimboDocument(t, e) {
  10686. return this.Hs(t, e).next((t => {
  10687. t ? this.Ws.delete(e.toString()) : this.Ws.add(e.toString());
  10688. }));
  10689. }
  10690. Ls(t) {
  10691. // For eager GC, we don't care about the document size, there are no size thresholds.
  10692. return 0;
  10693. }
  10694. Hs(t, e) {
  10695. return Rt.or([ () => Rt.resolve(this.Qs.containsKey(e)), () => this.persistence.getTargetCache().containsKey(t, e), () => this.persistence.Gs(t, e) ]);
  10696. }
  10697. }
  10698. class jo {
  10699. constructor(t, e) {
  10700. this.persistence = t, this.Js = new os((t => qt(t.path)), ((t, e) => t.isEqual(e))),
  10701. this.garbageCollector = To(this, e);
  10702. }
  10703. static zs(t, e) {
  10704. return new jo(t, e);
  10705. }
  10706. // No-ops, present so memory persistence doesn't have to care which delegate
  10707. // it has.
  10708. Us() {}
  10709. Ks(t) {
  10710. return Rt.resolve();
  10711. }
  10712. forEachTarget(t, e) {
  10713. return this.persistence.getTargetCache().forEachTarget(t, e);
  10714. }
  10715. zn(t) {
  10716. const e = this.Jn(t);
  10717. return this.persistence.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));
  10718. }
  10719. Jn(t) {
  10720. let e = 0;
  10721. return this.Wn(t, (t => {
  10722. e++;
  10723. })).next((() => e));
  10724. }
  10725. Wn(t, e) {
  10726. return Rt.forEach(this.Js, ((n, s) => this.Xn(t, n, s).next((t => t ? Rt.resolve() : e(s)))));
  10727. }
  10728. removeTargets(t, e, n) {
  10729. return this.persistence.getTargetCache().removeTargets(t, e, n);
  10730. }
  10731. removeOrphanedDocuments(t, e) {
  10732. let n = 0;
  10733. const s = this.persistence.getRemoteDocumentCache(), i = s.newChangeBuffer();
  10734. return s.Cs(t, (s => this.Xn(t, s, e).next((t => {
  10735. t || (n++, i.removeEntry(s, rt.min()));
  10736. })))).next((() => i.apply(t))).next((() => n));
  10737. }
  10738. markPotentiallyOrphaned(t, e) {
  10739. return this.Js.set(e, t.currentSequenceNumber), Rt.resolve();
  10740. }
  10741. removeTarget(t, e) {
  10742. const n = e.withSequenceNumber(t.currentSequenceNumber);
  10743. return this.persistence.getTargetCache().updateTargetData(t, n);
  10744. }
  10745. addReference(t, e, n) {
  10746. return this.Js.set(n, t.currentSequenceNumber), Rt.resolve();
  10747. }
  10748. removeReference(t, e, n) {
  10749. return this.Js.set(n, t.currentSequenceNumber), Rt.resolve();
  10750. }
  10751. updateLimboDocument(t, e) {
  10752. return this.Js.set(e, t.currentSequenceNumber), Rt.resolve();
  10753. }
  10754. Ls(t) {
  10755. let e = t.key.toString().length;
  10756. return t.isFoundDocument() && (e += ze(t.data.value)), e;
  10757. }
  10758. Xn(t, e, n) {
  10759. return Rt.or([ () => this.persistence.Gs(t, e), () => this.persistence.getTargetCache().containsKey(t, e), () => {
  10760. const t = this.Js.get(e);
  10761. return Rt.resolve(void 0 !== t && t > n);
  10762. } ]);
  10763. }
  10764. getCacheSize(t) {
  10765. return this.persistence.getRemoteDocumentCache().getSize(t);
  10766. }
  10767. }
  10768. /**
  10769. * @license
  10770. * Copyright 2020 Google LLC
  10771. *
  10772. * Licensed under the Apache License, Version 2.0 (the "License");
  10773. * you may not use this file except in compliance with the License.
  10774. * You may obtain a copy of the License at
  10775. *
  10776. * http://www.apache.org/licenses/LICENSE-2.0
  10777. *
  10778. * Unless required by applicable law or agreed to in writing, software
  10779. * distributed under the License is distributed on an "AS IS" BASIS,
  10780. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10781. * See the License for the specific language governing permissions and
  10782. * limitations under the License.
  10783. */
  10784. /** Performs database creation and schema upgrades. */ class zo {
  10785. constructor(t) {
  10786. this.serializer = t;
  10787. }
  10788. /**
  10789. * Performs database creation and schema upgrades.
  10790. *
  10791. * Note that in production, this method is only ever used to upgrade the schema
  10792. * to SCHEMA_VERSION. Different values of toVersion are only used for testing
  10793. * and local feature development.
  10794. */ O(t, e, n, s) {
  10795. const i = new Pt("createOrUpgrade", e);
  10796. n < 1 && s >= 1 && (function(t) {
  10797. t.createObjectStore("owner");
  10798. }(t), function(t) {
  10799. t.createObjectStore("mutationQueues", {
  10800. keyPath: "userId"
  10801. });
  10802. t.createObjectStore("mutations", {
  10803. keyPath: "batchId",
  10804. autoIncrement: !0
  10805. }).createIndex("userMutationsIndex", Qt, {
  10806. unique: !0
  10807. }), t.createObjectStore("documentMutations");
  10808. }
  10809. /**
  10810. * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads
  10811. * and rewrites all data.
  10812. */ (t), Wo(t), function(t) {
  10813. t.createObjectStore("remoteDocuments");
  10814. }(t));
  10815. // Migration 2 to populate the targetGlobal object no longer needed since
  10816. // migration 3 unconditionally clears it.
  10817. let r = Rt.resolve();
  10818. return n < 3 && s >= 3 && (
  10819. // Brand new clients don't need to drop and recreate--only clients that
  10820. // potentially have corrupt data.
  10821. 0 !== n && (!function(t) {
  10822. t.deleteObjectStore("targetDocuments"), t.deleteObjectStore("targets"), t.deleteObjectStore("targetGlobal");
  10823. }(t), Wo(t)), r = r.next((() =>
  10824. /**
  10825. * Creates the target global singleton row.
  10826. *
  10827. * @param txn - The version upgrade transaction for indexeddb
  10828. */
  10829. function(t) {
  10830. const e = t.store("targetGlobal"), n = {
  10831. highestTargetId: 0,
  10832. highestListenSequenceNumber: 0,
  10833. lastRemoteSnapshotVersion: rt.min().toTimestamp(),
  10834. targetCount: 0
  10835. };
  10836. return e.put("targetGlobalKey", n);
  10837. }(i)))), n < 4 && s >= 4 && (0 !== n && (
  10838. // Schema version 3 uses auto-generated keys to generate globally unique
  10839. // mutation batch IDs (this was previously ensured internally by the
  10840. // client). To migrate to the new schema, we have to read all mutations
  10841. // and write them back out. We preserve the existing batch IDs to guarantee
  10842. // consistency with other object stores. Any further mutation batch IDs will
  10843. // be auto-generated.
  10844. r = r.next((() => function(t, e) {
  10845. return e.store("mutations").j().next((n => {
  10846. t.deleteObjectStore("mutations");
  10847. t.createObjectStore("mutations", {
  10848. keyPath: "batchId",
  10849. autoIncrement: !0
  10850. }).createIndex("userMutationsIndex", Qt, {
  10851. unique: !0
  10852. });
  10853. const s = e.store("mutations"), i = n.map((t => s.put(t)));
  10854. return Rt.waitFor(i);
  10855. }));
  10856. }(t, i)))), r = r.next((() => {
  10857. !function(t) {
  10858. t.createObjectStore("clientMetadata", {
  10859. keyPath: "clientId"
  10860. });
  10861. }(t);
  10862. }))), n < 5 && s >= 5 && (r = r.next((() => this.Ys(i)))), n < 6 && s >= 6 && (r = r.next((() => (function(t) {
  10863. t.createObjectStore("remoteDocumentGlobal");
  10864. }(t), this.Xs(i))))), n < 7 && s >= 7 && (r = r.next((() => this.Zs(i)))), n < 8 && s >= 8 && (r = r.next((() => this.ti(t, i)))),
  10865. n < 9 && s >= 9 && (r = r.next((() => {
  10866. // Multi-Tab used to manage its own changelog, but this has been moved
  10867. // to the DbRemoteDocument object store itself. Since the previous change
  10868. // log only contained transient data, we can drop its object store.
  10869. !function(t) {
  10870. t.objectStoreNames.contains("remoteDocumentChanges") && t.deleteObjectStore("remoteDocumentChanges");
  10871. }(t);
  10872. // Note: Schema version 9 used to create a read time index for the
  10873. // RemoteDocumentCache. This is now done with schema version 13.
  10874. }))), n < 10 && s >= 10 && (r = r.next((() => this.ei(i)))), n < 11 && s >= 11 && (r = r.next((() => {
  10875. !function(t) {
  10876. t.createObjectStore("bundles", {
  10877. keyPath: "bundleId"
  10878. });
  10879. }(t), function(t) {
  10880. t.createObjectStore("namedQueries", {
  10881. keyPath: "name"
  10882. });
  10883. }(t);
  10884. }))), n < 12 && s >= 12 && (r = r.next((() => {
  10885. !function(t) {
  10886. const e = t.createObjectStore("documentOverlays", {
  10887. keyPath: oe
  10888. });
  10889. e.createIndex("collectionPathOverlayIndex", ue, {
  10890. unique: !1
  10891. }), e.createIndex("collectionGroupOverlayIndex", ce, {
  10892. unique: !1
  10893. });
  10894. }(t);
  10895. }))), n < 13 && s >= 13 && (r = r.next((() => function(t) {
  10896. const e = t.createObjectStore("remoteDocumentsV14", {
  10897. keyPath: Ht
  10898. });
  10899. e.createIndex("documentKeyIndex", Jt), e.createIndex("collectionGroupIndex", Yt);
  10900. }(t))).next((() => this.ni(t, i))).next((() => t.deleteObjectStore("remoteDocuments")))),
  10901. n < 14 && s >= 14 && (r = r.next((() => this.si(t, i)))), n < 15 && s >= 15 && (r = r.next((() => function(t) {
  10902. t.createObjectStore("indexConfiguration", {
  10903. keyPath: "indexId",
  10904. autoIncrement: !0
  10905. }).createIndex("collectionGroupIndex", "collectionGroup", {
  10906. unique: !1
  10907. });
  10908. t.createObjectStore("indexState", {
  10909. keyPath: ne
  10910. }).createIndex("sequenceNumberIndex", se, {
  10911. unique: !1
  10912. });
  10913. t.createObjectStore("indexEntries", {
  10914. keyPath: ie
  10915. }).createIndex("documentKeyIndex", re, {
  10916. unique: !1
  10917. });
  10918. }(t)))), r;
  10919. }
  10920. Xs(t) {
  10921. let e = 0;
  10922. return t.store("remoteDocuments").X(((t, n) => {
  10923. e += ro(n);
  10924. })).next((() => {
  10925. const n = {
  10926. byteSize: e
  10927. };
  10928. return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey", n);
  10929. }));
  10930. }
  10931. Ys(t) {
  10932. const e = t.store("mutationQueues"), n = t.store("mutations");
  10933. return e.j().next((e => Rt.forEach(e, (e => {
  10934. const s = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);
  10935. return n.j("userMutationsIndex", s).next((n => Rt.forEach(n, (n => {
  10936. F(n.userId === e.userId);
  10937. const s = _r(this.serializer, n);
  10938. return io(t, e.userId, s).next((() => {}));
  10939. }))));
  10940. }))));
  10941. }
  10942. /**
  10943. * Ensures that every document in the remote document cache has a corresponding sentinel row
  10944. * with a sequence number. Missing rows are given the most recently used sequence number.
  10945. */ Zs(t) {
  10946. const e = t.store("targetDocuments"), n = t.store("remoteDocuments");
  10947. return t.store("targetGlobal").get("targetGlobalKey").next((t => {
  10948. const s = [];
  10949. return n.X(((n, i) => {
  10950. const r = new ut(n), o = function(t) {
  10951. return [ 0, qt(t) ];
  10952. }(r);
  10953. s.push(e.get(o).next((n => n ? Rt.resolve() : (n => e.put({
  10954. targetId: 0,
  10955. path: qt(n),
  10956. sequenceNumber: t.highestListenSequenceNumber
  10957. }))(r))));
  10958. })).next((() => Rt.waitFor(s)));
  10959. }));
  10960. }
  10961. ti(t, e) {
  10962. // Create the index.
  10963. t.createObjectStore("collectionParents", {
  10964. keyPath: ee
  10965. });
  10966. const n = e.store("collectionParents"), s = new Wr, i = t => {
  10967. if (s.add(t)) {
  10968. const e = t.lastSegment(), s = t.popLast();
  10969. return n.put({
  10970. collectionId: e,
  10971. parent: qt(s)
  10972. });
  10973. }
  10974. };
  10975. // Helper to add an index entry iff we haven't already written it.
  10976. // Index existing remote documents.
  10977. return e.store("remoteDocuments").X({
  10978. Y: !0
  10979. }, ((t, e) => {
  10980. const n = new ut(t);
  10981. return i(n.popLast());
  10982. })).next((() => e.store("documentMutations").X({
  10983. Y: !0
  10984. }, (([t, e, n], s) => {
  10985. const r = Gt(e);
  10986. return i(r.popLast());
  10987. }))));
  10988. }
  10989. ei(t) {
  10990. const e = t.store("targets");
  10991. return e.X(((t, n) => {
  10992. const s = mr(n), i = gr(this.serializer, s);
  10993. return e.put(i);
  10994. }));
  10995. }
  10996. ni(t, e) {
  10997. const n = e.store("remoteDocuments"), s = [];
  10998. return n.X(((t, n) => {
  10999. const i = e.store("remoteDocumentsV14"), r = (o = n, o.document ? new ht(ut.fromString(o.document.name).popFirst(5)) : o.noDocument ? ht.fromSegments(o.noDocument.path) : o.unknownDocument ? ht.fromSegments(o.unknownDocument.path) : O()).path.toArray();
  11000. var o;
  11001. /**
  11002. * @license
  11003. * Copyright 2017 Google LLC
  11004. *
  11005. * Licensed under the Apache License, Version 2.0 (the "License");
  11006. * you may not use this file except in compliance with the License.
  11007. * You may obtain a copy of the License at
  11008. *
  11009. * http://www.apache.org/licenses/LICENSE-2.0
  11010. *
  11011. * Unless required by applicable law or agreed to in writing, software
  11012. * distributed under the License is distributed on an "AS IS" BASIS,
  11013. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11014. * See the License for the specific language governing permissions and
  11015. * limitations under the License.
  11016. */ const u = {
  11017. prefixPath: r.slice(0, r.length - 2),
  11018. collectionGroup: r[r.length - 2],
  11019. documentId: r[r.length - 1],
  11020. readTime: n.readTime || [ 0, 0 ],
  11021. unknownDocument: n.unknownDocument,
  11022. noDocument: n.noDocument,
  11023. document: n.document,
  11024. hasCommittedMutations: !!n.hasCommittedMutations
  11025. };
  11026. s.push(i.put(u));
  11027. })).next((() => Rt.waitFor(s)));
  11028. }
  11029. si(t, e) {
  11030. const n = e.store("mutations"), s = Po(this.serializer), i = new Ko(Qo.zs, this.serializer.fe);
  11031. return n.j().next((t => {
  11032. const n = new Map;
  11033. return t.forEach((t => {
  11034. var e;
  11035. let s = null !== (e = n.get(t.userId)) && void 0 !== e ? e : gs();
  11036. _r(this.serializer, t).keys().forEach((t => s = s.add(t))), n.set(t.userId, s);
  11037. })), Rt.forEach(n, ((t, n) => {
  11038. const r = new V(n), o = Rr.de(this.serializer, r), u = i.getIndexManager(r), c = oo.de(r, this.serializer, u, i.referenceDelegate);
  11039. return new ko(s, c, o, u).recalculateAndSaveOverlaysForDocumentKeys(new we(e, Ot.ct), t).next();
  11040. }));
  11041. }));
  11042. }
  11043. }
  11044. function Wo(t) {
  11045. t.createObjectStore("targetDocuments", {
  11046. keyPath: Zt
  11047. }).createIndex("documentTargetsIndex", te, {
  11048. unique: !0
  11049. });
  11050. // NOTE: This is unique only because the TargetId is the suffix.
  11051. t.createObjectStore("targets", {
  11052. keyPath: "targetId"
  11053. }).createIndex("queryTargetsIndex", Xt, {
  11054. unique: !0
  11055. }), t.createObjectStore("targetGlobal");
  11056. }
  11057. const Ho = "Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";
  11058. /**
  11059. * Oldest acceptable age in milliseconds for client metadata before the client
  11060. * is considered inactive and its associated data is garbage collected.
  11061. */
  11062. /**
  11063. * An IndexedDB-backed instance of Persistence. Data is stored persistently
  11064. * across sessions.
  11065. *
  11066. * On Web only, the Firestore SDKs support shared access to its persistence
  11067. * layer. This allows multiple browser tabs to read and write to IndexedDb and
  11068. * to synchronize state even without network connectivity. Shared access is
  11069. * currently optional and not enabled unless all clients invoke
  11070. * `enablePersistence()` with `{synchronizeTabs:true}`.
  11071. *
  11072. * In multi-tab mode, if multiple clients are active at the same time, the SDK
  11073. * will designate one client as the “primary client”. An effort is made to pick
  11074. * a visible, network-connected and active client, and this client is
  11075. * responsible for letting other clients know about its presence. The primary
  11076. * client writes a unique client-generated identifier (the client ID) to
  11077. * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to
  11078. * update this entry, another client can acquire the lease and take over as
  11079. * primary.
  11080. *
  11081. * Some persistence operations in the SDK are designated as primary-client only
  11082. * operations. This includes the acknowledgment of mutations and all updates of
  11083. * remote documents. The effects of these operations are written to persistence
  11084. * and then broadcast to other tabs via LocalStorage (see
  11085. * `WebStorageSharedClientState`), which then refresh their state from
  11086. * persistence.
  11087. *
  11088. * Similarly, the primary client listens to notifications sent by secondary
  11089. * clients to discover persistence changes written by secondary clients, such as
  11090. * the addition of new mutations and query targets.
  11091. *
  11092. * If multi-tab is not enabled and another tab already obtained the primary
  11093. * lease, IndexedDbPersistence enters a failed state and all subsequent
  11094. * operations will automatically fail.
  11095. *
  11096. * Additionally, there is an optimization so that when a tab is closed, the
  11097. * primary lease is released immediately (this is especially important to make
  11098. * sure that a refreshed tab is able to immediately re-acquire the primary
  11099. * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload
  11100. * since it is an asynchronous API. So in addition to attempting to give up the
  11101. * lease, the leaseholder writes its client ID to a "zombiedClient" entry in
  11102. * LocalStorage which acts as an indicator that another tab should go ahead and
  11103. * take the primary lease immediately regardless of the current lease timestamp.
  11104. *
  11105. * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no
  11106. * longer optional.
  11107. */
  11108. class Jo {
  11109. constructor(
  11110. /**
  11111. * Whether to synchronize the in-memory state of multiple tabs and share
  11112. * access to local persistence.
  11113. */
  11114. t, e, n, s, i, r, o, u, c,
  11115. /**
  11116. * If set to true, forcefully obtains database access. Existing tabs will
  11117. * no longer be able to access IndexedDB.
  11118. */
  11119. a, h = 15) {
  11120. if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = n,
  11121. this.ii = i, this.window = r, this.document = o, this.ri = c, this.oi = a, this.ui = h,
  11122. this.Os = null, this.Fs = !1, this.isPrimary = !1, this.networkEnabled = !0,
  11123. /** Our window.unload handler, if registered. */
  11124. this.ci = null, this.inForeground = !1,
  11125. /** Our 'visibilitychange' listener if registered. */
  11126. this.ai = null,
  11127. /** The client metadata refresh task. */
  11128. this.hi = null,
  11129. /** The last time we garbage collected the client metadata object store. */
  11130. this.li = Number.NEGATIVE_INFINITY,
  11131. /** A listener to notify on primary state changes. */
  11132. this.fi = t => Promise.resolve(), !Jo.D()) throw new U(q.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
  11133. this.referenceDelegate = new Eo(this, s), this.di = e + "main", this.serializer = new ar(u),
  11134. this.wi = new bt(this.di, this.ui, new zo(this.serializer)), this.Bs = new fo(this.referenceDelegate, this.serializer),
  11135. this.remoteDocumentCache = Po(this.serializer), this.qs = new Er, this.window && this.window.localStorage ? this._i = this.window.localStorage : (this._i = null,
  11136. !1 === a && k("IndexedDbPersistence", "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."));
  11137. }
  11138. /**
  11139. * Attempt to start IndexedDb persistence.
  11140. *
  11141. * @returns Whether persistence was enabled.
  11142. */ start() {
  11143. // NOTE: This is expected to fail sometimes (in the case of another tab
  11144. // already having the persistence lock), so it's the first thing we should
  11145. // do.
  11146. return this.mi().then((() => {
  11147. if (!this.isPrimary && !this.allowTabSynchronization)
  11148. // Fail `start()` if `synchronizeTabs` is disabled and we cannot
  11149. // obtain the primary lease.
  11150. throw new U(q.FAILED_PRECONDITION, Ho);
  11151. return this.gi(), this.yi(), this.pi(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (t => this.Bs.getHighestSequenceNumber(t)));
  11152. })).then((t => {
  11153. this.Os = new Ot(t, this.ri);
  11154. })).then((() => {
  11155. this.Fs = !0;
  11156. })).catch((t => (this.wi && this.wi.close(), Promise.reject(t))));
  11157. }
  11158. /**
  11159. * Registers a listener that gets called when the primary state of the
  11160. * instance changes. Upon registering, this listener is invoked immediately
  11161. * with the current primary state.
  11162. *
  11163. * PORTING NOTE: This is only used for Web multi-tab.
  11164. */ Ii(t) {
  11165. return this.fi = async e => {
  11166. if (this.started) return t(e);
  11167. }, t(this.isPrimary);
  11168. }
  11169. /**
  11170. * Registers a listener that gets called when the database receives a
  11171. * version change event indicating that it has deleted.
  11172. *
  11173. * PORTING NOTE: This is only used for Web multi-tab.
  11174. */ setDatabaseDeletedListener(t) {
  11175. this.wi.B((async e => {
  11176. // Check if an attempt is made to delete IndexedDB.
  11177. null === e.newVersion && await t();
  11178. }));
  11179. }
  11180. /**
  11181. * Adjusts the current network state in the client's metadata, potentially
  11182. * affecting the primary lease.
  11183. *
  11184. * PORTING NOTE: This is only used for Web multi-tab.
  11185. */ setNetworkEnabled(t) {
  11186. this.networkEnabled !== t && (this.networkEnabled = t,
  11187. // Schedule a primary lease refresh for immediate execution. The eventual
  11188. // lease update will be propagated via `primaryStateListener`.
  11189. this.ii.enqueueAndForget((async () => {
  11190. this.started && await this.mi();
  11191. })));
  11192. }
  11193. /**
  11194. * Updates the client metadata in IndexedDb and attempts to either obtain or
  11195. * extend the primary lease for the local client. Asynchronously notifies the
  11196. * primary state listener if the client either newly obtained or released its
  11197. * primary lease.
  11198. */ mi() {
  11199. return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (t => Xo(t).put({
  11200. clientId: this.clientId,
  11201. updateTimeMs: Date.now(),
  11202. networkEnabled: this.networkEnabled,
  11203. inForeground: this.inForeground
  11204. }).next((() => {
  11205. if (this.isPrimary) return this.Ti(t).next((t => {
  11206. t || (this.isPrimary = !1, this.ii.enqueueRetryable((() => this.fi(!1))));
  11207. }));
  11208. })).next((() => this.Ei(t))).next((e => this.isPrimary && !e ? this.Ai(t).next((() => !1)) : !!e && this.vi(t).next((() => !0)))))).catch((t => {
  11209. if (Dt(t))
  11210. // Proceed with the existing state. Any subsequent access to
  11211. // IndexedDB will verify the lease.
  11212. return N("IndexedDbPersistence", "Failed to extend owner lease: ", t), this.isPrimary;
  11213. if (!this.allowTabSynchronization) throw t;
  11214. return N("IndexedDbPersistence", "Releasing owner lease after error during lease refresh", t),
  11215. /* isPrimary= */ !1;
  11216. })).then((t => {
  11217. this.isPrimary !== t && this.ii.enqueueRetryable((() => this.fi(t))), this.isPrimary = t;
  11218. }));
  11219. }
  11220. Ti(t) {
  11221. return Yo(t).get("owner").next((t => Rt.resolve(this.Ri(t))));
  11222. }
  11223. Pi(t) {
  11224. return Xo(t).delete(this.clientId);
  11225. }
  11226. /**
  11227. * If the garbage collection threshold has passed, prunes the
  11228. * RemoteDocumentChanges and the ClientMetadata store based on the last update
  11229. * time of all clients.
  11230. */ async bi() {
  11231. if (this.isPrimary && !this.Vi(this.li, 18e5)) {
  11232. this.li = Date.now();
  11233. const t = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (t => {
  11234. const e = _e(t, "clientMetadata");
  11235. return e.j().next((t => {
  11236. const n = this.Si(t, 18e5), s = t.filter((t => -1 === n.indexOf(t)));
  11237. // Delete metadata for clients that are no longer considered active.
  11238. return Rt.forEach(s, (t => e.delete(t.clientId))).next((() => s));
  11239. }));
  11240. })).catch((() => []));
  11241. // Delete potential leftover entries that may continue to mark the
  11242. // inactive clients as zombied in LocalStorage.
  11243. // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for
  11244. // the client atomically, but we can't. So we opt to delete the IndexedDb
  11245. // entries first to avoid potentially reviving a zombied client.
  11246. if (this._i) for (const e of t) this._i.removeItem(this.Di(e.clientId));
  11247. }
  11248. }
  11249. /**
  11250. * Schedules a recurring timer to update the client metadata and to either
  11251. * extend or acquire the primary lease if the client is eligible.
  11252. */ pi() {
  11253. this.hi = this.ii.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.mi().then((() => this.bi())).then((() => this.pi()))));
  11254. }
  11255. /** Checks whether `client` is the local client. */ Ri(t) {
  11256. return !!t && t.ownerId === this.clientId;
  11257. }
  11258. /**
  11259. * Evaluate the state of all active clients and determine whether the local
  11260. * client is or can act as the holder of the primary lease. Returns whether
  11261. * the client is eligible for the lease, but does not actually acquire it.
  11262. * May return 'false' even if there is no active leaseholder and another
  11263. * (foreground) client should become leaseholder instead.
  11264. */ Ei(t) {
  11265. if (this.oi) return Rt.resolve(!0);
  11266. return Yo(t).get("owner").next((e => {
  11267. // A client is eligible for the primary lease if:
  11268. // - its network is enabled and the client's tab is in the foreground.
  11269. // - its network is enabled and no other client's tab is in the
  11270. // foreground.
  11271. // - every clients network is disabled and the client's tab is in the
  11272. // foreground.
  11273. // - every clients network is disabled and no other client's tab is in
  11274. // the foreground.
  11275. // - the `forceOwningTab` setting was passed in.
  11276. if (null !== e && this.Vi(e.leaseTimestampMs, 5e3) && !this.Ci(e.ownerId)) {
  11277. if (this.Ri(e) && this.networkEnabled) return !0;
  11278. if (!this.Ri(e)) {
  11279. if (!e.allowTabSynchronization)
  11280. // Fail the `canActAsPrimary` check if the current leaseholder has
  11281. // not opted into multi-tab synchronization. If this happens at
  11282. // client startup, we reject the Promise returned by
  11283. // `enablePersistence()` and the user can continue to use Firestore
  11284. // with in-memory persistence.
  11285. // If this fails during a lease refresh, we will instead block the
  11286. // AsyncQueue from executing further operations. Note that this is
  11287. // acceptable since mixing & matching different `synchronizeTabs`
  11288. // settings is not supported.
  11289. // TODO(b/114226234): Remove this check when `synchronizeTabs` can
  11290. // no longer be turned off.
  11291. throw new U(q.FAILED_PRECONDITION, Ho);
  11292. return !1;
  11293. }
  11294. }
  11295. return !(!this.networkEnabled || !this.inForeground) || Xo(t).j().next((t => void 0 === this.Si(t, 5e3).find((t => {
  11296. if (this.clientId !== t.clientId) {
  11297. const e = !this.networkEnabled && t.networkEnabled, n = !this.inForeground && t.inForeground, s = this.networkEnabled === t.networkEnabled;
  11298. if (e || n && s) return !0;
  11299. }
  11300. return !1;
  11301. }))));
  11302. })).next((t => (this.isPrimary !== t && N("IndexedDbPersistence", `Client ${t ? "is" : "is not"} eligible for a primary lease.`),
  11303. t)));
  11304. }
  11305. async shutdown() {
  11306. // The shutdown() operations are idempotent and can be called even when
  11307. // start() aborted (e.g. because it couldn't acquire the persistence lease).
  11308. this.Fs = !1, this.xi(), this.hi && (this.hi.cancel(), this.hi = null), this.Ni(),
  11309. this.ki(),
  11310. // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
  11311. // has obtained the primary lease.
  11312. await this.wi.runTransaction("shutdown", "readwrite", [ "owner", "clientMetadata" ], (t => {
  11313. const e = new we(t, Ot.ct);
  11314. return this.Ai(e).next((() => this.Pi(e)));
  11315. })), this.wi.close(),
  11316. // Remove the entry marking the client as zombied from LocalStorage since
  11317. // we successfully deleted its metadata from IndexedDb.
  11318. this.Mi();
  11319. }
  11320. /**
  11321. * Returns clients that are not zombied and have an updateTime within the
  11322. * provided threshold.
  11323. */ Si(t, e) {
  11324. return t.filter((t => this.Vi(t.updateTimeMs, e) && !this.Ci(t.clientId)));
  11325. }
  11326. /**
  11327. * Returns the IDs of the clients that are currently active. If multi-tab
  11328. * is not supported, returns an array that only contains the local client's
  11329. * ID.
  11330. *
  11331. * PORTING NOTE: This is only used for Web multi-tab.
  11332. */ $i() {
  11333. return this.runTransaction("getActiveClients", "readonly", (t => Xo(t).j().next((t => this.Si(t, 18e5).map((t => t.clientId))))));
  11334. }
  11335. get started() {
  11336. return this.Fs;
  11337. }
  11338. getMutationQueue(t, e) {
  11339. return oo.de(t, this.serializer, e, this.referenceDelegate);
  11340. }
  11341. getTargetCache() {
  11342. return this.Bs;
  11343. }
  11344. getRemoteDocumentCache() {
  11345. return this.remoteDocumentCache;
  11346. }
  11347. getIndexManager(t) {
  11348. return new Jr(t, this.serializer.fe.databaseId);
  11349. }
  11350. getDocumentOverlayCache(t) {
  11351. return Rr.de(this.serializer, t);
  11352. }
  11353. getBundleCache() {
  11354. return this.qs;
  11355. }
  11356. runTransaction(t, e, n) {
  11357. N("IndexedDbPersistence", "Starting transaction:", t);
  11358. const s = "readonly" === e ? "readonly" : "readwrite", i = 15 === (r = this.ui) ? de : 14 === r ? fe : 13 === r ? le : 12 === r ? he : 11 === r ? ae : void O();
  11359. /** Returns the object stores for the provided schema. */
  11360. var r;
  11361. let o;
  11362. // Do all transactions as readwrite against all object stores, since we
  11363. // are the only reader/writer.
  11364. return this.wi.runTransaction(t, s, i, (s => (o = new we(s, this.Os ? this.Os.next() : Ot.ct),
  11365. "readwrite-primary" === e ? this.Ti(o).next((t => !!t || this.Ei(o))).next((e => {
  11366. if (!e) throw k(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1,
  11367. this.ii.enqueueRetryable((() => this.fi(!1))), new U(q.FAILED_PRECONDITION, Et);
  11368. return n(o);
  11369. })).next((t => this.vi(o).next((() => t)))) : this.Oi(o).next((() => n(o)))))).then((t => (o.raiseOnCommittedEvent(),
  11370. t)));
  11371. }
  11372. /**
  11373. * Verifies that the current tab is the primary leaseholder or alternatively
  11374. * that the leaseholder has opted into multi-tab synchronization.
  11375. */
  11376. // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
  11377. // be turned off.
  11378. Oi(t) {
  11379. return Yo(t).get("owner").next((t => {
  11380. if (null !== t && this.Vi(t.leaseTimestampMs, 5e3) && !this.Ci(t.ownerId) && !this.Ri(t) && !(this.oi || this.allowTabSynchronization && t.allowTabSynchronization)) throw new U(q.FAILED_PRECONDITION, Ho);
  11381. }));
  11382. }
  11383. /**
  11384. * Obtains or extends the new primary lease for the local client. This
  11385. * method does not verify that the client is eligible for this lease.
  11386. */ vi(t) {
  11387. const e = {
  11388. ownerId: this.clientId,
  11389. allowTabSynchronization: this.allowTabSynchronization,
  11390. leaseTimestampMs: Date.now()
  11391. };
  11392. return Yo(t).put("owner", e);
  11393. }
  11394. static D() {
  11395. return bt.D();
  11396. }
  11397. /** Checks the primary lease and removes it if we are the current primary. */ Ai(t) {
  11398. const e = Yo(t);
  11399. return e.get("owner").next((t => this.Ri(t) ? (N("IndexedDbPersistence", "Releasing primary lease."),
  11400. e.delete("owner")) : Rt.resolve()));
  11401. }
  11402. /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ Vi(t, e) {
  11403. const n = Date.now();
  11404. return !(t < n - e) && (!(t > n) || (k(`Detected an update time that is in the future: ${t} > ${n}`),
  11405. !1));
  11406. }
  11407. gi() {
  11408. null !== this.document && "function" == typeof this.document.addEventListener && (this.ai = () => {
  11409. this.ii.enqueueAndForget((() => (this.inForeground = "visible" === this.document.visibilityState,
  11410. this.mi())));
  11411. }, this.document.addEventListener("visibilitychange", this.ai), this.inForeground = "visible" === this.document.visibilityState);
  11412. }
  11413. Ni() {
  11414. this.ai && (this.document.removeEventListener("visibilitychange", this.ai), this.ai = null);
  11415. }
  11416. /**
  11417. * Attaches a window.unload handler that will synchronously write our
  11418. * clientId to a "zombie client id" location in LocalStorage. This can be used
  11419. * by tabs trying to acquire the primary lease to determine that the lease
  11420. * is no longer valid even if the timestamp is recent. This is particularly
  11421. * important for the refresh case (so the tab correctly re-acquires the
  11422. * primary lease). LocalStorage is used for this rather than IndexedDb because
  11423. * it is a synchronous API and so can be used reliably from an unload
  11424. * handler.
  11425. */ yi() {
  11426. var t;
  11427. "function" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.ci = () => {
  11428. // Note: In theory, this should be scheduled on the AsyncQueue since it
  11429. // accesses internal state. We execute this code directly during shutdown
  11430. // to make sure it gets a chance to run.
  11431. this.xi();
  11432. const t = /(?:Version|Mobile)\/1[456]/;
  11433. util.isSafari() && (navigator.appVersion.match(t) || navigator.userAgent.match(t)) &&
  11434. // On Safari 14, 15, and 16, we do not run any cleanup actions as it might
  11435. // trigger a bug that prevents Safari from re-opening IndexedDB during
  11436. // the next page load.
  11437. // See https://bugs.webkit.org/show_bug.cgi?id=226547
  11438. this.ii.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.ii.enqueueAndForget((() => this.shutdown()));
  11439. }, this.window.addEventListener("pagehide", this.ci));
  11440. }
  11441. ki() {
  11442. this.ci && (this.window.removeEventListener("pagehide", this.ci), this.ci = null);
  11443. }
  11444. /**
  11445. * Returns whether a client is "zombied" based on its LocalStorage entry.
  11446. * Clients become zombied when their tab closes without running all of the
  11447. * cleanup logic in `shutdown()`.
  11448. */ Ci(t) {
  11449. var e;
  11450. try {
  11451. const n = null !== (null === (e = this._i) || void 0 === e ? void 0 : e.getItem(this.Di(t)));
  11452. return N("IndexedDbPersistence", `Client '${t}' ${n ? "is" : "is not"} zombied in LocalStorage`),
  11453. n;
  11454. } catch (t) {
  11455. // Gracefully handle if LocalStorage isn't working.
  11456. return k("IndexedDbPersistence", "Failed to get zombied client id.", t), !1;
  11457. }
  11458. }
  11459. /**
  11460. * Record client as zombied (a client that had its tab closed). Zombied
  11461. * clients are ignored during primary tab selection.
  11462. */ xi() {
  11463. if (this._i) try {
  11464. this._i.setItem(this.Di(this.clientId), String(Date.now()));
  11465. } catch (t) {
  11466. // Gracefully handle if LocalStorage isn't available / working.
  11467. k("Failed to set zombie client id.", t);
  11468. }
  11469. }
  11470. /** Removes the zombied client entry if it exists. */ Mi() {
  11471. if (this._i) try {
  11472. this._i.removeItem(this.Di(this.clientId));
  11473. } catch (t) {
  11474. // Ignore
  11475. }
  11476. }
  11477. Di(t) {
  11478. return `firestore_zombie_${this.persistenceKey}_${t}`;
  11479. }
  11480. }
  11481. /**
  11482. * Helper to get a typed SimpleDbStore for the primary client object store.
  11483. */ function Yo(t) {
  11484. return _e(t, "owner");
  11485. }
  11486. /**
  11487. * Helper to get a typed SimpleDbStore for the client metadata object store.
  11488. */ function Xo(t) {
  11489. return _e(t, "clientMetadata");
  11490. }
  11491. /**
  11492. * Generates a string used as a prefix when storing data in IndexedDB and
  11493. * LocalStorage.
  11494. */ function Zo(t, e) {
  11495. // Use two different prefix formats:
  11496. // * firestore / persistenceKey / projectID . databaseID / ...
  11497. // * firestore / persistenceKey / projectID / ...
  11498. // projectIDs are DNS-compatible names and cannot contain dots
  11499. // so there's no danger of collisions.
  11500. let n = t.projectId;
  11501. return t.isDefaultDatabase || (n += "." + t.database), "firestore/" + e + "/" + n + "/";
  11502. }
  11503. /**
  11504. * @license
  11505. * Copyright 2017 Google LLC
  11506. *
  11507. * Licensed under the Apache License, Version 2.0 (the "License");
  11508. * you may not use this file except in compliance with the License.
  11509. * You may obtain a copy of the License at
  11510. *
  11511. * http://www.apache.org/licenses/LICENSE-2.0
  11512. *
  11513. * Unless required by applicable law or agreed to in writing, software
  11514. * distributed under the License is distributed on an "AS IS" BASIS,
  11515. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11516. * See the License for the specific language governing permissions and
  11517. * limitations under the License.
  11518. */
  11519. /**
  11520. * A set of changes to what documents are currently in view and out of view for
  11521. * a given query. These changes are sent to the LocalStore by the View (via
  11522. * the SyncEngine) and are used to pin / unpin documents as appropriate.
  11523. */
  11524. class tu {
  11525. constructor(t, e, n, s) {
  11526. this.targetId = t, this.fromCache = e, this.Fi = n, this.Bi = s;
  11527. }
  11528. static Li(t, e) {
  11529. let n = gs(), s = gs();
  11530. for (const t of e.docChanges) switch (t.type) {
  11531. case 0 /* ChangeType.Added */ :
  11532. n = n.add(t.doc.key);
  11533. break;
  11534. case 1 /* ChangeType.Removed */ :
  11535. s = s.add(t.doc.key);
  11536. // do nothing
  11537. }
  11538. return new tu(t, e.fromCache, n, s);
  11539. }
  11540. }
  11541. /**
  11542. * @license
  11543. * Copyright 2019 Google LLC
  11544. *
  11545. * Licensed under the Apache License, Version 2.0 (the "License");
  11546. * you may not use this file except in compliance with the License.
  11547. * You may obtain a copy of the License at
  11548. *
  11549. * http://www.apache.org/licenses/LICENSE-2.0
  11550. *
  11551. * Unless required by applicable law or agreed to in writing, software
  11552. * distributed under the License is distributed on an "AS IS" BASIS,
  11553. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11554. * See the License for the specific language governing permissions and
  11555. * limitations under the License.
  11556. */
  11557. /**
  11558. * The Firestore query engine.
  11559. *
  11560. * Firestore queries can be executed in three modes. The Query Engine determines
  11561. * what mode to use based on what data is persisted. The mode only determines
  11562. * the runtime complexity of the query - the result set is equivalent across all
  11563. * implementations.
  11564. *
  11565. * The Query engine will use indexed-based execution if a user has configured
  11566. * any index that can be used to execute query (via `setIndexConfiguration()`).
  11567. * Otherwise, the engine will try to optimize the query by re-using a previously
  11568. * persisted query result. If that is not possible, the query will be executed
  11569. * via a full collection scan.
  11570. *
  11571. * Index-based execution is the default when available. The query engine
  11572. * supports partial indexed execution and merges the result from the index
  11573. * lookup with documents that have not yet been indexed. The index evaluation
  11574. * matches the backend's format and as such, the SDK can use indexing for all
  11575. * queries that the backend supports.
  11576. *
  11577. * If no index exists, the query engine tries to take advantage of the target
  11578. * document mapping in the TargetCache. These mappings exists for all queries
  11579. * that have been synced with the backend at least once and allow the query
  11580. * engine to only read documents that previously matched a query plus any
  11581. * documents that were edited after the query was last listened to.
  11582. *
  11583. * There are some cases when this optimization is not guaranteed to produce
  11584. * the same results as full collection scans. In these cases, query
  11585. * processing falls back to full scans. These cases are:
  11586. *
  11587. * - Limit queries where a document that matched the query previously no longer
  11588. * matches the query.
  11589. *
  11590. * - Limit queries where a document edit may cause the document to sort below
  11591. * another document that is in the local cache.
  11592. *
  11593. * - Queries that have never been CURRENT or free of limbo documents.
  11594. */ class eu {
  11595. constructor() {
  11596. this.qi = !1;
  11597. }
  11598. /** Sets the document view to query against. */ initialize(t, e) {
  11599. this.Ui = t, this.indexManager = e, this.qi = !0;
  11600. }
  11601. /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(t, e, n, s) {
  11602. return this.Ki(t, e).next((i => i || this.Gi(t, e, s, n))).next((n => n || this.Qi(t, e)));
  11603. }
  11604. /**
  11605. * Performs an indexed query that evaluates the query based on a collection's
  11606. * persisted index values. Returns `null` if an index is not available.
  11607. */ Ki(t, e) {
  11608. if (Qn(e))
  11609. // Queries that match all documents don't benefit from using
  11610. // key-based lookups. It is more efficient to scan all documents in a
  11611. // collection, rather than to perform individual lookups.
  11612. return Rt.resolve(null);
  11613. let n = Jn(e);
  11614. return this.indexManager.getIndexType(t, n).next((s => 0 /* IndexType.NONE */ === s ? null : (null !== e.limit && 1 /* IndexType.PARTIAL */ === s && (
  11615. // We cannot apply a limit for targets that are served using a partial
  11616. // index. If a partial index will be used to serve the target, the
  11617. // query may return a superset of documents that match the target
  11618. // (e.g. if the index doesn't include all the target's filters), or
  11619. // may return the correct set of documents in the wrong order (e.g. if
  11620. // the index doesn't include a segment for one of the orderBys).
  11621. // Therefore, a limit should not be applied in such cases.
  11622. e = Xn(e, null, "F" /* LimitType.First */), n = Jn(e)), this.indexManager.getDocumentsMatchingTarget(t, n).next((s => {
  11623. const i = gs(...s);
  11624. return this.Ui.getDocuments(t, i).next((s => this.indexManager.getMinOffset(t, n).next((n => {
  11625. const r = this.ji(e, s);
  11626. return this.zi(e, r, i, n.readTime) ? this.Ki(t, Xn(e, null, "F" /* LimitType.First */)) : this.Wi(t, r, e, n);
  11627. }))));
  11628. })))));
  11629. }
  11630. /**
  11631. * Performs a query based on the target's persisted query mapping. Returns
  11632. * `null` if the mapping is not available or cannot be used.
  11633. */ Gi(t, e, n, s) {
  11634. return Qn(e) || s.isEqual(rt.min()) ? this.Qi(t, e) : this.Ui.getDocuments(t, n).next((i => {
  11635. const r = this.ji(e, i);
  11636. return this.zi(e, r, n, s) ? this.Qi(t, e) : (C() <= logger.LogLevel.DEBUG && N("QueryEngine", "Re-using previous result from %s to execute query: %s", s.toString(), es(e)),
  11637. this.Wi(t, r, e, yt(s, -1)));
  11638. }));
  11639. // Queries that have never seen a snapshot without limbo free documents
  11640. // should also be run as a full collection scan.
  11641. }
  11642. /** Applies the query filter and sorting to the provided documents. */ ji(t, e) {
  11643. // Sort the documents and re-apply the query filter since previously
  11644. // matching documents do not necessarily still match the query.
  11645. let n = new Ee(is(t));
  11646. return e.forEach(((e, s) => {
  11647. ns(t, s) && (n = n.add(s));
  11648. })), n;
  11649. }
  11650. /**
  11651. * Determines if a limit query needs to be refilled from cache, making it
  11652. * ineligible for index-free execution.
  11653. *
  11654. * @param query - The query.
  11655. * @param sortedPreviousResults - The documents that matched the query when it
  11656. * was last synchronized, sorted by the query's comparator.
  11657. * @param remoteKeys - The document keys that matched the query at the last
  11658. * snapshot.
  11659. * @param limboFreeSnapshotVersion - The version of the snapshot when the
  11660. * query was last synchronized.
  11661. */ zi(t, e, n, s) {
  11662. if (null === t.limit)
  11663. // Queries without limits do not need to be refilled.
  11664. return !1;
  11665. if (n.size !== e.size)
  11666. // The query needs to be refilled if a previously matching document no
  11667. // longer matches.
  11668. return !0;
  11669. // Limit queries are not eligible for index-free query execution if there is
  11670. // a potential that an older document from cache now sorts before a document
  11671. // that was previously part of the limit. This, however, can only happen if
  11672. // the document at the edge of the limit goes out of limit.
  11673. // If a document that is not the limit boundary sorts differently,
  11674. // the boundary of the limit itself did not change and documents from cache
  11675. // will continue to be "rejected" by this boundary. Therefore, we can ignore
  11676. // any modifications that don't affect the last document.
  11677. const i = "F" /* LimitType.First */ === t.limitType ? e.last() : e.first();
  11678. return !!i && (i.hasPendingWrites || i.version.compareTo(s) > 0);
  11679. }
  11680. Qi(t, e) {
  11681. return C() <= logger.LogLevel.DEBUG && N("QueryEngine", "Using full collection scan to execute query:", es(e)),
  11682. this.Ui.getDocumentsMatchingQuery(t, e, It.min());
  11683. }
  11684. /**
  11685. * Combines the results from an indexed execution with the remaining documents
  11686. * that have not yet been indexed.
  11687. */ Wi(t, e, n, s) {
  11688. // Retrieve all results for documents that were updated since the offset.
  11689. return this.Ui.getDocumentsMatchingQuery(t, n, s).next((t => (
  11690. // Merge with existing results
  11691. e.forEach((e => {
  11692. t = t.insert(e.key, e);
  11693. })), t)));
  11694. }
  11695. }
  11696. /**
  11697. * @license
  11698. * Copyright 2020 Google LLC
  11699. *
  11700. * Licensed under the Apache License, Version 2.0 (the "License");
  11701. * you may not use this file except in compliance with the License.
  11702. * You may obtain a copy of the License at
  11703. *
  11704. * http://www.apache.org/licenses/LICENSE-2.0
  11705. *
  11706. * Unless required by applicable law or agreed to in writing, software
  11707. * distributed under the License is distributed on an "AS IS" BASIS,
  11708. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11709. * See the License for the specific language governing permissions and
  11710. * limitations under the License.
  11711. */
  11712. /**
  11713. * Implements `LocalStore` interface.
  11714. *
  11715. * Note: some field defined in this class might have public access level, but
  11716. * the class is not exported so they are only accessible from this module.
  11717. * This is useful to implement optional features (like bundles) in free
  11718. * functions, such that they are tree-shakeable.
  11719. */
  11720. class nu {
  11721. constructor(
  11722. /** Manages our in-memory or durable persistence. */
  11723. t, e, n, s) {
  11724. this.persistence = t, this.Hi = e, this.serializer = s,
  11725. /**
  11726. * Maps a targetID to data about its target.
  11727. *
  11728. * PORTING NOTE: We are using an immutable data structure on Web to make re-runs
  11729. * of `applyRemoteEvent()` idempotent.
  11730. */
  11731. this.Ji = new pe(et),
  11732. /** Maps a target to its targetID. */
  11733. // TODO(wuandy): Evaluate if TargetId can be part of Target.
  11734. this.Yi = new os((t => $n(t)), On),
  11735. /**
  11736. * A per collection group index of the last read time processed by
  11737. * `getNewDocumentChanges()`.
  11738. *
  11739. * PORTING NOTE: This is only used for multi-tab synchronization.
  11740. */
  11741. this.Xi = new Map, this.Zi = t.getRemoteDocumentCache(), this.Bs = t.getTargetCache(),
  11742. this.qs = t.getBundleCache(), this.tr(n);
  11743. }
  11744. tr(t) {
  11745. // TODO(indexing): Add spec tests that test these components change after a
  11746. // user change
  11747. this.documentOverlayCache = this.persistence.getDocumentOverlayCache(t), this.indexManager = this.persistence.getIndexManager(t),
  11748. this.mutationQueue = this.persistence.getMutationQueue(t, this.indexManager), this.localDocuments = new ko(this.Zi, this.mutationQueue, this.documentOverlayCache, this.indexManager),
  11749. this.Zi.setIndexManager(this.indexManager), this.Hi.initialize(this.localDocuments, this.indexManager);
  11750. }
  11751. collectGarbage(t) {
  11752. return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (e => t.collect(e, this.Ji)));
  11753. }
  11754. }
  11755. function su(
  11756. /** Manages our in-memory or durable persistence. */
  11757. t, e, n, s) {
  11758. return new nu(t, e, n, s);
  11759. }
  11760. /**
  11761. * Tells the LocalStore that the currently authenticated user has changed.
  11762. *
  11763. * In response the local store switches the mutation queue to the new user and
  11764. * returns any resulting document changes.
  11765. */
  11766. // PORTING NOTE: Android and iOS only return the documents affected by the
  11767. // change.
  11768. async function iu(t, e) {
  11769. const n = L(t);
  11770. return await n.persistence.runTransaction("Handle user change", "readonly", (t => {
  11771. // Swap out the mutation queue, grabbing the pending mutation batches
  11772. // before and after.
  11773. let s;
  11774. return n.mutationQueue.getAllMutationBatches(t).next((i => (s = i, n.tr(e), n.mutationQueue.getAllMutationBatches(t)))).next((e => {
  11775. const i = [], r = [];
  11776. // Union the old/new changed keys.
  11777. let o = gs();
  11778. for (const t of s) {
  11779. i.push(t.batchId);
  11780. for (const e of t.mutations) o = o.add(e.key);
  11781. }
  11782. for (const t of e) {
  11783. r.push(t.batchId);
  11784. for (const e of t.mutations) o = o.add(e.key);
  11785. }
  11786. // Return the set of all (potentially) changed documents and the list
  11787. // of mutation batch IDs that were affected by change.
  11788. return n.localDocuments.getDocuments(t, o).next((t => ({
  11789. er: t,
  11790. removedBatchIds: i,
  11791. addedBatchIds: r
  11792. })));
  11793. }));
  11794. }));
  11795. }
  11796. /* Accepts locally generated Mutations and commit them to storage. */
  11797. /**
  11798. * Acknowledges the given batch.
  11799. *
  11800. * On the happy path when a batch is acknowledged, the local store will
  11801. *
  11802. * + remove the batch from the mutation queue;
  11803. * + apply the changes to the remote document cache;
  11804. * + recalculate the latency compensated view implied by those changes (there
  11805. * may be mutations in the queue that affect the documents but haven't been
  11806. * acknowledged yet); and
  11807. * + give the changed documents back the sync engine
  11808. *
  11809. * @returns The resulting (modified) documents.
  11810. */
  11811. function ru(t, e) {
  11812. const n = L(t);
  11813. return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (t => {
  11814. const s = e.batch.keys(), i = n.Zi.newChangeBuffer({
  11815. trackRemovals: !0
  11816. });
  11817. return function(t, e, n, s) {
  11818. const i = n.batch, r = i.keys();
  11819. let o = Rt.resolve();
  11820. return r.forEach((t => {
  11821. o = o.next((() => s.getEntry(e, t))).next((e => {
  11822. const r = n.docVersions.get(t);
  11823. F(null !== r), e.version.compareTo(r) < 0 && (i.applyToRemoteDocument(e, n), e.isValidDocument() && (
  11824. // We use the commitVersion as the readTime rather than the
  11825. // document's updateTime since the updateTime is not advanced
  11826. // for updates that do not modify the underlying document.
  11827. e.setReadTime(n.commitVersion), s.addEntry(e)));
  11828. }));
  11829. })), o.next((() => t.mutationQueue.removeMutationBatch(e, i)));
  11830. }
  11831. /** Returns the local view of the documents affected by a mutation batch. */
  11832. // PORTING NOTE: Multi-Tab only.
  11833. (n, t, e, i).next((() => i.apply(t))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, function(t) {
  11834. let e = gs();
  11835. for (let n = 0; n < t.mutationResults.length; ++n) {
  11836. t.mutationResults[n].transformResults.length > 0 && (e = e.add(t.batch.mutations[n].key));
  11837. }
  11838. return e;
  11839. }
  11840. /**
  11841. * Removes mutations from the MutationQueue for the specified batch;
  11842. * LocalDocuments will be recalculated.
  11843. *
  11844. * @returns The resulting modified documents.
  11845. */ (e)))).next((() => n.localDocuments.getDocuments(t, s)));
  11846. }));
  11847. }
  11848. /**
  11849. * Returns the last consistent snapshot processed (used by the RemoteStore to
  11850. * determine whether to buffer incoming snapshots from the backend).
  11851. */
  11852. function ou(t) {
  11853. const e = L(t);
  11854. return e.persistence.runTransaction("Get last remote snapshot version", "readonly", (t => e.Bs.getLastRemoteSnapshotVersion(t)));
  11855. }
  11856. /**
  11857. * Updates the "ground-state" (remote) documents. We assume that the remote
  11858. * event reflects any write batches that have been acknowledged or rejected
  11859. * (i.e. we do not re-apply local mutations to updates from this event).
  11860. *
  11861. * LocalDocuments are re-calculated if there are remaining mutations in the
  11862. * queue.
  11863. */ function uu(t, e) {
  11864. const n = L(t), s = e.snapshotVersion;
  11865. let i = n.Ji;
  11866. return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (t => {
  11867. const r = n.Zi.newChangeBuffer({
  11868. trackRemovals: !0
  11869. });
  11870. // Reset newTargetDataByTargetMap in case this transaction gets re-run.
  11871. i = n.Ji;
  11872. const o = [];
  11873. e.targetChanges.forEach(((r, u) => {
  11874. const c = i.get(u);
  11875. if (!c) return;
  11876. // Only update the remote keys if the target is still active. This
  11877. // ensures that we can persist the updated target data along with
  11878. // the updated assignment.
  11879. o.push(n.Bs.removeMatchingKeys(t, r.removedDocuments, u).next((() => n.Bs.addMatchingKeys(t, r.addedDocuments, u))));
  11880. let a = c.withSequenceNumber(t.currentSequenceNumber);
  11881. null !== e.targetMismatches.get(u) ? a = a.withResumeToken(Ve.EMPTY_BYTE_STRING, rt.min()).withLastLimboFreeSnapshotVersion(rt.min()) : r.resumeToken.approximateByteSize() > 0 && (a = a.withResumeToken(r.resumeToken, s)),
  11882. i = i.insert(u, a),
  11883. // Update the target data if there are target changes (or if
  11884. // sufficient time has passed since the last update).
  11885. /**
  11886. * Returns true if the newTargetData should be persisted during an update of
  11887. * an active target. TargetData should always be persisted when a target is
  11888. * being released and should not call this function.
  11889. *
  11890. * While the target is active, TargetData updates can be omitted when nothing
  11891. * about the target has changed except metadata like the resume token or
  11892. * snapshot version. Occasionally it's worth the extra write to prevent these
  11893. * values from getting too stale after a crash, but this doesn't have to be
  11894. * too frequent.
  11895. */
  11896. function(t, e, n) {
  11897. // Always persist target data if we don't already have a resume token.
  11898. if (0 === t.resumeToken.approximateByteSize()) return !0;
  11899. // Don't allow resume token changes to be buffered indefinitely. This
  11900. // allows us to be reasonably up-to-date after a crash and avoids needing
  11901. // to loop over all active queries on shutdown. Especially in the browser
  11902. // we may not get time to do anything interesting while the current tab is
  11903. // closing.
  11904. if (e.snapshotVersion.toMicroseconds() - t.snapshotVersion.toMicroseconds() >= 3e8) return !0;
  11905. // Otherwise if the only thing that has changed about a target is its resume
  11906. // token it's not worth persisting. Note that the RemoteStore keeps an
  11907. // in-memory view of the currently active targets which includes the current
  11908. // resume token, so stream failure or user changes will still use an
  11909. // up-to-date resume token regardless of what we do here.
  11910. return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;
  11911. }
  11912. /**
  11913. * Notifies local store of the changed views to locally pin documents.
  11914. */ (c, a, r) && o.push(n.Bs.updateTargetData(t, a));
  11915. }));
  11916. let u = cs(), c = gs();
  11917. // HACK: The only reason we allow a null snapshot version is so that we
  11918. // can synthesize remote events when we get permission denied errors while
  11919. // trying to resolve the state of a locally cached document that is in
  11920. // limbo.
  11921. if (e.documentUpdates.forEach((s => {
  11922. e.resolvedLimboDocuments.has(s) && o.push(n.persistence.referenceDelegate.updateLimboDocument(t, s));
  11923. })),
  11924. // Each loop iteration only affects its "own" doc, so it's safe to get all
  11925. // the remote documents in advance in a single call.
  11926. o.push(cu(t, r, e.documentUpdates).next((t => {
  11927. u = t.nr, c = t.sr;
  11928. }))), !s.isEqual(rt.min())) {
  11929. const e = n.Bs.getLastRemoteSnapshotVersion(t).next((e => n.Bs.setTargetsMetadata(t, t.currentSequenceNumber, s)));
  11930. o.push(e);
  11931. }
  11932. return Rt.waitFor(o).next((() => r.apply(t))).next((() => n.localDocuments.getLocalViewOfDocuments(t, u, c))).next((() => u));
  11933. })).then((t => (n.Ji = i, t)));
  11934. }
  11935. /**
  11936. * Populates document change buffer with documents from backend or a bundle.
  11937. * Returns the document changes resulting from applying those documents, and
  11938. * also a set of documents whose existence state are changed as a result.
  11939. *
  11940. * @param txn - Transaction to use to read existing documents from storage.
  11941. * @param documentBuffer - Document buffer to collect the resulted changes to be
  11942. * applied to storage.
  11943. * @param documents - Documents to be applied.
  11944. */ function cu(t, e, n) {
  11945. let s = gs(), i = gs();
  11946. return n.forEach((t => s = s.add(t))), e.getEntries(t, s).next((t => {
  11947. let s = cs();
  11948. return n.forEach(((n, r) => {
  11949. const o = t.get(n);
  11950. // Check if see if there is a existence state change for this document.
  11951. r.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)),
  11952. // Note: The order of the steps below is important, since we want
  11953. // to ensure that rejected limbo resolutions (which fabricate
  11954. // NoDocuments with SnapshotVersion.min()) never add documents to
  11955. // cache.
  11956. r.isNoDocument() && r.version.isEqual(rt.min()) ? (
  11957. // NoDocuments with SnapshotVersion.min() are used in manufactured
  11958. // events. We remove these documents from cache since we lost
  11959. // access.
  11960. e.removeEntry(n, r.readTime), s = s.insert(n, r)) : !o.isValidDocument() || r.version.compareTo(o.version) > 0 || 0 === r.version.compareTo(o.version) && o.hasPendingWrites ? (e.addEntry(r),
  11961. s = s.insert(n, r)) : N("LocalStore", "Ignoring outdated watch update for ", n, ". Current version:", o.version, " Watch version:", r.version);
  11962. })), {
  11963. nr: s,
  11964. sr: i
  11965. };
  11966. }));
  11967. }
  11968. /**
  11969. * Gets the mutation batch after the passed in batchId in the mutation queue
  11970. * or null if empty.
  11971. * @param afterBatchId - If provided, the batch to search after.
  11972. * @returns The next mutation or null if there wasn't one.
  11973. */
  11974. function au(t, e) {
  11975. const n = L(t);
  11976. return n.persistence.runTransaction("Get next mutation batch", "readonly", (t => (void 0 === e && (e = -1),
  11977. n.mutationQueue.getNextMutationBatchAfterBatchId(t, e))));
  11978. }
  11979. /**
  11980. * Reads the current value of a Document with a given key or null if not
  11981. * found - used for testing.
  11982. */
  11983. /**
  11984. * Assigns the given target an internal ID so that its results can be pinned so
  11985. * they don't get GC'd. A target must be allocated in the local store before
  11986. * the store can be used to manage its view.
  11987. *
  11988. * Allocating an already allocated `Target` will return the existing `TargetData`
  11989. * for that `Target`.
  11990. */
  11991. function hu(t, e) {
  11992. const n = L(t);
  11993. return n.persistence.runTransaction("Allocate target", "readwrite", (t => {
  11994. let s;
  11995. return n.Bs.getTargetData(t, e).next((i => i ? (
  11996. // This target has been listened to previously, so reuse the
  11997. // previous targetID.
  11998. // TODO(mcg): freshen last accessed date?
  11999. s = i, Rt.resolve(s)) : n.Bs.allocateTargetId(t).next((i => (s = new cr(e, i, "TargetPurposeListen" /* TargetPurpose.Listen */ , t.currentSequenceNumber),
  12000. n.Bs.addTargetData(t, s).next((() => s)))))));
  12001. })).then((t => {
  12002. // If Multi-Tab is enabled, the existing target data may be newer than
  12003. // the in-memory data
  12004. const s = n.Ji.get(t.targetId);
  12005. return (null === s || t.snapshotVersion.compareTo(s.snapshotVersion) > 0) && (n.Ji = n.Ji.insert(t.targetId, t),
  12006. n.Yi.set(e, t.targetId)), t;
  12007. }));
  12008. }
  12009. /**
  12010. * Returns the TargetData as seen by the LocalStore, including updates that may
  12011. * have not yet been persisted to the TargetCache.
  12012. */
  12013. // Visible for testing.
  12014. /**
  12015. * Unpins all the documents associated with the given target. If
  12016. * `keepPersistedTargetData` is set to false and Eager GC enabled, the method
  12017. * directly removes the associated target data from the target cache.
  12018. *
  12019. * Releasing a non-existing `Target` is a no-op.
  12020. */
  12021. // PORTING NOTE: `keepPersistedTargetData` is multi-tab only.
  12022. async function lu(t, e, n) {
  12023. const s = L(t), i = s.Ji.get(e), r = n ? "readwrite" : "readwrite-primary";
  12024. try {
  12025. n || await s.persistence.runTransaction("Release target", r, (t => s.persistence.referenceDelegate.removeTarget(t, i)));
  12026. } catch (t) {
  12027. if (!Dt(t)) throw t;
  12028. // All `releaseTarget` does is record the final metadata state for the
  12029. // target, but we've been recording this periodically during target
  12030. // activity. If we lose this write this could cause a very slight
  12031. // difference in the order of target deletion during GC, but we
  12032. // don't define exact LRU semantics so this is acceptable.
  12033. N("LocalStore", `Failed to update sequence numbers for target ${e}: ${t}`);
  12034. }
  12035. s.Ji = s.Ji.remove(e), s.Yi.delete(i.target);
  12036. }
  12037. /**
  12038. * Runs the specified query against the local store and returns the results,
  12039. * potentially taking advantage of query data from previous executions (such
  12040. * as the set of remote keys).
  12041. *
  12042. * @param usePreviousResults - Whether results from previous executions can
  12043. * be used to optimize this query execution.
  12044. */ function fu(t, e, n) {
  12045. const s = L(t);
  12046. let i = rt.min(), r = gs();
  12047. return s.persistence.runTransaction("Execute query", "readonly", (t => function(t, e, n) {
  12048. const s = L(t), i = s.Yi.get(n);
  12049. return void 0 !== i ? Rt.resolve(s.Ji.get(i)) : s.Bs.getTargetData(e, n);
  12050. }(s, t, Jn(e)).next((e => {
  12051. if (e) return i = e.lastLimboFreeSnapshotVersion, s.Bs.getMatchingKeysForTargetId(t, e.targetId).next((t => {
  12052. r = t;
  12053. }));
  12054. })).next((() => s.Hi.getDocumentsMatchingQuery(t, e, n ? i : rt.min(), n ? r : gs()))).next((t => (_u(s, ss(e), t),
  12055. {
  12056. documents: t,
  12057. ir: r
  12058. })))));
  12059. }
  12060. // PORTING NOTE: Multi-Tab only.
  12061. function du(t, e) {
  12062. const n = L(t), s = L(n.Bs), i = n.Ji.get(e);
  12063. return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (t => s.le(t, e).next((t => t ? t.target : null))));
  12064. }
  12065. /**
  12066. * Returns the set of documents that have been updated since the last call.
  12067. * If this is the first call, returns the set of changes since client
  12068. * initialization. Further invocations will return document that have changed
  12069. * since the prior call.
  12070. */
  12071. // PORTING NOTE: Multi-Tab only.
  12072. function wu(t, e) {
  12073. const n = L(t), s = n.Xi.get(e) || rt.min();
  12074. // Get the current maximum read time for the collection. This should always
  12075. // exist, but to reduce the chance for regressions we default to
  12076. // SnapshotVersion.Min()
  12077. // TODO(indexing): Consider removing the default value.
  12078. return n.persistence.runTransaction("Get new document changes", "readonly", (t => n.Zi.getAllFromCollectionGroup(t, e, yt(s, -1),
  12079. /* limit= */ Number.MAX_SAFE_INTEGER))).then((t => (_u(n, e, t), t)));
  12080. }
  12081. /** Sets the collection group's maximum read time from the given documents. */
  12082. // PORTING NOTE: Multi-Tab only.
  12083. function _u(t, e, n) {
  12084. let s = t.Xi.get(e) || rt.min();
  12085. n.forEach(((t, e) => {
  12086. e.readTime.compareTo(s) > 0 && (s = e.readTime);
  12087. })), t.Xi.set(e, s);
  12088. }
  12089. /**
  12090. * Creates a new target using the given bundle name, which will be used to
  12091. * hold the keys of all documents from the bundle in query-document mappings.
  12092. * This ensures that the loaded documents do not get garbage collected
  12093. * right away.
  12094. */
  12095. /**
  12096. * Applies the documents from a bundle to the "ground-state" (remote)
  12097. * documents.
  12098. *
  12099. * LocalDocuments are re-calculated if there are remaining mutations in the
  12100. * queue.
  12101. */
  12102. async function mu(t, e, n, s) {
  12103. const i = L(t);
  12104. let r = gs(), o = cs();
  12105. for (const t of n) {
  12106. const n = e.rr(t.metadata.name);
  12107. t.document && (r = r.add(n));
  12108. const s = e.ur(t);
  12109. s.setReadTime(e.cr(t.metadata.readTime)), o = o.insert(n, s);
  12110. }
  12111. const u = i.Zi.newChangeBuffer({
  12112. trackRemovals: !0
  12113. }), c = await hu(i, function(t) {
  12114. // It is OK that the path used for the query is not valid, because this will
  12115. // not be read and queried.
  12116. return Jn(Gn(ut.fromString(`__bundle__/docs/${t}`)));
  12117. }(s));
  12118. // Allocates a target to hold all document keys from the bundle, such that
  12119. // they will not get garbage collected right away.
  12120. return i.persistence.runTransaction("Apply bundle documents", "readwrite", (t => cu(t, u, o).next((e => (u.apply(t),
  12121. e))).next((e => i.Bs.removeMatchingKeysForTargetId(t, c.targetId).next((() => i.Bs.addMatchingKeys(t, r, c.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(t, e.nr, e.sr))).next((() => e.nr))))));
  12122. }
  12123. /**
  12124. * Returns a promise of a boolean to indicate if the given bundle has already
  12125. * been loaded and the create time is newer than the current loading bundle.
  12126. */
  12127. /**
  12128. * Saves the given `NamedQuery` to local persistence.
  12129. */
  12130. async function gu(t, e, n = gs()) {
  12131. // Allocate a target for the named query such that it can be resumed
  12132. // from associated read time if users use it to listen.
  12133. // NOTE: this also means if no corresponding target exists, the new target
  12134. // will remain active and will not get collected, unless users happen to
  12135. // unlisten the query somehow.
  12136. const s = await hu(t, Jn(yr(e.bundledQuery))), i = L(t);
  12137. return i.persistence.runTransaction("Save named query", "readwrite", (t => {
  12138. const r = Ni(e.readTime);
  12139. // Simply save the query itself if it is older than what the SDK already
  12140. // has.
  12141. if (s.snapshotVersion.compareTo(r) >= 0) return i.qs.saveNamedQuery(t, e);
  12142. // Update existing target data because the query from the bundle is newer.
  12143. const o = s.withResumeToken(Ve.EMPTY_BYTE_STRING, r);
  12144. return i.Ji = i.Ji.insert(o.targetId, o), i.Bs.updateTargetData(t, o).next((() => i.Bs.removeMatchingKeysForTargetId(t, s.targetId))).next((() => i.Bs.addMatchingKeys(t, n, s.targetId))).next((() => i.qs.saveNamedQuery(t, e)));
  12145. }));
  12146. }
  12147. /** Assembles the key for a client state in WebStorage */
  12148. function yu(t, e) {
  12149. return `firestore_clients_${t}_${e}`;
  12150. }
  12151. // The format of the WebStorage key that stores the mutation state is:
  12152. // firestore_mutations_<persistence_prefix>_<batch_id>
  12153. // (for unauthenticated users)
  12154. // or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>
  12155. // 'user_uid' is last to avoid needing to escape '_' characters that it might
  12156. // contain.
  12157. /** Assembles the key for a mutation batch in WebStorage */
  12158. function pu(t, e, n) {
  12159. let s = `firestore_mutations_${t}_${n}`;
  12160. return e.isAuthenticated() && (s += `_${e.uid}`), s;
  12161. }
  12162. // The format of the WebStorage key that stores a query target's metadata is:
  12163. // firestore_targets_<persistence_prefix>_<target_id>
  12164. /** Assembles the key for a query state in WebStorage */
  12165. function Iu(t, e) {
  12166. return `firestore_targets_${t}_${e}`;
  12167. }
  12168. // The WebStorage prefix that stores the primary tab's online state. The
  12169. // format of the key is:
  12170. // firestore_online_state_<persistence_prefix>
  12171. /**
  12172. * Holds the state of a mutation batch, including its user ID, batch ID and
  12173. * whether the batch is 'pending', 'acknowledged' or 'rejected'.
  12174. */
  12175. // Visible for testing
  12176. class Tu {
  12177. constructor(t, e, n, s) {
  12178. this.user = t, this.batchId = e, this.state = n, this.error = s;
  12179. }
  12180. /**
  12181. * Parses a MutationMetadata from its JSON representation in WebStorage.
  12182. * Logs a warning and returns null if the format of the data is not valid.
  12183. */ static ar(t, e, n) {
  12184. const s = JSON.parse(n);
  12185. let i, r = "object" == typeof s && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(s.state) && (void 0 === s.error || "object" == typeof s.error);
  12186. return r && s.error && (r = "string" == typeof s.error.message && "string" == typeof s.error.code,
  12187. r && (i = new U(s.error.code, s.error.message))), r ? new Tu(t, e, s.state, i) : (k("SharedClientState", `Failed to parse mutation state for ID '${e}': ${n}`),
  12188. null);
  12189. }
  12190. hr() {
  12191. const t = {
  12192. state: this.state,
  12193. updateTimeMs: Date.now()
  12194. };
  12195. return this.error && (t.error = {
  12196. code: this.error.code,
  12197. message: this.error.message
  12198. }), JSON.stringify(t);
  12199. }
  12200. }
  12201. /**
  12202. * Holds the state of a query target, including its target ID and whether the
  12203. * target is 'not-current', 'current' or 'rejected'.
  12204. */
  12205. // Visible for testing
  12206. class Eu {
  12207. constructor(t, e, n) {
  12208. this.targetId = t, this.state = e, this.error = n;
  12209. }
  12210. /**
  12211. * Parses a QueryTargetMetadata from its JSON representation in WebStorage.
  12212. * Logs a warning and returns null if the format of the data is not valid.
  12213. */ static ar(t, e) {
  12214. const n = JSON.parse(e);
  12215. let s, i = "object" == typeof n && -1 !== [ "not-current", "current", "rejected" ].indexOf(n.state) && (void 0 === n.error || "object" == typeof n.error);
  12216. return i && n.error && (i = "string" == typeof n.error.message && "string" == typeof n.error.code,
  12217. i && (s = new U(n.error.code, n.error.message))), i ? new Eu(t, n.state, s) : (k("SharedClientState", `Failed to parse target state for ID '${t}': ${e}`),
  12218. null);
  12219. }
  12220. hr() {
  12221. const t = {
  12222. state: this.state,
  12223. updateTimeMs: Date.now()
  12224. };
  12225. return this.error && (t.error = {
  12226. code: this.error.code,
  12227. message: this.error.message
  12228. }), JSON.stringify(t);
  12229. }
  12230. }
  12231. /**
  12232. * This class represents the immutable ClientState for a client read from
  12233. * WebStorage, containing the list of active query targets.
  12234. */ class Au {
  12235. constructor(t, e) {
  12236. this.clientId = t, this.activeTargetIds = e;
  12237. }
  12238. /**
  12239. * Parses a RemoteClientState from the JSON representation in WebStorage.
  12240. * Logs a warning and returns null if the format of the data is not valid.
  12241. */ static ar(t, e) {
  12242. const n = JSON.parse(e);
  12243. let s = "object" == typeof n && n.activeTargetIds instanceof Array, i = ps();
  12244. for (let t = 0; s && t < n.activeTargetIds.length; ++t) s = Lt(n.activeTargetIds[t]),
  12245. i = i.add(n.activeTargetIds[t]);
  12246. return s ? new Au(t, i) : (k("SharedClientState", `Failed to parse client data for instance '${t}': ${e}`),
  12247. null);
  12248. }
  12249. }
  12250. /**
  12251. * This class represents the online state for all clients participating in
  12252. * multi-tab. The online state is only written to by the primary client, and
  12253. * used in secondary clients to update their query views.
  12254. */ class vu {
  12255. constructor(t, e) {
  12256. this.clientId = t, this.onlineState = e;
  12257. }
  12258. /**
  12259. * Parses a SharedOnlineState from its JSON representation in WebStorage.
  12260. * Logs a warning and returns null if the format of the data is not valid.
  12261. */ static ar(t) {
  12262. const e = JSON.parse(t);
  12263. return "object" == typeof e && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(e.onlineState) && "string" == typeof e.clientId ? new vu(e.clientId, e.onlineState) : (k("SharedClientState", `Failed to parse online state: ${t}`),
  12264. null);
  12265. }
  12266. }
  12267. /**
  12268. * Metadata state of the local client. Unlike `RemoteClientState`, this class is
  12269. * mutable and keeps track of all pending mutations, which allows us to
  12270. * update the range of pending mutation batch IDs as new mutations are added or
  12271. * removed.
  12272. *
  12273. * The data in `LocalClientState` is not read from WebStorage and instead
  12274. * updated via its instance methods. The updated state can be serialized via
  12275. * `toWebStorageJSON()`.
  12276. */
  12277. // Visible for testing.
  12278. class Ru {
  12279. constructor() {
  12280. this.activeTargetIds = ps();
  12281. }
  12282. lr(t) {
  12283. this.activeTargetIds = this.activeTargetIds.add(t);
  12284. }
  12285. dr(t) {
  12286. this.activeTargetIds = this.activeTargetIds.delete(t);
  12287. }
  12288. /**
  12289. * Converts this entry into a JSON-encoded format we can use for WebStorage.
  12290. * Does not encode `clientId` as it is part of the key in WebStorage.
  12291. */ hr() {
  12292. const t = {
  12293. activeTargetIds: this.activeTargetIds.toArray(),
  12294. updateTimeMs: Date.now()
  12295. };
  12296. return JSON.stringify(t);
  12297. }
  12298. }
  12299. /**
  12300. * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the
  12301. * backing store for the SharedClientState. It keeps track of all active
  12302. * clients and supports modifications of the local client's data.
  12303. */ class Pu {
  12304. constructor(t, e, n, s, i) {
  12305. this.window = t, this.ii = e, this.persistenceKey = n, this.wr = s, this.syncEngine = null,
  12306. this.onlineStateHandler = null, this.sequenceNumberHandler = null, this._r = this.mr.bind(this),
  12307. this.gr = new pe(et), this.started = !1,
  12308. /**
  12309. * Captures WebStorage events that occur before `start()` is called. These
  12310. * events are replayed once `WebStorageSharedClientState` is started.
  12311. */
  12312. this.yr = [];
  12313. // Escape the special characters mentioned here:
  12314. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
  12315. const r = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  12316. this.storage = this.window.localStorage, this.currentUser = i, this.pr = yu(this.persistenceKey, this.wr),
  12317. this.Ir =
  12318. /** Assembles the key for the current sequence number. */
  12319. function(t) {
  12320. return `firestore_sequence_number_${t}`;
  12321. }
  12322. /**
  12323. * @license
  12324. * Copyright 2018 Google LLC
  12325. *
  12326. * Licensed under the Apache License, Version 2.0 (the "License");
  12327. * you may not use this file except in compliance with the License.
  12328. * You may obtain a copy of the License at
  12329. *
  12330. * http://www.apache.org/licenses/LICENSE-2.0
  12331. *
  12332. * Unless required by applicable law or agreed to in writing, software
  12333. * distributed under the License is distributed on an "AS IS" BASIS,
  12334. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12335. * See the License for the specific language governing permissions and
  12336. * limitations under the License.
  12337. */ (this.persistenceKey), this.gr = this.gr.insert(this.wr, new Ru), this.Tr = new RegExp(`^firestore_clients_${r}_([^_]*)$`),
  12338. this.Er = new RegExp(`^firestore_mutations_${r}_(\\d+)(?:_(.*))?$`), this.Ar = new RegExp(`^firestore_targets_${r}_(\\d+)$`),
  12339. this.vr =
  12340. /** Assembles the key for the online state of the primary tab. */
  12341. function(t) {
  12342. return `firestore_online_state_${t}`;
  12343. }
  12344. // The WebStorage prefix that plays as a event to indicate the remote documents
  12345. // might have changed due to some secondary tabs loading a bundle.
  12346. // format of the key is:
  12347. // firestore_bundle_loaded_v2_<persistenceKey>
  12348. // The version ending with "v2" stores the list of modified collection groups.
  12349. (this.persistenceKey), this.Rr = function(t) {
  12350. return `firestore_bundle_loaded_v2_${t}`;
  12351. }
  12352. // The WebStorage key prefix for the key that stores the last sequence number allocated. The key
  12353. // looks like 'firestore_sequence_number_<persistence_prefix>'.
  12354. (this.persistenceKey),
  12355. // Rather than adding the storage observer during start(), we add the
  12356. // storage observer during initialization. This ensures that we collect
  12357. // events before other components populate their initial state (during their
  12358. // respective start() calls). Otherwise, we might for example miss a
  12359. // mutation that is added after LocalStore's start() processed the existing
  12360. // mutations but before we observe WebStorage events.
  12361. this.window.addEventListener("storage", this._r);
  12362. }
  12363. /** Returns 'true' if WebStorage is available in the current environment. */ static D(t) {
  12364. return !(!t || !t.localStorage);
  12365. }
  12366. async start() {
  12367. // Retrieve the list of existing clients to backfill the data in
  12368. // SharedClientState.
  12369. const t = await this.syncEngine.$i();
  12370. for (const e of t) {
  12371. if (e === this.wr) continue;
  12372. const t = this.getItem(yu(this.persistenceKey, e));
  12373. if (t) {
  12374. const n = Au.ar(e, t);
  12375. n && (this.gr = this.gr.insert(n.clientId, n));
  12376. }
  12377. }
  12378. this.Pr();
  12379. // Check if there is an existing online state and call the callback handler
  12380. // if applicable.
  12381. const e = this.storage.getItem(this.vr);
  12382. if (e) {
  12383. const t = this.br(e);
  12384. t && this.Vr(t);
  12385. }
  12386. for (const t of this.yr) this.mr(t);
  12387. this.yr = [],
  12388. // Register a window unload hook to remove the client metadata entry from
  12389. // WebStorage even if `shutdown()` was not called.
  12390. this.window.addEventListener("pagehide", (() => this.shutdown())), this.started = !0;
  12391. }
  12392. writeSequenceNumber(t) {
  12393. this.setItem(this.Ir, JSON.stringify(t));
  12394. }
  12395. getAllActiveQueryTargets() {
  12396. return this.Sr(this.gr);
  12397. }
  12398. isActiveQueryTarget(t) {
  12399. let e = !1;
  12400. return this.gr.forEach(((n, s) => {
  12401. s.activeTargetIds.has(t) && (e = !0);
  12402. })), e;
  12403. }
  12404. addPendingMutation(t) {
  12405. this.Dr(t, "pending");
  12406. }
  12407. updateMutationState(t, e, n) {
  12408. this.Dr(t, e, n),
  12409. // Once a final mutation result is observed by other clients, they no longer
  12410. // access the mutation's metadata entry. Since WebStorage replays events
  12411. // in order, it is safe to delete the entry right after updating it.
  12412. this.Cr(t);
  12413. }
  12414. addLocalQueryTarget(t) {
  12415. let e = "not-current";
  12416. // Lookup an existing query state if the target ID was already registered
  12417. // by another tab
  12418. if (this.isActiveQueryTarget(t)) {
  12419. const n = this.storage.getItem(Iu(this.persistenceKey, t));
  12420. if (n) {
  12421. const s = Eu.ar(t, n);
  12422. s && (e = s.state);
  12423. }
  12424. }
  12425. return this.Nr.lr(t), this.Pr(), e;
  12426. }
  12427. removeLocalQueryTarget(t) {
  12428. this.Nr.dr(t), this.Pr();
  12429. }
  12430. isLocalQueryTarget(t) {
  12431. return this.Nr.activeTargetIds.has(t);
  12432. }
  12433. clearQueryState(t) {
  12434. this.removeItem(Iu(this.persistenceKey, t));
  12435. }
  12436. updateQueryState(t, e, n) {
  12437. this.kr(t, e, n);
  12438. }
  12439. handleUserChange(t, e, n) {
  12440. e.forEach((t => {
  12441. this.Cr(t);
  12442. })), this.currentUser = t, n.forEach((t => {
  12443. this.addPendingMutation(t);
  12444. }));
  12445. }
  12446. setOnlineState(t) {
  12447. this.Mr(t);
  12448. }
  12449. notifyBundleLoaded(t) {
  12450. this.$r(t);
  12451. }
  12452. shutdown() {
  12453. this.started && (this.window.removeEventListener("storage", this._r), this.removeItem(this.pr),
  12454. this.started = !1);
  12455. }
  12456. getItem(t) {
  12457. const e = this.storage.getItem(t);
  12458. return N("SharedClientState", "READ", t, e), e;
  12459. }
  12460. setItem(t, e) {
  12461. N("SharedClientState", "SET", t, e), this.storage.setItem(t, e);
  12462. }
  12463. removeItem(t) {
  12464. N("SharedClientState", "REMOVE", t), this.storage.removeItem(t);
  12465. }
  12466. mr(t) {
  12467. // Note: The function is typed to take Event to be interface-compatible with
  12468. // `Window.addEventListener`.
  12469. const e = t;
  12470. if (e.storageArea === this.storage) {
  12471. if (N("SharedClientState", "EVENT", e.key, e.newValue), e.key === this.pr) return void k("Received WebStorage notification for local change. Another client might have garbage-collected our state");
  12472. this.ii.enqueueRetryable((async () => {
  12473. if (this.started) {
  12474. if (null !== e.key) if (this.Tr.test(e.key)) {
  12475. if (null == e.newValue) {
  12476. const t = this.Or(e.key);
  12477. return this.Fr(t, null);
  12478. }
  12479. {
  12480. const t = this.Br(e.key, e.newValue);
  12481. if (t) return this.Fr(t.clientId, t);
  12482. }
  12483. } else if (this.Er.test(e.key)) {
  12484. if (null !== e.newValue) {
  12485. const t = this.Lr(e.key, e.newValue);
  12486. if (t) return this.qr(t);
  12487. }
  12488. } else if (this.Ar.test(e.key)) {
  12489. if (null !== e.newValue) {
  12490. const t = this.Ur(e.key, e.newValue);
  12491. if (t) return this.Kr(t);
  12492. }
  12493. } else if (e.key === this.vr) {
  12494. if (null !== e.newValue) {
  12495. const t = this.br(e.newValue);
  12496. if (t) return this.Vr(t);
  12497. }
  12498. } else if (e.key === this.Ir) {
  12499. const t = function(t) {
  12500. let e = Ot.ct;
  12501. if (null != t) try {
  12502. const n = JSON.parse(t);
  12503. F("number" == typeof n), e = n;
  12504. } catch (t) {
  12505. k("SharedClientState", "Failed to read sequence number from WebStorage", t);
  12506. }
  12507. return e;
  12508. }
  12509. /**
  12510. * `MemorySharedClientState` is a simple implementation of SharedClientState for
  12511. * clients using memory persistence. The state in this class remains fully
  12512. * isolated and no synchronization is performed.
  12513. */ (e.newValue);
  12514. t !== Ot.ct && this.sequenceNumberHandler(t);
  12515. } else if (e.key === this.Rr) {
  12516. const t = this.Gr(e.newValue);
  12517. await Promise.all(t.map((t => this.syncEngine.Qr(t))));
  12518. }
  12519. } else this.yr.push(e);
  12520. }));
  12521. }
  12522. }
  12523. get Nr() {
  12524. return this.gr.get(this.wr);
  12525. }
  12526. Pr() {
  12527. this.setItem(this.pr, this.Nr.hr());
  12528. }
  12529. Dr(t, e, n) {
  12530. const s = new Tu(this.currentUser, t, e, n), i = pu(this.persistenceKey, this.currentUser, t);
  12531. this.setItem(i, s.hr());
  12532. }
  12533. Cr(t) {
  12534. const e = pu(this.persistenceKey, this.currentUser, t);
  12535. this.removeItem(e);
  12536. }
  12537. Mr(t) {
  12538. const e = {
  12539. clientId: this.wr,
  12540. onlineState: t
  12541. };
  12542. this.storage.setItem(this.vr, JSON.stringify(e));
  12543. }
  12544. kr(t, e, n) {
  12545. const s = Iu(this.persistenceKey, t), i = new Eu(t, e, n);
  12546. this.setItem(s, i.hr());
  12547. }
  12548. $r(t) {
  12549. const e = JSON.stringify(Array.from(t));
  12550. this.setItem(this.Rr, e);
  12551. }
  12552. /**
  12553. * Parses a client state key in WebStorage. Returns null if the key does not
  12554. * match the expected key format.
  12555. */ Or(t) {
  12556. const e = this.Tr.exec(t);
  12557. return e ? e[1] : null;
  12558. }
  12559. /**
  12560. * Parses a client state in WebStorage. Returns 'null' if the value could not
  12561. * be parsed.
  12562. */ Br(t, e) {
  12563. const n = this.Or(t);
  12564. return Au.ar(n, e);
  12565. }
  12566. /**
  12567. * Parses a mutation batch state in WebStorage. Returns 'null' if the value
  12568. * could not be parsed.
  12569. */ Lr(t, e) {
  12570. const n = this.Er.exec(t), s = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;
  12571. return Tu.ar(new V(i), s, e);
  12572. }
  12573. /**
  12574. * Parses a query target state from WebStorage. Returns 'null' if the value
  12575. * could not be parsed.
  12576. */ Ur(t, e) {
  12577. const n = this.Ar.exec(t), s = Number(n[1]);
  12578. return Eu.ar(s, e);
  12579. }
  12580. /**
  12581. * Parses an online state from WebStorage. Returns 'null' if the value
  12582. * could not be parsed.
  12583. */ br(t) {
  12584. return vu.ar(t);
  12585. }
  12586. Gr(t) {
  12587. return JSON.parse(t);
  12588. }
  12589. async qr(t) {
  12590. if (t.user.uid === this.currentUser.uid) return this.syncEngine.jr(t.batchId, t.state, t.error);
  12591. N("SharedClientState", `Ignoring mutation for non-active user ${t.user.uid}`);
  12592. }
  12593. Kr(t) {
  12594. return this.syncEngine.zr(t.targetId, t.state, t.error);
  12595. }
  12596. Fr(t, e) {
  12597. const n = e ? this.gr.insert(t, e) : this.gr.remove(t), s = this.Sr(this.gr), i = this.Sr(n), r = [], o = [];
  12598. return i.forEach((t => {
  12599. s.has(t) || r.push(t);
  12600. })), s.forEach((t => {
  12601. i.has(t) || o.push(t);
  12602. })), this.syncEngine.Wr(r, o).then((() => {
  12603. this.gr = n;
  12604. }));
  12605. }
  12606. Vr(t) {
  12607. // We check whether the client that wrote this online state is still active
  12608. // by comparing its client ID to the list of clients kept active in
  12609. // IndexedDb. If a client does not update their IndexedDb client state
  12610. // within 5 seconds, it is considered inactive and we don't emit an online
  12611. // state event.
  12612. this.gr.get(t.clientId) && this.onlineStateHandler(t.onlineState);
  12613. }
  12614. Sr(t) {
  12615. let e = ps();
  12616. return t.forEach(((t, n) => {
  12617. e = e.unionWith(n.activeTargetIds);
  12618. })), e;
  12619. }
  12620. }
  12621. class bu {
  12622. constructor() {
  12623. this.Hr = new Ru, this.Jr = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;
  12624. }
  12625. addPendingMutation(t) {
  12626. // No op.
  12627. }
  12628. updateMutationState(t, e, n) {
  12629. // No op.
  12630. }
  12631. addLocalQueryTarget(t) {
  12632. return this.Hr.lr(t), this.Jr[t] || "not-current";
  12633. }
  12634. updateQueryState(t, e, n) {
  12635. this.Jr[t] = e;
  12636. }
  12637. removeLocalQueryTarget(t) {
  12638. this.Hr.dr(t);
  12639. }
  12640. isLocalQueryTarget(t) {
  12641. return this.Hr.activeTargetIds.has(t);
  12642. }
  12643. clearQueryState(t) {
  12644. delete this.Jr[t];
  12645. }
  12646. getAllActiveQueryTargets() {
  12647. return this.Hr.activeTargetIds;
  12648. }
  12649. isActiveQueryTarget(t) {
  12650. return this.Hr.activeTargetIds.has(t);
  12651. }
  12652. start() {
  12653. return this.Hr = new Ru, Promise.resolve();
  12654. }
  12655. handleUserChange(t, e, n) {
  12656. // No op.
  12657. }
  12658. setOnlineState(t) {
  12659. // No op.
  12660. }
  12661. shutdown() {}
  12662. writeSequenceNumber(t) {}
  12663. notifyBundleLoaded(t) {
  12664. // No op.
  12665. }
  12666. }
  12667. /**
  12668. * @license
  12669. * Copyright 2019 Google LLC
  12670. *
  12671. * Licensed under the Apache License, Version 2.0 (the "License");
  12672. * you may not use this file except in compliance with the License.
  12673. * You may obtain a copy of the License at
  12674. *
  12675. * http://www.apache.org/licenses/LICENSE-2.0
  12676. *
  12677. * Unless required by applicable law or agreed to in writing, software
  12678. * distributed under the License is distributed on an "AS IS" BASIS,
  12679. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12680. * See the License for the specific language governing permissions and
  12681. * limitations under the License.
  12682. */ class Vu {
  12683. Yr(t) {
  12684. // No-op.
  12685. }
  12686. shutdown() {
  12687. // No-op.
  12688. }
  12689. }
  12690. /**
  12691. * @license
  12692. * Copyright 2019 Google LLC
  12693. *
  12694. * Licensed under the Apache License, Version 2.0 (the "License");
  12695. * you may not use this file except in compliance with the License.
  12696. * You may obtain a copy of the License at
  12697. *
  12698. * http://www.apache.org/licenses/LICENSE-2.0
  12699. *
  12700. * Unless required by applicable law or agreed to in writing, software
  12701. * distributed under the License is distributed on an "AS IS" BASIS,
  12702. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12703. * See the License for the specific language governing permissions and
  12704. * limitations under the License.
  12705. */
  12706. // References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()
  12707. /* eslint-disable no-restricted-globals */
  12708. /**
  12709. * Browser implementation of ConnectivityMonitor.
  12710. */
  12711. class Su {
  12712. constructor() {
  12713. this.Xr = () => this.Zr(), this.eo = () => this.no(), this.so = [], this.io();
  12714. }
  12715. Yr(t) {
  12716. this.so.push(t);
  12717. }
  12718. shutdown() {
  12719. window.removeEventListener("online", this.Xr), window.removeEventListener("offline", this.eo);
  12720. }
  12721. io() {
  12722. window.addEventListener("online", this.Xr), window.addEventListener("offline", this.eo);
  12723. }
  12724. Zr() {
  12725. N("ConnectivityMonitor", "Network connectivity changed: AVAILABLE");
  12726. for (const t of this.so) t(0 /* NetworkStatus.AVAILABLE */);
  12727. }
  12728. no() {
  12729. N("ConnectivityMonitor", "Network connectivity changed: UNAVAILABLE");
  12730. for (const t of this.so) t(1 /* NetworkStatus.UNAVAILABLE */);
  12731. }
  12732. // TODO(chenbrian): Consider passing in window either into this component or
  12733. // here for testing via FakeWindow.
  12734. /** Checks that all used attributes of window are available. */
  12735. static D() {
  12736. return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
  12737. }
  12738. }
  12739. /**
  12740. * @license
  12741. * Copyright 2023 Google LLC
  12742. *
  12743. * Licensed under the Apache License, Version 2.0 (the "License");
  12744. * you may not use this file except in compliance with the License.
  12745. * You may obtain a copy of the License at
  12746. *
  12747. * http://www.apache.org/licenses/LICENSE-2.0
  12748. *
  12749. * Unless required by applicable law or agreed to in writing, software
  12750. * distributed under the License is distributed on an "AS IS" BASIS,
  12751. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12752. * See the License for the specific language governing permissions and
  12753. * limitations under the License.
  12754. */
  12755. /**
  12756. * The value returned from the most recent invocation of
  12757. * `generateUniqueDebugId()`, or null if it has never been invoked.
  12758. */ let Du = null;
  12759. /**
  12760. * Generates and returns an initial value for `lastUniqueDebugId`.
  12761. *
  12762. * The returned value is randomly selected from a range of integers that are
  12763. * represented as 8 hexadecimal digits. This means that (within reason) any
  12764. * numbers generated by incrementing the returned number by 1 will also be
  12765. * represented by 8 hexadecimal digits. This leads to all "IDs" having the same
  12766. * length when converted to a hexadecimal string, making reading logs containing
  12767. * these IDs easier to follow. And since the return value is randomly selected
  12768. * it will help to differentiate between logs from different executions.
  12769. */
  12770. /**
  12771. * Generates and returns a unique ID as a hexadecimal string.
  12772. *
  12773. * The returned ID is intended to be used in debug logging messages to help
  12774. * correlate log messages that may be spatially separated in the logs, but
  12775. * logically related. For example, a network connection could include the same
  12776. * "debug ID" string in all of its log messages to help trace a specific
  12777. * connection over time.
  12778. *
  12779. * @return the 10-character generated ID (e.g. "0xa1b2c3d4").
  12780. */
  12781. function Cu() {
  12782. return null === Du ? Du = 268435456 + Math.round(2147483648 * Math.random()) : Du++,
  12783. "0x" + Du.toString(16);
  12784. }
  12785. /**
  12786. * @license
  12787. * Copyright 2020 Google LLC
  12788. *
  12789. * Licensed under the Apache License, Version 2.0 (the "License");
  12790. * you may not use this file except in compliance with the License.
  12791. * You may obtain a copy of the License at
  12792. *
  12793. * http://www.apache.org/licenses/LICENSE-2.0
  12794. *
  12795. * Unless required by applicable law or agreed to in writing, software
  12796. * distributed under the License is distributed on an "AS IS" BASIS,
  12797. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12798. * See the License for the specific language governing permissions and
  12799. * limitations under the License.
  12800. */ const xu = {
  12801. BatchGetDocuments: "batchGet",
  12802. Commit: "commit",
  12803. RunQuery: "runQuery",
  12804. RunAggregationQuery: "runAggregationQuery"
  12805. };
  12806. /**
  12807. * Maps RPC names to the corresponding REST endpoint name.
  12808. *
  12809. * We use array notation to avoid mangling.
  12810. */
  12811. /**
  12812. * @license
  12813. * Copyright 2017 Google LLC
  12814. *
  12815. * Licensed under the Apache License, Version 2.0 (the "License");
  12816. * you may not use this file except in compliance with the License.
  12817. * You may obtain a copy of the License at
  12818. *
  12819. * http://www.apache.org/licenses/LICENSE-2.0
  12820. *
  12821. * Unless required by applicable law or agreed to in writing, software
  12822. * distributed under the License is distributed on an "AS IS" BASIS,
  12823. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12824. * See the License for the specific language governing permissions and
  12825. * limitations under the License.
  12826. */
  12827. /**
  12828. * Provides a simple helper class that implements the Stream interface to
  12829. * bridge to other implementations that are streams but do not implement the
  12830. * interface. The stream callbacks are invoked with the callOn... methods.
  12831. */
  12832. class Nu {
  12833. constructor(t) {
  12834. this.ro = t.ro, this.oo = t.oo;
  12835. }
  12836. uo(t) {
  12837. this.co = t;
  12838. }
  12839. ao(t) {
  12840. this.ho = t;
  12841. }
  12842. onMessage(t) {
  12843. this.lo = t;
  12844. }
  12845. close() {
  12846. this.oo();
  12847. }
  12848. send(t) {
  12849. this.ro(t);
  12850. }
  12851. fo() {
  12852. this.co();
  12853. }
  12854. wo(t) {
  12855. this.ho(t);
  12856. }
  12857. _o(t) {
  12858. this.lo(t);
  12859. }
  12860. }
  12861. /**
  12862. * @license
  12863. * Copyright 2017 Google LLC
  12864. *
  12865. * Licensed under the Apache License, Version 2.0 (the "License");
  12866. * you may not use this file except in compliance with the License.
  12867. * You may obtain a copy of the License at
  12868. *
  12869. * http://www.apache.org/licenses/LICENSE-2.0
  12870. *
  12871. * Unless required by applicable law or agreed to in writing, software
  12872. * distributed under the License is distributed on an "AS IS" BASIS,
  12873. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12874. * See the License for the specific language governing permissions and
  12875. * limitations under the License.
  12876. */ const ku = "WebChannelConnection";
  12877. class Mu extends
  12878. /**
  12879. * Base class for all Rest-based connections to the backend (WebChannel and
  12880. * HTTP).
  12881. */
  12882. class {
  12883. constructor(t) {
  12884. this.databaseInfo = t, this.databaseId = t.databaseId;
  12885. const e = t.ssl ? "https" : "http";
  12886. this.mo = e + "://" + t.host, this.yo = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents";
  12887. }
  12888. get po() {
  12889. // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
  12890. // where to run the query, and expect the `request` to NOT specify the "path".
  12891. return !1;
  12892. }
  12893. Io(t, e, n, s, i) {
  12894. const r = Cu(), o = this.To(t, e);
  12895. N("RestConnection", `Sending RPC '${t}' ${r}:`, o, n);
  12896. const u = {};
  12897. return this.Eo(u, s, i), this.Ao(t, o, u, n).then((e => (N("RestConnection", `Received RPC '${t}' ${r}: `, e),
  12898. e)), (e => {
  12899. throw M("RestConnection", `RPC '${t}' ${r} failed with error: `, e, "url: ", o, "request:", n),
  12900. e;
  12901. }));
  12902. }
  12903. vo(t, e, n, s, i, r) {
  12904. // The REST API automatically aggregates all of the streamed results, so we
  12905. // can just use the normal invoke() method.
  12906. return this.Io(t, e, n, s, i);
  12907. }
  12908. /**
  12909. * Modifies the headers for a request, adding any authorization token if
  12910. * present and any additional headers for the request.
  12911. */ Eo(t, e, n) {
  12912. t["X-Goog-Api-Client"] = "gl-js/ fire/" + S,
  12913. // Content-Type: text/plain will avoid preflight requests which might
  12914. // mess with CORS and redirects by proxies. If we add custom headers
  12915. // we will need to change this code to potentially use the $httpOverwrite
  12916. // parameter supported by ESF to avoid triggering preflight requests.
  12917. t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId),
  12918. e && e.headers.forEach(((e, n) => t[n] = e)), n && n.headers.forEach(((e, n) => t[n] = e));
  12919. }
  12920. To(t, e) {
  12921. const n = xu[t];
  12922. return `${this.mo}/v1/${e}:${n}`;
  12923. }
  12924. } {
  12925. constructor(t) {
  12926. super(t), this.forceLongPolling = t.forceLongPolling, this.autoDetectLongPolling = t.autoDetectLongPolling,
  12927. this.useFetchStreams = t.useFetchStreams, this.longPollingOptions = t.longPollingOptions;
  12928. }
  12929. Ao(t, e, n, s) {
  12930. const i = Cu();
  12931. return new Promise(((r, o) => {
  12932. const u = new webchannelWrapper.XhrIo;
  12933. u.setWithCredentials(!0), u.listenOnce(webchannelWrapper.EventType.COMPLETE, (() => {
  12934. try {
  12935. switch (u.getLastErrorCode()) {
  12936. case webchannelWrapper.ErrorCode.NO_ERROR:
  12937. const e = u.getResponseJson();
  12938. N(ku, `XHR for RPC '${t}' ${i} received:`, JSON.stringify(e)), r(e);
  12939. break;
  12940. case webchannelWrapper.ErrorCode.TIMEOUT:
  12941. N(ku, `RPC '${t}' ${i} timed out`), o(new U(q.DEADLINE_EXCEEDED, "Request time out"));
  12942. break;
  12943. case webchannelWrapper.ErrorCode.HTTP_ERROR:
  12944. const n = u.getStatus();
  12945. if (N(ku, `RPC '${t}' ${i} failed with status:`, n, "response text:", u.getResponseText()),
  12946. n > 0) {
  12947. let t = u.getResponseJson();
  12948. Array.isArray(t) && (t = t[0]);
  12949. const e = null == t ? void 0 : t.error;
  12950. if (e && e.status && e.message) {
  12951. const t = function(t) {
  12952. const e = t.toLowerCase().replace(/_/g, "-");
  12953. return Object.values(q).indexOf(e) >= 0 ? e : q.UNKNOWN;
  12954. }(e.status);
  12955. o(new U(t, e.message));
  12956. } else o(new U(q.UNKNOWN, "Server responded with status " + u.getStatus()));
  12957. } else
  12958. // If we received an HTTP_ERROR but there's no status code,
  12959. // it's most probably a connection issue
  12960. o(new U(q.UNAVAILABLE, "Connection failed."));
  12961. break;
  12962. default:
  12963. O();
  12964. }
  12965. } finally {
  12966. N(ku, `RPC '${t}' ${i} completed.`);
  12967. }
  12968. }));
  12969. const c = JSON.stringify(s);
  12970. N(ku, `RPC '${t}' ${i} sending request:`, s), u.send(e, "POST", c, n, 15);
  12971. }));
  12972. }
  12973. Ro(t, e, n) {
  12974. const s = Cu(), i = [ this.mo, "/", "google.firestore.v1.Firestore", "/", t, "/channel" ], r = webchannelWrapper.createWebChannelTransport(), o = webchannelWrapper.getStatEventTarget(), u = {
  12975. // Required for backend stickiness, routing behavior is based on this
  12976. // parameter.
  12977. httpSessionIdParam: "gsessionid",
  12978. initMessageHeaders: {},
  12979. messageUrlParams: {
  12980. // This param is used to improve routing and project isolation by the
  12981. // backend and must be included in every request.
  12982. database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`
  12983. },
  12984. sendRawJson: !0,
  12985. supportsCrossDomainXhr: !0,
  12986. internalChannelParams: {
  12987. // Override the default timeout (randomized between 10-20 seconds) since
  12988. // a large write batch on a slow internet connection may take a long
  12989. // time to send to the backend. Rather than have WebChannel impose a
  12990. // tight timeout which could lead to infinite timeouts and retries, we
  12991. // set it very large (5-10 minutes) and rely on the browser's builtin
  12992. // timeouts to kick in if the request isn't working.
  12993. forwardChannelRequestTimeoutMs: 6e5
  12994. },
  12995. forceLongPolling: this.forceLongPolling,
  12996. detectBufferingProxy: this.autoDetectLongPolling
  12997. }, c = this.longPollingOptions.timeoutSeconds;
  12998. void 0 !== c && (u.longPollingTimeout = Math.round(1e3 * c)), this.useFetchStreams && (u.xmlHttpFactory = new webchannelWrapper.FetchXmlHttpFactory({})),
  12999. this.Eo(u.initMessageHeaders, e, n),
  13000. // Sending the custom headers we just added to request.initMessageHeaders
  13001. // (Authorization, etc.) will trigger the browser to make a CORS preflight
  13002. // request because the XHR will no longer meet the criteria for a "simple"
  13003. // CORS request:
  13004. // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
  13005. // Therefore to avoid the CORS preflight request (an extra network
  13006. // roundtrip), we use the encodeInitMessageHeaders option to specify that
  13007. // the headers should instead be encoded in the request's POST payload,
  13008. // which is recognized by the webchannel backend.
  13009. u.encodeInitMessageHeaders = !0;
  13010. const a = i.join("");
  13011. N(ku, `Creating RPC '${t}' stream ${s}: ${a}`, u);
  13012. const h = r.createWebChannel(a, u);
  13013. // WebChannel supports sending the first message with the handshake - saving
  13014. // a network round trip. However, it will have to call send in the same
  13015. // JS event loop as open. In order to enforce this, we delay actually
  13016. // opening the WebChannel until send is called. Whether we have called
  13017. // open is tracked with this variable.
  13018. let l = !1, f = !1;
  13019. // A flag to determine whether the stream was closed (by us or through an
  13020. // error/close event) to avoid delivering multiple close events or sending
  13021. // on a closed stream
  13022. const d = new Nu({
  13023. ro: e => {
  13024. f ? N(ku, `Not sending because RPC '${t}' stream ${s} is closed:`, e) : (l || (N(ku, `Opening RPC '${t}' stream ${s} transport.`),
  13025. h.open(), l = !0), N(ku, `RPC '${t}' stream ${s} sending:`, e), h.send(e));
  13026. },
  13027. oo: () => h.close()
  13028. }), w = (t, e, n) => {
  13029. // TODO(dimond): closure typing seems broken because WebChannel does
  13030. // not implement goog.events.Listenable
  13031. t.listen(e, (t => {
  13032. try {
  13033. n(t);
  13034. } catch (t) {
  13035. setTimeout((() => {
  13036. throw t;
  13037. }), 0);
  13038. }
  13039. }));
  13040. };
  13041. // Closure events are guarded and exceptions are swallowed, so catch any
  13042. // exception and rethrow using a setTimeout so they become visible again.
  13043. // Note that eventually this function could go away if we are confident
  13044. // enough the code is exception free.
  13045. return w(h, webchannelWrapper.WebChannel.EventType.OPEN, (() => {
  13046. f || N(ku, `RPC '${t}' stream ${s} transport opened.`);
  13047. })), w(h, webchannelWrapper.WebChannel.EventType.CLOSE, (() => {
  13048. f || (f = !0, N(ku, `RPC '${t}' stream ${s} transport closed`), d.wo());
  13049. })), w(h, webchannelWrapper.WebChannel.EventType.ERROR, (e => {
  13050. f || (f = !0, M(ku, `RPC '${t}' stream ${s} transport errored:`, e), d.wo(new U(q.UNAVAILABLE, "The operation could not be completed")));
  13051. })), w(h, webchannelWrapper.WebChannel.EventType.MESSAGE, (e => {
  13052. var n;
  13053. if (!f) {
  13054. const i = e.data[0];
  13055. F(!!i);
  13056. // TODO(b/35143891): There is a bug in One Platform that caused errors
  13057. // (and only errors) to be wrapped in an extra array. To be forward
  13058. // compatible with the bug we need to check either condition. The latter
  13059. // can be removed once the fix has been rolled out.
  13060. // Use any because msgData.error is not typed.
  13061. const r = i, o = r.error || (null === (n = r[0]) || void 0 === n ? void 0 : n.error);
  13062. if (o) {
  13063. N(ku, `RPC '${t}' stream ${s} received error:`, o);
  13064. // error.status will be a string like 'OK' or 'NOT_FOUND'.
  13065. const e = o.status;
  13066. let n =
  13067. /**
  13068. * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
  13069. *
  13070. * @returns The Code equivalent to the given status string or undefined if
  13071. * there is no match.
  13072. */
  13073. function(t) {
  13074. // lookup by string
  13075. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13076. const e = ii[t];
  13077. if (void 0 !== e) return ui(e);
  13078. }(e), i = o.message;
  13079. void 0 === n && (n = q.INTERNAL, i = "Unknown error status: " + e + " with message " + o.message),
  13080. // Mark closed so no further events are propagated
  13081. f = !0, d.wo(new U(n, i)), h.close();
  13082. } else N(ku, `RPC '${t}' stream ${s} received:`, i), d._o(i);
  13083. }
  13084. })), w(o, webchannelWrapper.Event.STAT_EVENT, (e => {
  13085. e.stat === webchannelWrapper.Stat.PROXY ? N(ku, `RPC '${t}' stream ${s} detected buffering proxy`) : e.stat === webchannelWrapper.Stat.NOPROXY && N(ku, `RPC '${t}' stream ${s} detected no buffering proxy`);
  13086. })), setTimeout((() => {
  13087. // Technically we could/should wait for the WebChannel opened event,
  13088. // but because we want to send the first message with the WebChannel
  13089. // handshake we pretend the channel opened here (asynchronously), and
  13090. // then delay the actual open until the first message is sent.
  13091. d.fo();
  13092. }), 0), d;
  13093. }
  13094. }
  13095. /**
  13096. * @license
  13097. * Copyright 2020 Google LLC
  13098. *
  13099. * Licensed under the Apache License, Version 2.0 (the "License");
  13100. * you may not use this file except in compliance with the License.
  13101. * You may obtain a copy of the License at
  13102. *
  13103. * http://www.apache.org/licenses/LICENSE-2.0
  13104. *
  13105. * Unless required by applicable law or agreed to in writing, software
  13106. * distributed under the License is distributed on an "AS IS" BASIS,
  13107. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13108. * See the License for the specific language governing permissions and
  13109. * limitations under the License.
  13110. */
  13111. /** Initializes the WebChannelConnection for the browser. */
  13112. /**
  13113. * @license
  13114. * Copyright 2020 Google LLC
  13115. *
  13116. * Licensed under the Apache License, Version 2.0 (the "License");
  13117. * you may not use this file except in compliance with the License.
  13118. * You may obtain a copy of the License at
  13119. *
  13120. * http://www.apache.org/licenses/LICENSE-2.0
  13121. *
  13122. * Unless required by applicable law or agreed to in writing, software
  13123. * distributed under the License is distributed on an "AS IS" BASIS,
  13124. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13125. * See the License for the specific language governing permissions and
  13126. * limitations under the License.
  13127. */
  13128. /** The Platform's 'window' implementation or null if not available. */
  13129. function $u() {
  13130. // `window` is not always available, e.g. in ReactNative and WebWorkers.
  13131. // eslint-disable-next-line no-restricted-globals
  13132. return "undefined" != typeof window ? window : null;
  13133. }
  13134. /** The Platform's 'document' implementation or null if not available. */ function Ou() {
  13135. // `document` is not always available, e.g. in ReactNative and WebWorkers.
  13136. // eslint-disable-next-line no-restricted-globals
  13137. return "undefined" != typeof document ? document : null;
  13138. }
  13139. /**
  13140. * @license
  13141. * Copyright 2020 Google LLC
  13142. *
  13143. * Licensed under the Apache License, Version 2.0 (the "License");
  13144. * you may not use this file except in compliance with the License.
  13145. * You may obtain a copy of the License at
  13146. *
  13147. * http://www.apache.org/licenses/LICENSE-2.0
  13148. *
  13149. * Unless required by applicable law or agreed to in writing, software
  13150. * distributed under the License is distributed on an "AS IS" BASIS,
  13151. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13152. * See the License for the specific language governing permissions and
  13153. * limitations under the License.
  13154. */ function Fu(t) {
  13155. return new Vi(t, /* useProto3Json= */ !0);
  13156. }
  13157. /**
  13158. * @license
  13159. * Copyright 2017 Google LLC
  13160. *
  13161. * Licensed under the Apache License, Version 2.0 (the "License");
  13162. * you may not use this file except in compliance with the License.
  13163. * You may obtain a copy of the License at
  13164. *
  13165. * http://www.apache.org/licenses/LICENSE-2.0
  13166. *
  13167. * Unless required by applicable law or agreed to in writing, software
  13168. * distributed under the License is distributed on an "AS IS" BASIS,
  13169. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13170. * See the License for the specific language governing permissions and
  13171. * limitations under the License.
  13172. */
  13173. /**
  13174. * A helper for running delayed tasks following an exponential backoff curve
  13175. * between attempts.
  13176. *
  13177. * Each delay is made up of a "base" delay which follows the exponential
  13178. * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
  13179. * base delay. This prevents clients from accidentally synchronizing their
  13180. * delays causing spikes of load to the backend.
  13181. */
  13182. class Bu {
  13183. constructor(
  13184. /**
  13185. * The AsyncQueue to run backoff operations on.
  13186. */
  13187. t,
  13188. /**
  13189. * The ID to use when scheduling backoff operations on the AsyncQueue.
  13190. */
  13191. e,
  13192. /**
  13193. * The initial delay (used as the base delay on the first retry attempt).
  13194. * Note that jitter will still be applied, so the actual delay could be as
  13195. * little as 0.5*initialDelayMs.
  13196. */
  13197. n = 1e3
  13198. /**
  13199. * The multiplier to use to determine the extended base delay after each
  13200. * attempt.
  13201. */ , s = 1.5
  13202. /**
  13203. * The maximum base delay after which no further backoff is performed.
  13204. * Note that jitter will still be applied, so the actual delay could be as
  13205. * much as 1.5*maxDelayMs.
  13206. */ , i = 6e4) {
  13207. this.ii = t, this.timerId = e, this.Po = n, this.bo = s, this.Vo = i, this.So = 0,
  13208. this.Do = null,
  13209. /** The last backoff attempt, as epoch milliseconds. */
  13210. this.Co = Date.now(), this.reset();
  13211. }
  13212. /**
  13213. * Resets the backoff delay.
  13214. *
  13215. * The very next backoffAndWait() will have no delay. If it is called again
  13216. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  13217. * subsequent ones will increase according to the backoffFactor.
  13218. */ reset() {
  13219. this.So = 0;
  13220. }
  13221. /**
  13222. * Resets the backoff delay to the maximum delay (e.g. for use after a
  13223. * RESOURCE_EXHAUSTED error).
  13224. */ xo() {
  13225. this.So = this.Vo;
  13226. }
  13227. /**
  13228. * Returns a promise that resolves after currentDelayMs, and increases the
  13229. * delay for any subsequent attempts. If there was a pending backoff operation
  13230. * already, it will be canceled.
  13231. */ No(t) {
  13232. // Cancel any pending backoff operation.
  13233. this.cancel();
  13234. // First schedule using the current base (which may be 0 and should be
  13235. // honored as such).
  13236. const e = Math.floor(this.So + this.ko()), n = Math.max(0, Date.now() - this.Co), s = Math.max(0, e - n);
  13237. // Guard against lastAttemptTime being in the future due to a clock change.
  13238. s > 0 && N("ExponentialBackoff", `Backing off for ${s} ms (base delay: ${this.So} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`),
  13239. this.Do = this.ii.enqueueAfterDelay(this.timerId, s, (() => (this.Co = Date.now(),
  13240. t()))),
  13241. // Apply backoff factor to determine next delay and ensure it is within
  13242. // bounds.
  13243. this.So *= this.bo, this.So < this.Po && (this.So = this.Po), this.So > this.Vo && (this.So = this.Vo);
  13244. }
  13245. Mo() {
  13246. null !== this.Do && (this.Do.skipDelay(), this.Do = null);
  13247. }
  13248. cancel() {
  13249. null !== this.Do && (this.Do.cancel(), this.Do = null);
  13250. }
  13251. /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ ko() {
  13252. return (Math.random() - .5) * this.So;
  13253. }
  13254. }
  13255. /**
  13256. * @license
  13257. * Copyright 2017 Google LLC
  13258. *
  13259. * Licensed under the Apache License, Version 2.0 (the "License");
  13260. * you may not use this file except in compliance with the License.
  13261. * You may obtain a copy of the License at
  13262. *
  13263. * http://www.apache.org/licenses/LICENSE-2.0
  13264. *
  13265. * Unless required by applicable law or agreed to in writing, software
  13266. * distributed under the License is distributed on an "AS IS" BASIS,
  13267. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13268. * See the License for the specific language governing permissions and
  13269. * limitations under the License.
  13270. */
  13271. /**
  13272. * A PersistentStream is an abstract base class that represents a streaming RPC
  13273. * to the Firestore backend. It's built on top of the connections own support
  13274. * for streaming RPCs, and adds several critical features for our clients:
  13275. *
  13276. * - Exponential backoff on failure
  13277. * - Authentication via CredentialsProvider
  13278. * - Dispatching all callbacks into the shared worker queue
  13279. * - Closing idle streams after 60 seconds of inactivity
  13280. *
  13281. * Subclasses of PersistentStream implement serialization of models to and
  13282. * from the JSON representation of the protocol buffers for a specific
  13283. * streaming RPC.
  13284. *
  13285. * ## Starting and Stopping
  13286. *
  13287. * Streaming RPCs are stateful and need to be start()ed before messages can
  13288. * be sent and received. The PersistentStream will call the onOpen() function
  13289. * of the listener once the stream is ready to accept requests.
  13290. *
  13291. * Should a start() fail, PersistentStream will call the registered onClose()
  13292. * listener with a FirestoreError indicating what went wrong.
  13293. *
  13294. * A PersistentStream can be started and stopped repeatedly.
  13295. *
  13296. * Generic types:
  13297. * SendType: The type of the outgoing message of the underlying
  13298. * connection stream
  13299. * ReceiveType: The type of the incoming message of the underlying
  13300. * connection stream
  13301. * ListenerType: The type of the listener that will be used for callbacks
  13302. */
  13303. class Lu {
  13304. constructor(t, e, n, s, i, r, o, u) {
  13305. this.ii = t, this.$o = n, this.Oo = s, this.connection = i, this.authCredentialsProvider = r,
  13306. this.appCheckCredentialsProvider = o, this.listener = u, this.state = 0 /* PersistentStreamState.Initial */ ,
  13307. /**
  13308. * A close count that's incremented every time the stream is closed; used by
  13309. * getCloseGuardedDispatcher() to invalidate callbacks that happen after
  13310. * close.
  13311. */
  13312. this.Fo = 0, this.Bo = null, this.Lo = null, this.stream = null, this.qo = new Bu(t, e);
  13313. }
  13314. /**
  13315. * Returns true if start() has been called and no error has occurred. True
  13316. * indicates the stream is open or in the process of opening (which
  13317. * encompasses respecting backoff, getting auth tokens, and starting the
  13318. * actual RPC). Use isOpen() to determine if the stream is open and ready for
  13319. * outbound requests.
  13320. */ Uo() {
  13321. return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.Ko();
  13322. }
  13323. /**
  13324. * Returns true if the underlying RPC is open (the onOpen() listener has been
  13325. * called) and the stream is ready for outbound requests.
  13326. */ Ko() {
  13327. return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;
  13328. }
  13329. /**
  13330. * Starts the RPC. Only allowed if isStarted() returns false. The stream is
  13331. * not immediately ready for use: onOpen() will be invoked when the RPC is
  13332. * ready for outbound requests, at which point isOpen() will return true.
  13333. *
  13334. * When start returns, isStarted() will return true.
  13335. */ start() {
  13336. 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Go();
  13337. }
  13338. /**
  13339. * Stops the RPC. This call is idempotent and allowed regardless of the
  13340. * current isStarted() state.
  13341. *
  13342. * When stop returns, isStarted() and isOpen() will both return false.
  13343. */ async stop() {
  13344. this.Uo() && await this.close(0 /* PersistentStreamState.Initial */);
  13345. }
  13346. /**
  13347. * After an error the stream will usually back off on the next attempt to
  13348. * start it. If the error warrants an immediate restart of the stream, the
  13349. * sender can use this to indicate that the receiver should not back off.
  13350. *
  13351. * Each error will call the onClose() listener. That function can decide to
  13352. * inhibit backoff if required.
  13353. */ Qo() {
  13354. this.state = 0 /* PersistentStreamState.Initial */ , this.qo.reset();
  13355. }
  13356. /**
  13357. * Marks this stream as idle. If no further actions are performed on the
  13358. * stream for one minute, the stream will automatically close itself and
  13359. * notify the stream's onClose() handler with Status.OK. The stream will then
  13360. * be in a !isStarted() state, requiring the caller to start the stream again
  13361. * before further use.
  13362. *
  13363. * Only streams that are in state 'Open' can be marked idle, as all other
  13364. * states imply pending network operations.
  13365. */ jo() {
  13366. // Starts the idle time if we are in state 'Open' and are not yet already
  13367. // running a timer (in which case the previous idle timeout still applies).
  13368. this.Ko() && null === this.Bo && (this.Bo = this.ii.enqueueAfterDelay(this.$o, 6e4, (() => this.zo())));
  13369. }
  13370. /** Sends a message to the underlying stream. */ Wo(t) {
  13371. this.Ho(), this.stream.send(t);
  13372. }
  13373. /** Called by the idle timer when the stream should close due to inactivity. */ async zo() {
  13374. if (this.Ko())
  13375. // When timing out an idle stream there's no reason to force the stream into backoff when
  13376. // it restarts so set the stream state to Initial instead of Error.
  13377. return this.close(0 /* PersistentStreamState.Initial */);
  13378. }
  13379. /** Marks the stream as active again. */ Ho() {
  13380. this.Bo && (this.Bo.cancel(), this.Bo = null);
  13381. }
  13382. /** Cancels the health check delayed operation. */ Jo() {
  13383. this.Lo && (this.Lo.cancel(), this.Lo = null);
  13384. }
  13385. /**
  13386. * Closes the stream and cleans up as necessary:
  13387. *
  13388. * * closes the underlying GRPC stream;
  13389. * * calls the onClose handler with the given 'error';
  13390. * * sets internal stream state to 'finalState';
  13391. * * adjusts the backoff timer based on the error
  13392. *
  13393. * A new stream can be opened by calling start().
  13394. *
  13395. * @param finalState - the intended state of the stream after closing.
  13396. * @param error - the error the connection was closed with.
  13397. */ async close(t, e) {
  13398. // Cancel any outstanding timers (they're guaranteed not to execute).
  13399. this.Ho(), this.Jo(), this.qo.cancel(),
  13400. // Invalidates any stream-related callbacks (e.g. from auth or the
  13401. // underlying stream), guaranteeing they won't execute.
  13402. this.Fo++, 4 /* PersistentStreamState.Error */ !== t ?
  13403. // If this is an intentional close ensure we don't delay our next connection attempt.
  13404. this.qo.reset() : e && e.code === q.RESOURCE_EXHAUSTED ? (
  13405. // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
  13406. k(e.toString()), k("Using maximum backoff delay to prevent overloading the backend."),
  13407. this.qo.xo()) : e && e.code === q.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (
  13408. // "unauthenticated" error means the token was rejected. This should rarely
  13409. // happen since both Auth and AppCheck ensure a sufficient TTL when we
  13410. // request a token. If a user manually resets their system clock this can
  13411. // fail, however. In this case, we should get a Code.UNAUTHENTICATED error
  13412. // before we received the first message and we need to invalidate the token
  13413. // to ensure that we fetch a new token.
  13414. this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()),
  13415. // Clean up the underlying stream because we are no longer interested in events.
  13416. null !== this.stream && (this.Yo(), this.stream.close(), this.stream = null),
  13417. // This state must be assigned before calling onClose() to allow the callback to
  13418. // inhibit backoff or otherwise manipulate the state in its non-started state.
  13419. this.state = t,
  13420. // Notify the listener that the stream closed.
  13421. await this.listener.ao(e);
  13422. }
  13423. /**
  13424. * Can be overridden to perform additional cleanup before the stream is closed.
  13425. * Calling super.tearDown() is not required.
  13426. */ Yo() {}
  13427. auth() {
  13428. this.state = 1 /* PersistentStreamState.Starting */;
  13429. const t = this.Xo(this.Fo), e = this.Fo;
  13430. // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
  13431. Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([t, n]) => {
  13432. // Stream can be stopped while waiting for authentication.
  13433. // TODO(mikelehen): We really should just use dispatchIfNotClosed
  13434. // and let this dispatch onto the queue, but that opened a spec test can
  13435. // of worms that I don't want to deal with in this PR.
  13436. this.Fo === e &&
  13437. // Normally we'd have to schedule the callback on the AsyncQueue.
  13438. // However, the following calls are safe to be called outside the
  13439. // AsyncQueue since they don't chain asynchronous calls
  13440. this.Zo(t, n);
  13441. }), (e => {
  13442. t((() => {
  13443. const t = new U(q.UNKNOWN, "Fetching auth token failed: " + e.message);
  13444. return this.tu(t);
  13445. }));
  13446. }));
  13447. }
  13448. Zo(t, e) {
  13449. const n = this.Xo(this.Fo);
  13450. this.stream = this.eu(t, e), this.stream.uo((() => {
  13451. n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.Lo = this.ii.enqueueAfterDelay(this.Oo, 1e4, (() => (this.Ko() && (this.state = 3 /* PersistentStreamState.Healthy */),
  13452. Promise.resolve()))), this.listener.uo())));
  13453. })), this.stream.ao((t => {
  13454. n((() => this.tu(t)));
  13455. })), this.stream.onMessage((t => {
  13456. n((() => this.onMessage(t)));
  13457. }));
  13458. }
  13459. Go() {
  13460. this.state = 5 /* PersistentStreamState.Backoff */ , this.qo.No((async () => {
  13461. this.state = 0 /* PersistentStreamState.Initial */ , this.start();
  13462. }));
  13463. }
  13464. // Visible for tests
  13465. tu(t) {
  13466. // In theory the stream could close cleanly, however, in our current model
  13467. // we never expect this to happen because if we stop a stream ourselves,
  13468. // this callback will never be called. To prevent cases where we retry
  13469. // without a backoff accidentally, we set the stream to error in all cases.
  13470. return N("PersistentStream", `close with error: ${t}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , t);
  13471. }
  13472. /**
  13473. * Returns a "dispatcher" function that dispatches operations onto the
  13474. * AsyncQueue but only runs them if closeCount remains unchanged. This allows
  13475. * us to turn auth / stream callbacks into no-ops if the stream is closed /
  13476. * re-opened, etc.
  13477. */ Xo(t) {
  13478. return e => {
  13479. this.ii.enqueueAndForget((() => this.Fo === t ? e() : (N("PersistentStream", "stream callback skipped by getCloseGuardedDispatcher."),
  13480. Promise.resolve())));
  13481. };
  13482. }
  13483. }
  13484. /**
  13485. * A PersistentStream that implements the Listen RPC.
  13486. *
  13487. * Once the Listen stream has called the onOpen() listener, any number of
  13488. * listen() and unlisten() calls can be made to control what changes will be
  13489. * sent from the server for ListenResponses.
  13490. */ class qu extends Lu {
  13491. constructor(t, e, n, s, i, r) {
  13492. super(t, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */ , "listen_stream_idle" /* TimerId.ListenStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , e, n, s, r),
  13493. this.serializer = i;
  13494. }
  13495. eu(t, e) {
  13496. return this.connection.Ro("Listen", t, e);
  13497. }
  13498. onMessage(t) {
  13499. // A successful response means the stream is healthy
  13500. this.qo.reset();
  13501. const e = Qi(this.serializer, t), n = function(t) {
  13502. // We have only reached a consistent snapshot for the entire stream if there
  13503. // is a read_time set and it applies to all targets (i.e. the list of
  13504. // targets is empty). The backend is guaranteed to send such responses.
  13505. if (!("targetChange" in t)) return rt.min();
  13506. const e = t.targetChange;
  13507. return e.targetIds && e.targetIds.length ? rt.min() : e.readTime ? Ni(e.readTime) : rt.min();
  13508. }(t);
  13509. return this.listener.nu(e, n);
  13510. }
  13511. /**
  13512. * Registers interest in the results of the given target. If the target
  13513. * includes a resumeToken it will be included in the request. Results that
  13514. * affect the target will be streamed back as WatchChange messages that
  13515. * reference the targetId.
  13516. */ su(t) {
  13517. const e = {};
  13518. e.database = Li(this.serializer), e.addTarget = function(t, e) {
  13519. let n;
  13520. const s = e.target;
  13521. if (n = Fn(s) ? {
  13522. documents: Hi(t, s)
  13523. } : {
  13524. query: Ji(t, s)
  13525. }, n.targetId = e.targetId, e.resumeToken.approximateByteSize() > 0) {
  13526. n.resumeToken = Ci(t, e.resumeToken);
  13527. const s = Si(t, e.expectedCount);
  13528. null !== s && (n.expectedCount = s);
  13529. } else if (e.snapshotVersion.compareTo(rt.min()) > 0) {
  13530. // TODO(wuandy): Consider removing above check because it is most likely true.
  13531. // Right now, many tests depend on this behaviour though (leaving min() out
  13532. // of serialization).
  13533. n.readTime = Di(t, e.snapshotVersion.toTimestamp());
  13534. const s = Si(t, e.expectedCount);
  13535. null !== s && (n.expectedCount = s);
  13536. }
  13537. return n;
  13538. }(this.serializer, t);
  13539. const n = Xi(this.serializer, t);
  13540. n && (e.labels = n), this.Wo(e);
  13541. }
  13542. /**
  13543. * Unregisters interest in the results of the target associated with the
  13544. * given targetId.
  13545. */ iu(t) {
  13546. const e = {};
  13547. e.database = Li(this.serializer), e.removeTarget = t, this.Wo(e);
  13548. }
  13549. }
  13550. /**
  13551. * A Stream that implements the Write RPC.
  13552. *
  13553. * The Write RPC requires the caller to maintain special streamToken
  13554. * state in between calls, to help the server understand which responses the
  13555. * client has processed by the time the next request is made. Every response
  13556. * will contain a streamToken; this value must be passed to the next
  13557. * request.
  13558. *
  13559. * After calling start() on this stream, the next request must be a handshake,
  13560. * containing whatever streamToken is on hand. Once a response to this
  13561. * request is received, all pending mutations may be submitted. When
  13562. * submitting multiple batches of mutations at the same time, it's
  13563. * okay to use the same streamToken for the calls to writeMutations.
  13564. *
  13565. * TODO(b/33271235): Use proto types
  13566. */ class Uu extends Lu {
  13567. constructor(t, e, n, s, i, r) {
  13568. super(t, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */ , "write_stream_idle" /* TimerId.WriteStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , e, n, s, r),
  13569. this.serializer = i, this.ru = !1;
  13570. }
  13571. /**
  13572. * Tracks whether or not a handshake has been successfully exchanged and
  13573. * the stream is ready to accept mutations.
  13574. */ get ou() {
  13575. return this.ru;
  13576. }
  13577. // Override of PersistentStream.start
  13578. start() {
  13579. this.ru = !1, this.lastStreamToken = void 0, super.start();
  13580. }
  13581. Yo() {
  13582. this.ru && this.uu([]);
  13583. }
  13584. eu(t, e) {
  13585. return this.connection.Ro("Write", t, e);
  13586. }
  13587. onMessage(t) {
  13588. if (
  13589. // Always capture the last stream token.
  13590. F(!!t.streamToken), this.lastStreamToken = t.streamToken, this.ru) {
  13591. // A successful first write response means the stream is healthy,
  13592. // Note, that we could consider a successful handshake healthy, however,
  13593. // the write itself might be causing an error we want to back off from.
  13594. this.qo.reset();
  13595. const e = Wi(t.writeResults, t.commitTime), n = Ni(t.commitTime);
  13596. return this.listener.cu(n, e);
  13597. }
  13598. // The first response is always the handshake response
  13599. return F(!t.writeResults || 0 === t.writeResults.length), this.ru = !0, this.listener.au();
  13600. }
  13601. /**
  13602. * Sends an initial streamToken to the server, performing the handshake
  13603. * required to make the StreamingWrite RPC work. Subsequent
  13604. * calls should wait until onHandshakeComplete was called.
  13605. */ hu() {
  13606. // TODO(dimond): Support stream resumption. We intentionally do not set the
  13607. // stream token on the handshake, ignoring any stream token we might have.
  13608. const t = {};
  13609. t.database = Li(this.serializer), this.Wo(t);
  13610. }
  13611. /** Sends a group of mutations to the Firestore backend to apply. */ uu(t) {
  13612. const e = {
  13613. streamToken: this.lastStreamToken,
  13614. writes: t.map((t => ji(this.serializer, t)))
  13615. };
  13616. this.Wo(e);
  13617. }
  13618. }
  13619. /**
  13620. * @license
  13621. * Copyright 2017 Google LLC
  13622. *
  13623. * Licensed under the Apache License, Version 2.0 (the "License");
  13624. * you may not use this file except in compliance with the License.
  13625. * You may obtain a copy of the License at
  13626. *
  13627. * http://www.apache.org/licenses/LICENSE-2.0
  13628. *
  13629. * Unless required by applicable law or agreed to in writing, software
  13630. * distributed under the License is distributed on an "AS IS" BASIS,
  13631. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13632. * See the License for the specific language governing permissions and
  13633. * limitations under the License.
  13634. */
  13635. /**
  13636. * Datastore and its related methods are a wrapper around the external Google
  13637. * Cloud Datastore grpc API, which provides an interface that is more convenient
  13638. * for the rest of the client SDK architecture to consume.
  13639. */
  13640. /**
  13641. * An implementation of Datastore that exposes additional state for internal
  13642. * consumption.
  13643. */
  13644. class Ku extends class {} {
  13645. constructor(t, e, n, s) {
  13646. super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = n,
  13647. this.serializer = s, this.lu = !1;
  13648. }
  13649. fu() {
  13650. if (this.lu) throw new U(q.FAILED_PRECONDITION, "The client has already been terminated.");
  13651. }
  13652. /** Invokes the provided RPC with auth and AppCheck tokens. */ Io(t, e, n) {
  13653. return this.fu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.connection.Io(t, e, n, s, i))).catch((t => {
  13654. throw "FirebaseError" === t.name ? (t.code === q.UNAUTHENTICATED && (this.authCredentials.invalidateToken(),
  13655. this.appCheckCredentials.invalidateToken()), t) : new U(q.UNKNOWN, t.toString());
  13656. }));
  13657. }
  13658. /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ vo(t, e, n, s) {
  13659. return this.fu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, r]) => this.connection.vo(t, e, n, i, r, s))).catch((t => {
  13660. throw "FirebaseError" === t.name ? (t.code === q.UNAUTHENTICATED && (this.authCredentials.invalidateToken(),
  13661. this.appCheckCredentials.invalidateToken()), t) : new U(q.UNKNOWN, t.toString());
  13662. }));
  13663. }
  13664. terminate() {
  13665. this.lu = !0;
  13666. }
  13667. }
  13668. // TODO(firestorexp): Make sure there is only one Datastore instance per
  13669. // firestore-exp client.
  13670. async function Gu(t, e, n) {
  13671. var s;
  13672. const i = L(t), {request: r, du: o} = function(t, e, n) {
  13673. const s = Ji(t, e), i = {}, r = [];
  13674. let o = 0;
  13675. return n.forEach((t => {
  13676. // Map all client-side aliases to a unique short-form
  13677. // alias. This avoids issues with client-side aliases that
  13678. // exceed the 1500-byte string size limit.
  13679. const e = "aggregate_" + o++;
  13680. i[e] = t.alias, "count" === t.yt ? r.push({
  13681. alias: e,
  13682. count: {}
  13683. }) : "avg" === t.yt ? r.push({
  13684. alias: e,
  13685. avg: {
  13686. field: sr(t.fieldPath)
  13687. }
  13688. }) : "sum" === t.yt && r.push({
  13689. alias: e,
  13690. sum: {
  13691. field: sr(t.fieldPath)
  13692. }
  13693. });
  13694. })), {
  13695. request: {
  13696. structuredAggregationQuery: {
  13697. aggregations: r,
  13698. structuredQuery: s.structuredQuery
  13699. },
  13700. parent: s.parent
  13701. },
  13702. du: i
  13703. };
  13704. }(i.serializer, Jn(e), n), u = r.parent;
  13705. i.connection.po || delete r.parent;
  13706. const c = (await i.vo("RunAggregationQuery", u, r, /*expectedResponseCount=*/ 1)).filter((t => !!t.result));
  13707. // Omit RunAggregationQueryResponse that only contain readTimes.
  13708. F(1 === c.length);
  13709. // Remap the short-form aliases that were sent to the server
  13710. // to the client-side aliases. Users will access the results
  13711. // using the client-side alias.
  13712. const a = null === (s = c[0].result) || void 0 === s ? void 0 : s.aggregateFields;
  13713. return Object.keys(a).reduce(((t, e) => (t[o[e]] = a[e], t)), {});
  13714. }
  13715. /**
  13716. * A component used by the RemoteStore to track the OnlineState (that is,
  13717. * whether or not the client as a whole should be considered to be online or
  13718. * offline), implementing the appropriate heuristics.
  13719. *
  13720. * In particular, when the client is trying to connect to the backend, we
  13721. * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for
  13722. * a connection to succeed. If we have too many failures or the timeout elapses,
  13723. * then we set the OnlineState to Offline, and the client will behave as if
  13724. * it is offline (get()s will return cached data, etc.).
  13725. */
  13726. class Qu {
  13727. constructor(t, e) {
  13728. this.asyncQueue = t, this.onlineStateHandler = e,
  13729. /** The current OnlineState. */
  13730. this.state = "Unknown" /* OnlineState.Unknown */ ,
  13731. /**
  13732. * A count of consecutive failures to open the stream. If it reaches the
  13733. * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
  13734. * Offline.
  13735. */
  13736. this.wu = 0,
  13737. /**
  13738. * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
  13739. * transition from OnlineState.Unknown to OnlineState.Offline without waiting
  13740. * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
  13741. */
  13742. this._u = null,
  13743. /**
  13744. * Whether the client should log a warning message if it fails to connect to
  13745. * the backend (initially true, cleared after a successful stream, or if we've
  13746. * logged the message already).
  13747. */
  13748. this.mu = !0;
  13749. }
  13750. /**
  13751. * Called by RemoteStore when a watch stream is started (including on each
  13752. * backoff attempt).
  13753. *
  13754. * If this is the first attempt, it sets the OnlineState to Unknown and starts
  13755. * the onlineStateTimer.
  13756. */ gu() {
  13757. 0 === this.wu && (this.yu("Unknown" /* OnlineState.Unknown */), this._u = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this._u = null,
  13758. this.pu("Backend didn't respond within 10 seconds."), this.yu("Offline" /* OnlineState.Offline */),
  13759. Promise.resolve()))));
  13760. }
  13761. /**
  13762. * Updates our OnlineState as appropriate after the watch stream reports a
  13763. * failure. The first failure moves us to the 'Unknown' state. We then may
  13764. * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
  13765. * actually transition to the 'Offline' state.
  13766. */ Iu(t) {
  13767. "Online" /* OnlineState.Online */ === this.state ? this.yu("Unknown" /* OnlineState.Unknown */) : (this.wu++,
  13768. this.wu >= 1 && (this.Tu(), this.pu(`Connection failed 1 times. Most recent error: ${t.toString()}`),
  13769. this.yu("Offline" /* OnlineState.Offline */)));
  13770. }
  13771. /**
  13772. * Explicitly sets the OnlineState to the specified state.
  13773. *
  13774. * Note that this resets our timers / failure counters, etc. used by our
  13775. * Offline heuristics, so must not be used in place of
  13776. * handleWatchStreamStart() and handleWatchStreamFailure().
  13777. */ set(t) {
  13778. this.Tu(), this.wu = 0, "Online" /* OnlineState.Online */ === t && (
  13779. // We've connected to watch at least once. Don't warn the developer
  13780. // about being offline going forward.
  13781. this.mu = !1), this.yu(t);
  13782. }
  13783. yu(t) {
  13784. t !== this.state && (this.state = t, this.onlineStateHandler(t));
  13785. }
  13786. pu(t) {
  13787. const e = `Could not reach Cloud Firestore backend. ${t}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;
  13788. this.mu ? (k(e), this.mu = !1) : N("OnlineStateTracker", e);
  13789. }
  13790. Tu() {
  13791. null !== this._u && (this._u.cancel(), this._u = null);
  13792. }
  13793. }
  13794. /**
  13795. * @license
  13796. * Copyright 2017 Google LLC
  13797. *
  13798. * Licensed under the Apache License, Version 2.0 (the "License");
  13799. * you may not use this file except in compliance with the License.
  13800. * You may obtain a copy of the License at
  13801. *
  13802. * http://www.apache.org/licenses/LICENSE-2.0
  13803. *
  13804. * Unless required by applicable law or agreed to in writing, software
  13805. * distributed under the License is distributed on an "AS IS" BASIS,
  13806. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13807. * See the License for the specific language governing permissions and
  13808. * limitations under the License.
  13809. */ class ju {
  13810. constructor(
  13811. /**
  13812. * The local store, used to fill the write pipeline with outbound mutations.
  13813. */
  13814. t,
  13815. /** The client-side proxy for interacting with the backend. */
  13816. e, n, s, i) {
  13817. this.localStore = t, this.datastore = e, this.asyncQueue = n, this.remoteSyncer = {},
  13818. /**
  13819. * A list of up to MAX_PENDING_WRITES writes that we have fetched from the
  13820. * LocalStore via fillWritePipeline() and have or will send to the write
  13821. * stream.
  13822. *
  13823. * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
  13824. * restart the write stream. When the stream is established the writes in the
  13825. * pipeline will be sent in order.
  13826. *
  13827. * Writes remain in writePipeline until they are acknowledged by the backend
  13828. * and thus will automatically be re-sent if the stream is interrupted /
  13829. * restarted before they're acknowledged.
  13830. *
  13831. * Write responses from the backend are linked to their originating request
  13832. * purely based on order, and so we can just shift() writes from the front of
  13833. * the writePipeline as we receive responses.
  13834. */
  13835. this.Eu = [],
  13836. /**
  13837. * A mapping of watched targets that the client cares about tracking and the
  13838. * user has explicitly called a 'listen' for this target.
  13839. *
  13840. * These targets may or may not have been sent to or acknowledged by the
  13841. * server. On re-establishing the listen stream, these targets should be sent
  13842. * to the server. The targets removed with unlistens are removed eagerly
  13843. * without waiting for confirmation from the listen stream.
  13844. */
  13845. this.Au = new Map,
  13846. /**
  13847. * A set of reasons for why the RemoteStore may be offline. If empty, the
  13848. * RemoteStore may start its network connections.
  13849. */
  13850. this.vu = new Set,
  13851. /**
  13852. * Event handlers that get called when the network is disabled or enabled.
  13853. *
  13854. * PORTING NOTE: These functions are used on the Web client to create the
  13855. * underlying streams (to support tree-shakeable streams). On Android and iOS,
  13856. * the streams are created during construction of RemoteStore.
  13857. */
  13858. this.Ru = [], this.Pu = i, this.Pu.Yr((t => {
  13859. n.enqueueAndForget((async () => {
  13860. // Porting Note: Unlike iOS, `restartNetwork()` is called even when the
  13861. // network becomes unreachable as we don't have any other way to tear
  13862. // down our streams.
  13863. ec(this) && (N("RemoteStore", "Restarting streams for network reachability change."),
  13864. await async function(t) {
  13865. const e = L(t);
  13866. e.vu.add(4 /* OfflineCause.ConnectivityChange */), await Wu(e), e.bu.set("Unknown" /* OnlineState.Unknown */),
  13867. e.vu.delete(4 /* OfflineCause.ConnectivityChange */), await zu(e);
  13868. }(this));
  13869. }));
  13870. })), this.bu = new Qu(n, s);
  13871. }
  13872. }
  13873. async function zu(t) {
  13874. if (ec(t)) for (const e of t.Ru) await e(/* enabled= */ !0);
  13875. }
  13876. /**
  13877. * Temporarily disables the network. The network can be re-enabled using
  13878. * enableNetwork().
  13879. */ async function Wu(t) {
  13880. for (const e of t.Ru) await e(/* enabled= */ !1);
  13881. }
  13882. /**
  13883. * Starts new listen for the given target. Uses resume token if provided. It
  13884. * is a no-op if the target of given `TargetData` is already being listened to.
  13885. */
  13886. function Hu(t, e) {
  13887. const n = L(t);
  13888. n.Au.has(e.targetId) || (
  13889. // Mark this as something the client is currently listening for.
  13890. n.Au.set(e.targetId, e), tc(n) ?
  13891. // The listen will be sent in onWatchStreamOpen
  13892. Zu(n) : pc(n).Ko() && Yu(n, e));
  13893. }
  13894. /**
  13895. * Removes the listen from server. It is a no-op if the given target id is
  13896. * not being listened to.
  13897. */ function Ju(t, e) {
  13898. const n = L(t), s = pc(n);
  13899. n.Au.delete(e), s.Ko() && Xu(n, e), 0 === n.Au.size && (s.Ko() ? s.jo() : ec(n) &&
  13900. // Revert to OnlineState.Unknown if the watch stream is not open and we
  13901. // have no listeners, since without any listens to send we cannot
  13902. // confirm if the stream is healthy and upgrade to OnlineState.Online.
  13903. n.bu.set("Unknown" /* OnlineState.Unknown */));
  13904. }
  13905. /**
  13906. * We need to increment the the expected number of pending responses we're due
  13907. * from watch so we wait for the ack to process any messages from this target.
  13908. */ function Yu(t, e) {
  13909. if (t.Vu.qt(e.targetId), e.resumeToken.approximateByteSize() > 0 || e.snapshotVersion.compareTo(rt.min()) > 0) {
  13910. const n = t.remoteSyncer.getRemoteKeysForTarget(e.targetId).size;
  13911. e = e.withExpectedCount(n);
  13912. }
  13913. pc(t).su(e);
  13914. }
  13915. /**
  13916. * We need to increment the expected number of pending responses we're due
  13917. * from watch so we wait for the removal on the server before we process any
  13918. * messages from this target.
  13919. */ function Xu(t, e) {
  13920. t.Vu.qt(e), pc(t).iu(e);
  13921. }
  13922. function Zu(t) {
  13923. t.Vu = new Ei({
  13924. getRemoteKeysForTarget: e => t.remoteSyncer.getRemoteKeysForTarget(e),
  13925. le: e => t.Au.get(e) || null,
  13926. ue: () => t.datastore.serializer.databaseId
  13927. }), pc(t).start(), t.bu.gu();
  13928. }
  13929. /**
  13930. * Returns whether the watch stream should be started because it's necessary
  13931. * and has not yet been started.
  13932. */ function tc(t) {
  13933. return ec(t) && !pc(t).Uo() && t.Au.size > 0;
  13934. }
  13935. function ec(t) {
  13936. return 0 === L(t).vu.size;
  13937. }
  13938. function nc(t) {
  13939. t.Vu = void 0;
  13940. }
  13941. async function sc(t) {
  13942. t.Au.forEach(((e, n) => {
  13943. Yu(t, e);
  13944. }));
  13945. }
  13946. async function ic(t, e) {
  13947. nc(t),
  13948. // If we still need the watch stream, retry the connection.
  13949. tc(t) ? (t.bu.Iu(e), Zu(t)) :
  13950. // No need to restart watch stream because there are no active targets.
  13951. // The online state is set to unknown because there is no active attempt
  13952. // at establishing a connection
  13953. t.bu.set("Unknown" /* OnlineState.Unknown */);
  13954. }
  13955. async function rc(t, e, n) {
  13956. if (
  13957. // Mark the client as online since we got a message from the server
  13958. t.bu.set("Online" /* OnlineState.Online */), e instanceof Ii && 2 /* WatchTargetChangeState.Removed */ === e.state && e.cause)
  13959. // There was an error on a target, don't wait for a consistent snapshot
  13960. // to raise events
  13961. try {
  13962. await
  13963. /** Handles an error on a target */
  13964. async function(t, e) {
  13965. const n = e.cause;
  13966. for (const s of e.targetIds)
  13967. // A watched target might have been removed already.
  13968. t.Au.has(s) && (await t.remoteSyncer.rejectListen(s, n), t.Au.delete(s), t.Vu.removeTarget(s));
  13969. }
  13970. /**
  13971. * Attempts to fill our write pipeline with writes from the LocalStore.
  13972. *
  13973. * Called internally to bootstrap or refill the write pipeline and by
  13974. * SyncEngine whenever there are new mutations to process.
  13975. *
  13976. * Starts the write stream if necessary.
  13977. */ (t, e);
  13978. } catch (n) {
  13979. N("RemoteStore", "Failed to remove targets %s: %s ", e.targetIds.join(","), n),
  13980. await oc(t, n);
  13981. } else if (e instanceof yi ? t.Vu.Ht(e) : e instanceof pi ? t.Vu.ne(e) : t.Vu.Xt(e),
  13982. !n.isEqual(rt.min())) try {
  13983. const e = await ou(t.localStore);
  13984. n.compareTo(e) >= 0 &&
  13985. // We have received a target change with a global snapshot if the snapshot
  13986. // version is not equal to SnapshotVersion.min().
  13987. await
  13988. /**
  13989. * Takes a batch of changes from the Datastore, repackages them as a
  13990. * RemoteEvent, and passes that on to the listener, which is typically the
  13991. * SyncEngine.
  13992. */
  13993. function(t, e) {
  13994. const n = t.Vu.ce(e);
  13995. // Update in-memory resume tokens. LocalStore will update the
  13996. // persistent view of these when applying the completed RemoteEvent.
  13997. return n.targetChanges.forEach(((n, s) => {
  13998. if (n.resumeToken.approximateByteSize() > 0) {
  13999. const i = t.Au.get(s);
  14000. // A watched target might have been removed already.
  14001. i && t.Au.set(s, i.withResumeToken(n.resumeToken, e));
  14002. }
  14003. })),
  14004. // Re-establish listens for the targets that have been invalidated by
  14005. // existence filter mismatches.
  14006. n.targetMismatches.forEach(((e, n) => {
  14007. const s = t.Au.get(e);
  14008. if (!s)
  14009. // A watched target might have been removed already.
  14010. return;
  14011. // Clear the resume token for the target, since we're in a known mismatch
  14012. // state.
  14013. t.Au.set(e, s.withResumeToken(Ve.EMPTY_BYTE_STRING, s.snapshotVersion)),
  14014. // Cause a hard reset by unwatching and rewatching immediately, but
  14015. // deliberately don't send a resume token so that we get a full update.
  14016. Xu(t, e);
  14017. // Mark the target we send as being on behalf of an existence filter
  14018. // mismatch, but don't actually retain that in listenTargets. This ensures
  14019. // that we flag the first re-listen this way without impacting future
  14020. // listens of this target (that might happen e.g. on reconnect).
  14021. const i = new cr(s.target, e, n, s.sequenceNumber);
  14022. Yu(t, i);
  14023. })), t.remoteSyncer.applyRemoteEvent(n);
  14024. }(t, n);
  14025. } catch (e) {
  14026. N("RemoteStore", "Failed to raise snapshot:", e), await oc(t, e);
  14027. }
  14028. }
  14029. /**
  14030. * Recovery logic for IndexedDB errors that takes the network offline until
  14031. * `op` succeeds. Retries are scheduled with backoff using
  14032. * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is
  14033. * validated via a generic operation.
  14034. *
  14035. * The returned Promise is resolved once the network is disabled and before
  14036. * any retry attempt.
  14037. */ async function oc(t, e, n) {
  14038. if (!Dt(e)) throw e;
  14039. t.vu.add(1 /* OfflineCause.IndexedDbFailed */),
  14040. // Disable network and raise offline snapshots
  14041. await Wu(t), t.bu.set("Offline" /* OnlineState.Offline */), n || (
  14042. // Use a simple read operation to determine if IndexedDB recovered.
  14043. // Ideally, we would expose a health check directly on SimpleDb, but
  14044. // RemoteStore only has access to persistence through LocalStore.
  14045. n = () => ou(t.localStore)),
  14046. // Probe IndexedDB periodically and re-enable network
  14047. t.asyncQueue.enqueueRetryable((async () => {
  14048. N("RemoteStore", "Retrying IndexedDB access"), await n(), t.vu.delete(1 /* OfflineCause.IndexedDbFailed */),
  14049. await zu(t);
  14050. }));
  14051. }
  14052. /**
  14053. * Executes `op`. If `op` fails, takes the network offline until `op`
  14054. * succeeds. Returns after the first attempt.
  14055. */ function uc(t, e) {
  14056. return e().catch((n => oc(t, n, e)));
  14057. }
  14058. async function cc(t) {
  14059. const e = L(t), n = Ic(e);
  14060. let s = e.Eu.length > 0 ? e.Eu[e.Eu.length - 1].batchId : -1;
  14061. for (;ac(e); ) try {
  14062. const t = await au(e.localStore, s);
  14063. if (null === t) {
  14064. 0 === e.Eu.length && n.jo();
  14065. break;
  14066. }
  14067. s = t.batchId, hc(e, t);
  14068. } catch (t) {
  14069. await oc(e, t);
  14070. }
  14071. lc(e) && fc(e);
  14072. }
  14073. /**
  14074. * Returns true if we can add to the write pipeline (i.e. the network is
  14075. * enabled and the write pipeline is not full).
  14076. */ function ac(t) {
  14077. return ec(t) && t.Eu.length < 10;
  14078. }
  14079. /**
  14080. * Queues additional writes to be sent to the write stream, sending them
  14081. * immediately if the write stream is established.
  14082. */ function hc(t, e) {
  14083. t.Eu.push(e);
  14084. const n = Ic(t);
  14085. n.Ko() && n.ou && n.uu(e.mutations);
  14086. }
  14087. function lc(t) {
  14088. return ec(t) && !Ic(t).Uo() && t.Eu.length > 0;
  14089. }
  14090. function fc(t) {
  14091. Ic(t).start();
  14092. }
  14093. async function dc(t) {
  14094. Ic(t).hu();
  14095. }
  14096. async function wc(t) {
  14097. const e = Ic(t);
  14098. // Send the write pipeline now that the stream is established.
  14099. for (const n of t.Eu) e.uu(n.mutations);
  14100. }
  14101. async function _c(t, e, n) {
  14102. const s = t.Eu.shift(), i = ti.from(s, e, n);
  14103. await uc(t, (() => t.remoteSyncer.applySuccessfulWrite(i))),
  14104. // It's possible that with the completion of this mutation another
  14105. // slot has freed up.
  14106. await cc(t);
  14107. }
  14108. async function mc(t, e) {
  14109. // If the write stream closed after the write handshake completes, a write
  14110. // operation failed and we fail the pending operation.
  14111. e && Ic(t).ou &&
  14112. // This error affects the actual write.
  14113. await async function(t, e) {
  14114. // Only handle permanent errors here. If it's transient, just let the retry
  14115. // logic kick in.
  14116. if (n = e.code, oi(n) && n !== q.ABORTED) {
  14117. // This was a permanent error, the request itself was the problem
  14118. // so it's not going to succeed if we resend it.
  14119. const n = t.Eu.shift();
  14120. // In this case it's also unlikely that the server itself is melting
  14121. // down -- this was just a bad request so inhibit backoff on the next
  14122. // restart.
  14123. Ic(t).Qo(), await uc(t, (() => t.remoteSyncer.rejectFailedWrite(n.batchId, e))),
  14124. // It's possible that with the completion of this mutation
  14125. // another slot has freed up.
  14126. await cc(t);
  14127. }
  14128. var n;
  14129. }(t, e),
  14130. // The write stream might have been started by refilling the write
  14131. // pipeline for failed writes
  14132. lc(t) && fc(t);
  14133. }
  14134. async function gc(t, e) {
  14135. const n = L(t);
  14136. n.asyncQueue.verifyOperationInProgress(), N("RemoteStore", "RemoteStore received new credentials");
  14137. const s = ec(n);
  14138. // Tear down and re-create our network streams. This will ensure we get a
  14139. // fresh auth token for the new user and re-fill the write pipeline with
  14140. // new mutations from the LocalStore (since mutations are per-user).
  14141. n.vu.add(3 /* OfflineCause.CredentialChange */), await Wu(n), s &&
  14142. // Don't set the network status to Unknown if we are offline.
  14143. n.bu.set("Unknown" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(e),
  14144. n.vu.delete(3 /* OfflineCause.CredentialChange */), await zu(n);
  14145. }
  14146. /**
  14147. * Toggles the network state when the client gains or loses its primary lease.
  14148. */ async function yc(t, e) {
  14149. const n = L(t);
  14150. e ? (n.vu.delete(2 /* OfflineCause.IsSecondary */), await zu(n)) : e || (n.vu.add(2 /* OfflineCause.IsSecondary */),
  14151. await Wu(n), n.bu.set("Unknown" /* OnlineState.Unknown */));
  14152. }
  14153. /**
  14154. * If not yet initialized, registers the WatchStream and its network state
  14155. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  14156. * already available.
  14157. *
  14158. * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.
  14159. * This is not done on Web to allow it to be tree-shaken.
  14160. */ function pc(t) {
  14161. return t.Su || (
  14162. // Create stream (but note that it is not started yet).
  14163. t.Su = function(t, e, n) {
  14164. const s = L(t);
  14165. return s.fu(), new qu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.serializer, n);
  14166. }
  14167. /**
  14168. * @license
  14169. * Copyright 2018 Google LLC
  14170. *
  14171. * Licensed under the Apache License, Version 2.0 (the "License");
  14172. * you may not use this file except in compliance with the License.
  14173. * You may obtain a copy of the License at
  14174. *
  14175. * http://www.apache.org/licenses/LICENSE-2.0
  14176. *
  14177. * Unless required by applicable law or agreed to in writing, software
  14178. * distributed under the License is distributed on an "AS IS" BASIS,
  14179. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14180. * See the License for the specific language governing permissions and
  14181. * limitations under the License.
  14182. */ (t.datastore, t.asyncQueue, {
  14183. uo: sc.bind(null, t),
  14184. ao: ic.bind(null, t),
  14185. nu: rc.bind(null, t)
  14186. }), t.Ru.push((async e => {
  14187. e ? (t.Su.Qo(), tc(t) ? Zu(t) : t.bu.set("Unknown" /* OnlineState.Unknown */)) : (await t.Su.stop(),
  14188. nc(t));
  14189. }))), t.Su;
  14190. }
  14191. /**
  14192. * If not yet initialized, registers the WriteStream and its network state
  14193. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  14194. * already available.
  14195. *
  14196. * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.
  14197. * This is not done on Web to allow it to be tree-shaken.
  14198. */ function Ic(t) {
  14199. return t.Du || (
  14200. // Create stream (but note that it is not started yet).
  14201. t.Du = function(t, e, n) {
  14202. const s = L(t);
  14203. return s.fu(), new Uu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.serializer, n);
  14204. }(t.datastore, t.asyncQueue, {
  14205. uo: dc.bind(null, t),
  14206. ao: mc.bind(null, t),
  14207. au: wc.bind(null, t),
  14208. cu: _c.bind(null, t)
  14209. }), t.Ru.push((async e => {
  14210. e ? (t.Du.Qo(),
  14211. // This will start the write stream if necessary.
  14212. await cc(t)) : (await t.Du.stop(), t.Eu.length > 0 && (N("RemoteStore", `Stopping write stream with ${t.Eu.length} pending writes`),
  14213. t.Eu = []));
  14214. }))), t.Du;
  14215. }
  14216. /**
  14217. * @license
  14218. * Copyright 2017 Google LLC
  14219. *
  14220. * Licensed under the Apache License, Version 2.0 (the "License");
  14221. * you may not use this file except in compliance with the License.
  14222. * You may obtain a copy of the License at
  14223. *
  14224. * http://www.apache.org/licenses/LICENSE-2.0
  14225. *
  14226. * Unless required by applicable law or agreed to in writing, software
  14227. * distributed under the License is distributed on an "AS IS" BASIS,
  14228. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14229. * See the License for the specific language governing permissions and
  14230. * limitations under the License.
  14231. */
  14232. /**
  14233. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  14234. *
  14235. * It is created via DelayedOperation.createAndSchedule().
  14236. *
  14237. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  14238. *
  14239. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  14240. * in newer versions of TypeScript defines `finally`, which is not available in
  14241. * IE.
  14242. */
  14243. class Tc {
  14244. constructor(t, e, n, s, i) {
  14245. this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = s, this.removalCallback = i,
  14246. this.deferred = new K, this.then = this.deferred.promise.then.bind(this.deferred.promise),
  14247. // It's normal for the deferred promise to be canceled (due to cancellation)
  14248. // and so we attach a dummy catch callback to avoid
  14249. // 'UnhandledPromiseRejectionWarning' log spam.
  14250. this.deferred.promise.catch((t => {}));
  14251. }
  14252. /**
  14253. * Creates and returns a DelayedOperation that has been scheduled to be
  14254. * executed on the provided asyncQueue after the provided delayMs.
  14255. *
  14256. * @param asyncQueue - The queue to schedule the operation on.
  14257. * @param id - A Timer ID identifying the type of operation this is.
  14258. * @param delayMs - The delay (ms) before the operation should be scheduled.
  14259. * @param op - The operation to run.
  14260. * @param removalCallback - A callback to be called synchronously once the
  14261. * operation is executed or canceled, notifying the AsyncQueue to remove it
  14262. * from its delayedOperations list.
  14263. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  14264. * the DelayedOperation class public.
  14265. */ static createAndSchedule(t, e, n, s, i) {
  14266. const r = Date.now() + n, o = new Tc(t, e, r, s, i);
  14267. return o.start(n), o;
  14268. }
  14269. /**
  14270. * Starts the timer. This is called immediately after construction by
  14271. * createAndSchedule().
  14272. */ start(t) {
  14273. this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t);
  14274. }
  14275. /**
  14276. * Queues the operation to run immediately (if it hasn't already been run or
  14277. * canceled).
  14278. */ skipDelay() {
  14279. return this.handleDelayElapsed();
  14280. }
  14281. /**
  14282. * Cancels the operation if it hasn't already been executed or canceled. The
  14283. * promise will be rejected.
  14284. *
  14285. * As long as the operation has not yet been run, calling cancel() provides a
  14286. * guarantee that the operation will not be run.
  14287. */ cancel(t) {
  14288. null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new U(q.CANCELLED, "Operation cancelled" + (t ? ": " + t : ""))));
  14289. }
  14290. handleDelayElapsed() {
  14291. this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(),
  14292. this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve()));
  14293. }
  14294. clearTimeout() {
  14295. null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle),
  14296. this.timerHandle = null);
  14297. }
  14298. }
  14299. /**
  14300. * Returns a FirestoreError that can be surfaced to the user if the provided
  14301. * error is an IndexedDbTransactionError. Re-throws the error otherwise.
  14302. */ function Ec(t, e) {
  14303. if (k("AsyncQueue", `${e}: ${t}`), Dt(t)) return new U(q.UNAVAILABLE, `${e}: ${t}`);
  14304. throw t;
  14305. }
  14306. /**
  14307. * @license
  14308. * Copyright 2017 Google LLC
  14309. *
  14310. * Licensed under the Apache License, Version 2.0 (the "License");
  14311. * you may not use this file except in compliance with the License.
  14312. * You may obtain a copy of the License at
  14313. *
  14314. * http://www.apache.org/licenses/LICENSE-2.0
  14315. *
  14316. * Unless required by applicable law or agreed to in writing, software
  14317. * distributed under the License is distributed on an "AS IS" BASIS,
  14318. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14319. * See the License for the specific language governing permissions and
  14320. * limitations under the License.
  14321. */
  14322. /**
  14323. * DocumentSet is an immutable (copy-on-write) collection that holds documents
  14324. * in order specified by the provided comparator. We always add a document key
  14325. * comparator on top of what is provided to guarantee document equality based on
  14326. * the key.
  14327. */ class Ac {
  14328. /** The default ordering is by key if the comparator is omitted */
  14329. constructor(t) {
  14330. // We are adding document key comparator to the end as it's the only
  14331. // guaranteed unique property of a document.
  14332. this.comparator = t ? (e, n) => t(e, n) || ht.comparator(e.key, n.key) : (t, e) => ht.comparator(t.key, e.key),
  14333. this.keyedMap = hs(), this.sortedSet = new pe(this.comparator);
  14334. }
  14335. /**
  14336. * Returns an empty copy of the existing DocumentSet, using the same
  14337. * comparator.
  14338. */ static emptySet(t) {
  14339. return new Ac(t.comparator);
  14340. }
  14341. has(t) {
  14342. return null != this.keyedMap.get(t);
  14343. }
  14344. get(t) {
  14345. return this.keyedMap.get(t);
  14346. }
  14347. first() {
  14348. return this.sortedSet.minKey();
  14349. }
  14350. last() {
  14351. return this.sortedSet.maxKey();
  14352. }
  14353. isEmpty() {
  14354. return this.sortedSet.isEmpty();
  14355. }
  14356. /**
  14357. * Returns the index of the provided key in the document set, or -1 if the
  14358. * document key is not present in the set;
  14359. */ indexOf(t) {
  14360. const e = this.keyedMap.get(t);
  14361. return e ? this.sortedSet.indexOf(e) : -1;
  14362. }
  14363. get size() {
  14364. return this.sortedSet.size;
  14365. }
  14366. /** Iterates documents in order defined by "comparator" */ forEach(t) {
  14367. this.sortedSet.inorderTraversal(((e, n) => (t(e), !1)));
  14368. }
  14369. /** Inserts or updates a document with the same key */ add(t) {
  14370. // First remove the element if we have it.
  14371. const e = this.delete(t.key);
  14372. return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));
  14373. }
  14374. /** Deletes a document with a given key */ delete(t) {
  14375. const e = this.get(t);
  14376. return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;
  14377. }
  14378. isEqual(t) {
  14379. if (!(t instanceof Ac)) return !1;
  14380. if (this.size !== t.size) return !1;
  14381. const e = this.sortedSet.getIterator(), n = t.sortedSet.getIterator();
  14382. for (;e.hasNext(); ) {
  14383. const t = e.getNext().key, s = n.getNext().key;
  14384. if (!t.isEqual(s)) return !1;
  14385. }
  14386. return !0;
  14387. }
  14388. toString() {
  14389. const t = [];
  14390. return this.forEach((e => {
  14391. t.push(e.toString());
  14392. })), 0 === t.length ? "DocumentSet ()" : "DocumentSet (\n " + t.join(" \n") + "\n)";
  14393. }
  14394. copy(t, e) {
  14395. const n = new Ac;
  14396. return n.comparator = this.comparator, n.keyedMap = t, n.sortedSet = e, n;
  14397. }
  14398. }
  14399. /**
  14400. * @license
  14401. * Copyright 2017 Google LLC
  14402. *
  14403. * Licensed under the Apache License, Version 2.0 (the "License");
  14404. * you may not use this file except in compliance with the License.
  14405. * You may obtain a copy of the License at
  14406. *
  14407. * http://www.apache.org/licenses/LICENSE-2.0
  14408. *
  14409. * Unless required by applicable law or agreed to in writing, software
  14410. * distributed under the License is distributed on an "AS IS" BASIS,
  14411. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14412. * See the License for the specific language governing permissions and
  14413. * limitations under the License.
  14414. */
  14415. /**
  14416. * DocumentChangeSet keeps track of a set of changes to docs in a query, merging
  14417. * duplicate events for the same doc.
  14418. */ class vc {
  14419. constructor() {
  14420. this.Cu = new pe(ht.comparator);
  14421. }
  14422. track(t) {
  14423. const e = t.doc.key, n = this.Cu.get(e);
  14424. n ?
  14425. // Merge the new change with the existing change.
  14426. 0 /* ChangeType.Added */ !== t.type && 3 /* ChangeType.Metadata */ === n.type ? this.Cu = this.Cu.insert(e, t) : 3 /* ChangeType.Metadata */ === t.type && 1 /* ChangeType.Removed */ !== n.type ? this.Cu = this.Cu.insert(e, {
  14427. type: n.type,
  14428. doc: t.doc
  14429. }) : 2 /* ChangeType.Modified */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Cu = this.Cu.insert(e, {
  14430. type: 2 /* ChangeType.Modified */ ,
  14431. doc: t.doc
  14432. }) : 2 /* ChangeType.Modified */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Cu = this.Cu.insert(e, {
  14433. type: 0 /* ChangeType.Added */ ,
  14434. doc: t.doc
  14435. }) : 1 /* ChangeType.Removed */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Cu = this.Cu.remove(e) : 1 /* ChangeType.Removed */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Cu = this.Cu.insert(e, {
  14436. type: 1 /* ChangeType.Removed */ ,
  14437. doc: n.doc
  14438. }) : 0 /* ChangeType.Added */ === t.type && 1 /* ChangeType.Removed */ === n.type ? this.Cu = this.Cu.insert(e, {
  14439. type: 2 /* ChangeType.Modified */ ,
  14440. doc: t.doc
  14441. }) :
  14442. // This includes these cases, which don't make sense:
  14443. // Added->Added
  14444. // Removed->Removed
  14445. // Modified->Added
  14446. // Removed->Modified
  14447. // Metadata->Added
  14448. // Removed->Metadata
  14449. O() : this.Cu = this.Cu.insert(e, t);
  14450. }
  14451. xu() {
  14452. const t = [];
  14453. return this.Cu.inorderTraversal(((e, n) => {
  14454. t.push(n);
  14455. })), t;
  14456. }
  14457. }
  14458. class Rc {
  14459. constructor(t, e, n, s, i, r, o, u, c) {
  14460. this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = s, this.mutatedKeys = i,
  14461. this.fromCache = r, this.syncStateChanged = o, this.excludesMetadataChanges = u,
  14462. this.hasCachedResults = c;
  14463. }
  14464. /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(t, e, n, s, i) {
  14465. const r = [];
  14466. return e.forEach((t => {
  14467. r.push({
  14468. type: 0 /* ChangeType.Added */ ,
  14469. doc: t
  14470. });
  14471. })), new Rc(t, e, Ac.emptySet(e), r, n, s,
  14472. /* syncStateChanged= */ !0,
  14473. /* excludesMetadataChanges= */ !1, i);
  14474. }
  14475. get hasPendingWrites() {
  14476. return !this.mutatedKeys.isEmpty();
  14477. }
  14478. isEqual(t) {
  14479. if (!(this.fromCache === t.fromCache && this.hasCachedResults === t.hasCachedResults && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && Zn(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;
  14480. const e = this.docChanges, n = t.docChanges;
  14481. if (e.length !== n.length) return !1;
  14482. for (let t = 0; t < e.length; t++) if (e[t].type !== n[t].type || !e[t].doc.isEqual(n[t].doc)) return !1;
  14483. return !0;
  14484. }
  14485. }
  14486. /**
  14487. * @license
  14488. * Copyright 2017 Google LLC
  14489. *
  14490. * Licensed under the Apache License, Version 2.0 (the "License");
  14491. * you may not use this file except in compliance with the License.
  14492. * You may obtain a copy of the License at
  14493. *
  14494. * http://www.apache.org/licenses/LICENSE-2.0
  14495. *
  14496. * Unless required by applicable law or agreed to in writing, software
  14497. * distributed under the License is distributed on an "AS IS" BASIS,
  14498. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14499. * See the License for the specific language governing permissions and
  14500. * limitations under the License.
  14501. */
  14502. /**
  14503. * Holds the listeners and the last received ViewSnapshot for a query being
  14504. * tracked by EventManager.
  14505. */ class Pc {
  14506. constructor() {
  14507. this.Nu = void 0, this.listeners = [];
  14508. }
  14509. }
  14510. class bc {
  14511. constructor() {
  14512. this.queries = new os((t => ts(t)), Zn), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14513. this.ku = new Set;
  14514. }
  14515. }
  14516. async function Vc(t, e) {
  14517. const n = L(t), s = e.query;
  14518. let i = !1, r = n.queries.get(s);
  14519. if (r || (i = !0, r = new Pc), i) try {
  14520. r.Nu = await n.onListen(s);
  14521. } catch (t) {
  14522. const n = Ec(t, `Initialization of query '${es(e.query)}' failed`);
  14523. return void e.onError(n);
  14524. }
  14525. if (n.queries.set(s, r), r.listeners.push(e),
  14526. // Run global snapshot listeners if a consistent snapshot has been emitted.
  14527. e.Mu(n.onlineState), r.Nu) {
  14528. e.$u(r.Nu) && xc(n);
  14529. }
  14530. }
  14531. async function Sc(t, e) {
  14532. const n = L(t), s = e.query;
  14533. let i = !1;
  14534. const r = n.queries.get(s);
  14535. if (r) {
  14536. const t = r.listeners.indexOf(e);
  14537. t >= 0 && (r.listeners.splice(t, 1), i = 0 === r.listeners.length);
  14538. }
  14539. if (i) return n.queries.delete(s), n.onUnlisten(s);
  14540. }
  14541. function Dc(t, e) {
  14542. const n = L(t);
  14543. let s = !1;
  14544. for (const t of e) {
  14545. const e = t.query, i = n.queries.get(e);
  14546. if (i) {
  14547. for (const e of i.listeners) e.$u(t) && (s = !0);
  14548. i.Nu = t;
  14549. }
  14550. }
  14551. s && xc(n);
  14552. }
  14553. function Cc(t, e, n) {
  14554. const s = L(t), i = s.queries.get(e);
  14555. if (i) for (const t of i.listeners) t.onError(n);
  14556. // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
  14557. // after an error.
  14558. s.queries.delete(e);
  14559. }
  14560. // Call all global snapshot listeners that have been set.
  14561. function xc(t) {
  14562. t.ku.forEach((t => {
  14563. t.next();
  14564. }));
  14565. }
  14566. /**
  14567. * QueryListener takes a series of internal view snapshots and determines
  14568. * when to raise the event.
  14569. *
  14570. * It uses an Observer to dispatch events.
  14571. */ class Nc {
  14572. constructor(t, e, n) {
  14573. this.query = t, this.Ou = e,
  14574. /**
  14575. * Initial snapshots (e.g. from cache) may not be propagated to the wrapped
  14576. * observer. This flag is set to true once we've actually raised an event.
  14577. */
  14578. this.Fu = !1, this.Bu = null, this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14579. this.options = n || {};
  14580. }
  14581. /**
  14582. * Applies the new ViewSnapshot to this listener, raising a user-facing event
  14583. * if applicable (depending on what changed, whether the user has opted into
  14584. * metadata-only changes, etc.). Returns true if a user-facing event was
  14585. * indeed raised.
  14586. */ $u(t) {
  14587. if (!this.options.includeMetadataChanges) {
  14588. // Remove the metadata only changes.
  14589. const e = [];
  14590. for (const n of t.docChanges) 3 /* ChangeType.Metadata */ !== n.type && e.push(n);
  14591. t = new Rc(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged,
  14592. /* excludesMetadataChanges= */ !0, t.hasCachedResults);
  14593. }
  14594. let e = !1;
  14595. return this.Fu ? this.Lu(t) && (this.Ou.next(t), e = !0) : this.qu(t, this.onlineState) && (this.Uu(t),
  14596. e = !0), this.Bu = t, e;
  14597. }
  14598. onError(t) {
  14599. this.Ou.error(t);
  14600. }
  14601. /** Returns whether a snapshot was raised. */ Mu(t) {
  14602. this.onlineState = t;
  14603. let e = !1;
  14604. return this.Bu && !this.Fu && this.qu(this.Bu, t) && (this.Uu(this.Bu), e = !0),
  14605. e;
  14606. }
  14607. qu(t, e) {
  14608. // Always raise the first event when we're synced
  14609. if (!t.fromCache) return !0;
  14610. // NOTE: We consider OnlineState.Unknown as online (it should become Offline
  14611. // or Online if we wait long enough).
  14612. const n = "Offline" /* OnlineState.Offline */ !== e;
  14613. // Don't raise the event if we're online, aren't synced yet (checked
  14614. // above) and are waiting for a sync.
  14615. return (!this.options.Ku || !n) && (!t.docs.isEmpty() || t.hasCachedResults || "Offline" /* OnlineState.Offline */ === e);
  14616. // Raise data from cache if we have any documents, have cached results before,
  14617. // or we are offline.
  14618. }
  14619. Lu(t) {
  14620. // We don't need to handle includeDocumentMetadataChanges here because
  14621. // the Metadata only changes have already been stripped out if needed.
  14622. // At this point the only changes we will see are the ones we should
  14623. // propagate.
  14624. if (t.docChanges.length > 0) return !0;
  14625. const e = this.Bu && this.Bu.hasPendingWrites !== t.hasPendingWrites;
  14626. return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;
  14627. // Generally we should have hit one of the cases above, but it's possible
  14628. // to get here if there were only metadata docChanges and they got
  14629. // stripped out.
  14630. }
  14631. Uu(t) {
  14632. t = Rc.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache, t.hasCachedResults),
  14633. this.Fu = !0, this.Ou.next(t);
  14634. }
  14635. }
  14636. /**
  14637. * @license
  14638. * Copyright 2020 Google LLC
  14639. *
  14640. * Licensed under the Apache License, Version 2.0 (the "License");
  14641. * you may not use this file except in compliance with the License.
  14642. * You may obtain a copy of the License at
  14643. *
  14644. * http://www.apache.org/licenses/LICENSE-2.0
  14645. *
  14646. * Unless required by applicable law or agreed to in writing, software
  14647. * distributed under the License is distributed on an "AS IS" BASIS,
  14648. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14649. * See the License for the specific language governing permissions and
  14650. * limitations under the License.
  14651. */
  14652. /**
  14653. * A complete element in the bundle stream, together with the byte length it
  14654. * occupies in the stream.
  14655. */ class kc {
  14656. constructor(t,
  14657. // How many bytes this element takes to store in the bundle.
  14658. e) {
  14659. this.Gu = t, this.byteLength = e;
  14660. }
  14661. Qu() {
  14662. return "metadata" in this.Gu;
  14663. }
  14664. }
  14665. /**
  14666. * @license
  14667. * Copyright 2020 Google LLC
  14668. *
  14669. * Licensed under the Apache License, Version 2.0 (the "License");
  14670. * you may not use this file except in compliance with the License.
  14671. * You may obtain a copy of the License at
  14672. *
  14673. * http://www.apache.org/licenses/LICENSE-2.0
  14674. *
  14675. * Unless required by applicable law or agreed to in writing, software
  14676. * distributed under the License is distributed on an "AS IS" BASIS,
  14677. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14678. * See the License for the specific language governing permissions and
  14679. * limitations under the License.
  14680. */
  14681. /**
  14682. * Helper to convert objects from bundles to model objects in the SDK.
  14683. */ class Mc {
  14684. constructor(t) {
  14685. this.serializer = t;
  14686. }
  14687. rr(t) {
  14688. return Oi(this.serializer, t);
  14689. }
  14690. /**
  14691. * Converts a BundleDocument to a MutableDocument.
  14692. */ ur(t) {
  14693. return t.metadata.exists ? Ki(this.serializer, t.document, !1) : an.newNoDocument(this.rr(t.metadata.name), this.cr(t.metadata.readTime));
  14694. }
  14695. cr(t) {
  14696. return Ni(t);
  14697. }
  14698. }
  14699. /**
  14700. * A class to process the elements from a bundle, load them into local
  14701. * storage and provide progress update while loading.
  14702. */ class $c {
  14703. constructor(t, e, n) {
  14704. this.ju = t, this.localStore = e, this.serializer = n,
  14705. /** Batched queries to be saved into storage */
  14706. this.queries = [],
  14707. /** Batched documents to be saved into storage */
  14708. this.documents = [],
  14709. /** The collection groups affected by this bundle. */
  14710. this.collectionGroups = new Set, this.progress = Oc(t);
  14711. }
  14712. /**
  14713. * Adds an element from the bundle to the loader.
  14714. *
  14715. * Returns a new progress if adding the element leads to a new progress,
  14716. * otherwise returns null.
  14717. */ zu(t) {
  14718. this.progress.bytesLoaded += t.byteLength;
  14719. let e = this.progress.documentsLoaded;
  14720. if (t.Gu.namedQuery) this.queries.push(t.Gu.namedQuery); else if (t.Gu.documentMetadata) {
  14721. this.documents.push({
  14722. metadata: t.Gu.documentMetadata
  14723. }), t.Gu.documentMetadata.exists || ++e;
  14724. const n = ut.fromString(t.Gu.documentMetadata.name);
  14725. this.collectionGroups.add(n.get(n.length - 2));
  14726. } else t.Gu.document && (this.documents[this.documents.length - 1].document = t.Gu.document,
  14727. ++e);
  14728. return e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e,
  14729. Object.assign({}, this.progress)) : null;
  14730. }
  14731. Wu(t) {
  14732. const e = new Map, n = new Mc(this.serializer);
  14733. for (const s of t) if (s.metadata.queries) {
  14734. const t = n.rr(s.metadata.name);
  14735. for (const n of s.metadata.queries) {
  14736. const s = (e.get(n) || gs()).add(t);
  14737. e.set(n, s);
  14738. }
  14739. }
  14740. return e;
  14741. }
  14742. /**
  14743. * Update the progress to 'Success' and return the updated progress.
  14744. */ async complete() {
  14745. const t = await mu(this.localStore, new Mc(this.serializer), this.documents, this.ju.id), e = this.Wu(this.documents);
  14746. for (const t of this.queries) await gu(this.localStore, t, e.get(t.name));
  14747. return this.progress.taskState = "Success", {
  14748. progress: this.progress,
  14749. Hu: this.collectionGroups,
  14750. Ju: t
  14751. };
  14752. }
  14753. }
  14754. /**
  14755. * Returns a `LoadBundleTaskProgress` representing the initial progress of
  14756. * loading a bundle.
  14757. */ function Oc(t) {
  14758. return {
  14759. taskState: "Running",
  14760. documentsLoaded: 0,
  14761. bytesLoaded: 0,
  14762. totalDocuments: t.totalDocuments,
  14763. totalBytes: t.totalBytes
  14764. };
  14765. }
  14766. /**
  14767. * Returns a `LoadBundleTaskProgress` representing the progress that the loading
  14768. * has succeeded.
  14769. */
  14770. /**
  14771. * @license
  14772. * Copyright 2017 Google LLC
  14773. *
  14774. * Licensed under the Apache License, Version 2.0 (the "License");
  14775. * you may not use this file except in compliance with the License.
  14776. * You may obtain a copy of the License at
  14777. *
  14778. * http://www.apache.org/licenses/LICENSE-2.0
  14779. *
  14780. * Unless required by applicable law or agreed to in writing, software
  14781. * distributed under the License is distributed on an "AS IS" BASIS,
  14782. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14783. * See the License for the specific language governing permissions and
  14784. * limitations under the License.
  14785. */
  14786. class Fc {
  14787. constructor(t) {
  14788. this.key = t;
  14789. }
  14790. }
  14791. class Bc {
  14792. constructor(t) {
  14793. this.key = t;
  14794. }
  14795. }
  14796. /**
  14797. * View is responsible for computing the final merged truth of what docs are in
  14798. * a query. It gets notified of local and remote changes to docs, and applies
  14799. * the query filters and limits to determine the most correct possible results.
  14800. */ class Lc {
  14801. constructor(t,
  14802. /** Documents included in the remote target */
  14803. e) {
  14804. this.query = t, this.Yu = e, this.Xu = null, this.hasCachedResults = !1,
  14805. /**
  14806. * A flag whether the view is current with the backend. A view is considered
  14807. * current after it has seen the current flag from the backend and did not
  14808. * lose consistency within the watch stream (e.g. because of an existence
  14809. * filter mismatch).
  14810. */
  14811. this.current = !1,
  14812. /** Documents in the view but not in the remote target */
  14813. this.Zu = gs(),
  14814. /** Document Keys that have local changes */
  14815. this.mutatedKeys = gs(), this.tc = is(t), this.ec = new Ac(this.tc);
  14816. }
  14817. /**
  14818. * The set of remote documents that the server has told us belongs to the target associated with
  14819. * this view.
  14820. */ get nc() {
  14821. return this.Yu;
  14822. }
  14823. /**
  14824. * Iterates over a set of doc changes, applies the query limit, and computes
  14825. * what the new results should be, what the changes were, and whether we may
  14826. * need to go back to the local cache for more results. Does not make any
  14827. * changes to the view.
  14828. * @param docChanges - The doc changes to apply to this view.
  14829. * @param previousChanges - If this is being called with a refill, then start
  14830. * with this set of docs and changes instead of the current view.
  14831. * @returns a new set of docs, changes, and refill flag.
  14832. */ sc(t, e) {
  14833. const n = e ? e.ic : new vc, s = e ? e.ec : this.ec;
  14834. let i = e ? e.mutatedKeys : this.mutatedKeys, r = s, o = !1;
  14835. // Track the last doc in a (full) limit. This is necessary, because some
  14836. // update (a delete, or an update moving a doc past the old limit) might
  14837. // mean there is some other document in the local cache that either should
  14838. // come (1) between the old last limit doc and the new last document, in the
  14839. // case of updates, or (2) after the new last document, in the case of
  14840. // deletes. So we keep this doc at the old limit to compare the updates to.
  14841. // Note that this should never get used in a refill (when previousChanges is
  14842. // set), because there will only be adds -- no deletes or updates.
  14843. const u = "F" /* LimitType.First */ === this.query.limitType && s.size === this.query.limit ? s.last() : null, c = "L" /* LimitType.Last */ === this.query.limitType && s.size === this.query.limit ? s.first() : null;
  14844. // Drop documents out to meet limit/limitToLast requirement.
  14845. if (t.inorderTraversal(((t, e) => {
  14846. const a = s.get(t), h = ns(this.query, e) ? e : null, l = !!a && this.mutatedKeys.has(a.key), f = !!h && (h.hasLocalMutations ||
  14847. // We only consider committed mutations for documents that were
  14848. // mutated during the lifetime of the view.
  14849. this.mutatedKeys.has(h.key) && h.hasCommittedMutations);
  14850. let d = !1;
  14851. // Calculate change
  14852. if (a && h) {
  14853. a.data.isEqual(h.data) ? l !== f && (n.track({
  14854. type: 3 /* ChangeType.Metadata */ ,
  14855. doc: h
  14856. }), d = !0) : this.rc(a, h) || (n.track({
  14857. type: 2 /* ChangeType.Modified */ ,
  14858. doc: h
  14859. }), d = !0, (u && this.tc(h, u) > 0 || c && this.tc(h, c) < 0) && (
  14860. // This doc moved from inside the limit to outside the limit.
  14861. // That means there may be some other doc in the local cache
  14862. // that should be included instead.
  14863. o = !0));
  14864. } else !a && h ? (n.track({
  14865. type: 0 /* ChangeType.Added */ ,
  14866. doc: h
  14867. }), d = !0) : a && !h && (n.track({
  14868. type: 1 /* ChangeType.Removed */ ,
  14869. doc: a
  14870. }), d = !0, (u || c) && (
  14871. // A doc was removed from a full limit query. We'll need to
  14872. // requery from the local cache to see if we know about some other
  14873. // doc that should be in the results.
  14874. o = !0));
  14875. d && (h ? (r = r.add(h), i = f ? i.add(t) : i.delete(t)) : (r = r.delete(t), i = i.delete(t)));
  14876. })), null !== this.query.limit) for (;r.size > this.query.limit; ) {
  14877. const t = "F" /* LimitType.First */ === this.query.limitType ? r.last() : r.first();
  14878. r = r.delete(t.key), i = i.delete(t.key), n.track({
  14879. type: 1 /* ChangeType.Removed */ ,
  14880. doc: t
  14881. });
  14882. }
  14883. return {
  14884. ec: r,
  14885. ic: n,
  14886. zi: o,
  14887. mutatedKeys: i
  14888. };
  14889. }
  14890. rc(t, e) {
  14891. // We suppress the initial change event for documents that were modified as
  14892. // part of a write acknowledgment (e.g. when the value of a server transform
  14893. // is applied) as Watch will send us the same document again.
  14894. // By suppressing the event, we only raise two user visible events (one with
  14895. // `hasPendingWrites` and the final state of the document) instead of three
  14896. // (one with `hasPendingWrites`, the modified document with
  14897. // `hasPendingWrites` and the final state of the document).
  14898. return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;
  14899. }
  14900. /**
  14901. * Updates the view with the given ViewDocumentChanges and optionally updates
  14902. * limbo docs and sync state from the provided target change.
  14903. * @param docChanges - The set of changes to make to the view's docs.
  14904. * @param updateLimboDocuments - Whether to update limbo documents based on
  14905. * this change.
  14906. * @param targetChange - A target change to apply for computing limbo docs and
  14907. * sync state.
  14908. * @returns A new ViewChange with the given docs, changes, and sync state.
  14909. */
  14910. // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
  14911. applyChanges(t, e, n) {
  14912. const s = this.ec;
  14913. this.ec = t.ec, this.mutatedKeys = t.mutatedKeys;
  14914. // Sort changes based on type and query comparator
  14915. const i = t.ic.xu();
  14916. i.sort(((t, e) => function(t, e) {
  14917. const n = t => {
  14918. switch (t) {
  14919. case 0 /* ChangeType.Added */ :
  14920. return 1;
  14921. case 2 /* ChangeType.Modified */ :
  14922. case 3 /* ChangeType.Metadata */ :
  14923. // A metadata change is converted to a modified change at the public
  14924. // api layer. Since we sort by document key and then change type,
  14925. // metadata and modified changes must be sorted equivalently.
  14926. return 2;
  14927. case 1 /* ChangeType.Removed */ :
  14928. return 0;
  14929. default:
  14930. return O();
  14931. }
  14932. };
  14933. return n(t) - n(e);
  14934. }
  14935. /**
  14936. * @license
  14937. * Copyright 2020 Google LLC
  14938. *
  14939. * Licensed under the Apache License, Version 2.0 (the "License");
  14940. * you may not use this file except in compliance with the License.
  14941. * You may obtain a copy of the License at
  14942. *
  14943. * http://www.apache.org/licenses/LICENSE-2.0
  14944. *
  14945. * Unless required by applicable law or agreed to in writing, software
  14946. * distributed under the License is distributed on an "AS IS" BASIS,
  14947. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14948. * See the License for the specific language governing permissions and
  14949. * limitations under the License.
  14950. */ (t.type, e.type) || this.tc(t.doc, e.doc))), this.oc(n);
  14951. const r = e ? this.uc() : [], o = 0 === this.Zu.size && this.current ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , u = o !== this.Xu;
  14952. if (this.Xu = o, 0 !== i.length || u) {
  14953. return {
  14954. snapshot: new Rc(this.query, t.ec, s, i, t.mutatedKeys, 0 /* SyncState.Local */ === o, u,
  14955. /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),
  14956. cc: r
  14957. };
  14958. }
  14959. // no changes
  14960. return {
  14961. cc: r
  14962. };
  14963. }
  14964. /**
  14965. * Applies an OnlineState change to the view, potentially generating a
  14966. * ViewChange if the view's syncState changes as a result.
  14967. */ Mu(t) {
  14968. return this.current && "Offline" /* OnlineState.Offline */ === t ? (
  14969. // If we're offline, set `current` to false and then call applyChanges()
  14970. // to refresh our syncState and generate a ViewChange as appropriate. We
  14971. // are guaranteed to get a new TargetChange that sets `current` back to
  14972. // true once the client is back online.
  14973. this.current = !1, this.applyChanges({
  14974. ec: this.ec,
  14975. ic: new vc,
  14976. mutatedKeys: this.mutatedKeys,
  14977. zi: !1
  14978. },
  14979. /* updateLimboDocuments= */ !1)) : {
  14980. cc: []
  14981. };
  14982. }
  14983. /**
  14984. * Returns whether the doc for the given key should be in limbo.
  14985. */ ac(t) {
  14986. // If the remote end says it's part of this query, it's not in limbo.
  14987. return !this.Yu.has(t) && (
  14988. // The local store doesn't think it's a result, so it shouldn't be in limbo.
  14989. !!this.ec.has(t) && !this.ec.get(t).hasLocalMutations);
  14990. }
  14991. /**
  14992. * Updates syncedDocuments, current, and limbo docs based on the given change.
  14993. * Returns the list of changes to which docs are in limbo.
  14994. */ oc(t) {
  14995. t && (t.addedDocuments.forEach((t => this.Yu = this.Yu.add(t))), t.modifiedDocuments.forEach((t => {})),
  14996. t.removedDocuments.forEach((t => this.Yu = this.Yu.delete(t))), this.current = t.current);
  14997. }
  14998. uc() {
  14999. // We can only determine limbo documents when we're in-sync with the server.
  15000. if (!this.current) return [];
  15001. // TODO(klimt): Do this incrementally so that it's not quadratic when
  15002. // updating many documents.
  15003. const t = this.Zu;
  15004. this.Zu = gs(), this.ec.forEach((t => {
  15005. this.ac(t.key) && (this.Zu = this.Zu.add(t.key));
  15006. }));
  15007. // Diff the new limbo docs with the old limbo docs.
  15008. const e = [];
  15009. return t.forEach((t => {
  15010. this.Zu.has(t) || e.push(new Bc(t));
  15011. })), this.Zu.forEach((n => {
  15012. t.has(n) || e.push(new Fc(n));
  15013. })), e;
  15014. }
  15015. /**
  15016. * Update the in-memory state of the current view with the state read from
  15017. * persistence.
  15018. *
  15019. * We update the query view whenever a client's primary status changes:
  15020. * - When a client transitions from primary to secondary, it can miss
  15021. * LocalStorage updates and its query views may temporarily not be
  15022. * synchronized with the state on disk.
  15023. * - For secondary to primary transitions, the client needs to update the list
  15024. * of `syncedDocuments` since secondary clients update their query views
  15025. * based purely on synthesized RemoteEvents.
  15026. *
  15027. * @param queryResult.documents - The documents that match the query according
  15028. * to the LocalStore.
  15029. * @param queryResult.remoteKeys - The keys of the documents that match the
  15030. * query according to the backend.
  15031. *
  15032. * @returns The ViewChange that resulted from this synchronization.
  15033. */
  15034. // PORTING NOTE: Multi-tab only.
  15035. hc(t) {
  15036. this.Yu = t.ir, this.Zu = gs();
  15037. const e = this.sc(t.documents);
  15038. return this.applyChanges(e, /*updateLimboDocuments=*/ !0);
  15039. }
  15040. /**
  15041. * Returns a view snapshot as if this query was just listened to. Contains
  15042. * a document add for every existing document and the `fromCache` and
  15043. * `hasPendingWrites` status of the already established view.
  15044. */
  15045. // PORTING NOTE: Multi-tab only.
  15046. lc() {
  15047. return Rc.fromInitialDocuments(this.query, this.ec, this.mutatedKeys, 0 /* SyncState.Local */ === this.Xu, this.hasCachedResults);
  15048. }
  15049. }
  15050. /**
  15051. * QueryView contains all of the data that SyncEngine needs to keep track of for
  15052. * a particular query.
  15053. */
  15054. class qc {
  15055. constructor(
  15056. /**
  15057. * The query itself.
  15058. */
  15059. t,
  15060. /**
  15061. * The target number created by the client that is used in the watch
  15062. * stream to identify this query.
  15063. */
  15064. e,
  15065. /**
  15066. * The view is responsible for computing the final merged truth of what
  15067. * docs are in the query. It gets notified of local and remote changes,
  15068. * and applies the query filters and limits to determine the most correct
  15069. * possible results.
  15070. */
  15071. n) {
  15072. this.query = t, this.targetId = e, this.view = n;
  15073. }
  15074. }
  15075. /** Tracks a limbo resolution. */ class Uc {
  15076. constructor(t) {
  15077. this.key = t,
  15078. /**
  15079. * Set to true once we've received a document. This is used in
  15080. * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
  15081. * decide whether it needs to manufacture a delete event for the target once
  15082. * the target is CURRENT.
  15083. */
  15084. this.fc = !1;
  15085. }
  15086. }
  15087. /**
  15088. * An implementation of `SyncEngine` coordinating with other parts of SDK.
  15089. *
  15090. * The parts of SyncEngine that act as a callback to RemoteStore need to be
  15091. * registered individually. This is done in `syncEngineWrite()` and
  15092. * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods
  15093. * serve as entry points to RemoteStore's functionality.
  15094. *
  15095. * Note: some field defined in this class might have public access level, but
  15096. * the class is not exported so they are only accessible from this module.
  15097. * This is useful to implement optional features (like bundles) in free
  15098. * functions, such that they are tree-shakeable.
  15099. */ class Kc {
  15100. constructor(t, e, n,
  15101. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  15102. s, i, r) {
  15103. this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = s,
  15104. this.currentUser = i, this.maxConcurrentLimboResolutions = r, this.dc = {}, this.wc = new os((t => ts(t)), Zn),
  15105. this._c = new Map,
  15106. /**
  15107. * The keys of documents that are in limbo for which we haven't yet started a
  15108. * limbo resolution query. The strings in this set are the result of calling
  15109. * `key.path.canonicalString()` where `key` is a `DocumentKey` object.
  15110. *
  15111. * The `Set` type was chosen because it provides efficient lookup and removal
  15112. * of arbitrary elements and it also maintains insertion order, providing the
  15113. * desired queue-like FIFO semantics.
  15114. */
  15115. this.mc = new Set,
  15116. /**
  15117. * Keeps track of the target ID for each document that is in limbo with an
  15118. * active target.
  15119. */
  15120. this.gc = new pe(ht.comparator),
  15121. /**
  15122. * Keeps track of the information about an active limbo resolution for each
  15123. * active target ID that was started for the purpose of limbo resolution.
  15124. */
  15125. this.yc = new Map, this.Ic = new Oo,
  15126. /** Stores user completion handlers, indexed by User and BatchId. */
  15127. this.Tc = {},
  15128. /** Stores user callbacks waiting for all pending writes to be acknowledged. */
  15129. this.Ec = new Map, this.Ac = lo.Mn(), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  15130. // The primary state is set to `true` or `false` immediately after Firestore
  15131. // startup. In the interim, a client should only be considered primary if
  15132. // `isPrimary` is true.
  15133. this.vc = void 0;
  15134. }
  15135. get isPrimaryClient() {
  15136. return !0 === this.vc;
  15137. }
  15138. }
  15139. /**
  15140. * Initiates the new listen, resolves promise when listen enqueued to the
  15141. * server. All the subsequent view snapshots or errors are sent to the
  15142. * subscribed handlers. Returns the initial snapshot.
  15143. */
  15144. async function Gc(t, e) {
  15145. const n = pa(t);
  15146. let s, i;
  15147. const r = n.wc.get(e);
  15148. if (r)
  15149. // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
  15150. // already exists when EventManager calls us for the first time. This
  15151. // happens when the primary tab is already listening to this query on
  15152. // behalf of another tab and the user of the primary also starts listening
  15153. // to the query. EventManager will not have an assigned target ID in this
  15154. // case and calls `listen` to obtain this ID.
  15155. s = r.targetId, n.sharedClientState.addLocalQueryTarget(s), i = r.view.lc(); else {
  15156. const t = await hu(n.localStore, Jn(e)), r = n.sharedClientState.addLocalQueryTarget(t.targetId);
  15157. s = t.targetId, i = await Qc(n, e, s, "current" === r, t.resumeToken), n.isPrimaryClient && Hu(n.remoteStore, t);
  15158. }
  15159. return i;
  15160. }
  15161. /**
  15162. * Registers a view for a previously unknown query and computes its initial
  15163. * snapshot.
  15164. */ async function Qc(t, e, n, s, i) {
  15165. // PORTING NOTE: On Web only, we inject the code that registers new Limbo
  15166. // targets based on view changes. This allows us to only depend on Limbo
  15167. // changes when user code includes queries.
  15168. t.Rc = (e, n, s) => async function(t, e, n, s) {
  15169. let i = e.view.sc(n);
  15170. i.zi && (
  15171. // The query has a limit and some docs were removed, so we need
  15172. // to re-run the query against the local store to make sure we
  15173. // didn't lose any good docs that had been past the limit.
  15174. i = await fu(t.localStore, e.query,
  15175. /* usePreviousResults= */ !1).then((({documents: t}) => e.view.sc(t, i))));
  15176. const r = s && s.targetChanges.get(e.targetId), o = e.view.applyChanges(i,
  15177. /* updateLimboDocuments= */ t.isPrimaryClient, r);
  15178. return ia(t, e.targetId, o.cc), o.snapshot;
  15179. }(t, e, n, s);
  15180. const r = await fu(t.localStore, e,
  15181. /* usePreviousResults= */ !0), o = new Lc(e, r.ir), u = o.sc(r.documents), c = gi.createSynthesizedTargetChangeForCurrentChange(n, s && "Offline" /* OnlineState.Offline */ !== t.onlineState, i), a = o.applyChanges(u,
  15182. /* updateLimboDocuments= */ t.isPrimaryClient, c);
  15183. ia(t, n, a.cc);
  15184. const h = new qc(e, n, o);
  15185. return t.wc.set(e, h), t._c.has(n) ? t._c.get(n).push(e) : t._c.set(n, [ e ]), a.snapshot;
  15186. }
  15187. /** Stops listening to the query. */ async function jc(t, e) {
  15188. const n = L(t), s = n.wc.get(e), i = n._c.get(s.targetId);
  15189. if (i.length > 1) return n._c.set(s.targetId, i.filter((t => !Zn(t, e)))), void n.wc.delete(e);
  15190. // No other queries are mapped to the target, clean up the query and the target.
  15191. if (n.isPrimaryClient) {
  15192. // We need to remove the local query target first to allow us to verify
  15193. // whether any other client is still interested in this target.
  15194. n.sharedClientState.removeLocalQueryTarget(s.targetId);
  15195. n.sharedClientState.isActiveQueryTarget(s.targetId) || await lu(n.localStore, s.targetId,
  15196. /*keepPersistedTargetData=*/ !1).then((() => {
  15197. n.sharedClientState.clearQueryState(s.targetId), Ju(n.remoteStore, s.targetId),
  15198. na(n, s.targetId);
  15199. })).catch(vt);
  15200. } else na(n, s.targetId), await lu(n.localStore, s.targetId,
  15201. /*keepPersistedTargetData=*/ !0);
  15202. }
  15203. /**
  15204. * Initiates the write of local mutation batch which involves adding the
  15205. * writes to the mutation queue, notifying the remote store about new
  15206. * mutations and raising events for any changes this write caused.
  15207. *
  15208. * The promise returned by this call is resolved when the above steps
  15209. * have completed, *not* when the write was acked by the backend. The
  15210. * userCallback is resolved once the write was acked/rejected by the
  15211. * backend (or failed locally for any other reason).
  15212. */ async function zc(t, e, n) {
  15213. const s = Ia(t);
  15214. try {
  15215. const t = await function(t, e) {
  15216. const n = L(t), s = it.now(), i = e.reduce(((t, e) => t.add(e.key)), gs());
  15217. let r, o;
  15218. return n.persistence.runTransaction("Locally write mutations", "readwrite", (t => {
  15219. // Figure out which keys do not have a remote version in the cache, this
  15220. // is needed to create the right overlay mutation: if no remote version
  15221. // presents, we do not need to create overlays as patch mutations.
  15222. // TODO(Overlay): Is there a better way to determine this? Using the
  15223. // document version does not work because local mutations set them back
  15224. // to 0.
  15225. let u = cs(), c = gs();
  15226. return n.Zi.getEntries(t, i).next((t => {
  15227. u = t, u.forEach(((t, e) => {
  15228. e.isValidDocument() || (c = c.add(t));
  15229. }));
  15230. })).next((() => n.localDocuments.getOverlayedDocuments(t, u))).next((i => {
  15231. r = i;
  15232. // For non-idempotent mutations (such as `FieldValue.increment()`),
  15233. // we record the base state in a separate patch mutation. This is
  15234. // later used to guarantee consistent values and prevents flicker
  15235. // even if the backend sends us an update that already includes our
  15236. // transform.
  15237. const o = [];
  15238. for (const t of e) {
  15239. const e = Gs(t, r.get(t.key).overlayedDocument);
  15240. null != e &&
  15241. // NOTE: The base state should only be applied if there's some
  15242. // existing document to override, so use a Precondition of
  15243. // exists=true
  15244. o.push(new zs(t.key, e, cn(e.value.mapValue), Fs.exists(!0)));
  15245. }
  15246. return n.mutationQueue.addMutationBatch(t, s, o, e);
  15247. })).next((e => {
  15248. o = e;
  15249. const s = e.applyToLocalDocumentSet(r, c);
  15250. return n.documentOverlayCache.saveOverlays(t, e.batchId, s);
  15251. }));
  15252. })).then((() => ({
  15253. batchId: o.batchId,
  15254. changes: ls(r)
  15255. })));
  15256. }(s.localStore, e);
  15257. s.sharedClientState.addPendingMutation(t.batchId), function(t, e, n) {
  15258. let s = t.Tc[t.currentUser.toKey()];
  15259. s || (s = new pe(et));
  15260. s = s.insert(e, n), t.Tc[t.currentUser.toKey()] = s;
  15261. }
  15262. /**
  15263. * Resolves or rejects the user callback for the given batch and then discards
  15264. * it.
  15265. */ (s, t.batchId, n), await ua(s, t.changes), await cc(s.remoteStore);
  15266. } catch (t) {
  15267. // If we can't persist the mutation, we reject the user callback and
  15268. // don't send the mutation. The user can then retry the write.
  15269. const e = Ec(t, "Failed to persist write");
  15270. n.reject(e);
  15271. }
  15272. }
  15273. /**
  15274. * Applies one remote event to the sync engine, notifying any views of the
  15275. * changes, and releasing any pending mutation batches that would become
  15276. * visible because of the snapshot version the remote event contains.
  15277. */ async function Wc(t, e) {
  15278. const n = L(t);
  15279. try {
  15280. const t = await uu(n.localStore, e);
  15281. // Update `receivedDocument` as appropriate for any limbo targets.
  15282. e.targetChanges.forEach(((t, e) => {
  15283. const s = n.yc.get(e);
  15284. s && (
  15285. // Since this is a limbo resolution lookup, it's for a single document
  15286. // and it could be added, modified, or removed, but not a combination.
  15287. F(t.addedDocuments.size + t.modifiedDocuments.size + t.removedDocuments.size <= 1),
  15288. t.addedDocuments.size > 0 ? s.fc = !0 : t.modifiedDocuments.size > 0 ? F(s.fc) : t.removedDocuments.size > 0 && (F(s.fc),
  15289. s.fc = !1));
  15290. })), await ua(n, t, e);
  15291. } catch (t) {
  15292. await vt(t);
  15293. }
  15294. }
  15295. /**
  15296. * Applies an OnlineState change to the sync engine and notifies any views of
  15297. * the change.
  15298. */ function Hc(t, e, n) {
  15299. const s = L(t);
  15300. // If we are the secondary client, we explicitly ignore the remote store's
  15301. // online state (the local client may go offline, even though the primary
  15302. // tab remains online) and only apply the primary tab's online state from
  15303. // SharedClientState.
  15304. if (s.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !s.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {
  15305. const t = [];
  15306. s.wc.forEach(((n, s) => {
  15307. const i = s.view.Mu(e);
  15308. i.snapshot && t.push(i.snapshot);
  15309. })), function(t, e) {
  15310. const n = L(t);
  15311. n.onlineState = e;
  15312. let s = !1;
  15313. n.queries.forEach(((t, n) => {
  15314. for (const t of n.listeners)
  15315. // Run global snapshot listeners if a consistent snapshot has been emitted.
  15316. t.Mu(e) && (s = !0);
  15317. })), s && xc(n);
  15318. }(s.eventManager, e), t.length && s.dc.nu(t), s.onlineState = e, s.isPrimaryClient && s.sharedClientState.setOnlineState(e);
  15319. }
  15320. }
  15321. /**
  15322. * Rejects the listen for the given targetID. This can be triggered by the
  15323. * backend for any active target.
  15324. *
  15325. * @param syncEngine - The sync engine implementation.
  15326. * @param targetId - The targetID corresponds to one previously initiated by the
  15327. * user as part of TargetData passed to listen() on RemoteStore.
  15328. * @param err - A description of the condition that has forced the rejection.
  15329. * Nearly always this will be an indication that the user is no longer
  15330. * authorized to see the data matching the target.
  15331. */ async function Jc(t, e, n) {
  15332. const s = L(t);
  15333. // PORTING NOTE: Multi-tab only.
  15334. s.sharedClientState.updateQueryState(e, "rejected", n);
  15335. const i = s.yc.get(e), r = i && i.key;
  15336. if (r) {
  15337. // TODO(klimt): We really only should do the following on permission
  15338. // denied errors, but we don't have the cause code here.
  15339. // It's a limbo doc. Create a synthetic event saying it was deleted.
  15340. // This is kind of a hack. Ideally, we would have a method in the local
  15341. // store to purge a document. However, it would be tricky to keep all of
  15342. // the local store's invariants with another method.
  15343. let t = new pe(ht.comparator);
  15344. // TODO(b/217189216): This limbo document should ideally have a read time,
  15345. // so that it is picked up by any read-time based scans. The backend,
  15346. // however, does not send a read time for target removals.
  15347. t = t.insert(r, an.newNoDocument(r, rt.min()));
  15348. const n = gs().add(r), i = new mi(rt.min(),
  15349. /* targetChanges= */ new Map,
  15350. /* targetMismatches= */ new pe(et), t, n);
  15351. await Wc(s, i),
  15352. // Since this query failed, we won't want to manually unlisten to it.
  15353. // We only remove it from bookkeeping after we successfully applied the
  15354. // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
  15355. // this query when the RemoteStore restarts the Watch stream, which should
  15356. // re-trigger the target failure.
  15357. s.gc = s.gc.remove(r), s.yc.delete(e), oa(s);
  15358. } else await lu(s.localStore, e,
  15359. /* keepPersistedTargetData */ !1).then((() => na(s, e, n))).catch(vt);
  15360. }
  15361. async function Yc(t, e) {
  15362. const n = L(t), s = e.batch.batchId;
  15363. try {
  15364. const t = await ru(n.localStore, e);
  15365. // The local store may or may not be able to apply the write result and
  15366. // raise events immediately (depending on whether the watcher is caught
  15367. // up), so we raise user callbacks first so that they consistently happen
  15368. // before listen events.
  15369. ea(n, s, /*error=*/ null), ta(n, s), n.sharedClientState.updateMutationState(s, "acknowledged"),
  15370. await ua(n, t);
  15371. } catch (t) {
  15372. await vt(t);
  15373. }
  15374. }
  15375. async function Xc(t, e, n) {
  15376. const s = L(t);
  15377. try {
  15378. const t = await function(t, e) {
  15379. const n = L(t);
  15380. return n.persistence.runTransaction("Reject batch", "readwrite-primary", (t => {
  15381. let s;
  15382. return n.mutationQueue.lookupMutationBatch(t, e).next((e => (F(null !== e), s = e.keys(),
  15383. n.mutationQueue.removeMutationBatch(t, e)))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, s))).next((() => n.localDocuments.getDocuments(t, s)));
  15384. }));
  15385. }
  15386. /**
  15387. * Returns the largest (latest) batch id in mutation queue that is pending
  15388. * server response.
  15389. *
  15390. * Returns `BATCHID_UNKNOWN` if the queue is empty.
  15391. */ (s.localStore, e);
  15392. // The local store may or may not be able to apply the write result and
  15393. // raise events immediately (depending on whether the watcher is caught up),
  15394. // so we raise user callbacks first so that they consistently happen before
  15395. // listen events.
  15396. ea(s, e, n), ta(s, e), s.sharedClientState.updateMutationState(e, "rejected", n),
  15397. await ua(s, t);
  15398. } catch (n) {
  15399. await vt(n);
  15400. }
  15401. }
  15402. /**
  15403. * Registers a user callback that resolves when all pending mutations at the moment of calling
  15404. * are acknowledged .
  15405. */ async function Zc(t, e) {
  15406. const n = L(t);
  15407. ec(n.remoteStore) || N("SyncEngine", "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");
  15408. try {
  15409. const t = await function(t) {
  15410. const e = L(t);
  15411. return e.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (t => e.mutationQueue.getHighestUnacknowledgedBatchId(t)));
  15412. }(n.localStore);
  15413. if (-1 === t)
  15414. // Trigger the callback right away if there is no pending writes at the moment.
  15415. return void e.resolve();
  15416. const s = n.Ec.get(t) || [];
  15417. s.push(e), n.Ec.set(t, s);
  15418. } catch (t) {
  15419. const n = Ec(t, "Initialization of waitForPendingWrites() operation failed");
  15420. e.reject(n);
  15421. }
  15422. }
  15423. /**
  15424. * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,
  15425. * if there are any.
  15426. */ function ta(t, e) {
  15427. (t.Ec.get(e) || []).forEach((t => {
  15428. t.resolve();
  15429. })), t.Ec.delete(e);
  15430. }
  15431. /** Reject all outstanding callbacks waiting for pending writes to complete. */ function ea(t, e, n) {
  15432. const s = L(t);
  15433. let i = s.Tc[s.currentUser.toKey()];
  15434. // NOTE: Mutations restored from persistence won't have callbacks, so it's
  15435. // okay for there to be no callback for this ID.
  15436. if (i) {
  15437. const t = i.get(e);
  15438. t && (n ? t.reject(n) : t.resolve(), i = i.remove(e)), s.Tc[s.currentUser.toKey()] = i;
  15439. }
  15440. }
  15441. function na(t, e, n = null) {
  15442. t.sharedClientState.removeLocalQueryTarget(e);
  15443. for (const s of t._c.get(e)) t.wc.delete(s), n && t.dc.Pc(s, n);
  15444. if (t._c.delete(e), t.isPrimaryClient) {
  15445. t.Ic.Is(e).forEach((e => {
  15446. t.Ic.containsKey(e) ||
  15447. // We removed the last reference for this key
  15448. sa(t, e);
  15449. }));
  15450. }
  15451. }
  15452. function sa(t, e) {
  15453. t.mc.delete(e.path.canonicalString());
  15454. // It's possible that the target already got removed because the query failed. In that case,
  15455. // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.
  15456. const n = t.gc.get(e);
  15457. null !== n && (Ju(t.remoteStore, n), t.gc = t.gc.remove(e), t.yc.delete(n), oa(t));
  15458. }
  15459. function ia(t, e, n) {
  15460. for (const s of n) if (s instanceof Fc) t.Ic.addReference(s.key, e), ra(t, s); else if (s instanceof Bc) {
  15461. N("SyncEngine", "Document no longer in limbo: " + s.key), t.Ic.removeReference(s.key, e);
  15462. t.Ic.containsKey(s.key) ||
  15463. // We removed the last reference for this key
  15464. sa(t, s.key);
  15465. } else O();
  15466. }
  15467. function ra(t, e) {
  15468. const n = e.key, s = n.path.canonicalString();
  15469. t.gc.get(n) || t.mc.has(s) || (N("SyncEngine", "New document in limbo: " + n), t.mc.add(s),
  15470. oa(t));
  15471. }
  15472. /**
  15473. * Starts listens for documents in limbo that are enqueued for resolution,
  15474. * subject to a maximum number of concurrent resolutions.
  15475. *
  15476. * Without bounding the number of concurrent resolutions, the server can fail
  15477. * with "resource exhausted" errors which can lead to pathological client
  15478. * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.
  15479. */ function oa(t) {
  15480. for (;t.mc.size > 0 && t.gc.size < t.maxConcurrentLimboResolutions; ) {
  15481. const e = t.mc.values().next().value;
  15482. t.mc.delete(e);
  15483. const n = new ht(ut.fromString(e)), s = t.Ac.next();
  15484. t.yc.set(s, new Uc(n)), t.gc = t.gc.insert(n, s), Hu(t.remoteStore, new cr(Jn(Gn(n.path)), s, "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ , Ot.ct));
  15485. }
  15486. }
  15487. async function ua(t, e, n) {
  15488. const s = L(t), i = [], r = [], o = [];
  15489. s.wc.isEmpty() || (s.wc.forEach(((t, u) => {
  15490. o.push(s.Rc(u, e, n).then((t => {
  15491. // Update views if there are actual changes.
  15492. if (
  15493. // If there are changes, or we are handling a global snapshot, notify
  15494. // secondary clients to update query state.
  15495. (t || n) && s.isPrimaryClient && s.sharedClientState.updateQueryState(u.targetId, (null == t ? void 0 : t.fromCache) ? "not-current" : "current"),
  15496. t) {
  15497. i.push(t);
  15498. const e = tu.Li(u.targetId, t);
  15499. r.push(e);
  15500. }
  15501. })));
  15502. })), await Promise.all(o), s.dc.nu(i), await async function(t, e) {
  15503. const n = L(t);
  15504. try {
  15505. await n.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (t => Rt.forEach(e, (e => Rt.forEach(e.Fi, (s => n.persistence.referenceDelegate.addReference(t, e.targetId, s))).next((() => Rt.forEach(e.Bi, (s => n.persistence.referenceDelegate.removeReference(t, e.targetId, s)))))))));
  15506. } catch (t) {
  15507. if (!Dt(t)) throw t;
  15508. // If `notifyLocalViewChanges` fails, we did not advance the sequence
  15509. // number for the documents that were included in this transaction.
  15510. // This might trigger them to be deleted earlier than they otherwise
  15511. // would have, but it should not invalidate the integrity of the data.
  15512. N("LocalStore", "Failed to update sequence numbers: " + t);
  15513. }
  15514. for (const t of e) {
  15515. const e = t.targetId;
  15516. if (!t.fromCache) {
  15517. const t = n.Ji.get(e), s = t.snapshotVersion, i = t.withLastLimboFreeSnapshotVersion(s);
  15518. // Advance the last limbo free snapshot version
  15519. n.Ji = n.Ji.insert(e, i);
  15520. }
  15521. }
  15522. }(s.localStore, r));
  15523. }
  15524. async function ca(t, e) {
  15525. const n = L(t);
  15526. if (!n.currentUser.isEqual(e)) {
  15527. N("SyncEngine", "User change. New user:", e.toKey());
  15528. const t = await iu(n.localStore, e);
  15529. n.currentUser = e,
  15530. // Fails tasks waiting for pending writes requested by previous user.
  15531. function(t, e) {
  15532. t.Ec.forEach((t => {
  15533. t.forEach((t => {
  15534. t.reject(new U(q.CANCELLED, e));
  15535. }));
  15536. })), t.Ec.clear();
  15537. }(n, "'waitForPendingWrites' promise is rejected due to a user change."),
  15538. // TODO(b/114226417): Consider calling this only in the primary tab.
  15539. n.sharedClientState.handleUserChange(e, t.removedBatchIds, t.addedBatchIds), await ua(n, t.er);
  15540. }
  15541. }
  15542. function aa(t, e) {
  15543. const n = L(t), s = n.yc.get(e);
  15544. if (s && s.fc) return gs().add(s.key);
  15545. {
  15546. let t = gs();
  15547. const s = n._c.get(e);
  15548. if (!s) return t;
  15549. for (const e of s) {
  15550. const s = n.wc.get(e);
  15551. t = t.unionWith(s.view.nc);
  15552. }
  15553. return t;
  15554. }
  15555. }
  15556. /**
  15557. * Reconcile the list of synced documents in an existing view with those
  15558. * from persistence.
  15559. */ async function ha(t, e) {
  15560. const n = L(t), s = await fu(n.localStore, e.query,
  15561. /* usePreviousResults= */ !0), i = e.view.hc(s);
  15562. return n.isPrimaryClient && ia(n, e.targetId, i.cc), i;
  15563. }
  15564. /**
  15565. * Retrieves newly changed documents from remote document cache and raises
  15566. * snapshots if needed.
  15567. */
  15568. // PORTING NOTE: Multi-Tab only.
  15569. async function la(t, e) {
  15570. const n = L(t);
  15571. return wu(n.localStore, e).then((t => ua(n, t)));
  15572. }
  15573. /** Applies a mutation state to an existing batch. */
  15574. // PORTING NOTE: Multi-Tab only.
  15575. async function fa(t, e, n, s) {
  15576. const i = L(t), r = await function(t, e) {
  15577. const n = L(t), s = L(n.mutationQueue);
  15578. return n.persistence.runTransaction("Lookup mutation documents", "readonly", (t => s.Sn(t, e).next((e => e ? n.localDocuments.getDocuments(t, e) : Rt.resolve(null)))));
  15579. }
  15580. // PORTING NOTE: Multi-Tab only.
  15581. (i.localStore, e);
  15582. null !== r ? ("pending" === n ?
  15583. // If we are the primary client, we need to send this write to the
  15584. // backend. Secondary clients will ignore these writes since their remote
  15585. // connection is disabled.
  15586. await cc(i.remoteStore) : "acknowledged" === n || "rejected" === n ? (
  15587. // NOTE: Both these methods are no-ops for batches that originated from
  15588. // other clients.
  15589. ea(i, e, s || null), ta(i, e), function(t, e) {
  15590. L(L(t).mutationQueue).Cn(e);
  15591. }
  15592. // PORTING NOTE: Multi-Tab only.
  15593. (i.localStore, e)) : O(), await ua(i, r)) :
  15594. // A throttled tab may not have seen the mutation before it was completed
  15595. // and removed from the mutation queue, in which case we won't have cached
  15596. // the affected documents. In this case we can safely ignore the update
  15597. // since that means we didn't apply the mutation locally at all (if we
  15598. // had, we would have cached the affected documents), and so we will just
  15599. // see any resulting document changes via normal remote document updates
  15600. // as applicable.
  15601. N("SyncEngine", "Cannot apply mutation batch with id: " + e);
  15602. }
  15603. /** Applies a query target change from a different tab. */
  15604. // PORTING NOTE: Multi-Tab only.
  15605. async function da(t, e) {
  15606. const n = L(t);
  15607. if (pa(n), Ia(n), !0 === e && !0 !== n.vc) {
  15608. // Secondary tabs only maintain Views for their local listeners and the
  15609. // Views internal state may not be 100% populated (in particular
  15610. // secondary tabs don't track syncedDocuments, the set of documents the
  15611. // server considers to be in the target). So when a secondary becomes
  15612. // primary, we need to need to make sure that all views for all targets
  15613. // match the state on disk.
  15614. const t = n.sharedClientState.getAllActiveQueryTargets(), e = await wa(n, t.toArray());
  15615. n.vc = !0, await yc(n.remoteStore, !0);
  15616. for (const t of e) Hu(n.remoteStore, t);
  15617. } else if (!1 === e && !1 !== n.vc) {
  15618. const t = [];
  15619. let e = Promise.resolve();
  15620. n._c.forEach(((s, i) => {
  15621. n.sharedClientState.isLocalQueryTarget(i) ? t.push(i) : e = e.then((() => (na(n, i),
  15622. lu(n.localStore, i,
  15623. /*keepPersistedTargetData=*/ !0)))), Ju(n.remoteStore, i);
  15624. })), await e, await wa(n, t),
  15625. // PORTING NOTE: Multi-Tab only.
  15626. function(t) {
  15627. const e = L(t);
  15628. e.yc.forEach(((t, n) => {
  15629. Ju(e.remoteStore, n);
  15630. })), e.Ic.Ts(), e.yc = new Map, e.gc = new pe(ht.comparator);
  15631. }
  15632. /**
  15633. * Reconcile the query views of the provided query targets with the state from
  15634. * persistence. Raises snapshots for any changes that affect the local
  15635. * client and returns the updated state of all target's query data.
  15636. *
  15637. * @param syncEngine - The sync engine implementation
  15638. * @param targets - the list of targets with views that need to be recomputed
  15639. * @param transitionToPrimary - `true` iff the tab transitions from a secondary
  15640. * tab to a primary tab
  15641. */
  15642. // PORTING NOTE: Multi-Tab only.
  15643. (n), n.vc = !1, await yc(n.remoteStore, !1);
  15644. }
  15645. }
  15646. async function wa(t, e, n) {
  15647. const s = L(t), i = [], r = [];
  15648. for (const t of e) {
  15649. let e;
  15650. const n = s._c.get(t);
  15651. if (n && 0 !== n.length) {
  15652. // For queries that have a local View, we fetch their current state
  15653. // from LocalStore (as the resume token and the snapshot version
  15654. // might have changed) and reconcile their views with the persisted
  15655. // state (the list of syncedDocuments may have gotten out of sync).
  15656. e = await hu(s.localStore, Jn(n[0]));
  15657. for (const t of n) {
  15658. const e = s.wc.get(t), n = await ha(s, e);
  15659. n.snapshot && r.push(n.snapshot);
  15660. }
  15661. } else {
  15662. // For queries that never executed on this client, we need to
  15663. // allocate the target in LocalStore and initialize a new View.
  15664. const n = await du(s.localStore, t);
  15665. e = await hu(s.localStore, n), await Qc(s, _a(n), t,
  15666. /*current=*/ !1, e.resumeToken);
  15667. }
  15668. i.push(e);
  15669. }
  15670. return s.dc.nu(r), i;
  15671. }
  15672. /**
  15673. * Creates a `Query` object from the specified `Target`. There is no way to
  15674. * obtain the original `Query`, so we synthesize a `Query` from the `Target`
  15675. * object.
  15676. *
  15677. * The synthesized result might be different from the original `Query`, but
  15678. * since the synthesized `Query` should return the same results as the
  15679. * original one (only the presentation of results might differ), the potential
  15680. * difference will not cause issues.
  15681. */
  15682. // PORTING NOTE: Multi-Tab only.
  15683. function _a(t) {
  15684. return Kn(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, "F" /* LimitType.First */ , t.startAt, t.endAt);
  15685. }
  15686. /** Returns the IDs of the clients that are currently active. */
  15687. // PORTING NOTE: Multi-Tab only.
  15688. function ma(t) {
  15689. const e = L(t);
  15690. return L(L(e.localStore).persistence).$i();
  15691. }
  15692. /** Applies a query target change from a different tab. */
  15693. // PORTING NOTE: Multi-Tab only.
  15694. async function ga(t, e, n, s) {
  15695. const i = L(t);
  15696. if (i.vc)
  15697. // If we receive a target state notification via WebStorage, we are
  15698. // either already secondary or another tab has taken the primary lease.
  15699. return void N("SyncEngine", "Ignoring unexpected query state notification.");
  15700. const r = i._c.get(e);
  15701. if (r && r.length > 0) switch (n) {
  15702. case "current":
  15703. case "not-current":
  15704. {
  15705. const t = await wu(i.localStore, ss(r[0])), s = mi.createSynthesizedRemoteEventForCurrentChange(e, "current" === n, Ve.EMPTY_BYTE_STRING);
  15706. await ua(i, t, s);
  15707. break;
  15708. }
  15709. case "rejected":
  15710. await lu(i.localStore, e,
  15711. /* keepPersistedTargetData */ !0), na(i, e, s);
  15712. break;
  15713. default:
  15714. O();
  15715. }
  15716. }
  15717. /** Adds or removes Watch targets for queries from different tabs. */ async function ya(t, e, n) {
  15718. const s = pa(t);
  15719. if (s.vc) {
  15720. for (const t of e) {
  15721. if (s._c.has(t)) {
  15722. // A target might have been added in a previous attempt
  15723. N("SyncEngine", "Adding an already active target " + t);
  15724. continue;
  15725. }
  15726. const e = await du(s.localStore, t), n = await hu(s.localStore, e);
  15727. await Qc(s, _a(e), n.targetId,
  15728. /*current=*/ !1, n.resumeToken), Hu(s.remoteStore, n);
  15729. }
  15730. for (const t of n)
  15731. // Check that the target is still active since the target might have been
  15732. // removed if it has been rejected by the backend.
  15733. s._c.has(t) &&
  15734. // Release queries that are still active.
  15735. await lu(s.localStore, t,
  15736. /* keepPersistedTargetData */ !1).then((() => {
  15737. Ju(s.remoteStore, t), na(s, t);
  15738. })).catch(vt);
  15739. }
  15740. }
  15741. function pa(t) {
  15742. const e = L(t);
  15743. return e.remoteStore.remoteSyncer.applyRemoteEvent = Wc.bind(null, e), e.remoteStore.remoteSyncer.getRemoteKeysForTarget = aa.bind(null, e),
  15744. e.remoteStore.remoteSyncer.rejectListen = Jc.bind(null, e), e.dc.nu = Dc.bind(null, e.eventManager),
  15745. e.dc.Pc = Cc.bind(null, e.eventManager), e;
  15746. }
  15747. function Ia(t) {
  15748. const e = L(t);
  15749. return e.remoteStore.remoteSyncer.applySuccessfulWrite = Yc.bind(null, e), e.remoteStore.remoteSyncer.rejectFailedWrite = Xc.bind(null, e),
  15750. e;
  15751. }
  15752. /**
  15753. * Loads a Firestore bundle into the SDK. The returned promise resolves when
  15754. * the bundle finished loading.
  15755. *
  15756. * @param syncEngine - SyncEngine to use.
  15757. * @param bundleReader - Bundle to load into the SDK.
  15758. * @param task - LoadBundleTask used to update the loading progress to public API.
  15759. */ function Ta(t, e, n) {
  15760. const s = L(t);
  15761. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  15762. (
  15763. /** Loads a bundle and returns the list of affected collection groups. */
  15764. async function(t, e, n) {
  15765. try {
  15766. const s = await e.getMetadata();
  15767. if (await function(t, e) {
  15768. const n = L(t), s = Ni(e.createTime);
  15769. return n.persistence.runTransaction("hasNewerBundle", "readonly", (t => n.qs.getBundleMetadata(t, e.id))).then((t => !!t && t.createTime.compareTo(s) >= 0));
  15770. }
  15771. /**
  15772. * Saves the given `BundleMetadata` to local persistence.
  15773. */ (t.localStore, s)) return await e.close(), n._completeWith(function(t) {
  15774. return {
  15775. taskState: "Success",
  15776. documentsLoaded: t.totalDocuments,
  15777. bytesLoaded: t.totalBytes,
  15778. totalDocuments: t.totalDocuments,
  15779. totalBytes: t.totalBytes
  15780. };
  15781. }(s)), Promise.resolve(new Set);
  15782. n._updateProgress(Oc(s));
  15783. const i = new $c(s, t.localStore, e.serializer);
  15784. let r = await e.bc();
  15785. for (;r; ) {
  15786. const t = await i.zu(r);
  15787. t && n._updateProgress(t), r = await e.bc();
  15788. }
  15789. const o = await i.complete();
  15790. return await ua(t, o.Ju,
  15791. /* remoteEvent */ void 0),
  15792. // Save metadata, so loading the same bundle will skip.
  15793. await function(t, e) {
  15794. const n = L(t);
  15795. return n.persistence.runTransaction("Save bundle", "readwrite", (t => n.qs.saveBundleMetadata(t, e)));
  15796. }
  15797. /**
  15798. * Returns a promise of a `NamedQuery` associated with given query name. Promise
  15799. * resolves to undefined if no persisted data can be found.
  15800. */ (t.localStore, s), n._completeWith(o.progress), Promise.resolve(o.Hu);
  15801. } catch (t) {
  15802. return M("SyncEngine", `Loading bundle failed with ${t}`), n._failWith(t), Promise.resolve(new Set);
  15803. }
  15804. }
  15805. /**
  15806. * @license
  15807. * Copyright 2020 Google LLC
  15808. *
  15809. * Licensed under the Apache License, Version 2.0 (the "License");
  15810. * you may not use this file except in compliance with the License.
  15811. * You may obtain a copy of the License at
  15812. *
  15813. * http://www.apache.org/licenses/LICENSE-2.0
  15814. *
  15815. * Unless required by applicable law or agreed to in writing, software
  15816. * distributed under the License is distributed on an "AS IS" BASIS,
  15817. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15818. * See the License for the specific language governing permissions and
  15819. * limitations under the License.
  15820. */
  15821. /**
  15822. * Provides all components needed for Firestore with in-memory persistence.
  15823. * Uses EagerGC garbage collection.
  15824. */)(s, e, n).then((t => {
  15825. s.sharedClientState.notifyBundleLoaded(t);
  15826. }));
  15827. }
  15828. class Ea {
  15829. constructor() {
  15830. this.synchronizeTabs = !1;
  15831. }
  15832. async initialize(t) {
  15833. this.serializer = Fu(t.databaseInfo.databaseId), this.sharedClientState = this.createSharedClientState(t),
  15834. this.persistence = this.createPersistence(t), await this.persistence.start(), this.localStore = this.createLocalStore(t),
  15835. this.gcScheduler = this.createGarbageCollectionScheduler(t, this.localStore), this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(t, this.localStore);
  15836. }
  15837. createGarbageCollectionScheduler(t, e) {
  15838. return null;
  15839. }
  15840. createIndexBackfillerScheduler(t, e) {
  15841. return null;
  15842. }
  15843. createLocalStore(t) {
  15844. return su(this.persistence, new eu, t.initialUser, this.serializer);
  15845. }
  15846. createPersistence(t) {
  15847. return new Ko(Qo.zs, this.serializer);
  15848. }
  15849. createSharedClientState(t) {
  15850. return new bu;
  15851. }
  15852. async terminate() {
  15853. this.gcScheduler && this.gcScheduler.stop(), await this.sharedClientState.shutdown(),
  15854. await this.persistence.shutdown();
  15855. }
  15856. }
  15857. class Aa extends Ea {
  15858. constructor(t) {
  15859. super(), this.cacheSizeBytes = t;
  15860. }
  15861. createGarbageCollectionScheduler(t, e) {
  15862. F(this.persistence.referenceDelegate instanceof jo);
  15863. const n = this.persistence.referenceDelegate.garbageCollector;
  15864. return new po(n, t.asyncQueue, e);
  15865. }
  15866. createPersistence(t) {
  15867. const e = void 0 !== this.cacheSizeBytes ? so.withCacheSize(this.cacheSizeBytes) : so.DEFAULT;
  15868. return new Ko((t => jo.zs(t, e)), this.serializer);
  15869. }
  15870. }
  15871. /**
  15872. * Provides all components needed for Firestore with IndexedDB persistence.
  15873. */ class va extends Ea {
  15874. constructor(t, e, n) {
  15875. super(), this.Vc = t, this.cacheSizeBytes = e, this.forceOwnership = n, this.synchronizeTabs = !1;
  15876. }
  15877. async initialize(t) {
  15878. await super.initialize(t), await this.Vc.initialize(this, t),
  15879. // Enqueue writes from a previous session
  15880. await Ia(this.Vc.syncEngine), await cc(this.Vc.remoteStore),
  15881. // NOTE: This will immediately call the listener, so we make sure to
  15882. // set it after localStore / remoteStore are started.
  15883. await this.persistence.Ii((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(),
  15884. this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(),
  15885. Promise.resolve())));
  15886. }
  15887. createLocalStore(t) {
  15888. return su(this.persistence, new eu, t.initialUser, this.serializer);
  15889. }
  15890. createGarbageCollectionScheduler(t, e) {
  15891. const n = this.persistence.referenceDelegate.garbageCollector;
  15892. return new po(n, t.asyncQueue, e);
  15893. }
  15894. createIndexBackfillerScheduler(t, e) {
  15895. const n = new $t(e, this.persistence);
  15896. return new Mt(t.asyncQueue, n);
  15897. }
  15898. createPersistence(t) {
  15899. const e = Zo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? so.withCacheSize(this.cacheSizeBytes) : so.DEFAULT;
  15900. return new Jo(this.synchronizeTabs, e, t.clientId, n, t.asyncQueue, $u(), Ou(), this.serializer, this.sharedClientState, !!this.forceOwnership);
  15901. }
  15902. createSharedClientState(t) {
  15903. return new bu;
  15904. }
  15905. }
  15906. /**
  15907. * Provides all components needed for Firestore with multi-tab IndexedDB
  15908. * persistence.
  15909. *
  15910. * In the legacy client, this provider is used to provide both multi-tab and
  15911. * non-multi-tab persistence since we cannot tell at build time whether
  15912. * `synchronizeTabs` will be enabled.
  15913. */ class Ra extends va {
  15914. constructor(t, e) {
  15915. super(t, e, /* forceOwnership= */ !1), this.Vc = t, this.cacheSizeBytes = e, this.synchronizeTabs = !0;
  15916. }
  15917. async initialize(t) {
  15918. await super.initialize(t);
  15919. const e = this.Vc.syncEngine;
  15920. this.sharedClientState instanceof Pu && (this.sharedClientState.syncEngine = {
  15921. jr: fa.bind(null, e),
  15922. zr: ga.bind(null, e),
  15923. Wr: ya.bind(null, e),
  15924. $i: ma.bind(null, e),
  15925. Qr: la.bind(null, e)
  15926. }, await this.sharedClientState.start()),
  15927. // NOTE: This will immediately call the listener, so we make sure to
  15928. // set it after localStore / remoteStore are started.
  15929. await this.persistence.Ii((async t => {
  15930. await da(this.Vc.syncEngine, t), this.gcScheduler && (t && !this.gcScheduler.started ? this.gcScheduler.start() : t || this.gcScheduler.stop()),
  15931. this.indexBackfillerScheduler && (t && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : t || this.indexBackfillerScheduler.stop());
  15932. }));
  15933. }
  15934. createSharedClientState(t) {
  15935. const e = $u();
  15936. if (!Pu.D(e)) throw new U(q.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
  15937. const n = Zo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey);
  15938. return new Pu(e, t.asyncQueue, n, t.clientId, t.initialUser);
  15939. }
  15940. }
  15941. /**
  15942. * Initializes and wires the components that are needed to interface with the
  15943. * network.
  15944. */ class Pa {
  15945. async initialize(t, e) {
  15946. this.localStore || (this.localStore = t.localStore, this.sharedClientState = t.sharedClientState,
  15947. this.datastore = this.createDatastore(e), this.remoteStore = this.createRemoteStore(e),
  15948. this.eventManager = this.createEventManager(e), this.syncEngine = this.createSyncEngine(e,
  15949. /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = t => Hc(this.syncEngine, t, 1 /* OnlineStateSource.SharedClientState */),
  15950. this.remoteStore.remoteSyncer.handleCredentialChange = ca.bind(null, this.syncEngine),
  15951. await yc(this.remoteStore, this.syncEngine.isPrimaryClient));
  15952. }
  15953. createEventManager(t) {
  15954. return new bc;
  15955. }
  15956. createDatastore(t) {
  15957. const e = Fu(t.databaseInfo.databaseId), n = (s = t.databaseInfo, new Mu(s));
  15958. var s;
  15959. /** Return the Platform-specific connectivity monitor. */ return function(t, e, n, s) {
  15960. return new Ku(t, e, n, s);
  15961. }(t.authCredentials, t.appCheckCredentials, n, e);
  15962. }
  15963. createRemoteStore(t) {
  15964. return e = this.localStore, n = this.datastore, s = t.asyncQueue, i = t => Hc(this.syncEngine, t, 0 /* OnlineStateSource.RemoteStore */),
  15965. r = Su.D() ? new Su : new Vu, new ju(e, n, s, i, r);
  15966. var e, n, s, i, r;
  15967. /** Re-enables the network. Idempotent. */ }
  15968. createSyncEngine(t, e) {
  15969. return function(t, e, n,
  15970. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  15971. s, i, r, o) {
  15972. const u = new Kc(t, e, n, s, i, r);
  15973. return o && (u.vc = !0), u;
  15974. }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);
  15975. }
  15976. terminate() {
  15977. return async function(t) {
  15978. const e = L(t);
  15979. N("RemoteStore", "RemoteStore shutting down."), e.vu.add(5 /* OfflineCause.Shutdown */),
  15980. await Wu(e), e.Pu.shutdown(),
  15981. // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
  15982. // triggering spurious listener events with cached data, etc.
  15983. e.bu.set("Unknown" /* OnlineState.Unknown */);
  15984. }(this.remoteStore);
  15985. }
  15986. }
  15987. /**
  15988. * @license
  15989. * Copyright 2020 Google LLC
  15990. *
  15991. * Licensed under the Apache License, Version 2.0 (the "License");
  15992. * you may not use this file except in compliance with the License.
  15993. * You may obtain a copy of the License at
  15994. *
  15995. * http://www.apache.org/licenses/LICENSE-2.0
  15996. *
  15997. * Unless required by applicable law or agreed to in writing, software
  15998. * distributed under the License is distributed on an "AS IS" BASIS,
  15999. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16000. * See the License for the specific language governing permissions and
  16001. * limitations under the License.
  16002. */
  16003. /**
  16004. * How many bytes to read each time when `ReadableStreamReader.read()` is
  16005. * called. Only applicable for byte streams that we control (e.g. those backed
  16006. * by an UInt8Array).
  16007. */
  16008. /**
  16009. * Builds a `ByteStreamReader` from a UInt8Array.
  16010. * @param source - The data source to use.
  16011. * @param bytesPerRead - How many bytes each `read()` from the returned reader
  16012. * will read.
  16013. */
  16014. function ba(t, e = 10240) {
  16015. let n = 0;
  16016. // The TypeScript definition for ReadableStreamReader changed. We use
  16017. // `any` here to allow this code to compile with different versions.
  16018. // See https://github.com/microsoft/TypeScript/issues/42970
  16019. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16020. return {
  16021. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16022. async read() {
  16023. if (n < t.byteLength) {
  16024. const s = {
  16025. value: t.slice(n, n + e),
  16026. done: !1
  16027. };
  16028. return n += e, s;
  16029. }
  16030. return {
  16031. done: !0
  16032. };
  16033. },
  16034. async cancel() {},
  16035. releaseLock() {},
  16036. closed: Promise.resolve()
  16037. };
  16038. }
  16039. /**
  16040. * @license
  16041. * Copyright 2020 Google LLC
  16042. *
  16043. * Licensed under the Apache License, Version 2.0 (the "License");
  16044. * you may not use this file except in compliance with the License.
  16045. * You may obtain a copy of the License at
  16046. *
  16047. * http://www.apache.org/licenses/LICENSE-2.0
  16048. *
  16049. * Unless required by applicable law or agreed to in writing, software
  16050. * distributed under the License is distributed on an "AS IS" BASIS,
  16051. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16052. * See the License for the specific language governing permissions and
  16053. * limitations under the License.
  16054. */
  16055. /**
  16056. * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.
  16057. */
  16058. /**
  16059. * @license
  16060. * Copyright 2017 Google LLC
  16061. *
  16062. * Licensed under the Apache License, Version 2.0 (the "License");
  16063. * you may not use this file except in compliance with the License.
  16064. * You may obtain a copy of the License at
  16065. *
  16066. * http://www.apache.org/licenses/LICENSE-2.0
  16067. *
  16068. * Unless required by applicable law or agreed to in writing, software
  16069. * distributed under the License is distributed on an "AS IS" BASIS,
  16070. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16071. * See the License for the specific language governing permissions and
  16072. * limitations under the License.
  16073. */
  16074. /*
  16075. * A wrapper implementation of Observer<T> that will dispatch events
  16076. * asynchronously. To allow immediate silencing, a mute call is added which
  16077. * causes events scheduled to no longer be raised.
  16078. */
  16079. class Va {
  16080. constructor(t) {
  16081. this.observer = t,
  16082. /**
  16083. * When set to true, will not raise future events. Necessary to deal with
  16084. * async detachment of listener.
  16085. */
  16086. this.muted = !1;
  16087. }
  16088. next(t) {
  16089. this.observer.next && this.Sc(this.observer.next, t);
  16090. }
  16091. error(t) {
  16092. this.observer.error ? this.Sc(this.observer.error, t) : k("Uncaught Error in snapshot listener:", t.toString());
  16093. }
  16094. Dc() {
  16095. this.muted = !0;
  16096. }
  16097. Sc(t, e) {
  16098. this.muted || setTimeout((() => {
  16099. this.muted || t(e);
  16100. }), 0);
  16101. }
  16102. }
  16103. /**
  16104. * @license
  16105. * Copyright 2020 Google LLC
  16106. *
  16107. * Licensed under the Apache License, Version 2.0 (the "License");
  16108. * you may not use this file except in compliance with the License.
  16109. * You may obtain a copy of the License at
  16110. *
  16111. * http://www.apache.org/licenses/LICENSE-2.0
  16112. *
  16113. * Unless required by applicable law or agreed to in writing, software
  16114. * distributed under the License is distributed on an "AS IS" BASIS,
  16115. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16116. * See the License for the specific language governing permissions and
  16117. * limitations under the License.
  16118. */
  16119. /**
  16120. * A class representing a bundle.
  16121. *
  16122. * Takes a bundle stream or buffer, and presents abstractions to read bundled
  16123. * elements out of the underlying content.
  16124. */ class Sa {
  16125. constructor(
  16126. /** The reader to read from underlying binary bundle data source. */
  16127. t, e) {
  16128. this.Cc = t, this.serializer = e,
  16129. /** Cached bundle metadata. */
  16130. this.metadata = new K,
  16131. /**
  16132. * Internal buffer to hold bundle content, accumulating incomplete element
  16133. * content.
  16134. */
  16135. this.buffer = new Uint8Array, this.xc = new TextDecoder("utf-8"),
  16136. // Read the metadata (which is the first element).
  16137. this.Nc().then((t => {
  16138. t && t.Qu() ? this.metadata.resolve(t.Gu.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null == t ? void 0 : t.Gu)}`));
  16139. }), (t => this.metadata.reject(t)));
  16140. }
  16141. close() {
  16142. return this.Cc.cancel();
  16143. }
  16144. async getMetadata() {
  16145. return this.metadata.promise;
  16146. }
  16147. async bc() {
  16148. // Makes sure metadata is read before proceeding.
  16149. return await this.getMetadata(), this.Nc();
  16150. }
  16151. /**
  16152. * Reads from the head of internal buffer, and pulling more data from
  16153. * underlying stream if a complete element cannot be found, until an
  16154. * element(including the prefixed length and the JSON string) is found.
  16155. *
  16156. * Once a complete element is read, it is dropped from internal buffer.
  16157. *
  16158. * Returns either the bundled element, or null if we have reached the end of
  16159. * the stream.
  16160. */ async Nc() {
  16161. const t = await this.kc();
  16162. if (null === t) return null;
  16163. const e = this.xc.decode(t), n = Number(e);
  16164. isNaN(n) && this.Mc(`length string (${e}) is not valid number`);
  16165. const s = await this.$c(n);
  16166. return new kc(JSON.parse(s), t.length + n);
  16167. }
  16168. /** First index of '{' from the underlying buffer. */ Oc() {
  16169. return this.buffer.findIndex((t => t === "{".charCodeAt(0)));
  16170. }
  16171. /**
  16172. * Reads from the beginning of the internal buffer, until the first '{', and
  16173. * return the content.
  16174. *
  16175. * If reached end of the stream, returns a null.
  16176. */ async kc() {
  16177. for (;this.Oc() < 0; ) {
  16178. if (await this.Fc()) break;
  16179. }
  16180. // Broke out of the loop because underlying stream is closed, and there
  16181. // happens to be no more data to process.
  16182. if (0 === this.buffer.length) return null;
  16183. const t = this.Oc();
  16184. // Broke out of the loop because underlying stream is closed, but still
  16185. // cannot find an open bracket.
  16186. t < 0 && this.Mc("Reached the end of bundle when a length string is expected.");
  16187. const e = this.buffer.slice(0, t);
  16188. // Update the internal buffer to drop the read length.
  16189. return this.buffer = this.buffer.slice(t), e;
  16190. }
  16191. /**
  16192. * Reads from a specified position from the internal buffer, for a specified
  16193. * number of bytes, pulling more data from the underlying stream if needed.
  16194. *
  16195. * Returns a string decoded from the read bytes.
  16196. */ async $c(t) {
  16197. for (;this.buffer.length < t; ) {
  16198. await this.Fc() && this.Mc("Reached the end of bundle when more is expected.");
  16199. }
  16200. const e = this.xc.decode(this.buffer.slice(0, t));
  16201. // Update the internal buffer to drop the read json string.
  16202. return this.buffer = this.buffer.slice(t), e;
  16203. }
  16204. Mc(t) {
  16205. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16206. throw this.Cc.cancel(), new Error(`Invalid bundle format: ${t}`);
  16207. }
  16208. /**
  16209. * Pulls more data from underlying stream to internal buffer.
  16210. * Returns a boolean indicating whether the stream is finished.
  16211. */ async Fc() {
  16212. const t = await this.Cc.read();
  16213. if (!t.done) {
  16214. const e = new Uint8Array(this.buffer.length + t.value.length);
  16215. e.set(this.buffer), e.set(t.value, this.buffer.length), this.buffer = e;
  16216. }
  16217. return t.done;
  16218. }
  16219. }
  16220. /**
  16221. * @license
  16222. * Copyright 2017 Google LLC
  16223. *
  16224. * Licensed under the Apache License, Version 2.0 (the "License");
  16225. * you may not use this file except in compliance with the License.
  16226. * You may obtain a copy of the License at
  16227. *
  16228. * http://www.apache.org/licenses/LICENSE-2.0
  16229. *
  16230. * Unless required by applicable law or agreed to in writing, software
  16231. * distributed under the License is distributed on an "AS IS" BASIS,
  16232. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16233. * See the License for the specific language governing permissions and
  16234. * limitations under the License.
  16235. */
  16236. /**
  16237. * Internal transaction object responsible for accumulating the mutations to
  16238. * perform and the base versions for any documents read.
  16239. */
  16240. class Da {
  16241. constructor(t) {
  16242. this.datastore = t,
  16243. // The version of each document that was read during this transaction.
  16244. this.readVersions = new Map, this.mutations = [], this.committed = !1,
  16245. /**
  16246. * A deferred usage error that occurred previously in this transaction that
  16247. * will cause the transaction to fail once it actually commits.
  16248. */
  16249. this.lastWriteError = null,
  16250. /**
  16251. * Set of documents that have been written in the transaction.
  16252. *
  16253. * When there's more than one write to the same key in a transaction, any
  16254. * writes after the first are handled differently.
  16255. */
  16256. this.writtenDocs = new Set;
  16257. }
  16258. async lookup(t) {
  16259. if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new U(q.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes.");
  16260. const e = await async function(t, e) {
  16261. const n = L(t), s = Li(n.serializer) + "/documents", i = {
  16262. documents: e.map((t => $i(n.serializer, t)))
  16263. }, r = await n.vo("BatchGetDocuments", s, i, e.length), o = new Map;
  16264. r.forEach((t => {
  16265. const e = Gi(n.serializer, t);
  16266. o.set(e.key.toString(), e);
  16267. }));
  16268. const u = [];
  16269. return e.forEach((t => {
  16270. const e = o.get(t.toString());
  16271. F(!!e), u.push(e);
  16272. })), u;
  16273. }(this.datastore, t);
  16274. return e.forEach((t => this.recordVersion(t))), e;
  16275. }
  16276. set(t, e) {
  16277. this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16278. }
  16279. update(t, e) {
  16280. try {
  16281. this.write(e.toMutation(t, this.preconditionForUpdate(t)));
  16282. } catch (t) {
  16283. this.lastWriteError = t;
  16284. }
  16285. this.writtenDocs.add(t.toString());
  16286. }
  16287. delete(t) {
  16288. this.write(new Ys(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16289. }
  16290. async commit() {
  16291. if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;
  16292. const t = this.readVersions;
  16293. // For each mutation, note that the doc was written.
  16294. this.mutations.forEach((e => {
  16295. t.delete(e.key.toString());
  16296. })),
  16297. // For each document that was read but not written to, we want to perform
  16298. // a `verify` operation.
  16299. t.forEach(((t, e) => {
  16300. const n = ht.fromPath(e);
  16301. this.mutations.push(new Xs(n, this.precondition(n)));
  16302. })), await async function(t, e) {
  16303. const n = L(t), s = Li(n.serializer) + "/documents", i = {
  16304. writes: e.map((t => ji(n.serializer, t)))
  16305. };
  16306. await n.Io("Commit", s, i);
  16307. }(this.datastore, this.mutations), this.committed = !0;
  16308. }
  16309. recordVersion(t) {
  16310. let e;
  16311. if (t.isFoundDocument()) e = t.version; else {
  16312. if (!t.isNoDocument()) throw O();
  16313. // Represent a deleted doc using SnapshotVersion.min().
  16314. e = rt.min();
  16315. }
  16316. const n = this.readVersions.get(t.key.toString());
  16317. if (n) {
  16318. if (!e.isEqual(n))
  16319. // This transaction will fail no matter what.
  16320. throw new U(q.ABORTED, "Document version changed between two reads.");
  16321. } else this.readVersions.set(t.key.toString(), e);
  16322. }
  16323. /**
  16324. * Returns the version of this document when it was read in this transaction,
  16325. * as a precondition, or no precondition if it was not read.
  16326. */ precondition(t) {
  16327. const e = this.readVersions.get(t.toString());
  16328. return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(rt.min()) ? Fs.exists(!1) : Fs.updateTime(e) : Fs.none();
  16329. }
  16330. /**
  16331. * Returns the precondition for a document if the operation is an update.
  16332. */ preconditionForUpdate(t) {
  16333. const e = this.readVersions.get(t.toString());
  16334. // The first time a document is written, we want to take into account the
  16335. // read time and existence
  16336. if (!this.writtenDocs.has(t.toString()) && e) {
  16337. if (e.isEqual(rt.min()))
  16338. // The document doesn't exist, so fail the transaction.
  16339. // This has to be validated locally because you can't send a
  16340. // precondition that a document does not exist without changing the
  16341. // semantics of the backend write to be an insert. This is the reverse
  16342. // of what we want, since we want to assert that the document doesn't
  16343. // exist but then send the update and have it fail. Since we can't
  16344. // express that to the backend, we have to validate locally.
  16345. // Note: this can change once we can send separate verify writes in the
  16346. // transaction.
  16347. throw new U(q.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
  16348. // Document exists, base precondition on document update time.
  16349. return Fs.updateTime(e);
  16350. }
  16351. // Document was not read, so we just use the preconditions for a blind
  16352. // update.
  16353. return Fs.exists(!0);
  16354. }
  16355. write(t) {
  16356. this.ensureCommitNotCalled(), this.mutations.push(t);
  16357. }
  16358. ensureCommitNotCalled() {}
  16359. }
  16360. /**
  16361. * @license
  16362. * Copyright 2019 Google LLC
  16363. *
  16364. * Licensed under the Apache License, Version 2.0 (the "License");
  16365. * you may not use this file except in compliance with the License.
  16366. * You may obtain a copy of the License at
  16367. *
  16368. * http://www.apache.org/licenses/LICENSE-2.0
  16369. *
  16370. * Unless required by applicable law or agreed to in writing, software
  16371. * distributed under the License is distributed on an "AS IS" BASIS,
  16372. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16373. * See the License for the specific language governing permissions and
  16374. * limitations under the License.
  16375. */
  16376. /**
  16377. * TransactionRunner encapsulates the logic needed to run and retry transactions
  16378. * with backoff.
  16379. */ class Ca {
  16380. constructor(t, e, n, s, i) {
  16381. this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = s,
  16382. this.deferred = i, this.Bc = n.maxAttempts, this.qo = new Bu(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */);
  16383. }
  16384. /** Runs the transaction and sets the result on deferred. */ run() {
  16385. this.Bc -= 1, this.Lc();
  16386. }
  16387. Lc() {
  16388. this.qo.No((async () => {
  16389. const t = new Da(this.datastore), e = this.qc(t);
  16390. e && e.then((e => {
  16391. this.asyncQueue.enqueueAndForget((() => t.commit().then((() => {
  16392. this.deferred.resolve(e);
  16393. })).catch((t => {
  16394. this.Uc(t);
  16395. }))));
  16396. })).catch((t => {
  16397. this.Uc(t);
  16398. }));
  16399. }));
  16400. }
  16401. qc(t) {
  16402. try {
  16403. const e = this.updateFunction(t);
  16404. return !Ft(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")),
  16405. null);
  16406. } catch (t) {
  16407. // Do not retry errors thrown by user provided updateFunction.
  16408. return this.deferred.reject(t), null;
  16409. }
  16410. }
  16411. Uc(t) {
  16412. this.Bc > 0 && this.Kc(t) ? (this.Bc -= 1, this.asyncQueue.enqueueAndForget((() => (this.Lc(),
  16413. Promise.resolve())))) : this.deferred.reject(t);
  16414. }
  16415. Kc(t) {
  16416. if ("FirebaseError" === t.name) {
  16417. // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
  16418. // non-matching document versions with ABORTED. These errors should be retried.
  16419. const e = t.code;
  16420. return "aborted" === e || "failed-precondition" === e || "already-exists" === e || !oi(e);
  16421. }
  16422. return !1;
  16423. }
  16424. }
  16425. /**
  16426. * @license
  16427. * Copyright 2017 Google LLC
  16428. *
  16429. * Licensed under the Apache License, Version 2.0 (the "License");
  16430. * you may not use this file except in compliance with the License.
  16431. * You may obtain a copy of the License at
  16432. *
  16433. * http://www.apache.org/licenses/LICENSE-2.0
  16434. *
  16435. * Unless required by applicable law or agreed to in writing, software
  16436. * distributed under the License is distributed on an "AS IS" BASIS,
  16437. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16438. * See the License for the specific language governing permissions and
  16439. * limitations under the License.
  16440. */
  16441. /**
  16442. * FirestoreClient is a top-level class that constructs and owns all of the //
  16443. * pieces of the client SDK architecture. It is responsible for creating the //
  16444. * async queue that is shared by all of the other components in the system. //
  16445. */
  16446. class xa {
  16447. constructor(t, e,
  16448. /**
  16449. * Asynchronous queue responsible for all of our internal processing. When
  16450. * we get incoming work from the user (via public API) or the network
  16451. * (incoming GRPC messages), we should always schedule onto this queue.
  16452. * This ensures all of our work is properly serialized (e.g. we don't
  16453. * start processing a new operation while the previous one is waiting for
  16454. * an async I/O to complete).
  16455. */
  16456. n, s) {
  16457. this.authCredentials = t, this.appCheckCredentials = e, this.asyncQueue = n, this.databaseInfo = s,
  16458. this.user = V.UNAUTHENTICATED, this.clientId = tt.A(), this.authCredentialListener = () => Promise.resolve(),
  16459. this.appCheckCredentialListener = () => Promise.resolve(), this.authCredentials.start(n, (async t => {
  16460. N("FirestoreClient", "Received user=", t.uid), await this.authCredentialListener(t),
  16461. this.user = t;
  16462. })), this.appCheckCredentials.start(n, (t => (N("FirestoreClient", "Received new app check token=", t),
  16463. this.appCheckCredentialListener(t, this.user))));
  16464. }
  16465. async getConfiguration() {
  16466. return {
  16467. asyncQueue: this.asyncQueue,
  16468. databaseInfo: this.databaseInfo,
  16469. clientId: this.clientId,
  16470. authCredentials: this.authCredentials,
  16471. appCheckCredentials: this.appCheckCredentials,
  16472. initialUser: this.user,
  16473. maxConcurrentLimboResolutions: 100
  16474. };
  16475. }
  16476. setCredentialChangeListener(t) {
  16477. this.authCredentialListener = t;
  16478. }
  16479. setAppCheckTokenChangeListener(t) {
  16480. this.appCheckCredentialListener = t;
  16481. }
  16482. /**
  16483. * Checks that the client has not been terminated. Ensures that other methods on //
  16484. * this class cannot be called after the client is terminated. //
  16485. */ verifyNotTerminated() {
  16486. if (this.asyncQueue.isShuttingDown) throw new U(q.FAILED_PRECONDITION, "The client has already been terminated.");
  16487. }
  16488. terminate() {
  16489. this.asyncQueue.enterRestrictedMode();
  16490. const t = new K;
  16491. return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {
  16492. try {
  16493. this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(),
  16494. // The credentials provider must be terminated after shutting down the
  16495. // RemoteStore as it will prevent the RemoteStore from retrieving auth
  16496. // tokens.
  16497. this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), t.resolve();
  16498. } catch (e) {
  16499. const n = Ec(e, "Failed to shutdown persistence");
  16500. t.reject(n);
  16501. }
  16502. })), t.promise;
  16503. }
  16504. }
  16505. async function Na(t, e) {
  16506. t.asyncQueue.verifyOperationInProgress(), N("FirestoreClient", "Initializing OfflineComponentProvider");
  16507. const n = await t.getConfiguration();
  16508. await e.initialize(n);
  16509. let s = n.initialUser;
  16510. t.setCredentialChangeListener((async t => {
  16511. s.isEqual(t) || (await iu(e.localStore, t), s = t);
  16512. })),
  16513. // When a user calls clearPersistence() in one client, all other clients
  16514. // need to be terminated to allow the delete to succeed.
  16515. e.persistence.setDatabaseDeletedListener((() => t.terminate())), t._offlineComponents = e;
  16516. }
  16517. async function ka(t, e) {
  16518. t.asyncQueue.verifyOperationInProgress();
  16519. const n = await $a(t);
  16520. N("FirestoreClient", "Initializing OnlineComponentProvider");
  16521. const s = await t.getConfiguration();
  16522. await e.initialize(n, s),
  16523. // The CredentialChangeListener of the online component provider takes
  16524. // precedence over the offline component provider.
  16525. t.setCredentialChangeListener((t => gc(e.remoteStore, t))), t.setAppCheckTokenChangeListener(((t, n) => gc(e.remoteStore, n))),
  16526. t._onlineComponents = e;
  16527. }
  16528. /**
  16529. * Decides whether the provided error allows us to gracefully disable
  16530. * persistence (as opposed to crashing the client).
  16531. */ function Ma(t) {
  16532. return "FirebaseError" === t.name ? t.code === q.FAILED_PRECONDITION || t.code === q.UNIMPLEMENTED : !("undefined" != typeof DOMException && t instanceof DOMException) || (
  16533. // When the browser is out of quota we could get either quota exceeded
  16534. // or an aborted error depending on whether the error happened during
  16535. // schema migration.
  16536. 22 === t.code || 20 === t.code ||
  16537. // Firefox Private Browsing mode disables IndexedDb and returns
  16538. // INVALID_STATE for any usage.
  16539. 11 === t.code);
  16540. }
  16541. async function $a(t) {
  16542. if (!t._offlineComponents) if (t._uninitializedComponentsProvider) {
  16543. N("FirestoreClient", "Using user provided OfflineComponentProvider");
  16544. try {
  16545. await Na(t, t._uninitializedComponentsProvider._offline);
  16546. } catch (e) {
  16547. const n = e;
  16548. if (!Ma(n)) throw n;
  16549. M("Error using user provided cache. Falling back to memory cache: " + n), await Na(t, new Ea);
  16550. }
  16551. } else N("FirestoreClient", "Using default OfflineComponentProvider"), await Na(t, new Ea);
  16552. return t._offlineComponents;
  16553. }
  16554. async function Oa(t) {
  16555. return t._onlineComponents || (t._uninitializedComponentsProvider ? (N("FirestoreClient", "Using user provided OnlineComponentProvider"),
  16556. await ka(t, t._uninitializedComponentsProvider._online)) : (N("FirestoreClient", "Using default OnlineComponentProvider"),
  16557. await ka(t, new Pa))), t._onlineComponents;
  16558. }
  16559. function Fa(t) {
  16560. return $a(t).then((t => t.persistence));
  16561. }
  16562. function Ba(t) {
  16563. return $a(t).then((t => t.localStore));
  16564. }
  16565. function La(t) {
  16566. return Oa(t).then((t => t.remoteStore));
  16567. }
  16568. function qa(t) {
  16569. return Oa(t).then((t => t.syncEngine));
  16570. }
  16571. function Ua(t) {
  16572. return Oa(t).then((t => t.datastore));
  16573. }
  16574. async function Ka(t) {
  16575. const e = await Oa(t), n = e.eventManager;
  16576. return n.onListen = Gc.bind(null, e.syncEngine), n.onUnlisten = jc.bind(null, e.syncEngine),
  16577. n;
  16578. }
  16579. /** Enables the network connection and re-enqueues all pending operations. */ function Ga(t) {
  16580. return t.asyncQueue.enqueue((async () => {
  16581. const e = await Fa(t), n = await La(t);
  16582. return e.setNetworkEnabled(!0), function(t) {
  16583. const e = L(t);
  16584. return e.vu.delete(0 /* OfflineCause.UserDisabled */), zu(e);
  16585. }(n);
  16586. }));
  16587. }
  16588. /** Disables the network connection. Pending operations will not complete. */ function Qa(t) {
  16589. return t.asyncQueue.enqueue((async () => {
  16590. const e = await Fa(t), n = await La(t);
  16591. return e.setNetworkEnabled(!1), async function(t) {
  16592. const e = L(t);
  16593. e.vu.add(0 /* OfflineCause.UserDisabled */), await Wu(e),
  16594. // Set the OnlineState to Offline so get()s return from cache, etc.
  16595. e.bu.set("Offline" /* OnlineState.Offline */);
  16596. }(n);
  16597. }));
  16598. }
  16599. /**
  16600. * Returns a Promise that resolves when all writes that were pending at the time
  16601. * this method was called received server acknowledgement. An acknowledgement
  16602. * can be either acceptance or rejection.
  16603. */ function ja(t, e) {
  16604. const n = new K;
  16605. return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {
  16606. try {
  16607. const s = await function(t, e) {
  16608. const n = L(t);
  16609. return n.persistence.runTransaction("read document", "readonly", (t => n.localDocuments.getDocument(t, e)));
  16610. }(t, e);
  16611. s.isFoundDocument() ? n.resolve(s) : s.isNoDocument() ? n.resolve(null) : n.reject(new U(q.UNAVAILABLE, "Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"));
  16612. } catch (t) {
  16613. const s = Ec(t, `Failed to get document '${e} from cache`);
  16614. n.reject(s);
  16615. }
  16616. }
  16617. /**
  16618. * Retrieves a latency-compensated document from the backend via a
  16619. * SnapshotListener.
  16620. */ (await Ba(t), e, n))), n.promise;
  16621. }
  16622. function za(t, e, n = {}) {
  16623. const s = new K;
  16624. return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {
  16625. const r = new Va({
  16626. next: r => {
  16627. // Remove query first before passing event to user to avoid
  16628. // user actions affecting the now stale query.
  16629. e.enqueueAndForget((() => Sc(t, o)));
  16630. const u = r.docs.has(n);
  16631. !u && r.fromCache ?
  16632. // TODO(dimond): If we're online and the document doesn't
  16633. // exist then we resolve with a doc.exists set to false. If
  16634. // we're offline however, we reject the Promise in this
  16635. // case. Two options: 1) Cache the negative response from
  16636. // the server so we can deliver that even when you're
  16637. // offline 2) Actually reject the Promise in the online case
  16638. // if the document doesn't exist.
  16639. i.reject(new U(q.UNAVAILABLE, "Failed to get document because the client is offline.")) : u && r.fromCache && s && "server" === s.source ? i.reject(new U(q.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')) : i.resolve(r);
  16640. },
  16641. error: t => i.reject(t)
  16642. }), o = new Nc(Gn(n.path), r, {
  16643. includeMetadataChanges: !0,
  16644. Ku: !0
  16645. });
  16646. return Vc(t, o);
  16647. }(await Ka(t), t.asyncQueue, e, n, s))), s.promise;
  16648. }
  16649. function Wa(t, e) {
  16650. const n = new K;
  16651. return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {
  16652. try {
  16653. const s = await fu(t, e,
  16654. /* usePreviousResults= */ !0), i = new Lc(e, s.ir), r = i.sc(s.documents), o = i.applyChanges(r,
  16655. /* updateLimboDocuments= */ !1);
  16656. n.resolve(o.snapshot);
  16657. } catch (t) {
  16658. const s = Ec(t, `Failed to execute query '${e} against cache`);
  16659. n.reject(s);
  16660. }
  16661. }
  16662. /**
  16663. * Retrieves a latency-compensated query snapshot from the backend via a
  16664. * SnapshotListener.
  16665. */ (await Ba(t), e, n))), n.promise;
  16666. }
  16667. function Ha(t, e, n = {}) {
  16668. const s = new K;
  16669. return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {
  16670. const r = new Va({
  16671. next: n => {
  16672. // Remove query first before passing event to user to avoid
  16673. // user actions affecting the now stale query.
  16674. e.enqueueAndForget((() => Sc(t, o))), n.fromCache && "server" === s.source ? i.reject(new U(q.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i.resolve(n);
  16675. },
  16676. error: t => i.reject(t)
  16677. }), o = new Nc(n, r, {
  16678. includeMetadataChanges: !0,
  16679. Ku: !0
  16680. });
  16681. return Vc(t, o);
  16682. }(await Ka(t), t.asyncQueue, e, n, s))), s.promise;
  16683. }
  16684. function Ja(t, e) {
  16685. const n = new Va(e);
  16686. return t.asyncQueue.enqueueAndForget((async () => function(t, e) {
  16687. L(t).ku.add(e),
  16688. // Immediately fire an initial event, indicating all existing listeners
  16689. // are in-sync.
  16690. e.next();
  16691. }(await Ka(t), n))), () => {
  16692. n.Dc(), t.asyncQueue.enqueueAndForget((async () => function(t, e) {
  16693. L(t).ku.delete(e);
  16694. }(await Ka(t), n)));
  16695. };
  16696. }
  16697. /**
  16698. * Takes an updateFunction in which a set of reads and writes can be performed
  16699. * atomically. In the updateFunction, the client can read and write values
  16700. * using the supplied transaction object. After the updateFunction, all
  16701. * changes will be committed. If a retryable error occurs (ex: some other
  16702. * client has changed any of the data referenced), then the updateFunction
  16703. * will be called again after a backoff. If the updateFunction still fails
  16704. * after all retries, then the transaction will be rejected.
  16705. *
  16706. * The transaction object passed to the updateFunction contains methods for
  16707. * accessing documents and collections. Unlike other datastore access, data
  16708. * accessed with the transaction will not reflect local changes that have not
  16709. * been committed. For this reason, it is required that all reads are
  16710. * performed before any writes. Transactions must be performed while online.
  16711. */ function Ya(t, e, n, s) {
  16712. const i = function(t, e) {
  16713. let n;
  16714. n = "string" == typeof t ? hi().encode(t) : t;
  16715. return function(t, e) {
  16716. return new Sa(t, e);
  16717. }(function(t, e) {
  16718. if (t instanceof Uint8Array) return ba(t, e);
  16719. if (t instanceof ArrayBuffer) return ba(new Uint8Array(t), e);
  16720. if (t instanceof ReadableStream) return t.getReader();
  16721. throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream");
  16722. }(n), e);
  16723. }(n, Fu(e));
  16724. t.asyncQueue.enqueueAndForget((async () => {
  16725. Ta(await qa(t), i, s);
  16726. }));
  16727. }
  16728. function Xa(t, e) {
  16729. return t.asyncQueue.enqueue((async () => function(t, e) {
  16730. const n = L(t);
  16731. return n.persistence.runTransaction("Get named query", "readonly", (t => n.qs.getNamedQuery(t, e)));
  16732. }(await Ba(t), e)));
  16733. }
  16734. function Za(t, e) {
  16735. return t.asyncQueue.enqueue((async () => async function(t, e) {
  16736. const n = L(t), s = n.indexManager, i = [];
  16737. return n.persistence.runTransaction("Configure indexes", "readwrite", (t => s.getFieldIndexes(t).next((n =>
  16738. /**
  16739. * @license
  16740. * Copyright 2017 Google LLC
  16741. *
  16742. * Licensed under the Apache License, Version 2.0 (the "License");
  16743. * you may not use this file except in compliance with the License.
  16744. * You may obtain a copy of the License at
  16745. *
  16746. * http://www.apache.org/licenses/LICENSE-2.0
  16747. *
  16748. * Unless required by applicable law or agreed to in writing, software
  16749. * distributed under the License is distributed on an "AS IS" BASIS,
  16750. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16751. * See the License for the specific language governing permissions and
  16752. * limitations under the License.
  16753. */
  16754. /**
  16755. * Compares two array for equality using comparator. The method computes the
  16756. * intersection and invokes `onAdd` for every element that is in `after` but not
  16757. * `before`. `onRemove` is invoked for every element in `before` but missing
  16758. * from `after`.
  16759. *
  16760. * The method creates a copy of both `before` and `after` and runs in O(n log
  16761. * n), where n is the size of the two lists.
  16762. *
  16763. * @param before - The elements that exist in the original array.
  16764. * @param after - The elements to diff against the original array.
  16765. * @param comparator - The comparator for the elements in before and after.
  16766. * @param onAdd - A function to invoke for every element that is part of `
  16767. * after` but not `before`.
  16768. * @param onRemove - A function to invoke for every element that is part of
  16769. * `before` but not `after`.
  16770. */
  16771. function(t, e, n, s, i) {
  16772. t = [ ...t ], e = [ ...e ], t.sort(n), e.sort(n);
  16773. const r = t.length, o = e.length;
  16774. let u = 0, c = 0;
  16775. for (;u < o && c < r; ) {
  16776. const r = n(t[c], e[u]);
  16777. r < 0 ?
  16778. // The element was removed if the next element in our ordered
  16779. // walkthrough is only in `before`.
  16780. i(t[c++]) : r > 0 ?
  16781. // The element was added if the next element in our ordered walkthrough
  16782. // is only in `after`.
  16783. s(e[u++]) : (u++, c++);
  16784. }
  16785. for (;u < o; ) s(e[u++]);
  16786. for (;c < r; ) i(t[c++]);
  16787. }(n, e, wt, (e => {
  16788. i.push(s.addFieldIndex(t, e));
  16789. }), (e => {
  16790. i.push(s.deleteFieldIndex(t, e));
  16791. })))).next((() => Rt.waitFor(i)))));
  16792. }
  16793. /**
  16794. * @license
  16795. * Copyright 2019 Google LLC
  16796. *
  16797. * Licensed under the Apache License, Version 2.0 (the "License");
  16798. * you may not use this file except in compliance with the License.
  16799. * You may obtain a copy of the License at
  16800. *
  16801. * http://www.apache.org/licenses/LICENSE-2.0
  16802. *
  16803. * Unless required by applicable law or agreed to in writing, software
  16804. * distributed under the License is distributed on an "AS IS" BASIS,
  16805. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16806. * See the License for the specific language governing permissions and
  16807. * limitations under the License.
  16808. */
  16809. // The format of the LocalStorage key that stores the client state is:
  16810. // firestore_clients_<persistence_prefix>_<instance_key>
  16811. (await Ba(t), e)));
  16812. }
  16813. /**
  16814. * @license
  16815. * Copyright 2023 Google LLC
  16816. *
  16817. * Licensed under the Apache License, Version 2.0 (the "License");
  16818. * you may not use this file except in compliance with the License.
  16819. * You may obtain a copy of the License at
  16820. *
  16821. * http://www.apache.org/licenses/LICENSE-2.0
  16822. *
  16823. * Unless required by applicable law or agreed to in writing, software
  16824. * distributed under the License is distributed on an "AS IS" BASIS,
  16825. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16826. * See the License for the specific language governing permissions and
  16827. * limitations under the License.
  16828. */
  16829. /**
  16830. * Compares two `ExperimentalLongPollingOptions` objects for equality.
  16831. */
  16832. /**
  16833. * Creates and returns a new `ExperimentalLongPollingOptions` with the same
  16834. * option values as the given instance.
  16835. */
  16836. function th(t) {
  16837. const e = {};
  16838. return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e;
  16839. }
  16840. /**
  16841. * @license
  16842. * Copyright 2020 Google LLC
  16843. *
  16844. * Licensed under the Apache License, Version 2.0 (the "License");
  16845. * you may not use this file except in compliance with the License.
  16846. * You may obtain a copy of the License at
  16847. *
  16848. * http://www.apache.org/licenses/LICENSE-2.0
  16849. *
  16850. * Unless required by applicable law or agreed to in writing, software
  16851. * distributed under the License is distributed on an "AS IS" BASIS,
  16852. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16853. * See the License for the specific language governing permissions and
  16854. * limitations under the License.
  16855. */ const eh = new Map;
  16856. /**
  16857. * An instance map that ensures only one Datastore exists per Firestore
  16858. * instance.
  16859. */
  16860. /**
  16861. * @license
  16862. * Copyright 2017 Google LLC
  16863. *
  16864. * Licensed under the Apache License, Version 2.0 (the "License");
  16865. * you may not use this file except in compliance with the License.
  16866. * You may obtain a copy of the License at
  16867. *
  16868. * http://www.apache.org/licenses/LICENSE-2.0
  16869. *
  16870. * Unless required by applicable law or agreed to in writing, software
  16871. * distributed under the License is distributed on an "AS IS" BASIS,
  16872. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16873. * See the License for the specific language governing permissions and
  16874. * limitations under the License.
  16875. */
  16876. function nh(t, e, n) {
  16877. if (!n) throw new U(q.INVALID_ARGUMENT, `Function ${t}() cannot be called with an empty ${e}.`);
  16878. }
  16879. /**
  16880. * Validates that two boolean options are not set at the same time.
  16881. * @internal
  16882. */ function sh(t, e, n, s) {
  16883. if (!0 === e && !0 === s) throw new U(q.INVALID_ARGUMENT, `${t} and ${n} cannot be used together.`);
  16884. }
  16885. /**
  16886. * Validates that `path` refers to a document (indicated by the fact it contains
  16887. * an even numbers of segments).
  16888. */ function ih(t) {
  16889. if (!ht.isDocumentKey(t)) throw new U(q.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);
  16890. }
  16891. /**
  16892. * Validates that `path` refers to a collection (indicated by the fact it
  16893. * contains an odd numbers of segments).
  16894. */ function rh(t) {
  16895. if (ht.isDocumentKey(t)) throw new U(q.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);
  16896. }
  16897. /**
  16898. * Returns true if it's a non-null object without a custom prototype
  16899. * (i.e. excludes Array, Date, etc.).
  16900. */
  16901. /** Returns a string describing the type / value of the provided input. */
  16902. function oh(t) {
  16903. if (void 0 === t) return "undefined";
  16904. if (null === t) return "null";
  16905. if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`),
  16906. JSON.stringify(t);
  16907. if ("number" == typeof t || "boolean" == typeof t) return "" + t;
  16908. if ("object" == typeof t) {
  16909. if (t instanceof Array) return "an array";
  16910. {
  16911. const e =
  16912. /** try to get the constructor name for an object. */
  16913. function(t) {
  16914. if (t.constructor) return t.constructor.name;
  16915. return null;
  16916. }
  16917. /**
  16918. * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
  16919. * underlying instance. Throws if `obj` is not an instance of `T`.
  16920. *
  16921. * This cast is used in the Lite and Full SDK to verify instance types for
  16922. * arguments passed to the public API.
  16923. * @internal
  16924. */ (t);
  16925. return e ? `a custom ${e} object` : "an object";
  16926. }
  16927. }
  16928. return "function" == typeof t ? "a function" : O();
  16929. }
  16930. function uh(t,
  16931. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16932. e) {
  16933. if ("_delegate" in t && (
  16934. // Unwrap Compat types
  16935. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16936. t = t._delegate), !(t instanceof e)) {
  16937. if (e.name === t.constructor.name) throw new U(q.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
  16938. {
  16939. const n = oh(t);
  16940. throw new U(q.INVALID_ARGUMENT, `Expected type '${e.name}', but it was: ${n}`);
  16941. }
  16942. }
  16943. return t;
  16944. }
  16945. function ch(t, e) {
  16946. if (e <= 0) throw new U(q.INVALID_ARGUMENT, `Function ${t}() requires a positive number, but it was: ${e}.`);
  16947. }
  16948. /**
  16949. * @license
  16950. * Copyright 2020 Google LLC
  16951. *
  16952. * Licensed under the Apache License, Version 2.0 (the "License");
  16953. * you may not use this file except in compliance with the License.
  16954. * You may obtain a copy of the License at
  16955. *
  16956. * http://www.apache.org/licenses/LICENSE-2.0
  16957. *
  16958. * Unless required by applicable law or agreed to in writing, software
  16959. * distributed under the License is distributed on an "AS IS" BASIS,
  16960. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16961. * See the License for the specific language governing permissions and
  16962. * limitations under the License.
  16963. */
  16964. // settings() defaults:
  16965. /**
  16966. * A concrete type describing all the values that can be applied via a
  16967. * user-supplied `FirestoreSettings` object. This is a separate type so that
  16968. * defaults can be supplied and the value can be checked for equality.
  16969. */
  16970. class ah {
  16971. constructor(t) {
  16972. var e, n;
  16973. if (void 0 === t.host) {
  16974. if (void 0 !== t.ssl) throw new U(q.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
  16975. this.host = "firestore.googleapis.com", this.ssl = true;
  16976. } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;
  16977. if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties,
  16978. this.cache = t.localCache, void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {
  16979. if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new U(q.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  16980. this.cacheSizeBytes = t.cacheSizeBytes;
  16981. }
  16982. sh("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling),
  16983. this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true :
  16984. // For backwards compatibility, coerce the value to boolean even though
  16985. // the TypeScript compiler has narrowed the type to boolean already.
  16986. // noinspection PointlessBooleanExpressionJS
  16987. this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling,
  16988. this.experimentalLongPollingOptions = th(null !== (n = t.experimentalLongPollingOptions) && void 0 !== n ? n : {}),
  16989. function(t) {
  16990. if (void 0 !== t.timeoutSeconds) {
  16991. if (isNaN(t.timeoutSeconds)) throw new U(q.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`);
  16992. if (t.timeoutSeconds < 5) throw new U(q.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`);
  16993. if (t.timeoutSeconds > 30) throw new U(q.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`);
  16994. }
  16995. }
  16996. /**
  16997. * @license
  16998. * Copyright 2020 Google LLC
  16999. *
  17000. * Licensed under the Apache License, Version 2.0 (the "License");
  17001. * you may not use this file except in compliance with the License.
  17002. * You may obtain a copy of the License at
  17003. *
  17004. * http://www.apache.org/licenses/LICENSE-2.0
  17005. *
  17006. * Unless required by applicable law or agreed to in writing, software
  17007. * distributed under the License is distributed on an "AS IS" BASIS,
  17008. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17009. * See the License for the specific language governing permissions and
  17010. * limitations under the License.
  17011. */
  17012. /**
  17013. * The Cloud Firestore service interface.
  17014. *
  17015. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  17016. */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams;
  17017. }
  17018. isEqual(t) {
  17019. return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && (e = this.experimentalLongPollingOptions,
  17020. n = t.experimentalLongPollingOptions, e.timeoutSeconds === n.timeoutSeconds) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;
  17021. var e, n;
  17022. }
  17023. }
  17024. class hh {
  17025. /** @hideconstructor */
  17026. constructor(t, e, n, s) {
  17027. this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n,
  17028. this._app = s,
  17029. /**
  17030. * Whether it's a Firestore or Firestore Lite instance.
  17031. */
  17032. this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new ah({}),
  17033. this._settingsFrozen = !1;
  17034. }
  17035. /**
  17036. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  17037. * instance.
  17038. */ get app() {
  17039. if (!this._app) throw new U(q.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
  17040. return this._app;
  17041. }
  17042. get _initialized() {
  17043. return this._settingsFrozen;
  17044. }
  17045. get _terminated() {
  17046. return void 0 !== this._terminateTask;
  17047. }
  17048. _setSettings(t) {
  17049. if (this._settingsFrozen) throw new U(q.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");
  17050. this._settings = new ah(t), void 0 !== t.credentials && (this._authCredentials = function(t) {
  17051. if (!t) return new Q;
  17052. switch (t.type) {
  17053. case "firstParty":
  17054. return new H(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null);
  17055. case "provider":
  17056. return t.client;
  17057. default:
  17058. throw new U(q.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type");
  17059. }
  17060. }(t.credentials));
  17061. }
  17062. _getSettings() {
  17063. return this._settings;
  17064. }
  17065. _freezeSettings() {
  17066. return this._settingsFrozen = !0, this._settings;
  17067. }
  17068. _delete() {
  17069. return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;
  17070. }
  17071. /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {
  17072. return {
  17073. app: this._app,
  17074. databaseId: this._databaseId,
  17075. settings: this._settings
  17076. };
  17077. }
  17078. /**
  17079. * Terminates all components used by this client. Subclasses can override
  17080. * this method to clean up their own dependencies, but must also call this
  17081. * method.
  17082. *
  17083. * Only ever called once.
  17084. */ _terminate() {
  17085. /**
  17086. * Removes all components associated with the provided instance. Must be called
  17087. * when the `Firestore` instance is terminated.
  17088. */
  17089. return function(t) {
  17090. const e = eh.get(t);
  17091. e && (N("ComponentProvider", "Removing Datastore"), eh.delete(t), e.terminate());
  17092. }(this), Promise.resolve();
  17093. }
  17094. }
  17095. /**
  17096. * Modify this instance to communicate with the Cloud Firestore emulator.
  17097. *
  17098. * Note: This must be called before this instance has been used to do any
  17099. * operations.
  17100. *
  17101. * @param firestore - The `Firestore` instance to configure to connect to the
  17102. * emulator.
  17103. * @param host - the emulator host (ex: localhost).
  17104. * @param port - the emulator port (ex: 9000).
  17105. * @param options.mockUserToken - the mock auth token to use for unit testing
  17106. * Security Rules.
  17107. */ function lh(t, e, n, s = {}) {
  17108. var i;
  17109. const r = (t = uh(t, hh))._getSettings(), o = `${e}:${n}`;
  17110. if ("firestore.googleapis.com" !== r.host && r.host !== o && M("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),
  17111. t._setSettings(Object.assign(Object.assign({}, r), {
  17112. host: o,
  17113. ssl: !1
  17114. })), s.mockUserToken) {
  17115. let e, n;
  17116. if ("string" == typeof s.mockUserToken) e = s.mockUserToken, n = V.MOCK_USER; else {
  17117. // Let createMockUserToken validate first (catches common mistakes like
  17118. // invalid field "uid" and missing field "sub" / "user_id".)
  17119. e = util.createMockUserToken(s.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId);
  17120. const r = s.mockUserToken.sub || s.mockUserToken.user_id;
  17121. if (!r) throw new U(q.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
  17122. n = new V(r);
  17123. }
  17124. t._authCredentials = new j(new G(e, n));
  17125. }
  17126. }
  17127. /**
  17128. * @license
  17129. * Copyright 2020 Google LLC
  17130. *
  17131. * Licensed under the Apache License, Version 2.0 (the "License");
  17132. * you may not use this file except in compliance with the License.
  17133. * You may obtain a copy of the License at
  17134. *
  17135. * http://www.apache.org/licenses/LICENSE-2.0
  17136. *
  17137. * Unless required by applicable law or agreed to in writing, software
  17138. * distributed under the License is distributed on an "AS IS" BASIS,
  17139. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17140. * See the License for the specific language governing permissions and
  17141. * limitations under the License.
  17142. */
  17143. /**
  17144. * A `DocumentReference` refers to a document location in a Firestore database
  17145. * and can be used to write, read, or listen to the location. The document at
  17146. * the referenced location may or may not exist.
  17147. */ class fh {
  17148. /** @hideconstructor */
  17149. constructor(t,
  17150. /**
  17151. * If provided, the `FirestoreDataConverter` associated with this instance.
  17152. */
  17153. e, n) {
  17154. this.converter = e, this._key = n,
  17155. /** The type of this Firestore reference. */
  17156. this.type = "document", this.firestore = t;
  17157. }
  17158. get _path() {
  17159. return this._key.path;
  17160. }
  17161. /**
  17162. * The document's identifier within its collection.
  17163. */ get id() {
  17164. return this._key.path.lastSegment();
  17165. }
  17166. /**
  17167. * A string representing the path of the referenced document (relative
  17168. * to the root of the database).
  17169. */ get path() {
  17170. return this._key.path.canonicalString();
  17171. }
  17172. /**
  17173. * The collection this `DocumentReference` belongs to.
  17174. */ get parent() {
  17175. return new wh(this.firestore, this.converter, this._key.path.popLast());
  17176. }
  17177. withConverter(t) {
  17178. return new fh(this.firestore, t, this._key);
  17179. }
  17180. }
  17181. /**
  17182. * A `Query` refers to a query which you can read or listen to. You can also
  17183. * construct refined `Query` objects by adding filters and ordering.
  17184. */ class dh {
  17185. // This is the lite version of the Query class in the main SDK.
  17186. /** @hideconstructor protected */
  17187. constructor(t,
  17188. /**
  17189. * If provided, the `FirestoreDataConverter` associated with this instance.
  17190. */
  17191. e, n) {
  17192. this.converter = e, this._query = n,
  17193. /** The type of this Firestore reference. */
  17194. this.type = "query", this.firestore = t;
  17195. }
  17196. withConverter(t) {
  17197. return new dh(this.firestore, t, this._query);
  17198. }
  17199. }
  17200. /**
  17201. * A `CollectionReference` object can be used for adding documents, getting
  17202. * document references, and querying for documents (using {@link (query:1)}).
  17203. */ class wh extends dh {
  17204. /** @hideconstructor */
  17205. constructor(t, e, n) {
  17206. super(t, e, Gn(n)), this._path = n,
  17207. /** The type of this Firestore reference. */
  17208. this.type = "collection";
  17209. }
  17210. /** The collection's identifier. */ get id() {
  17211. return this._query.path.lastSegment();
  17212. }
  17213. /**
  17214. * A string representing the path of the referenced collection (relative
  17215. * to the root of the database).
  17216. */ get path() {
  17217. return this._query.path.canonicalString();
  17218. }
  17219. /**
  17220. * A reference to the containing `DocumentReference` if this is a
  17221. * subcollection. If this isn't a subcollection, the reference is null.
  17222. */ get parent() {
  17223. const t = this._path.popLast();
  17224. return t.isEmpty() ? null : new fh(this.firestore,
  17225. /* converter= */ null, new ht(t));
  17226. }
  17227. withConverter(t) {
  17228. return new wh(this.firestore, t, this._path);
  17229. }
  17230. }
  17231. function _h(t, e, ...n) {
  17232. if (t = util.getModularInstance(t), nh("collection", "path", e), t instanceof hh) {
  17233. const s = ut.fromString(e, ...n);
  17234. return rh(s), new wh(t, /* converter= */ null, s);
  17235. }
  17236. {
  17237. if (!(t instanceof fh || t instanceof wh)) throw new U(q.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  17238. const s = t._path.child(ut.fromString(e, ...n));
  17239. return rh(s), new wh(t.firestore,
  17240. /* converter= */ null, s);
  17241. }
  17242. }
  17243. // TODO(firestorelite): Consider using ErrorFactory -
  17244. // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
  17245. /**
  17246. * Creates and returns a new `Query` instance that includes all documents in the
  17247. * database that are contained in a collection or subcollection with the
  17248. * given `collectionId`.
  17249. *
  17250. * @param firestore - A reference to the root `Firestore` instance.
  17251. * @param collectionId - Identifies the collections to query over. Every
  17252. * collection or subcollection with this ID as the last segment of its path
  17253. * will be included. Cannot contain a slash.
  17254. * @returns The created `Query`.
  17255. */ function mh(t, e) {
  17256. if (t = uh(t, hh), nh("collectionGroup", "collection id", e), e.indexOf("/") >= 0) throw new U(q.INVALID_ARGUMENT, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);
  17257. return new dh(t,
  17258. /* converter= */ null, function(t) {
  17259. return new Un(ut.emptyPath(), t);
  17260. }(e));
  17261. }
  17262. function gh(t, e, ...n) {
  17263. if (t = util.getModularInstance(t),
  17264. // We allow omission of 'pathString' but explicitly prohibit passing in both
  17265. // 'undefined' and 'null'.
  17266. 1 === arguments.length && (e = tt.A()), nh("doc", "path", e), t instanceof hh) {
  17267. const s = ut.fromString(e, ...n);
  17268. return ih(s), new fh(t,
  17269. /* converter= */ null, new ht(s));
  17270. }
  17271. {
  17272. if (!(t instanceof fh || t instanceof wh)) throw new U(q.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  17273. const s = t._path.child(ut.fromString(e, ...n));
  17274. return ih(s), new fh(t.firestore, t instanceof wh ? t.converter : null, new ht(s));
  17275. }
  17276. }
  17277. /**
  17278. * Returns true if the provided references are equal.
  17279. *
  17280. * @param left - A reference to compare.
  17281. * @param right - A reference to compare.
  17282. * @returns true if the references point to the same location in the same
  17283. * Firestore database.
  17284. */ function yh(t, e) {
  17285. return t = util.getModularInstance(t), e = util.getModularInstance(e), (t instanceof fh || t instanceof wh) && (e instanceof fh || e instanceof wh) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter);
  17286. }
  17287. /**
  17288. * Returns true if the provided queries point to the same collection and apply
  17289. * the same constraints.
  17290. *
  17291. * @param left - A `Query` to compare.
  17292. * @param right - A `Query` to compare.
  17293. * @returns true if the references point to the same location in the same
  17294. * Firestore database.
  17295. */ function ph(t, e) {
  17296. return t = util.getModularInstance(t), e = util.getModularInstance(e), t instanceof dh && e instanceof dh && (t.firestore === e.firestore && Zn(t._query, e._query) && t.converter === e.converter);
  17297. }
  17298. /**
  17299. * @license
  17300. * Copyright 2020 Google LLC
  17301. *
  17302. * Licensed under the Apache License, Version 2.0 (the "License");
  17303. * you may not use this file except in compliance with the License.
  17304. * You may obtain a copy of the License at
  17305. *
  17306. * http://www.apache.org/licenses/LICENSE-2.0
  17307. *
  17308. * Unless required by applicable law or agreed to in writing, software
  17309. * distributed under the License is distributed on an "AS IS" BASIS,
  17310. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17311. * See the License for the specific language governing permissions and
  17312. * limitations under the License.
  17313. */ class Ih {
  17314. constructor() {
  17315. // The last promise in the queue.
  17316. this.Gc = Promise.resolve(),
  17317. // A list of retryable operations. Retryable operations are run in order and
  17318. // retried with backoff.
  17319. this.Qc = [],
  17320. // Is this AsyncQueue being shut down? Once it is set to true, it will not
  17321. // be changed again.
  17322. this.jc = !1,
  17323. // Operations scheduled to be queued in the future. Operations are
  17324. // automatically removed after they are run or canceled.
  17325. this.zc = [],
  17326. // visible for testing
  17327. this.Wc = null,
  17328. // Flag set while there's an outstanding AsyncQueue operation, used for
  17329. // assertion sanity-checks.
  17330. this.Hc = !1,
  17331. // Enabled during shutdown on Safari to prevent future access to IndexedDB.
  17332. this.Jc = !1,
  17333. // List of TimerIds to fast-forward delays for.
  17334. this.Yc = [],
  17335. // Backoff timer used to schedule retries for retryable operations
  17336. this.qo = new Bu(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */),
  17337. // Visibility handler that triggers an immediate retry of all retryable
  17338. // operations. Meant to speed up recovery when we regain file system access
  17339. // after page comes into foreground.
  17340. this.Xc = () => {
  17341. const t = Ou();
  17342. t && N("AsyncQueue", "Visibility state changed to " + t.visibilityState), this.qo.Mo();
  17343. };
  17344. const t = Ou();
  17345. t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.Xc);
  17346. }
  17347. get isShuttingDown() {
  17348. return this.jc;
  17349. }
  17350. /**
  17351. * Adds a new operation to the queue without waiting for it to complete (i.e.
  17352. * we ignore the Promise result).
  17353. */ enqueueAndForget(t) {
  17354. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  17355. this.enqueue(t);
  17356. }
  17357. enqueueAndForgetEvenWhileRestricted(t) {
  17358. this.Zc(),
  17359. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  17360. this.ta(t);
  17361. }
  17362. enterRestrictedMode(t) {
  17363. if (!this.jc) {
  17364. this.jc = !0, this.Jc = t || !1;
  17365. const e = Ou();
  17366. e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Xc);
  17367. }
  17368. }
  17369. enqueue(t) {
  17370. if (this.Zc(), this.jc)
  17371. // Return a Promise which never resolves.
  17372. return new Promise((() => {}));
  17373. // Create a deferred Promise that we can return to the callee. This
  17374. // allows us to return a "hanging Promise" only to the callee and still
  17375. // advance the queue even when the operation is not run.
  17376. const e = new K;
  17377. return this.ta((() => this.jc && this.Jc ? Promise.resolve() : (t().then(e.resolve, e.reject),
  17378. e.promise))).then((() => e.promise));
  17379. }
  17380. enqueueRetryable(t) {
  17381. this.enqueueAndForget((() => (this.Qc.push(t), this.ea())));
  17382. }
  17383. /**
  17384. * Runs the next operation from the retryable queue. If the operation fails,
  17385. * reschedules with backoff.
  17386. */ async ea() {
  17387. if (0 !== this.Qc.length) {
  17388. try {
  17389. await this.Qc[0](), this.Qc.shift(), this.qo.reset();
  17390. } catch (t) {
  17391. if (!Dt(t)) throw t;
  17392. // Failure will be handled by AsyncQueue
  17393. N("AsyncQueue", "Operation failed with retryable error: " + t);
  17394. }
  17395. this.Qc.length > 0 &&
  17396. // If there are additional operations, we re-schedule `retryNextOp()`.
  17397. // This is necessary to run retryable operations that failed during
  17398. // their initial attempt since we don't know whether they are already
  17399. // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
  17400. // needs to be re-run, we will run `op1`, `op1`, `op2` using the
  17401. // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
  17402. // call scheduled here.
  17403. // Since `backoffAndRun()` cancels an existing backoff and schedules a
  17404. // new backoff on every call, there is only ever a single additional
  17405. // operation in the queue.
  17406. this.qo.No((() => this.ea()));
  17407. }
  17408. }
  17409. ta(t) {
  17410. const e = this.Gc.then((() => (this.Hc = !0, t().catch((t => {
  17411. this.Wc = t, this.Hc = !1;
  17412. const e =
  17413. /**
  17414. * Chrome includes Error.message in Error.stack. Other browsers do not.
  17415. * This returns expected output of message + stack when available.
  17416. * @param error - Error or FirestoreError
  17417. */
  17418. function(t) {
  17419. let e = t.message || "";
  17420. t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack);
  17421. return e;
  17422. }
  17423. /**
  17424. * @license
  17425. * Copyright 2017 Google LLC
  17426. *
  17427. * Licensed under the Apache License, Version 2.0 (the "License");
  17428. * you may not use this file except in compliance with the License.
  17429. * You may obtain a copy of the License at
  17430. *
  17431. * http://www.apache.org/licenses/LICENSE-2.0
  17432. *
  17433. * Unless required by applicable law or agreed to in writing, software
  17434. * distributed under the License is distributed on an "AS IS" BASIS,
  17435. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17436. * See the License for the specific language governing permissions and
  17437. * limitations under the License.
  17438. */ (t);
  17439. // Re-throw the error so that this.tail becomes a rejected Promise and
  17440. // all further attempts to chain (via .then) will just short-circuit
  17441. // and return the rejected Promise.
  17442. throw k("INTERNAL UNHANDLED ERROR: ", e), t;
  17443. })).then((t => (this.Hc = !1, t))))));
  17444. return this.Gc = e, e;
  17445. }
  17446. enqueueAfterDelay(t, e, n) {
  17447. this.Zc(),
  17448. // Fast-forward delays for timerIds that have been overriden.
  17449. this.Yc.indexOf(t) > -1 && (e = 0);
  17450. const s = Tc.createAndSchedule(this, t, e, n, (t => this.na(t)));
  17451. return this.zc.push(s), s;
  17452. }
  17453. Zc() {
  17454. this.Wc && O();
  17455. }
  17456. verifyOperationInProgress() {}
  17457. /**
  17458. * Waits until all currently queued tasks are finished executing. Delayed
  17459. * operations are not run.
  17460. */ async sa() {
  17461. // Operations in the queue prior to draining may have enqueued additional
  17462. // operations. Keep draining the queue until the tail is no longer advanced,
  17463. // which indicates that no more new operations were enqueued and that all
  17464. // operations were executed.
  17465. let t;
  17466. do {
  17467. t = this.Gc, await t;
  17468. } while (t !== this.Gc);
  17469. }
  17470. /**
  17471. * For Tests: Determine if a delayed operation with a particular TimerId
  17472. * exists.
  17473. */ ia(t) {
  17474. for (const e of this.zc) if (e.timerId === t) return !0;
  17475. return !1;
  17476. }
  17477. /**
  17478. * For Tests: Runs some or all delayed operations early.
  17479. *
  17480. * @param lastTimerId - Delayed operations up to and including this TimerId
  17481. * will be drained. Pass TimerId.All to run all delayed operations.
  17482. * @returns a Promise that resolves once all operations have been run.
  17483. */ ra(t) {
  17484. // Note that draining may generate more delayed ops, so we do that first.
  17485. return this.sa().then((() => {
  17486. // Run ops in the same order they'd run if they ran naturally.
  17487. this.zc.sort(((t, e) => t.targetTimeMs - e.targetTimeMs));
  17488. for (const e of this.zc) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break;
  17489. return this.sa();
  17490. }));
  17491. }
  17492. /**
  17493. * For Tests: Skip all subsequent delays for a timer id.
  17494. */ oa(t) {
  17495. this.Yc.push(t);
  17496. }
  17497. /** Called once a DelayedOperation is run or canceled. */ na(t) {
  17498. // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
  17499. const e = this.zc.indexOf(t);
  17500. this.zc.splice(e, 1);
  17501. }
  17502. }
  17503. function Th(t) {
  17504. /**
  17505. * Returns true if obj is an object and contains at least one of the specified
  17506. * methods.
  17507. */
  17508. return function(t, e) {
  17509. if ("object" != typeof t || null === t) return !1;
  17510. const n = t;
  17511. for (const t of e) if (t in n && "function" == typeof n[t]) return !0;
  17512. return !1;
  17513. }
  17514. /**
  17515. * @license
  17516. * Copyright 2020 Google LLC
  17517. *
  17518. * Licensed under the Apache License, Version 2.0 (the "License");
  17519. * you may not use this file except in compliance with the License.
  17520. * You may obtain a copy of the License at
  17521. *
  17522. * http://www.apache.org/licenses/LICENSE-2.0
  17523. *
  17524. * Unless required by applicable law or agreed to in writing, software
  17525. * distributed under the License is distributed on an "AS IS" BASIS,
  17526. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17527. * See the License for the specific language governing permissions and
  17528. * limitations under the License.
  17529. */
  17530. /**
  17531. * Represents the task of loading a Firestore bundle. It provides progress of bundle
  17532. * loading, as well as task completion and error events.
  17533. *
  17534. * The API is compatible with `Promise<LoadBundleTaskProgress>`.
  17535. */ (t, [ "next", "error", "complete" ]);
  17536. }
  17537. class Eh {
  17538. constructor() {
  17539. this._progressObserver = {}, this._taskCompletionResolver = new K, this._lastProgress = {
  17540. taskState: "Running",
  17541. totalBytes: 0,
  17542. totalDocuments: 0,
  17543. bytesLoaded: 0,
  17544. documentsLoaded: 0
  17545. };
  17546. }
  17547. /**
  17548. * Registers functions to listen to bundle loading progress events.
  17549. * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
  17550. * each time a Firestore document is loaded from the bundle.
  17551. * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
  17552. * error, and there should be no more updates after this.
  17553. * @param complete - Called when the loading task is complete.
  17554. */ onProgress(t, e, n) {
  17555. this._progressObserver = {
  17556. next: t,
  17557. error: e,
  17558. complete: n
  17559. };
  17560. }
  17561. /**
  17562. * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
  17563. *
  17564. * @param onRejected - Called when an error occurs during bundle loading.
  17565. */ catch(t) {
  17566. return this._taskCompletionResolver.promise.catch(t);
  17567. }
  17568. /**
  17569. * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
  17570. *
  17571. * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
  17572. * The update will always have its `taskState` set to `"Success"`.
  17573. * @param onRejected - Called when an error occurs during bundle loading.
  17574. */ then(t, e) {
  17575. return this._taskCompletionResolver.promise.then(t, e);
  17576. }
  17577. /**
  17578. * Notifies all observers that bundle loading has completed, with a provided
  17579. * `LoadBundleTaskProgress` object.
  17580. *
  17581. * @private
  17582. */ _completeWith(t) {
  17583. this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(),
  17584. this._taskCompletionResolver.resolve(t);
  17585. }
  17586. /**
  17587. * Notifies all observers that bundle loading has failed, with a provided
  17588. * `Error` as the reason.
  17589. *
  17590. * @private
  17591. */ _failWith(t) {
  17592. this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress),
  17593. this._progressObserver.error && this._progressObserver.error(t), this._taskCompletionResolver.reject(t);
  17594. }
  17595. /**
  17596. * Notifies a progress update of loading a bundle.
  17597. * @param progress - The new progress.
  17598. *
  17599. * @private
  17600. */ _updateProgress(t) {
  17601. this._lastProgress = t, this._progressObserver.next && this._progressObserver.next(t);
  17602. }
  17603. }
  17604. /**
  17605. * @license
  17606. * Copyright 2020 Google LLC
  17607. *
  17608. * Licensed under the Apache License, Version 2.0 (the "License");
  17609. * you may not use this file except in compliance with the License.
  17610. * You may obtain a copy of the License at
  17611. *
  17612. * http://www.apache.org/licenses/LICENSE-2.0
  17613. *
  17614. * Unless required by applicable law or agreed to in writing, software
  17615. * distributed under the License is distributed on an "AS IS" BASIS,
  17616. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17617. * See the License for the specific language governing permissions and
  17618. * limitations under the License.
  17619. */
  17620. /**
  17621. * Constant used to indicate the LRU garbage collection should be disabled.
  17622. * Set this value as the `cacheSizeBytes` on the settings passed to the
  17623. * {@link Firestore} instance.
  17624. */ const Ah = -1;
  17625. /**
  17626. * The Cloud Firestore service interface.
  17627. *
  17628. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  17629. */ class vh extends hh {
  17630. /** @hideconstructor */
  17631. constructor(t, e, n, s) {
  17632. super(t, e, n, s),
  17633. /**
  17634. * Whether it's a {@link Firestore} or Firestore Lite instance.
  17635. */
  17636. this.type = "firestore", this._queue = new Ih, this._persistenceKey = (null == s ? void 0 : s.name) || "[DEFAULT]";
  17637. }
  17638. _terminate() {
  17639. return this._firestoreClient ||
  17640. // The client must be initialized to ensure that all subsequent API
  17641. // usage throws an exception.
  17642. Vh(this), this._firestoreClient.terminate();
  17643. }
  17644. }
  17645. /**
  17646. * Initializes a new instance of {@link Firestore} with the provided settings.
  17647. * Can only be called before any other function, including
  17648. * {@link (getFirestore:1)}. If the custom settings are empty, this function is
  17649. * equivalent to calling {@link (getFirestore:1)}.
  17650. *
  17651. * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
  17652. * be associated.
  17653. * @param settings - A settings object to configure the {@link Firestore} instance.
  17654. * @param databaseId - The name of the database.
  17655. * @returns A newly initialized {@link Firestore} instance.
  17656. */ function Rh(t, e, n) {
  17657. n || (n = "(default)");
  17658. const s = app._getProvider(t, "firestore");
  17659. if (s.isInitialized(n)) {
  17660. const t = s.getImmediate({
  17661. identifier: n
  17662. }), i = s.getOptions(n);
  17663. if (util.deepEqual(i, e)) return t;
  17664. throw new U(q.FAILED_PRECONDITION, "initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.");
  17665. }
  17666. if (void 0 !== e.cacheSizeBytes && void 0 !== e.localCache) throw new U(q.INVALID_ARGUMENT, "cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");
  17667. if (void 0 !== e.cacheSizeBytes && -1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new U(q.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  17668. return s.initialize({
  17669. options: e,
  17670. instanceIdentifier: n
  17671. });
  17672. }
  17673. function Ph(e, n) {
  17674. const s = "object" == typeof e ? e : app.getApp(), i = "string" == typeof e ? e : n || "(default)", r = app._getProvider(s, "firestore").getImmediate({
  17675. identifier: i
  17676. });
  17677. if (!r._initialized) {
  17678. const t = util.getDefaultEmulatorHostnameAndPort("firestore");
  17679. t && lh(r, ...t);
  17680. }
  17681. return r;
  17682. }
  17683. /**
  17684. * @internal
  17685. */ function bh(t) {
  17686. return t._firestoreClient || Vh(t), t._firestoreClient.verifyNotTerminated(), t._firestoreClient;
  17687. }
  17688. function Vh(t) {
  17689. var e, n, s;
  17690. const i = t._freezeSettings(), r = function(t, e, n, s) {
  17691. return new $e(t, e, n, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, th(s.experimentalLongPollingOptions), s.useFetchStreams);
  17692. }(t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || "", t._persistenceKey, i);
  17693. t._firestoreClient = new xa(t._authCredentials, t._appCheckCredentials, t._queue, r),
  17694. (null === (n = i.cache) || void 0 === n ? void 0 : n._offlineComponentProvider) && (null === (s = i.cache) || void 0 === s ? void 0 : s._onlineComponentProvider) && (t._firestoreClient._uninitializedComponentsProvider = {
  17695. _offlineKind: i.cache.kind,
  17696. _offline: i.cache._offlineComponentProvider,
  17697. _online: i.cache._onlineComponentProvider
  17698. });
  17699. }
  17700. /**
  17701. * Attempts to enable persistent storage, if possible.
  17702. *
  17703. * Must be called before any other functions (other than
  17704. * {@link initializeFirestore}, {@link (getFirestore:1)} or
  17705. * {@link clearIndexedDbPersistence}.
  17706. *
  17707. * If this fails, `enableIndexedDbPersistence()` will reject the promise it
  17708. * returns. Note that even after this failure, the {@link Firestore} instance will
  17709. * remain usable, however offline persistence will be disabled.
  17710. *
  17711. * There are several reasons why this can fail, which can be identified by
  17712. * the `code` on the error.
  17713. *
  17714. * * failed-precondition: The app is already open in another browser tab.
  17715. * * unimplemented: The browser is incompatible with the offline
  17716. * persistence implementation.
  17717. *
  17718. * Persistence cannot be used in a Node.js environment.
  17719. *
  17720. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17721. * @param persistenceSettings - Optional settings object to configure
  17722. * persistence.
  17723. * @returns A `Promise` that represents successfully enabling persistent storage.
  17724. * @deprecated This function will be removed in a future major release. Instead, set
  17725. * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to
  17726. * turn on IndexedDb cache. Calling this function when `FirestoreSettings.cache`
  17727. * is already specified will throw an exception.
  17728. */ function Sh(t, e) {
  17729. Bh(t = uh(t, vh));
  17730. const n = bh(t);
  17731. if (n._uninitializedComponentsProvider) throw new U(q.FAILED_PRECONDITION, "SDK cache is already specified.");
  17732. M("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
  17733. const s = t._freezeSettings(), i = new Pa;
  17734. return Ch(n, i, new va(i, s.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));
  17735. }
  17736. /**
  17737. * Attempts to enable multi-tab persistent storage, if possible. If enabled
  17738. * across all tabs, all operations share access to local persistence, including
  17739. * shared execution of queries and latency-compensated local document updates
  17740. * across all connected instances.
  17741. *
  17742. * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
  17743. * it returns. Note that even after this failure, the {@link Firestore} instance will
  17744. * remain usable, however offline persistence will be disabled.
  17745. *
  17746. * There are several reasons why this can fail, which can be identified by
  17747. * the `code` on the error.
  17748. *
  17749. * * failed-precondition: The app is already open in another browser tab and
  17750. * multi-tab is not enabled.
  17751. * * unimplemented: The browser is incompatible with the offline
  17752. * persistence implementation.
  17753. *
  17754. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17755. * @returns A `Promise` that represents successfully enabling persistent
  17756. * storage.
  17757. * @deprecated This function will be removed in a future major release. Instead, set
  17758. * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to
  17759. * turn on indexeddb cache. Calling this function when `FirestoreSettings.cache`
  17760. * is already specified will throw an exception.
  17761. */ function Dh(t) {
  17762. Bh(t = uh(t, vh));
  17763. const e = bh(t);
  17764. if (e._uninitializedComponentsProvider) throw new U(q.FAILED_PRECONDITION, "SDK cache is already specified.");
  17765. M("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
  17766. const n = t._freezeSettings(), s = new Pa;
  17767. return Ch(e, s, new Ra(s, n.cacheSizeBytes));
  17768. }
  17769. /**
  17770. * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.
  17771. * If the operation fails with a recoverable error (see
  17772. * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected
  17773. * but the client remains usable.
  17774. */ function Ch(t, e, n) {
  17775. const s = new K;
  17776. return t.asyncQueue.enqueue((async () => {
  17777. try {
  17778. await Na(t, n), await ka(t, e), s.resolve();
  17779. } catch (t) {
  17780. const e = t;
  17781. if (!Ma(e)) throw e;
  17782. M("Error enabling indexeddb cache. Falling back to memory cache: " + e), s.reject(e);
  17783. }
  17784. })).then((() => s.promise));
  17785. }
  17786. /**
  17787. * Clears the persistent storage. This includes pending writes and cached
  17788. * documents.
  17789. *
  17790. * Must be called while the {@link Firestore} instance is not started (after the app is
  17791. * terminated or when the app is first initialized). On startup, this function
  17792. * must be called before other functions (other than {@link
  17793. * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}
  17794. * instance is still running, the promise will be rejected with the error code
  17795. * of `failed-precondition`.
  17796. *
  17797. * Note: `clearIndexedDbPersistence()` is primarily intended to help write
  17798. * reliable tests that use Cloud Firestore. It uses an efficient mechanism for
  17799. * dropping existing data but does not attempt to securely overwrite or
  17800. * otherwise make cached data unrecoverable. For applications that are sensitive
  17801. * to the disclosure of cached data in between user sessions, we strongly
  17802. * recommend not enabling persistence at all.
  17803. *
  17804. * @param firestore - The {@link Firestore} instance to clear persistence for.
  17805. * @returns A `Promise` that is resolved when the persistent storage is
  17806. * cleared. Otherwise, the promise is rejected with an error.
  17807. */ function xh(t) {
  17808. if (t._initialized && !t._terminated) throw new U(q.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");
  17809. const e = new K;
  17810. return t._queue.enqueueAndForgetEvenWhileRestricted((async () => {
  17811. try {
  17812. await async function(t) {
  17813. if (!bt.D()) return Promise.resolve();
  17814. const e = t + "main";
  17815. await bt.delete(e);
  17816. }(Zo(t._databaseId, t._persistenceKey)), e.resolve();
  17817. } catch (t) {
  17818. e.reject(t);
  17819. }
  17820. })), e.promise;
  17821. }
  17822. /**
  17823. * Waits until all currently pending writes for the active user have been
  17824. * acknowledged by the backend.
  17825. *
  17826. * The returned promise resolves immediately if there are no outstanding writes.
  17827. * Otherwise, the promise waits for all previously issued writes (including
  17828. * those written in a previous app session), but it does not wait for writes
  17829. * that were added after the function is called. If you want to wait for
  17830. * additional writes, call `waitForPendingWrites()` again.
  17831. *
  17832. * Any outstanding `waitForPendingWrites()` promises are rejected during user
  17833. * changes.
  17834. *
  17835. * @returns A `Promise` which resolves when all currently pending writes have been
  17836. * acknowledged by the backend.
  17837. */ function Nh(t) {
  17838. return function(t) {
  17839. const e = new K;
  17840. return t.asyncQueue.enqueueAndForget((async () => Zc(await qa(t), e))), e.promise;
  17841. }(bh(t = uh(t, vh)));
  17842. }
  17843. /**
  17844. * Re-enables use of the network for this {@link Firestore} instance after a prior
  17845. * call to {@link disableNetwork}.
  17846. *
  17847. * @returns A `Promise` that is resolved once the network has been enabled.
  17848. */ function kh(t) {
  17849. return Ga(bh(t = uh(t, vh)));
  17850. }
  17851. /**
  17852. * Disables network usage for this instance. It can be re-enabled via {@link
  17853. * enableNetwork}. While the network is disabled, any snapshot listeners,
  17854. * `getDoc()` or `getDocs()` calls will return results from cache, and any write
  17855. * operations will be queued until the network is restored.
  17856. *
  17857. * @returns A `Promise` that is resolved once the network has been disabled.
  17858. */ function Mh(t) {
  17859. return Qa(bh(t = uh(t, vh)));
  17860. }
  17861. /**
  17862. * Terminates the provided {@link Firestore} instance.
  17863. *
  17864. * After calling `terminate()` only the `clearIndexedDbPersistence()` function
  17865. * may be used. Any other function will throw a `FirestoreError`.
  17866. *
  17867. * To restart after termination, create a new instance of FirebaseFirestore with
  17868. * {@link (getFirestore:1)}.
  17869. *
  17870. * Termination does not cancel any pending writes, and any promises that are
  17871. * awaiting a response from the server will not be resolved. If you have
  17872. * persistence enabled, the next time you start this instance, it will resume
  17873. * sending these writes to the server.
  17874. *
  17875. * Note: Under normal circumstances, calling `terminate()` is not required. This
  17876. * function is useful only when you want to force this instance to release all
  17877. * of its resources or in combination with `clearIndexedDbPersistence()` to
  17878. * ensure that all local state is destroyed between test runs.
  17879. *
  17880. * @returns A `Promise` that is resolved when the instance has been successfully
  17881. * terminated.
  17882. */ function $h(t) {
  17883. return app._removeServiceInstance(t.app, "firestore", t._databaseId.database), t._delete();
  17884. }
  17885. /**
  17886. * Loads a Firestore bundle into the local cache.
  17887. *
  17888. * @param firestore - The {@link Firestore} instance to load bundles for.
  17889. * @param bundleData - An object representing the bundle to be loaded. Valid
  17890. * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.
  17891. *
  17892. * @returns A `LoadBundleTask` object, which notifies callers with progress
  17893. * updates, and completion or error events. It can be used as a
  17894. * `Promise<LoadBundleTaskProgress>`.
  17895. */ function Oh(t, e) {
  17896. const n = bh(t = uh(t, vh)), s = new Eh;
  17897. return Ya(n, t._databaseId, e, s), s;
  17898. }
  17899. /**
  17900. * Reads a Firestore {@link Query} from local cache, identified by the given
  17901. * name.
  17902. *
  17903. * The named queries are packaged into bundles on the server side (along
  17904. * with resulting documents), and loaded to local cache using `loadBundle`. Once
  17905. * in local cache, use this method to extract a {@link Query} by name.
  17906. *
  17907. * @param firestore - The {@link Firestore} instance to read the query from.
  17908. * @param name - The name of the query.
  17909. * @returns A `Promise` that is resolved with the Query or `null`.
  17910. */ function Fh(t, e) {
  17911. return Xa(bh(t = uh(t, vh)), e).then((e => e ? new dh(t, null, e.query) : null));
  17912. }
  17913. function Bh(t) {
  17914. if (t._initialized || t._terminated) throw new U(q.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");
  17915. }
  17916. /**
  17917. * @license
  17918. * Copyright 2020 Google LLC
  17919. *
  17920. * Licensed under the Apache License, Version 2.0 (the "License");
  17921. * you may not use this file except in compliance with the License.
  17922. * You may obtain a copy of the License at
  17923. *
  17924. * http://www.apache.org/licenses/LICENSE-2.0
  17925. *
  17926. * Unless required by applicable law or agreed to in writing, software
  17927. * distributed under the License is distributed on an "AS IS" BASIS,
  17928. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17929. * See the License for the specific language governing permissions and
  17930. * limitations under the License.
  17931. */
  17932. /**
  17933. * @license
  17934. * Copyright 2022 Google LLC
  17935. *
  17936. * Licensed under the Apache License, Version 2.0 (the "License");
  17937. * you may not use this file except in compliance with the License.
  17938. * You may obtain a copy of the License at
  17939. *
  17940. * http://www.apache.org/licenses/LICENSE-2.0
  17941. *
  17942. * Unless required by applicable law or agreed to in writing, software
  17943. * distributed under the License is distributed on an "AS IS" BASIS,
  17944. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17945. * See the License for the specific language governing permissions and
  17946. * limitations under the License.
  17947. */
  17948. /**
  17949. * Represents an aggregation that can be performed by Firestore.
  17950. */
  17951. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  17952. class Lh {
  17953. /**
  17954. * Create a new AggregateField<T>
  17955. * @param _aggregateType Specifies the type of aggregation operation to perform.
  17956. * @param _internalFieldPath Optionally specifies the field that is aggregated.
  17957. * @internal
  17958. */
  17959. constructor(
  17960. // TODO (sum/avg) make aggregateType public when the feature is supported
  17961. t = "count", e) {
  17962. this._aggregateType = t, this._internalFieldPath = e,
  17963. /** A type string to uniquely identify instances of this class. */
  17964. this.type = "AggregateField";
  17965. }
  17966. }
  17967. /**
  17968. * The results of executing an aggregation query.
  17969. */ class qh {
  17970. /** @hideconstructor */
  17971. constructor(t, e, n) {
  17972. this._userDataWriter = e, this._data = n,
  17973. /** A type string to uniquely identify instances of this class. */
  17974. this.type = "AggregateQuerySnapshot", this.query = t;
  17975. }
  17976. /**
  17977. * Returns the results of the aggregations performed over the underlying
  17978. * query.
  17979. *
  17980. * The keys of the returned object will be the same as those of the
  17981. * `AggregateSpec` object specified to the aggregation method, and the values
  17982. * will be the corresponding aggregation result.
  17983. *
  17984. * @returns The results of the aggregations performed over the underlying
  17985. * query.
  17986. */ data() {
  17987. return this._userDataWriter.convertObjectMap(this._data);
  17988. }
  17989. }
  17990. /**
  17991. * @license
  17992. * Copyright 2020 Google LLC
  17993. *
  17994. * Licensed under the Apache License, Version 2.0 (the "License");
  17995. * you may not use this file except in compliance with the License.
  17996. * You may obtain a copy of the License at
  17997. *
  17998. * http://www.apache.org/licenses/LICENSE-2.0
  17999. *
  18000. * Unless required by applicable law or agreed to in writing, software
  18001. * distributed under the License is distributed on an "AS IS" BASIS,
  18002. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18003. * See the License for the specific language governing permissions and
  18004. * limitations under the License.
  18005. */
  18006. /**
  18007. * An immutable object representing an array of bytes.
  18008. */ class Uh {
  18009. /** @hideconstructor */
  18010. constructor(t) {
  18011. this._byteString = t;
  18012. }
  18013. /**
  18014. * Creates a new `Bytes` object from the given Base64 string, converting it to
  18015. * bytes.
  18016. *
  18017. * @param base64 - The Base64 string used to create the `Bytes` object.
  18018. */ static fromBase64String(t) {
  18019. try {
  18020. return new Uh(Ve.fromBase64String(t));
  18021. } catch (t) {
  18022. throw new U(q.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + t);
  18023. }
  18024. }
  18025. /**
  18026. * Creates a new `Bytes` object from the given Uint8Array.
  18027. *
  18028. * @param array - The Uint8Array used to create the `Bytes` object.
  18029. */ static fromUint8Array(t) {
  18030. return new Uh(Ve.fromUint8Array(t));
  18031. }
  18032. /**
  18033. * Returns the underlying bytes as a Base64-encoded string.
  18034. *
  18035. * @returns The Base64-encoded string created from the `Bytes` object.
  18036. */ toBase64() {
  18037. return this._byteString.toBase64();
  18038. }
  18039. /**
  18040. * Returns the underlying bytes in a new `Uint8Array`.
  18041. *
  18042. * @returns The Uint8Array created from the `Bytes` object.
  18043. */ toUint8Array() {
  18044. return this._byteString.toUint8Array();
  18045. }
  18046. /**
  18047. * Returns a string representation of the `Bytes` object.
  18048. *
  18049. * @returns A string representation of the `Bytes` object.
  18050. */ toString() {
  18051. return "Bytes(base64: " + this.toBase64() + ")";
  18052. }
  18053. /**
  18054. * Returns true if this `Bytes` object is equal to the provided one.
  18055. *
  18056. * @param other - The `Bytes` object to compare against.
  18057. * @returns true if this `Bytes` object is equal to the provided one.
  18058. */ isEqual(t) {
  18059. return this._byteString.isEqual(t._byteString);
  18060. }
  18061. }
  18062. /**
  18063. * @license
  18064. * Copyright 2020 Google LLC
  18065. *
  18066. * Licensed under the Apache License, Version 2.0 (the "License");
  18067. * you may not use this file except in compliance with the License.
  18068. * You may obtain a copy of the License at
  18069. *
  18070. * http://www.apache.org/licenses/LICENSE-2.0
  18071. *
  18072. * Unless required by applicable law or agreed to in writing, software
  18073. * distributed under the License is distributed on an "AS IS" BASIS,
  18074. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18075. * See the License for the specific language governing permissions and
  18076. * limitations under the License.
  18077. */
  18078. /**
  18079. * A `FieldPath` refers to a field in a document. The path may consist of a
  18080. * single field name (referring to a top-level field in the document), or a
  18081. * list of field names (referring to a nested field in the document).
  18082. *
  18083. * Create a `FieldPath` by providing field names. If more than one field
  18084. * name is provided, the path will point to a nested field in a document.
  18085. */ class Kh {
  18086. /**
  18087. * Creates a `FieldPath` from the provided field names. If more than one field
  18088. * name is provided, the path will point to a nested field in a document.
  18089. *
  18090. * @param fieldNames - A list of field names.
  18091. */
  18092. constructor(...t) {
  18093. for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new U(q.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
  18094. this._internalPath = new at(t);
  18095. }
  18096. /**
  18097. * Returns true if this `FieldPath` is equal to the provided one.
  18098. *
  18099. * @param other - The `FieldPath` to compare against.
  18100. * @returns true if this `FieldPath` is equal to the provided one.
  18101. */ isEqual(t) {
  18102. return this._internalPath.isEqual(t._internalPath);
  18103. }
  18104. }
  18105. /**
  18106. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  18107. * It can be used in queries to sort or filter by the document ID.
  18108. */ function Gh() {
  18109. return new Kh("__name__");
  18110. }
  18111. /**
  18112. * @license
  18113. * Copyright 2020 Google LLC
  18114. *
  18115. * Licensed under the Apache License, Version 2.0 (the "License");
  18116. * you may not use this file except in compliance with the License.
  18117. * You may obtain a copy of the License at
  18118. *
  18119. * http://www.apache.org/licenses/LICENSE-2.0
  18120. *
  18121. * Unless required by applicable law or agreed to in writing, software
  18122. * distributed under the License is distributed on an "AS IS" BASIS,
  18123. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18124. * See the License for the specific language governing permissions and
  18125. * limitations under the License.
  18126. */
  18127. /**
  18128. * Sentinel values that can be used when writing document fields with `set()`
  18129. * or `update()`.
  18130. */ class Qh {
  18131. /**
  18132. * @param _methodName - The public API endpoint that returns this class.
  18133. * @hideconstructor
  18134. */
  18135. constructor(t) {
  18136. this._methodName = t;
  18137. }
  18138. }
  18139. /**
  18140. * @license
  18141. * Copyright 2017 Google LLC
  18142. *
  18143. * Licensed under the Apache License, Version 2.0 (the "License");
  18144. * you may not use this file except in compliance with the License.
  18145. * You may obtain a copy of the License at
  18146. *
  18147. * http://www.apache.org/licenses/LICENSE-2.0
  18148. *
  18149. * Unless required by applicable law or agreed to in writing, software
  18150. * distributed under the License is distributed on an "AS IS" BASIS,
  18151. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18152. * See the License for the specific language governing permissions and
  18153. * limitations under the License.
  18154. */
  18155. /**
  18156. * An immutable object representing a geographic location in Firestore. The
  18157. * location is represented as latitude/longitude pair.
  18158. *
  18159. * Latitude values are in the range of [-90, 90].
  18160. * Longitude values are in the range of [-180, 180].
  18161. */ class jh {
  18162. /**
  18163. * Creates a new immutable `GeoPoint` object with the provided latitude and
  18164. * longitude values.
  18165. * @param latitude - The latitude as number between -90 and 90.
  18166. * @param longitude - The longitude as number between -180 and 180.
  18167. */
  18168. constructor(t, e) {
  18169. if (!isFinite(t) || t < -90 || t > 90) throw new U(q.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + t);
  18170. if (!isFinite(e) || e < -180 || e > 180) throw new U(q.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + e);
  18171. this._lat = t, this._long = e;
  18172. }
  18173. /**
  18174. * The latitude of this `GeoPoint` instance.
  18175. */ get latitude() {
  18176. return this._lat;
  18177. }
  18178. /**
  18179. * The longitude of this `GeoPoint` instance.
  18180. */ get longitude() {
  18181. return this._long;
  18182. }
  18183. /**
  18184. * Returns true if this `GeoPoint` is equal to the provided one.
  18185. *
  18186. * @param other - The `GeoPoint` to compare against.
  18187. * @returns true if this `GeoPoint` is equal to the provided one.
  18188. */ isEqual(t) {
  18189. return this._lat === t._lat && this._long === t._long;
  18190. }
  18191. /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {
  18192. return {
  18193. latitude: this._lat,
  18194. longitude: this._long
  18195. };
  18196. }
  18197. /**
  18198. * Actually private to JS consumers of our API, so this function is prefixed
  18199. * with an underscore.
  18200. */ _compareTo(t) {
  18201. return et(this._lat, t._lat) || et(this._long, t._long);
  18202. }
  18203. }
  18204. /**
  18205. * @license
  18206. * Copyright 2017 Google LLC
  18207. *
  18208. * Licensed under the Apache License, Version 2.0 (the "License");
  18209. * you may not use this file except in compliance with the License.
  18210. * You may obtain a copy of the License at
  18211. *
  18212. * http://www.apache.org/licenses/LICENSE-2.0
  18213. *
  18214. * Unless required by applicable law or agreed to in writing, software
  18215. * distributed under the License is distributed on an "AS IS" BASIS,
  18216. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18217. * See the License for the specific language governing permissions and
  18218. * limitations under the License.
  18219. */ const zh = /^__.*__$/;
  18220. /** The result of parsing document data (e.g. for a setData call). */ class Wh {
  18221. constructor(t, e, n) {
  18222. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  18223. }
  18224. toMutation(t, e) {
  18225. return null !== this.fieldMask ? new zs(t, this.data, this.fieldMask, e, this.fieldTransforms) : new js(t, this.data, e, this.fieldTransforms);
  18226. }
  18227. }
  18228. /** The result of parsing "update" data (i.e. for an updateData call). */ class Hh {
  18229. constructor(t,
  18230. // The fieldMask does not include document transforms.
  18231. e, n) {
  18232. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  18233. }
  18234. toMutation(t, e) {
  18235. return new zs(t, this.data, this.fieldMask, e, this.fieldTransforms);
  18236. }
  18237. }
  18238. function Jh(t) {
  18239. switch (t) {
  18240. case 0 /* UserDataSource.Set */ :
  18241. // fall through
  18242. case 2 /* UserDataSource.MergeSet */ :
  18243. // fall through
  18244. case 1 /* UserDataSource.Update */ :
  18245. return !0;
  18246. case 3 /* UserDataSource.Argument */ :
  18247. case 4 /* UserDataSource.ArrayArgument */ :
  18248. return !1;
  18249. default:
  18250. throw O();
  18251. }
  18252. }
  18253. /** A "context" object passed around while parsing user data. */ class Yh {
  18254. /**
  18255. * Initializes a ParseContext with the given source and path.
  18256. *
  18257. * @param settings - The settings for the parser.
  18258. * @param databaseId - The database ID of the Firestore instance.
  18259. * @param serializer - The serializer to use to generate the Value proto.
  18260. * @param ignoreUndefinedProperties - Whether to ignore undefined properties
  18261. * rather than throw.
  18262. * @param fieldTransforms - A mutable list of field transforms encountered
  18263. * while parsing the data.
  18264. * @param fieldMask - A mutable list of field paths encountered while parsing
  18265. * the data.
  18266. *
  18267. * TODO(b/34871131): We don't support array paths right now, so path can be
  18268. * null to indicate the context represents any location within an array (in
  18269. * which case certain features will not work and errors will be somewhat
  18270. * compromised).
  18271. */
  18272. constructor(t, e, n, s, i, r) {
  18273. this.settings = t, this.databaseId = e, this.serializer = n, this.ignoreUndefinedProperties = s,
  18274. // Minor hack: If fieldTransforms is undefined, we assume this is an
  18275. // external call and we need to validate the entire path.
  18276. void 0 === i && this.ua(), this.fieldTransforms = i || [], this.fieldMask = r || [];
  18277. }
  18278. get path() {
  18279. return this.settings.path;
  18280. }
  18281. get ca() {
  18282. return this.settings.ca;
  18283. }
  18284. /** Returns a new context with the specified settings overwritten. */ aa(t) {
  18285. return new Yh(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  18286. }
  18287. ha(t) {
  18288. var e;
  18289. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.aa({
  18290. path: n,
  18291. la: !1
  18292. });
  18293. return s.fa(t), s;
  18294. }
  18295. da(t) {
  18296. var e;
  18297. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.aa({
  18298. path: n,
  18299. la: !1
  18300. });
  18301. return s.ua(), s;
  18302. }
  18303. wa(t) {
  18304. // TODO(b/34871131): We don't support array paths right now; so make path
  18305. // undefined.
  18306. return this.aa({
  18307. path: void 0,
  18308. la: !0
  18309. });
  18310. }
  18311. _a(t) {
  18312. return gl(t, this.settings.methodName, this.settings.ma || !1, this.path, this.settings.ga);
  18313. }
  18314. /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) {
  18315. return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field)));
  18316. }
  18317. ua() {
  18318. // TODO(b/34871131): Remove null check once we have proper paths for fields
  18319. // within arrays.
  18320. if (this.path) for (let t = 0; t < this.path.length; t++) this.fa(this.path.get(t));
  18321. }
  18322. fa(t) {
  18323. if (0 === t.length) throw this._a("Document fields must not be empty");
  18324. if (Jh(this.ca) && zh.test(t)) throw this._a('Document fields cannot begin and end with "__"');
  18325. }
  18326. }
  18327. /**
  18328. * Helper for parsing raw user input (provided via the API) into internal model
  18329. * classes.
  18330. */ class Xh {
  18331. constructor(t, e, n) {
  18332. this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = n || Fu(t);
  18333. }
  18334. /** Creates a new top-level parse context. */ ya(t, e, n, s = !1) {
  18335. return new Yh({
  18336. ca: t,
  18337. methodName: e,
  18338. ga: n,
  18339. path: at.emptyPath(),
  18340. la: !1,
  18341. ma: s
  18342. }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);
  18343. }
  18344. }
  18345. function Zh(t) {
  18346. const e = t._freezeSettings(), n = Fu(t._databaseId);
  18347. return new Xh(t._databaseId, !!e.ignoreUndefinedProperties, n);
  18348. }
  18349. /** Parse document data from a set() call. */ function tl(t, e, n, s, i, r = {}) {
  18350. const o = t.ya(r.merge || r.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, i);
  18351. dl("Data must be an object, but it was:", o, s);
  18352. const u = ll(s, o);
  18353. let c, a;
  18354. if (r.merge) c = new Re(o.fieldMask), a = o.fieldTransforms; else if (r.mergeFields) {
  18355. const t = [];
  18356. for (const s of r.mergeFields) {
  18357. const i = wl(e, s, n);
  18358. if (!o.contains(i)) throw new U(q.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);
  18359. yl(t, i) || t.push(i);
  18360. }
  18361. c = new Re(t), a = o.fieldTransforms.filter((t => c.covers(t.field)));
  18362. } else c = null, a = o.fieldTransforms;
  18363. return new Wh(new un(u), c, a);
  18364. }
  18365. class el extends Qh {
  18366. _toFieldTransform(t) {
  18367. if (2 /* UserDataSource.MergeSet */ !== t.ca) throw 1 /* UserDataSource.Update */ === t.ca ? t._a(`${this._methodName}() can only appear at the top level of your update data`) : t._a(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);
  18368. // No transform to add for a delete, but we need to add it to our
  18369. // fieldMask so it gets deleted.
  18370. return t.fieldMask.push(t.path), null;
  18371. }
  18372. isEqual(t) {
  18373. return t instanceof el;
  18374. }
  18375. }
  18376. /**
  18377. * Creates a child context for parsing SerializableFieldValues.
  18378. *
  18379. * This is different than calling `ParseContext.contextWith` because it keeps
  18380. * the fieldTransforms and fieldMask separate.
  18381. *
  18382. * The created context has its `dataSource` set to `UserDataSource.Argument`.
  18383. * Although these values are used with writes, any elements in these FieldValues
  18384. * are not considered writes since they cannot contain any FieldValue sentinels,
  18385. * etc.
  18386. *
  18387. * @param fieldValue - The sentinel FieldValue for which to create a child
  18388. * context.
  18389. * @param context - The parent context.
  18390. * @param arrayElement - Whether or not the FieldValue has an array.
  18391. */ function nl(t, e, n) {
  18392. return new Yh({
  18393. ca: 3 /* UserDataSource.Argument */ ,
  18394. ga: e.settings.ga,
  18395. methodName: t._methodName,
  18396. la: n
  18397. }, e.databaseId, e.serializer, e.ignoreUndefinedProperties);
  18398. }
  18399. class sl extends Qh {
  18400. _toFieldTransform(t) {
  18401. return new Ms(t.path, new bs);
  18402. }
  18403. isEqual(t) {
  18404. return t instanceof sl;
  18405. }
  18406. }
  18407. class il extends Qh {
  18408. constructor(t, e) {
  18409. super(t), this.pa = e;
  18410. }
  18411. _toFieldTransform(t) {
  18412. const e = nl(this, t,
  18413. /*array=*/ !0), n = this.pa.map((t => hl(t, e))), s = new Vs(n);
  18414. return new Ms(t.path, s);
  18415. }
  18416. isEqual(t) {
  18417. // TODO(mrschmidt): Implement isEquals
  18418. return this === t;
  18419. }
  18420. }
  18421. class rl extends Qh {
  18422. constructor(t, e) {
  18423. super(t), this.pa = e;
  18424. }
  18425. _toFieldTransform(t) {
  18426. const e = nl(this, t,
  18427. /*array=*/ !0), n = this.pa.map((t => hl(t, e))), s = new Ds(n);
  18428. return new Ms(t.path, s);
  18429. }
  18430. isEqual(t) {
  18431. // TODO(mrschmidt): Implement isEquals
  18432. return this === t;
  18433. }
  18434. }
  18435. class ol extends Qh {
  18436. constructor(t, e) {
  18437. super(t), this.Ia = e;
  18438. }
  18439. _toFieldTransform(t) {
  18440. const e = new xs(t.serializer, Es(t.serializer, this.Ia));
  18441. return new Ms(t.path, e);
  18442. }
  18443. isEqual(t) {
  18444. // TODO(mrschmidt): Implement isEquals
  18445. return this === t;
  18446. }
  18447. }
  18448. /** Parse update data from an update() call. */ function ul(t, e, n, s) {
  18449. const i = t.ya(1 /* UserDataSource.Update */ , e, n);
  18450. dl("Data must be an object, but it was:", i, s);
  18451. const r = [], o = un.empty();
  18452. ge(s, ((t, s) => {
  18453. const u = ml(e, t, n);
  18454. // For Compat types, we have to "extract" the underlying types before
  18455. // performing validation.
  18456. s = util.getModularInstance(s);
  18457. const c = i.da(u);
  18458. if (s instanceof el)
  18459. // Add it to the field mask, but don't add anything to updateData.
  18460. r.push(u); else {
  18461. const t = hl(s, c);
  18462. null != t && (r.push(u), o.set(u, t));
  18463. }
  18464. }));
  18465. const u = new Re(r);
  18466. return new Hh(o, u, i.fieldTransforms);
  18467. }
  18468. /** Parse update data from a list of field/value arguments. */ function cl(t, e, n, s, i, r) {
  18469. const o = t.ya(1 /* UserDataSource.Update */ , e, n), u = [ wl(e, s, n) ], c = [ i ];
  18470. if (r.length % 2 != 0) throw new U(q.INVALID_ARGUMENT, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);
  18471. for (let t = 0; t < r.length; t += 2) u.push(wl(e, r[t])), c.push(r[t + 1]);
  18472. const a = [], h = un.empty();
  18473. // We iterate in reverse order to pick the last value for a field if the
  18474. // user specified the field multiple times.
  18475. for (let t = u.length - 1; t >= 0; --t) if (!yl(a, u[t])) {
  18476. const e = u[t];
  18477. let n = c[t];
  18478. // For Compat types, we have to "extract" the underlying types before
  18479. // performing validation.
  18480. n = util.getModularInstance(n);
  18481. const s = o.da(e);
  18482. if (n instanceof el)
  18483. // Add it to the field mask, but don't add anything to updateData.
  18484. a.push(e); else {
  18485. const t = hl(n, s);
  18486. null != t && (a.push(e), h.set(e, t));
  18487. }
  18488. }
  18489. const l = new Re(a);
  18490. return new Hh(h, l, o.fieldTransforms);
  18491. }
  18492. /**
  18493. * Parse a "query value" (e.g. value in a where filter or a value in a cursor
  18494. * bound).
  18495. *
  18496. * @param allowArrays - Whether the query value is an array that may directly
  18497. * contain additional arrays (e.g. the operand of an `in` query).
  18498. */ function al(t, e, n, s = !1) {
  18499. return hl(n, t.ya(s ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));
  18500. }
  18501. /**
  18502. * Parses user data to Protobuf Values.
  18503. *
  18504. * @param input - Data to be parsed.
  18505. * @param context - A context object representing the current path being parsed,
  18506. * the source of the data being parsed, etc.
  18507. * @returns The parsed value, or null if the value was a FieldValue sentinel
  18508. * that should not be included in the resulting parsed data.
  18509. */ function hl(t, e) {
  18510. if (fl(
  18511. // Unwrap the API type from the Compat SDK. This will return the API type
  18512. // from firestore-exp.
  18513. t = util.getModularInstance(t))) return dl("Unsupported field value:", e, t), ll(t, e);
  18514. if (t instanceof Qh)
  18515. // FieldValues usually parse into transforms (except deleteField())
  18516. // in which case we do not want to include this field in our parsed data
  18517. // (as doing so will overwrite the field directly prior to the transform
  18518. // trying to transform it). So we don't add this location to
  18519. // context.fieldMask and we return null as our parsing result.
  18520. /**
  18521. * "Parses" the provided FieldValueImpl, adding any necessary transforms to
  18522. * context.fieldTransforms.
  18523. */
  18524. return function(t, e) {
  18525. // Sentinels are only supported with writes, and not within arrays.
  18526. if (!Jh(e.ca)) throw e._a(`${t._methodName}() can only be used with update() and set()`);
  18527. if (!e.path) throw e._a(`${t._methodName}() is not currently supported inside arrays`);
  18528. const n = t._toFieldTransform(e);
  18529. n && e.fieldTransforms.push(n);
  18530. }
  18531. /**
  18532. * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
  18533. *
  18534. * @returns The parsed value
  18535. */ (t, e), null;
  18536. if (void 0 === t && e.ignoreUndefinedProperties)
  18537. // If the input is undefined it can never participate in the fieldMask, so
  18538. // don't handle this below. If `ignoreUndefinedProperties` is false,
  18539. // `parseScalarValue` will reject an undefined value.
  18540. return null;
  18541. if (
  18542. // If context.path is null we are inside an array and we don't support
  18543. // field mask paths more granular than the top-level array.
  18544. e.path && e.fieldMask.push(e.path), t instanceof Array) {
  18545. // TODO(b/34871131): Include the path containing the array in the error
  18546. // message.
  18547. // In the case of IN queries, the parsed data is an array (representing
  18548. // the set of values to be included for the IN query) that may directly
  18549. // contain additional arrays (each representing an individual field
  18550. // value), so we disable this validation.
  18551. if (e.settings.la && 4 /* UserDataSource.ArrayArgument */ !== e.ca) throw e._a("Nested arrays are not supported");
  18552. return function(t, e) {
  18553. const n = [];
  18554. let s = 0;
  18555. for (const i of t) {
  18556. let t = hl(i, e.wa(s));
  18557. null == t && (
  18558. // Just include nulls in the array for fields being replaced with a
  18559. // sentinel.
  18560. t = {
  18561. nullValue: "NULL_VALUE"
  18562. }), n.push(t), s++;
  18563. }
  18564. return {
  18565. arrayValue: {
  18566. values: n
  18567. }
  18568. };
  18569. }(t, e);
  18570. }
  18571. return function(t, e) {
  18572. if (null === (t = util.getModularInstance(t))) return {
  18573. nullValue: "NULL_VALUE"
  18574. };
  18575. if ("number" == typeof t) return Es(e.serializer, t);
  18576. if ("boolean" == typeof t) return {
  18577. booleanValue: t
  18578. };
  18579. if ("string" == typeof t) return {
  18580. stringValue: t
  18581. };
  18582. if (t instanceof Date) {
  18583. const n = it.fromDate(t);
  18584. return {
  18585. timestampValue: Di(e.serializer, n)
  18586. };
  18587. }
  18588. if (t instanceof it) {
  18589. // Firestore backend truncates precision down to microseconds. To ensure
  18590. // offline mode works the same with regards to truncation, perform the
  18591. // truncation immediately without waiting for the backend to do that.
  18592. const n = new it(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
  18593. return {
  18594. timestampValue: Di(e.serializer, n)
  18595. };
  18596. }
  18597. if (t instanceof jh) return {
  18598. geoPointValue: {
  18599. latitude: t.latitude,
  18600. longitude: t.longitude
  18601. }
  18602. };
  18603. if (t instanceof Uh) return {
  18604. bytesValue: Ci(e.serializer, t._byteString)
  18605. };
  18606. if (t instanceof fh) {
  18607. const n = e.databaseId, s = t.firestore._databaseId;
  18608. if (!s.isEqual(n)) throw e._a(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);
  18609. return {
  18610. referenceValue: ki(t.firestore._databaseId || e.databaseId, t._key.path)
  18611. };
  18612. }
  18613. throw e._a(`Unsupported field value: ${oh(t)}`);
  18614. }
  18615. /**
  18616. * Checks whether an object looks like a JSON object that should be converted
  18617. * into a struct. Normal class/prototype instances are considered to look like
  18618. * JSON objects since they should be converted to a struct value. Arrays, Dates,
  18619. * GeoPoints, etc. are not considered to look like JSON objects since they map
  18620. * to specific FieldValue types other than ObjectValue.
  18621. */ (t, e);
  18622. }
  18623. function ll(t, e) {
  18624. const n = {};
  18625. return ye(t) ?
  18626. // If we encounter an empty object, we explicitly add it to the update
  18627. // mask to ensure that the server creates a map entry.
  18628. e.path && e.path.length > 0 && e.fieldMask.push(e.path) : ge(t, ((t, s) => {
  18629. const i = hl(s, e.ha(t));
  18630. null != i && (n[t] = i);
  18631. })), {
  18632. mapValue: {
  18633. fields: n
  18634. }
  18635. };
  18636. }
  18637. function fl(t) {
  18638. return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof it || t instanceof jh || t instanceof Uh || t instanceof fh || t instanceof Qh);
  18639. }
  18640. function dl(t, e, n) {
  18641. if (!fl(n) || !function(t) {
  18642. return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));
  18643. }(n)) {
  18644. const s = oh(n);
  18645. throw "an object" === s ? e._a(t + " a custom object") : e._a(t + " " + s);
  18646. }
  18647. }
  18648. /**
  18649. * Helper that calls fromDotSeparatedString() but wraps any error thrown.
  18650. */ function wl(t, e, n) {
  18651. if ((
  18652. // If required, replace the FieldPath Compat class with with the firestore-exp
  18653. // FieldPath.
  18654. e = util.getModularInstance(e)) instanceof Kh) return e._internalPath;
  18655. if ("string" == typeof e) return ml(t, e);
  18656. throw gl("Field path arguments must be of type string or ", t,
  18657. /* hasConverter= */ !1,
  18658. /* path= */ void 0, n);
  18659. }
  18660. /**
  18661. * Matches any characters in a field path string that are reserved.
  18662. */ const _l = new RegExp("[~\\*/\\[\\]]");
  18663. /**
  18664. * Wraps fromDotSeparatedString with an error message about the method that
  18665. * was thrown.
  18666. * @param methodName - The publicly visible method name
  18667. * @param path - The dot-separated string form of a field path which will be
  18668. * split on dots.
  18669. * @param targetDoc - The document against which the field path will be
  18670. * evaluated.
  18671. */ function ml(t, e, n) {
  18672. if (e.search(_l) >= 0) throw gl(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t,
  18673. /* hasConverter= */ !1,
  18674. /* path= */ void 0, n);
  18675. try {
  18676. return new Kh(...e.split("."))._internalPath;
  18677. } catch (s) {
  18678. throw gl(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t,
  18679. /* hasConverter= */ !1,
  18680. /* path= */ void 0, n);
  18681. }
  18682. }
  18683. function gl(t, e, n, s, i) {
  18684. const r = s && !s.isEmpty(), o = void 0 !== i;
  18685. let u = `Function ${e}() called with invalid data`;
  18686. n && (u += " (via `toFirestore()`)"), u += ". ";
  18687. let c = "";
  18688. return (r || o) && (c += " (found", r && (c += ` in field ${s}`), o && (c += ` in document ${i}`),
  18689. c += ")"), new U(q.INVALID_ARGUMENT, u + t + c);
  18690. }
  18691. /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function yl(t, e) {
  18692. return t.some((t => t.isEqual(e)));
  18693. }
  18694. /**
  18695. * @license
  18696. * Copyright 2020 Google LLC
  18697. *
  18698. * Licensed under the Apache License, Version 2.0 (the "License");
  18699. * you may not use this file except in compliance with the License.
  18700. * You may obtain a copy of the License at
  18701. *
  18702. * http://www.apache.org/licenses/LICENSE-2.0
  18703. *
  18704. * Unless required by applicable law or agreed to in writing, software
  18705. * distributed under the License is distributed on an "AS IS" BASIS,
  18706. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18707. * See the License for the specific language governing permissions and
  18708. * limitations under the License.
  18709. */
  18710. /**
  18711. * A `DocumentSnapshot` contains data read from a document in your Firestore
  18712. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  18713. * get a specific field.
  18714. *
  18715. * For a `DocumentSnapshot` that points to a non-existing document, any data
  18716. * access will return 'undefined'. You can use the `exists()` method to
  18717. * explicitly verify a document's existence.
  18718. */ class pl {
  18719. // Note: This class is stripped down version of the DocumentSnapshot in
  18720. // the legacy SDK. The changes are:
  18721. // - No support for SnapshotMetadata.
  18722. // - No support for SnapshotOptions.
  18723. /** @hideconstructor protected */
  18724. constructor(t, e, n, s, i) {
  18725. this._firestore = t, this._userDataWriter = e, this._key = n, this._document = s,
  18726. this._converter = i;
  18727. }
  18728. /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {
  18729. return this._key.path.lastSegment();
  18730. }
  18731. /**
  18732. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  18733. */ get ref() {
  18734. return new fh(this._firestore, this._converter, this._key);
  18735. }
  18736. /**
  18737. * Signals whether or not the document at the snapshot's location exists.
  18738. *
  18739. * @returns true if the document exists.
  18740. */ exists() {
  18741. return null !== this._document;
  18742. }
  18743. /**
  18744. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  18745. * the document doesn't exist.
  18746. *
  18747. * @returns An `Object` containing all fields in the document or `undefined`
  18748. * if the document doesn't exist.
  18749. */ data() {
  18750. if (this._document) {
  18751. if (this._converter) {
  18752. // We only want to use the converter and create a new DocumentSnapshot
  18753. // if a converter has been provided.
  18754. const t = new Il(this._firestore, this._userDataWriter, this._key, this._document,
  18755. /* converter= */ null);
  18756. return this._converter.fromFirestore(t);
  18757. }
  18758. return this._userDataWriter.convertValue(this._document.data.value);
  18759. }
  18760. }
  18761. /**
  18762. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  18763. * document or field doesn't exist.
  18764. *
  18765. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  18766. * field.
  18767. * @returns The data at the specified field location or undefined if no such
  18768. * field exists in the document.
  18769. */
  18770. // We are using `any` here to avoid an explicit cast by our users.
  18771. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18772. get(t) {
  18773. if (this._document) {
  18774. const e = this._document.data.field(Tl("DocumentSnapshot.get", t));
  18775. if (null !== e) return this._userDataWriter.convertValue(e);
  18776. }
  18777. }
  18778. }
  18779. /**
  18780. * A `QueryDocumentSnapshot` contains data read from a document in your
  18781. * Firestore database as part of a query. The document is guaranteed to exist
  18782. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  18783. * specific field.
  18784. *
  18785. * A `QueryDocumentSnapshot` offers the same API surface as a
  18786. * `DocumentSnapshot`. Since query results contain only existing documents, the
  18787. * `exists` property will always be true and `data()` will never return
  18788. * 'undefined'.
  18789. */ class Il extends pl {
  18790. /**
  18791. * Retrieves all fields in the document as an `Object`.
  18792. *
  18793. * @override
  18794. * @returns An `Object` containing all fields in the document.
  18795. */
  18796. data() {
  18797. return super.data();
  18798. }
  18799. }
  18800. /**
  18801. * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
  18802. */ function Tl(t, e) {
  18803. return "string" == typeof e ? ml(t, e) : e instanceof Kh ? e._internalPath : e._delegate._internalPath;
  18804. }
  18805. /**
  18806. * @license
  18807. * Copyright 2020 Google LLC
  18808. *
  18809. * Licensed under the Apache License, Version 2.0 (the "License");
  18810. * you may not use this file except in compliance with the License.
  18811. * You may obtain a copy of the License at
  18812. *
  18813. * http://www.apache.org/licenses/LICENSE-2.0
  18814. *
  18815. * Unless required by applicable law or agreed to in writing, software
  18816. * distributed under the License is distributed on an "AS IS" BASIS,
  18817. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18818. * See the License for the specific language governing permissions and
  18819. * limitations under the License.
  18820. */ function El(t) {
  18821. if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new U(q.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
  18822. }
  18823. /**
  18824. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  18825. * to a Firestore query.
  18826. */ class Al {}
  18827. /**
  18828. * A `QueryConstraint` is used to narrow the set of documents returned by a
  18829. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  18830. * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
  18831. * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and
  18832. * can then be passed to {@link (query:1)} to create a new query instance that
  18833. * also contains this `QueryConstraint`.
  18834. */ class vl extends Al {}
  18835. function Rl(t, e, ...n) {
  18836. let s = [];
  18837. e instanceof Al && s.push(e), s = s.concat(n), function(t) {
  18838. const e = t.filter((t => t instanceof Vl)).length, n = t.filter((t => t instanceof Pl)).length;
  18839. if (e > 1 || e > 0 && n > 0) throw new U(q.INVALID_ARGUMENT, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.");
  18840. }
  18841. /**
  18842. * @license
  18843. * Copyright 2020 Google LLC
  18844. *
  18845. * Licensed under the Apache License, Version 2.0 (the "License");
  18846. * you may not use this file except in compliance with the License.
  18847. * You may obtain a copy of the License at
  18848. *
  18849. * http://www.apache.org/licenses/LICENSE-2.0
  18850. *
  18851. * Unless required by applicable law or agreed to in writing, software
  18852. * distributed under the License is distributed on an "AS IS" BASIS,
  18853. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18854. * See the License for the specific language governing permissions and
  18855. * limitations under the License.
  18856. */
  18857. /**
  18858. * Converts Firestore's internal types to the JavaScript types that we expose
  18859. * to the user.
  18860. *
  18861. * @internal
  18862. */ (s);
  18863. for (const e of s) t = e._apply(t);
  18864. return t;
  18865. }
  18866. /**
  18867. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  18868. * a Firestore query by filtering on one or more document fields.
  18869. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  18870. * be passed to {@link (query:1)} to create a new query instance that also contains
  18871. * this `QueryFieldFilterConstraint`.
  18872. */ class Pl extends vl {
  18873. /**
  18874. * @internal
  18875. */
  18876. constructor(t, e, n) {
  18877. super(), this._field = t, this._op = e, this._value = n,
  18878. /** The type of this query constraint */
  18879. this.type = "where";
  18880. }
  18881. static _create(t, e, n) {
  18882. return new Pl(t, e, n);
  18883. }
  18884. _apply(t) {
  18885. const e = this._parse(t);
  18886. return Ql(t._query, e), new dh(t.firestore, t.converter, Yn(t._query, e));
  18887. }
  18888. _parse(t) {
  18889. const e = Zh(t.firestore), n = function(t, e, n, s, i, r, o) {
  18890. let u;
  18891. if (i.isKeyField()) {
  18892. if ("array-contains" /* Operator.ARRAY_CONTAINS */ === r || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === r) throw new U(q.INVALID_ARGUMENT, `Invalid Query. You can't perform '${r}' queries on documentId().`);
  18893. if ("in" /* Operator.IN */ === r || "not-in" /* Operator.NOT_IN */ === r) {
  18894. Gl(o, r);
  18895. const e = [];
  18896. for (const n of o) e.push(Kl(s, t, n));
  18897. u = {
  18898. arrayValue: {
  18899. values: e
  18900. }
  18901. };
  18902. } else u = Kl(s, t, o);
  18903. } else "in" /* Operator.IN */ !== r && "not-in" /* Operator.NOT_IN */ !== r && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== r || Gl(o, r),
  18904. u = al(n, e, o,
  18905. /* allowArrays= */ "in" /* Operator.IN */ === r || "not-in" /* Operator.NOT_IN */ === r);
  18906. return mn.create(i, r, u);
  18907. }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value);
  18908. return n;
  18909. }
  18910. }
  18911. /**
  18912. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  18913. * must contain the specified field and that the value should satisfy the
  18914. * relation constraint provided.
  18915. *
  18916. * @param fieldPath - The path to compare
  18917. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  18918. * "&lt;=", "!=").
  18919. * @param value - The value for comparison
  18920. * @returns The created {@link QueryFieldFilterConstraint}.
  18921. */ function bl(t, e, n) {
  18922. const s = e, i = Tl("where", t);
  18923. return Pl._create(i, s, n);
  18924. }
  18925. /**
  18926. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  18927. * returned by a Firestore query by performing the logical OR or AND of multiple
  18928. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  18929. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  18930. * {@link and} and can then be passed to {@link (query:1)} to create a new query
  18931. * instance that also contains the `QueryCompositeFilterConstraint`.
  18932. */ class Vl extends Al {
  18933. /**
  18934. * @internal
  18935. */
  18936. constructor(
  18937. /** The type of this query constraint */
  18938. t, e) {
  18939. super(), this.type = t, this._queryConstraints = e;
  18940. }
  18941. static _create(t, e) {
  18942. return new Vl(t, e);
  18943. }
  18944. _parse(t) {
  18945. const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0));
  18946. return 1 === e.length ? e[0] : gn.create(e, this._getOperator());
  18947. }
  18948. _apply(t) {
  18949. const e = this._parse(t);
  18950. return 0 === e.getFilters().length ? t : (function(t, e) {
  18951. let n = t;
  18952. const s = e.getFlattenedFilters();
  18953. for (const t of s) Ql(n, t), n = Yn(n, t);
  18954. }
  18955. // Checks if any of the provided filter operators are included in the given list of filters and
  18956. // returns the first one that is, or null if none are.
  18957. (t._query, e), new dh(t.firestore, t.converter, Yn(t._query, e)));
  18958. }
  18959. _getQueryConstraints() {
  18960. return this._queryConstraints;
  18961. }
  18962. _getOperator() {
  18963. return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
  18964. }
  18965. }
  18966. /**
  18967. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  18968. * the given filter constraints. A disjunction filter includes a document if it
  18969. * satisfies any of the given filters.
  18970. *
  18971. * @param queryConstraints - Optional. The list of
  18972. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  18973. * created with calls to {@link where}, {@link or}, or {@link and}.
  18974. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18975. */ function Sl(...t) {
  18976. // Only support QueryFilterConstraints
  18977. return t.forEach((t => zl("or", t))), Vl._create("or" /* CompositeOperator.OR */ , t);
  18978. }
  18979. /**
  18980. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  18981. * the given filter constraints. A conjunction filter includes a document if it
  18982. * satisfies all of the given filters.
  18983. *
  18984. * @param queryConstraints - Optional. The list of
  18985. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  18986. * created with calls to {@link where}, {@link or}, or {@link and}.
  18987. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18988. */ function Dl(...t) {
  18989. // Only support QueryFilterConstraints
  18990. return t.forEach((t => zl("and", t))), Vl._create("and" /* CompositeOperator.AND */ , t);
  18991. }
  18992. /**
  18993. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  18994. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  18995. * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query
  18996. * instance that also contains this `QueryOrderByConstraint`.
  18997. *
  18998. * Note: Documents that do not contain the orderBy field will not be present in
  18999. * the query result.
  19000. */ class Cl extends vl {
  19001. /**
  19002. * @internal
  19003. */
  19004. constructor(t, e) {
  19005. super(), this._field = t, this._direction = e,
  19006. /** The type of this query constraint */
  19007. this.type = "orderBy";
  19008. }
  19009. static _create(t, e) {
  19010. return new Cl(t, e);
  19011. }
  19012. _apply(t) {
  19013. const e = function(t, e, n) {
  19014. if (null !== t.startAt) throw new U(q.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
  19015. if (null !== t.endAt) throw new U(q.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
  19016. const s = new dn(e, n);
  19017. return function(t, e) {
  19018. if (null === jn(t)) {
  19019. // This is the first order by. It must match any inequality.
  19020. const n = zn(t);
  19021. null !== n && jl(t, n, e.field);
  19022. }
  19023. }(t, s), s;
  19024. }
  19025. /**
  19026. * Create a `Bound` from a query and a document.
  19027. *
  19028. * Note that the `Bound` will always include the key of the document
  19029. * and so only the provided document will compare equal to the returned
  19030. * position.
  19031. *
  19032. * Will throw if the document does not contain all fields of the order by
  19033. * of the query or if any of the fields in the order by are an uncommitted
  19034. * server timestamp.
  19035. */ (t._query, this._field, this._direction);
  19036. return new dh(t.firestore, t.converter, function(t, e) {
  19037. // TODO(dimond): validate that orderBy does not list the same key twice.
  19038. const n = t.explicitOrderBy.concat([ e ]);
  19039. return new Un(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  19040. }(t._query, e));
  19041. }
  19042. }
  19043. /**
  19044. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  19045. * specified field, optionally in descending order instead of ascending.
  19046. *
  19047. * Note: Documents that do not contain the specified field will not be present
  19048. * in the query result.
  19049. *
  19050. * @param fieldPath - The field to sort by.
  19051. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  19052. * not specified, order will be ascending.
  19053. * @returns The created {@link QueryOrderByConstraint}.
  19054. */ function xl(t, e = "asc") {
  19055. const n = e, s = Tl("orderBy", t);
  19056. return Cl._create(s, n);
  19057. }
  19058. /**
  19059. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  19060. * a Firestore query.
  19061. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  19062. * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new
  19063. * query instance that also contains this `QueryLimitConstraint`.
  19064. */ class Nl extends vl {
  19065. /**
  19066. * @internal
  19067. */
  19068. constructor(
  19069. /** The type of this query constraint */
  19070. t, e, n) {
  19071. super(), this.type = t, this._limit = e, this._limitType = n;
  19072. }
  19073. static _create(t, e, n) {
  19074. return new Nl(t, e, n);
  19075. }
  19076. _apply(t) {
  19077. return new dh(t.firestore, t.converter, Xn(t._query, this._limit, this._limitType));
  19078. }
  19079. }
  19080. /**
  19081. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  19082. * documents.
  19083. *
  19084. * @param limit - The maximum number of items to return.
  19085. * @returns The created {@link QueryLimitConstraint}.
  19086. */ function kl(t) {
  19087. return ch("limit", t), Nl._create("limit", t, "F" /* LimitType.First */);
  19088. }
  19089. /**
  19090. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  19091. * documents.
  19092. *
  19093. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  19094. * otherwise an exception will be thrown during execution.
  19095. *
  19096. * @param limit - The maximum number of items to return.
  19097. * @returns The created {@link QueryLimitConstraint}.
  19098. */ function Ml(t) {
  19099. return ch("limitToLast", t), Nl._create("limitToLast", t, "L" /* LimitType.Last */);
  19100. }
  19101. /**
  19102. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  19103. * result set returned by a Firestore query.
  19104. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  19105. * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a
  19106. * new query instance that also contains this `QueryStartAtConstraint`.
  19107. */ class $l extends vl {
  19108. /**
  19109. * @internal
  19110. */
  19111. constructor(
  19112. /** The type of this query constraint */
  19113. t, e, n) {
  19114. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  19115. }
  19116. static _create(t, e, n) {
  19117. return new $l(t, e, n);
  19118. }
  19119. _apply(t) {
  19120. const e = Ul(t, this.type, this._docOrFields, this._inclusive);
  19121. return new dh(t.firestore, t.converter, function(t, e) {
  19122. return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);
  19123. }(t._query, e));
  19124. }
  19125. }
  19126. function Ol(...t) {
  19127. return $l._create("startAt", t,
  19128. /*inclusive=*/ !0);
  19129. }
  19130. function Fl(...t) {
  19131. return $l._create("startAfter", t,
  19132. /*inclusive=*/ !1);
  19133. }
  19134. /**
  19135. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  19136. * result set returned by a Firestore query.
  19137. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  19138. * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new
  19139. * query instance that also contains this `QueryEndAtConstraint`.
  19140. */ class Bl extends vl {
  19141. /**
  19142. * @internal
  19143. */
  19144. constructor(
  19145. /** The type of this query constraint */
  19146. t, e, n) {
  19147. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  19148. }
  19149. static _create(t, e, n) {
  19150. return new Bl(t, e, n);
  19151. }
  19152. _apply(t) {
  19153. const e = Ul(t, this.type, this._docOrFields, this._inclusive);
  19154. return new dh(t.firestore, t.converter, function(t, e) {
  19155. return new Un(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);
  19156. }(t._query, e));
  19157. }
  19158. }
  19159. function Ll(...t) {
  19160. return Bl._create("endBefore", t,
  19161. /*inclusive=*/ !1);
  19162. }
  19163. function ql(...t) {
  19164. return Bl._create("endAt", t,
  19165. /*inclusive=*/ !0);
  19166. }
  19167. /** Helper function to create a bound from a document or fields */ function Ul(t, e, n, s) {
  19168. if (n[0] = util.getModularInstance(n[0]), n[0] instanceof pl) return function(t, e, n, s, i) {
  19169. if (!s) throw new U(q.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);
  19170. const r = [];
  19171. // Because people expect to continue/end a query at the exact document
  19172. // provided, we need to use the implicit sort order rather than the explicit
  19173. // sort order, because it's guaranteed to contain the document key. That way
  19174. // the position becomes unambiguous and the query continues/ends exactly at
  19175. // the provided document. Without the key (by using the explicit sort
  19176. // orders), multiple documents could match the position, yielding duplicate
  19177. // results.
  19178. for (const n of Hn(t)) if (n.field.isKeyField()) r.push(We(e, s.key)); else {
  19179. const t = s.data.field(n.field);
  19180. if (Ne(t)) throw new U(q.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
  19181. if (null === t) {
  19182. const t = n.field.canonicalString();
  19183. throw new U(q.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`);
  19184. }
  19185. r.push(t);
  19186. }
  19187. return new hn(r, i);
  19188. }
  19189. /**
  19190. * Converts a list of field values to a `Bound` for the given query.
  19191. */ (t._query, t.firestore._databaseId, e, n[0]._document, s);
  19192. {
  19193. const i = Zh(t.firestore);
  19194. return function(t, e, n, s, i, r) {
  19195. // Use explicit order by's because it has to match the query the user made
  19196. const o = t.explicitOrderBy;
  19197. if (i.length > o.length) throw new U(q.INVALID_ARGUMENT, `Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);
  19198. const u = [];
  19199. for (let r = 0; r < i.length; r++) {
  19200. const c = i[r];
  19201. if (o[r].field.isKeyField()) {
  19202. if ("string" != typeof c) throw new U(q.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${s}(), but got a ${typeof c}`);
  19203. if (!Wn(t) && -1 !== c.indexOf("/")) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${s}() must be a plain document ID, but '${c}' contains a slash.`);
  19204. const n = t.path.child(ut.fromString(c));
  19205. if (!ht.isDocumentKey(n)) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${s}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);
  19206. const i = new ht(n);
  19207. u.push(We(e, i));
  19208. } else {
  19209. const t = al(n, s, c);
  19210. u.push(t);
  19211. }
  19212. }
  19213. return new hn(u, r);
  19214. }
  19215. /**
  19216. * Parses the given `documentIdValue` into a `ReferenceValue`, throwing
  19217. * appropriate errors if the value is anything other than a `DocumentReference`
  19218. * or `string`, or if the string is malformed.
  19219. */ (t._query, t.firestore._databaseId, i, e, n, s);
  19220. }
  19221. }
  19222. function Kl(t, e, n) {
  19223. if ("string" == typeof (n = util.getModularInstance(n))) {
  19224. if ("" === n) throw new U(q.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");
  19225. if (!Wn(e) && -1 !== n.indexOf("/")) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);
  19226. const s = e.path.child(ut.fromString(n));
  19227. if (!ht.isDocumentKey(s)) throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);
  19228. return We(t, new ht(s));
  19229. }
  19230. if (n instanceof fh) return We(t, n._key);
  19231. throw new U(q.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${oh(n)}.`);
  19232. }
  19233. /**
  19234. * Validates that the value passed into a disjunctive filter satisfies all
  19235. * array requirements.
  19236. */ function Gl(t, e) {
  19237. if (!Array.isArray(t) || 0 === t.length) throw new U(q.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);
  19238. }
  19239. /**
  19240. * Given an operator, returns the set of operators that cannot be used with it.
  19241. *
  19242. * This is not a comprehensive check, and this function should be removed in the
  19243. * long term. Validations should occur in the Firestore backend.
  19244. *
  19245. * Operators in a query must adhere to the following set of rules:
  19246. * 1. Only one inequality per query.
  19247. * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.
  19248. */ function Ql(t, e) {
  19249. if (e.isInequality()) {
  19250. const n = zn(t), s = e.field;
  19251. if (null !== n && !n.isEqual(s)) throw new U(q.INVALID_ARGUMENT, `Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${s.toString()}'`);
  19252. const i = jn(t);
  19253. null !== i && jl(t, s, i);
  19254. }
  19255. const n = function(t, e) {
  19256. for (const n of t) for (const t of n.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op;
  19257. return null;
  19258. }(t.filters, function(t) {
  19259. switch (t) {
  19260. case "!=" /* Operator.NOT_EQUAL */ :
  19261. return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ];
  19262. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  19263. case "in" /* Operator.IN */ :
  19264. return [ "not-in" /* Operator.NOT_IN */ ];
  19265. case "not-in" /* Operator.NOT_IN */ :
  19266. return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ];
  19267. default:
  19268. return [];
  19269. }
  19270. }(e.op));
  19271. if (null !== n)
  19272. // Special case when it's a duplicate op to give a slightly clearer error message.
  19273. throw n === e.op ? new U(q.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new U(q.INVALID_ARGUMENT, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);
  19274. }
  19275. function jl(t, e, n) {
  19276. if (!n.isEqual(e)) throw new U(q.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`);
  19277. }
  19278. function zl(t, e) {
  19279. if (!(e instanceof Pl || e instanceof Vl)) throw new U(q.INVALID_ARGUMENT, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
  19280. }
  19281. class Wl {
  19282. convertValue(t, e = "none") {
  19283. switch (Le(t)) {
  19284. case 0 /* TypeOrder.NullValue */ :
  19285. return null;
  19286. case 1 /* TypeOrder.BooleanValue */ :
  19287. return t.booleanValue;
  19288. case 2 /* TypeOrder.NumberValue */ :
  19289. return Ce(t.integerValue || t.doubleValue);
  19290. case 3 /* TypeOrder.TimestampValue */ :
  19291. return this.convertTimestamp(t.timestampValue);
  19292. case 4 /* TypeOrder.ServerTimestampValue */ :
  19293. return this.convertServerTimestamp(t, e);
  19294. case 5 /* TypeOrder.StringValue */ :
  19295. return t.stringValue;
  19296. case 6 /* TypeOrder.BlobValue */ :
  19297. return this.convertBytes(xe(t.bytesValue));
  19298. case 7 /* TypeOrder.RefValue */ :
  19299. return this.convertReference(t.referenceValue);
  19300. case 8 /* TypeOrder.GeoPointValue */ :
  19301. return this.convertGeoPoint(t.geoPointValue);
  19302. case 9 /* TypeOrder.ArrayValue */ :
  19303. return this.convertArray(t.arrayValue, e);
  19304. case 10 /* TypeOrder.ObjectValue */ :
  19305. return this.convertObject(t.mapValue, e);
  19306. default:
  19307. throw O();
  19308. }
  19309. }
  19310. convertObject(t, e) {
  19311. return this.convertObjectMap(t.fields, e);
  19312. }
  19313. /**
  19314. * @internal
  19315. */ convertObjectMap(t, e = "none") {
  19316. const n = {};
  19317. return ge(t, ((t, s) => {
  19318. n[t] = this.convertValue(s, e);
  19319. })), n;
  19320. }
  19321. convertGeoPoint(t) {
  19322. return new jh(Ce(t.latitude), Ce(t.longitude));
  19323. }
  19324. convertArray(t, e) {
  19325. return (t.values || []).map((t => this.convertValue(t, e)));
  19326. }
  19327. convertServerTimestamp(t, e) {
  19328. switch (e) {
  19329. case "previous":
  19330. const n = ke(t);
  19331. return null == n ? null : this.convertValue(n, e);
  19332. case "estimate":
  19333. return this.convertTimestamp(Me(t));
  19334. default:
  19335. return null;
  19336. }
  19337. }
  19338. convertTimestamp(t) {
  19339. const e = De(t);
  19340. return new it(e.seconds, e.nanos);
  19341. }
  19342. convertDocumentKey(t, e) {
  19343. const n = ut.fromString(t);
  19344. F(ur(n));
  19345. const s = new Oe(n.get(1), n.get(3)), i = new ht(n.popFirst(5));
  19346. return s.isEqual(e) ||
  19347. // TODO(b/64130202): Somehow support foreign references.
  19348. k(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`),
  19349. i;
  19350. }
  19351. }
  19352. /**
  19353. * @license
  19354. * Copyright 2020 Google LLC
  19355. *
  19356. * Licensed under the Apache License, Version 2.0 (the "License");
  19357. * you may not use this file except in compliance with the License.
  19358. * You may obtain a copy of the License at
  19359. *
  19360. * http://www.apache.org/licenses/LICENSE-2.0
  19361. *
  19362. * Unless required by applicable law or agreed to in writing, software
  19363. * distributed under the License is distributed on an "AS IS" BASIS,
  19364. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19365. * See the License for the specific language governing permissions and
  19366. * limitations under the License.
  19367. */
  19368. /**
  19369. * Converts custom model object of type T into `DocumentData` by applying the
  19370. * converter if it exists.
  19371. *
  19372. * This function is used when converting user objects to `DocumentData`
  19373. * because we want to provide the user with a more specific error message if
  19374. * their `set()` or fails due to invalid data originating from a `toFirestore()`
  19375. * call.
  19376. */ function Hl(t, e, n) {
  19377. let s;
  19378. // Cast to `any` in order to satisfy the union type constraint on
  19379. // toFirestore().
  19380. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19381. return s = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e,
  19382. s;
  19383. }
  19384. class Jl extends Wl {
  19385. constructor(t) {
  19386. super(), this.firestore = t;
  19387. }
  19388. convertBytes(t) {
  19389. return new Uh(t);
  19390. }
  19391. convertReference(t) {
  19392. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  19393. return new fh(this.firestore, /* converter= */ null, e);
  19394. }
  19395. }
  19396. /**
  19397. * @license
  19398. * Copyright 2022 Google LLC
  19399. *
  19400. * Licensed under the Apache License, Version 2.0 (the "License");
  19401. * you may not use this file except in compliance with the License.
  19402. * You may obtain a copy of the License at
  19403. *
  19404. * http://www.apache.org/licenses/LICENSE-2.0
  19405. *
  19406. * Unless required by applicable law or agreed to in writing, software
  19407. * distributed under the License is distributed on an "AS IS" BASIS,
  19408. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19409. * See the License for the specific language governing permissions and
  19410. * limitations under the License.
  19411. */
  19412. /**
  19413. * Create an AggregateField object that can be used to compute the sum of
  19414. * a specified field over a range of documents in the result set of a query.
  19415. * @param field Specifies the field to sum across the result set.
  19416. * @internal TODO (sum/avg) remove when public
  19417. */ function Yl(t) {
  19418. return new Lh("sum", wl("sum", t));
  19419. }
  19420. /**
  19421. * Create an AggregateField object that can be used to compute the average of
  19422. * a specified field over a range of documents in the result set of a query.
  19423. * @param field Specifies the field to average across the result set.
  19424. * @internal TODO (sum/avg) remove when public
  19425. */ function Xl(t) {
  19426. return new Lh("avg", wl("average", t));
  19427. }
  19428. /**
  19429. * Create an AggregateField object that can be used to compute the count of
  19430. * documents in the result set of a query.
  19431. * @internal TODO (sum/avg) remove when public
  19432. */ function Zl() {
  19433. return new Lh("count");
  19434. }
  19435. /**
  19436. * Compares two 'AggregateField` instances for equality.
  19437. *
  19438. * @param left Compare this AggregateField to the `right`.
  19439. * @param right Compare this AggregateField to the `left`.
  19440. * @internal TODO (sum/avg) remove when public
  19441. */ function tf(t, e) {
  19442. var n, s;
  19443. return t instanceof Lh && e instanceof Lh && t._aggregateType === e._aggregateType && (null === (n = t._internalFieldPath) || void 0 === n ? void 0 : n.canonicalString()) === (null === (s = e._internalFieldPath) || void 0 === s ? void 0 : s.canonicalString());
  19444. }
  19445. /**
  19446. * Compares two `AggregateQuerySnapshot` instances for equality.
  19447. *
  19448. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  19449. * underlying queries that compare equal, and the same data.
  19450. *
  19451. * @param left - The first `AggregateQuerySnapshot` to compare.
  19452. * @param right - The second `AggregateQuerySnapshot` to compare.
  19453. *
  19454. * @returns `true` if the objects are "equal", as defined above, or `false`
  19455. * otherwise.
  19456. */ function ef(t, e) {
  19457. return ph(t.query, e.query) && util.deepEqual(t.data(), e.data());
  19458. }
  19459. /**
  19460. * @license
  19461. * Copyright 2020 Google LLC
  19462. *
  19463. * Licensed under the Apache License, Version 2.0 (the "License");
  19464. * you may not use this file except in compliance with the License.
  19465. * You may obtain a copy of the License at
  19466. *
  19467. * http://www.apache.org/licenses/LICENSE-2.0
  19468. *
  19469. * Unless required by applicable law or agreed to in writing, software
  19470. * distributed under the License is distributed on an "AS IS" BASIS,
  19471. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19472. * See the License for the specific language governing permissions and
  19473. * limitations under the License.
  19474. */
  19475. /**
  19476. * Metadata about a snapshot, describing the state of the snapshot.
  19477. */ class nf {
  19478. /** @hideconstructor */
  19479. constructor(t, e) {
  19480. this.hasPendingWrites = t, this.fromCache = e;
  19481. }
  19482. /**
  19483. * Returns true if this `SnapshotMetadata` is equal to the provided one.
  19484. *
  19485. * @param other - The `SnapshotMetadata` to compare against.
  19486. * @returns true if this `SnapshotMetadata` is equal to the provided one.
  19487. */ isEqual(t) {
  19488. return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;
  19489. }
  19490. }
  19491. /**
  19492. * A `DocumentSnapshot` contains data read from a document in your Firestore
  19493. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  19494. * get a specific field.
  19495. *
  19496. * For a `DocumentSnapshot` that points to a non-existing document, any data
  19497. * access will return 'undefined'. You can use the `exists()` method to
  19498. * explicitly verify a document's existence.
  19499. */ class sf extends pl {
  19500. /** @hideconstructor protected */
  19501. constructor(t, e, n, s, i, r) {
  19502. super(t, e, n, s, r), this._firestore = t, this._firestoreImpl = t, this.metadata = i;
  19503. }
  19504. /**
  19505. * Returns whether or not the data exists. True if the document exists.
  19506. */ exists() {
  19507. return super.exists();
  19508. }
  19509. /**
  19510. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  19511. * the document doesn't exist.
  19512. *
  19513. * By default, `serverTimestamp()` values that have not yet been
  19514. * set to their final value will be returned as `null`. You can override
  19515. * this by passing an options object.
  19516. *
  19517. * @param options - An options object to configure how data is retrieved from
  19518. * the snapshot (for example the desired behavior for server timestamps that
  19519. * have not yet been set to their final value).
  19520. * @returns An `Object` containing all fields in the document or `undefined` if
  19521. * the document doesn't exist.
  19522. */ data(t = {}) {
  19523. if (this._document) {
  19524. if (this._converter) {
  19525. // We only want to use the converter and create a new DocumentSnapshot
  19526. // if a converter has been provided.
  19527. const e = new rf(this._firestore, this._userDataWriter, this._key, this._document, this.metadata,
  19528. /* converter= */ null);
  19529. return this._converter.fromFirestore(e, t);
  19530. }
  19531. return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);
  19532. }
  19533. }
  19534. /**
  19535. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  19536. * document or field doesn't exist.
  19537. *
  19538. * By default, a `serverTimestamp()` that has not yet been set to
  19539. * its final value will be returned as `null`. You can override this by
  19540. * passing an options object.
  19541. *
  19542. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  19543. * field.
  19544. * @param options - An options object to configure how the field is retrieved
  19545. * from the snapshot (for example the desired behavior for server timestamps
  19546. * that have not yet been set to their final value).
  19547. * @returns The data at the specified field location or undefined if no such
  19548. * field exists in the document.
  19549. */
  19550. // We are using `any` here to avoid an explicit cast by our users.
  19551. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19552. get(t, e = {}) {
  19553. if (this._document) {
  19554. const n = this._document.data.field(Tl("DocumentSnapshot.get", t));
  19555. if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);
  19556. }
  19557. }
  19558. }
  19559. /**
  19560. * A `QueryDocumentSnapshot` contains data read from a document in your
  19561. * Firestore database as part of a query. The document is guaranteed to exist
  19562. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  19563. * specific field.
  19564. *
  19565. * A `QueryDocumentSnapshot` offers the same API surface as a
  19566. * `DocumentSnapshot`. Since query results contain only existing documents, the
  19567. * `exists` property will always be true and `data()` will never return
  19568. * 'undefined'.
  19569. */ class rf extends sf {
  19570. /**
  19571. * Retrieves all fields in the document as an `Object`.
  19572. *
  19573. * By default, `serverTimestamp()` values that have not yet been
  19574. * set to their final value will be returned as `null`. You can override
  19575. * this by passing an options object.
  19576. *
  19577. * @override
  19578. * @param options - An options object to configure how data is retrieved from
  19579. * the snapshot (for example the desired behavior for server timestamps that
  19580. * have not yet been set to their final value).
  19581. * @returns An `Object` containing all fields in the document.
  19582. */
  19583. data(t = {}) {
  19584. return super.data(t);
  19585. }
  19586. }
  19587. /**
  19588. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  19589. * representing the results of a query. The documents can be accessed as an
  19590. * array via the `docs` property or enumerated using the `forEach` method. The
  19591. * number of documents can be determined via the `empty` and `size`
  19592. * properties.
  19593. */ class of {
  19594. /** @hideconstructor */
  19595. constructor(t, e, n, s) {
  19596. this._firestore = t, this._userDataWriter = e, this._snapshot = s, this.metadata = new nf(s.hasPendingWrites, s.fromCache),
  19597. this.query = n;
  19598. }
  19599. /** An array of all the documents in the `QuerySnapshot`. */ get docs() {
  19600. const t = [];
  19601. return this.forEach((e => t.push(e))), t;
  19602. }
  19603. /** The number of documents in the `QuerySnapshot`. */ get size() {
  19604. return this._snapshot.docs.size;
  19605. }
  19606. /** True if there are no documents in the `QuerySnapshot`. */ get empty() {
  19607. return 0 === this.size;
  19608. }
  19609. /**
  19610. * Enumerates all of the documents in the `QuerySnapshot`.
  19611. *
  19612. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  19613. * each document in the snapshot.
  19614. * @param thisArg - The `this` binding for the callback.
  19615. */ forEach(t, e) {
  19616. this._snapshot.docs.forEach((n => {
  19617. t.call(e, new rf(this._firestore, this._userDataWriter, n.key, n, new nf(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));
  19618. }));
  19619. }
  19620. /**
  19621. * Returns an array of the documents changes since the last snapshot. If this
  19622. * is the first snapshot, all documents will be in the list as 'added'
  19623. * changes.
  19624. *
  19625. * @param options - `SnapshotListenOptions` that control whether metadata-only
  19626. * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
  19627. * snapshot events.
  19628. */ docChanges(t = {}) {
  19629. const e = !!t.includeMetadataChanges;
  19630. if (e && this._snapshot.excludesMetadataChanges) throw new U(q.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
  19631. return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges =
  19632. /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */
  19633. function(t, e) {
  19634. if (t._snapshot.oldDocs.isEmpty()) {
  19635. let e = 0;
  19636. return t._snapshot.docChanges.map((n => {
  19637. const s = new rf(t._firestore, t._userDataWriter, n.doc.key, n.doc, new nf(t._snapshot.mutatedKeys.has(n.doc.key), t._snapshot.fromCache), t.query.converter);
  19638. return n.doc, {
  19639. type: "added",
  19640. doc: s,
  19641. oldIndex: -1,
  19642. newIndex: e++
  19643. };
  19644. }));
  19645. }
  19646. {
  19647. // A `DocumentSet` that is updated incrementally as changes are applied to use
  19648. // to lookup the index of a document.
  19649. let n = t._snapshot.oldDocs;
  19650. return t._snapshot.docChanges.filter((t => e || 3 /* ChangeType.Metadata */ !== t.type)).map((e => {
  19651. const s = new rf(t._firestore, t._userDataWriter, e.doc.key, e.doc, new nf(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);
  19652. let i = -1, r = -1;
  19653. return 0 /* ChangeType.Added */ !== e.type && (i = n.indexOf(e.doc.key), n = n.delete(e.doc.key)),
  19654. 1 /* ChangeType.Removed */ !== e.type && (n = n.add(e.doc), r = n.indexOf(e.doc.key)),
  19655. {
  19656. type: uf(e.type),
  19657. doc: s,
  19658. oldIndex: i,
  19659. newIndex: r
  19660. };
  19661. }));
  19662. }
  19663. }(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;
  19664. }
  19665. }
  19666. function uf(t) {
  19667. switch (t) {
  19668. case 0 /* ChangeType.Added */ :
  19669. return "added";
  19670. case 2 /* ChangeType.Modified */ :
  19671. case 3 /* ChangeType.Metadata */ :
  19672. return "modified";
  19673. case 1 /* ChangeType.Removed */ :
  19674. return "removed";
  19675. default:
  19676. return O();
  19677. }
  19678. }
  19679. // TODO(firestoreexp): Add tests for snapshotEqual with different snapshot
  19680. // metadata
  19681. /**
  19682. * Returns true if the provided snapshots are equal.
  19683. *
  19684. * @param left - A snapshot to compare.
  19685. * @param right - A snapshot to compare.
  19686. * @returns true if the snapshots are equal.
  19687. */ function cf(t, e) {
  19688. return t instanceof sf && e instanceof sf ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof of && e instanceof of && (t._firestore === e._firestore && ph(t.query, e.query) && t.metadata.isEqual(e.metadata) && t._snapshot.isEqual(e._snapshot));
  19689. }
  19690. /**
  19691. * @license
  19692. * Copyright 2020 Google LLC
  19693. *
  19694. * Licensed under the Apache License, Version 2.0 (the "License");
  19695. * you may not use this file except in compliance with the License.
  19696. * You may obtain a copy of the License at
  19697. *
  19698. * http://www.apache.org/licenses/LICENSE-2.0
  19699. *
  19700. * Unless required by applicable law or agreed to in writing, software
  19701. * distributed under the License is distributed on an "AS IS" BASIS,
  19702. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19703. * See the License for the specific language governing permissions and
  19704. * limitations under the License.
  19705. */
  19706. /**
  19707. * Reads the document referred to by this `DocumentReference`.
  19708. *
  19709. * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting
  19710. * for data from the server, but it may return cached data or fail if you are
  19711. * offline and the server cannot be reached. To specify this behavior, invoke
  19712. * {@link getDocFromCache} or {@link getDocFromServer}.
  19713. *
  19714. * @param reference - The reference of the document to fetch.
  19715. * @returns A Promise resolved with a `DocumentSnapshot` containing the
  19716. * current document contents.
  19717. */ function af(t) {
  19718. t = uh(t, fh);
  19719. const e = uh(t.firestore, vh);
  19720. return za(bh(e), t._key).then((n => Af(e, t, n)));
  19721. }
  19722. class hf extends Wl {
  19723. constructor(t) {
  19724. super(), this.firestore = t;
  19725. }
  19726. convertBytes(t) {
  19727. return new Uh(t);
  19728. }
  19729. convertReference(t) {
  19730. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  19731. return new fh(this.firestore, /* converter= */ null, e);
  19732. }
  19733. }
  19734. /**
  19735. * Reads the document referred to by this `DocumentReference` from cache.
  19736. * Returns an error if the document is not currently cached.
  19737. *
  19738. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19739. * current document contents.
  19740. */ function lf(t) {
  19741. t = uh(t, fh);
  19742. const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);
  19743. return ja(n, t._key).then((n => new sf(e, s, t._key, n, new nf(null !== n && n.hasLocalMutations,
  19744. /* fromCache= */ !0), t.converter)));
  19745. }
  19746. /**
  19747. * Reads the document referred to by this `DocumentReference` from the server.
  19748. * Returns an error if the network is not available.
  19749. *
  19750. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19751. * current document contents.
  19752. */ function ff(t) {
  19753. t = uh(t, fh);
  19754. const e = uh(t.firestore, vh);
  19755. return za(bh(e), t._key, {
  19756. source: "server"
  19757. }).then((n => Af(e, t, n)));
  19758. }
  19759. /**
  19760. * Executes the query and returns the results as a `QuerySnapshot`.
  19761. *
  19762. * Note: `getDocs()` attempts to provide up-to-date data when possible by
  19763. * waiting for data from the server, but it may return cached data or fail if
  19764. * you are offline and the server cannot be reached. To specify this behavior,
  19765. * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
  19766. *
  19767. * @returns A `Promise` that will be resolved with the results of the query.
  19768. */ function df(t) {
  19769. t = uh(t, dh);
  19770. const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);
  19771. return El(t._query), Ha(n, t._query).then((n => new of(e, s, t, n)));
  19772. }
  19773. /**
  19774. * Executes the query and returns the results as a `QuerySnapshot` from cache.
  19775. * Returns an empty result set if no documents matching the query are currently
  19776. * cached.
  19777. *
  19778. * @returns A `Promise` that will be resolved with the results of the query.
  19779. */ function wf(t) {
  19780. t = uh(t, dh);
  19781. const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);
  19782. return Wa(n, t._query).then((n => new of(e, s, t, n)));
  19783. }
  19784. /**
  19785. * Executes the query and returns the results as a `QuerySnapshot` from the
  19786. * server. Returns an error if the network is not available.
  19787. *
  19788. * @returns A `Promise` that will be resolved with the results of the query.
  19789. */ function _f(t) {
  19790. t = uh(t, dh);
  19791. const e = uh(t.firestore, vh), n = bh(e), s = new hf(e);
  19792. return Ha(n, t._query, {
  19793. source: "server"
  19794. }).then((n => new of(e, s, t, n)));
  19795. }
  19796. function mf(t, e, n) {
  19797. t = uh(t, fh);
  19798. const s = uh(t.firestore, vh), i = Hl(t.converter, e, n);
  19799. return Ef(s, [ tl(Zh(s), "setDoc", t._key, i, null !== t.converter, n).toMutation(t._key, Fs.none()) ]);
  19800. }
  19801. function gf(t, e, n, ...s) {
  19802. t = uh(t, fh);
  19803. const i = uh(t.firestore, vh), r = Zh(i);
  19804. let o;
  19805. o = "string" == typeof (
  19806. // For Compat types, we have to "extract" the underlying types before
  19807. // performing validation.
  19808. e = util.getModularInstance(e)) || e instanceof Kh ? cl(r, "updateDoc", t._key, e, n, s) : ul(r, "updateDoc", t._key, e);
  19809. return Ef(i, [ o.toMutation(t._key, Fs.exists(!0)) ]);
  19810. }
  19811. /**
  19812. * Deletes the document referred to by the specified `DocumentReference`.
  19813. *
  19814. * @param reference - A reference to the document to delete.
  19815. * @returns A Promise resolved once the document has been successfully
  19816. * deleted from the backend (note that it won't resolve while you're offline).
  19817. */ function yf(t) {
  19818. return Ef(uh(t.firestore, vh), [ new Ys(t._key, Fs.none()) ]);
  19819. }
  19820. /**
  19821. * Add a new document to specified `CollectionReference` with the given data,
  19822. * assigning it a document ID automatically.
  19823. *
  19824. * @param reference - A reference to the collection to add this document to.
  19825. * @param data - An Object containing the data for the new document.
  19826. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  19827. * newly created document after it has been written to the backend (Note that it
  19828. * won't resolve while you're offline).
  19829. */ function pf(t, e) {
  19830. const n = uh(t.firestore, vh), s = gh(t), i = Hl(t.converter, e);
  19831. return Ef(n, [ tl(Zh(t.firestore), "addDoc", s._key, i, null !== t.converter, {}).toMutation(s._key, Fs.exists(!1)) ]).then((() => s));
  19832. }
  19833. function If(t, ...e) {
  19834. var n, s, i;
  19835. t = util.getModularInstance(t);
  19836. let r = {
  19837. includeMetadataChanges: !1
  19838. }, o = 0;
  19839. "object" != typeof e[o] || Th(e[o]) || (r = e[o], o++);
  19840. const u = {
  19841. includeMetadataChanges: r.includeMetadataChanges
  19842. };
  19843. if (Th(e[o])) {
  19844. const t = e[o];
  19845. e[o] = null === (n = t.next) || void 0 === n ? void 0 : n.bind(t), e[o + 1] = null === (s = t.error) || void 0 === s ? void 0 : s.bind(t),
  19846. e[o + 2] = null === (i = t.complete) || void 0 === i ? void 0 : i.bind(t);
  19847. }
  19848. let c, a, h;
  19849. if (t instanceof fh) a = uh(t.firestore, vh), h = Gn(t._key.path), c = {
  19850. next: n => {
  19851. e[o] && e[o](Af(a, t, n));
  19852. },
  19853. error: e[o + 1],
  19854. complete: e[o + 2]
  19855. }; else {
  19856. const n = uh(t, dh);
  19857. a = uh(n.firestore, vh), h = n._query;
  19858. const s = new hf(a);
  19859. c = {
  19860. next: t => {
  19861. e[o] && e[o](new of(a, s, n, t));
  19862. },
  19863. error: e[o + 1],
  19864. complete: e[o + 2]
  19865. }, El(t._query);
  19866. }
  19867. return function(t, e, n, s) {
  19868. const i = new Va(s), r = new Nc(e, i, n);
  19869. return t.asyncQueue.enqueueAndForget((async () => Vc(await Ka(t), r))), () => {
  19870. i.Dc(), t.asyncQueue.enqueueAndForget((async () => Sc(await Ka(t), r)));
  19871. };
  19872. }(bh(a), h, u, c);
  19873. }
  19874. function Tf(t, e) {
  19875. return Ja(bh(t = uh(t, vh)), Th(e) ? e : {
  19876. next: e
  19877. });
  19878. }
  19879. /**
  19880. * Locally writes `mutations` on the async queue.
  19881. * @internal
  19882. */ function Ef(t, e) {
  19883. return function(t, e) {
  19884. const n = new K;
  19885. return t.asyncQueue.enqueueAndForget((async () => zc(await qa(t), e, n))), n.promise;
  19886. }(bh(t), e);
  19887. }
  19888. /**
  19889. * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`
  19890. * to a {@link DocumentSnapshot}.
  19891. */ function Af(t, e, n) {
  19892. const s = n.docs.get(e._key), i = new hf(t);
  19893. return new sf(t, i, e._key, s, new nf(n.hasPendingWrites, n.fromCache), e.converter);
  19894. }
  19895. /**
  19896. * @license
  19897. * Copyright 2022 Google LLC
  19898. *
  19899. * Licensed under the Apache License, Version 2.0 (the "License");
  19900. * you may not use this file except in compliance with the License.
  19901. * You may obtain a copy of the License at
  19902. *
  19903. * http://www.apache.org/licenses/LICENSE-2.0
  19904. *
  19905. * Unless required by applicable law or agreed to in writing, software
  19906. * distributed under the License is distributed on an "AS IS" BASIS,
  19907. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19908. * See the License for the specific language governing permissions and
  19909. * limitations under the License.
  19910. */
  19911. /**
  19912. * Calculates the number of documents in the result set of the given query,
  19913. * without actually downloading the documents.
  19914. *
  19915. * Using this function to count the documents is efficient because only the
  19916. * final count, not the documents' data, is downloaded. This function can even
  19917. * count the documents if the result set would be prohibitively large to
  19918. * download entirely (e.g. thousands of documents).
  19919. *
  19920. * The result received from the server is presented, unaltered, without
  19921. * considering any local state. That is, documents in the local cache are not
  19922. * taken into consideration, neither are local modifications not yet
  19923. * synchronized with the server. Previously-downloaded results, if any, are not
  19924. * used: every request using this source necessarily involves a round trip to
  19925. * the server.
  19926. *
  19927. * @param query - The query whose result set size to calculate.
  19928. * @returns A Promise that will be resolved with the count; the count can be
  19929. * retrieved from `snapshot.data().count`, where `snapshot` is the
  19930. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  19931. */ function vf(t) {
  19932. return Rf(t, {
  19933. count: Zl()
  19934. });
  19935. }
  19936. /**
  19937. * Calculates the specified aggregations over the documents in the result
  19938. * set of the given query, without actually downloading the documents.
  19939. *
  19940. * Using this function to perform aggregations is efficient because only the
  19941. * final aggregation values, not the documents' data, is downloaded. This
  19942. * function can even perform aggregations of the documents if the result set
  19943. * would be prohibitively large to download entirely (e.g. thousands of documents).
  19944. *
  19945. * The result received from the server is presented, unaltered, without
  19946. * considering any local state. That is, documents in the local cache are not
  19947. * taken into consideration, neither are local modifications not yet
  19948. * synchronized with the server. Previously-downloaded results, if any, are not
  19949. * used: every request using this source necessarily involves a round trip to
  19950. * the server.
  19951. *
  19952. * @param query The query whose result set to aggregate over.
  19953. * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates
  19954. * to perform over the result set. The AggregateSpec specifies aliases for each
  19955. * aggregate, which can be used to retrieve the aggregate result.
  19956. * @example
  19957. * ```typescript
  19958. * const aggregateSnapshot = await getAggregateFromServer(query, {
  19959. * countOfDocs: count(),
  19960. * totalHours: sum('hours'),
  19961. * averageScore: average('score')
  19962. * });
  19963. *
  19964. * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;
  19965. * const totalHours: number = aggregateSnapshot.data().totalHours;
  19966. * const averageScore: number | null = aggregateSnapshot.data().averageScore;
  19967. * ```
  19968. * @internal TODO (sum/avg) remove when public
  19969. */ function Rf(t, e) {
  19970. const n = uh(t.firestore, vh), s = bh(n), i = function(t, e) {
  19971. const n = [];
  19972. for (const s in t) Object.prototype.hasOwnProperty.call(t, s) && n.push(e(t[s], s, t));
  19973. return n;
  19974. }(e, ((t, e) => new ni(e, t._aggregateType, t._internalFieldPath)));
  19975. // Run the aggregation and convert the results
  19976. return function(t, e, n) {
  19977. const s = new K;
  19978. return t.asyncQueue.enqueueAndForget((async () => {
  19979. // TODO (sum/avg) should we update this to use the event manager?
  19980. // Implement and call executeAggregateQueryViaSnapshotListener, similar
  19981. // to the implementation in firestoreClientGetDocumentsViaSnapshotListener
  19982. // above
  19983. try {
  19984. // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.
  19985. const i = await Ua(t);
  19986. s.resolve(Gu(i, e, n));
  19987. } catch (t) {
  19988. s.reject(t);
  19989. }
  19990. })), s.promise;
  19991. }(s, t._query, i).then((e =>
  19992. /**
  19993. * Converts the core aggregration result to an `AggregateQuerySnapshot`
  19994. * that can be returned to the consumer.
  19995. * @param query
  19996. * @param aggregateResult Core aggregation result
  19997. * @internal
  19998. */
  19999. function(t, e, n) {
  20000. const s = new hf(t);
  20001. return new qh(e, s, n);
  20002. }
  20003. /**
  20004. * @license
  20005. * Copyright 2023 Google LLC
  20006. *
  20007. * Licensed under the Apache License, Version 2.0 (the "License");
  20008. * you may not use this file except in compliance with the License.
  20009. * You may obtain a copy of the License at
  20010. *
  20011. * http://www.apache.org/licenses/LICENSE-2.0
  20012. *
  20013. * Unless required by applicable law or agreed to in writing, software
  20014. * distributed under the License is distributed on an "AS IS" BASIS,
  20015. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20016. * See the License for the specific language governing permissions and
  20017. * limitations under the License.
  20018. */ (n, t, e)));
  20019. }
  20020. class Pf {
  20021. constructor(t) {
  20022. this.kind = "memory", this._onlineComponentProvider = new Pa, (null == t ? void 0 : t.garbageCollector) ? this._offlineComponentProvider = t.garbageCollector._offlineComponentProvider : this._offlineComponentProvider = new Ea;
  20023. }
  20024. toJSON() {
  20025. return {
  20026. kind: this.kind
  20027. };
  20028. }
  20029. }
  20030. class bf {
  20031. constructor(t) {
  20032. let e;
  20033. this.kind = "persistent", (null == t ? void 0 : t.tabManager) ? (t.tabManager._initialize(t),
  20034. e = t.tabManager) : (e = $f(void 0), e._initialize(t)), this._onlineComponentProvider = e._onlineComponentProvider,
  20035. this._offlineComponentProvider = e._offlineComponentProvider;
  20036. }
  20037. toJSON() {
  20038. return {
  20039. kind: this.kind
  20040. };
  20041. }
  20042. }
  20043. class Vf {
  20044. constructor() {
  20045. this.kind = "memoryEager", this._offlineComponentProvider = new Ea;
  20046. }
  20047. toJSON() {
  20048. return {
  20049. kind: this.kind
  20050. };
  20051. }
  20052. }
  20053. class Sf {
  20054. constructor(t) {
  20055. this.kind = "memoryLru", this._offlineComponentProvider = new Aa(t);
  20056. }
  20057. toJSON() {
  20058. return {
  20059. kind: this.kind
  20060. };
  20061. }
  20062. }
  20063. /**
  20064. * Creates an instance of `MemoryEagerGarbageCollector`. This is also the
  20065. * default garbage collector unless it is explicitly specified otherwise.
  20066. */ function Df() {
  20067. return new Vf;
  20068. }
  20069. /**
  20070. * Creates an instance of `MemoryLruGarbageCollector`.
  20071. *
  20072. * A target size can be specified as part of the setting parameter. The
  20073. * collector will start deleting documents once the cache size exceeds
  20074. * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).
  20075. */ function Cf(t) {
  20076. return new Sf(null == t ? void 0 : t.cacheSizeBytes);
  20077. }
  20078. /**
  20079. * Creates an instance of `MemoryLocalCache`. The instance can be set to
  20080. * `FirestoreSettings.cache` to tell the SDK which cache layer to use.
  20081. */ function xf(t) {
  20082. return new Pf(t);
  20083. }
  20084. /**
  20085. * Creates an instance of `PersistentLocalCache`. The instance can be set to
  20086. * `FirestoreSettings.cache` to tell the SDK which cache layer to use.
  20087. *
  20088. * Persistent cache cannot be used in a Node.js environment.
  20089. */ function Nf(t) {
  20090. return new bf(t);
  20091. }
  20092. class kf {
  20093. constructor(t) {
  20094. this.forceOwnership = t, this.kind = "persistentSingleTab";
  20095. }
  20096. toJSON() {
  20097. return {
  20098. kind: this.kind
  20099. };
  20100. }
  20101. /**
  20102. * @internal
  20103. */ _initialize(t) {
  20104. this._onlineComponentProvider = new Pa, this._offlineComponentProvider = new va(this._onlineComponentProvider, null == t ? void 0 : t.cacheSizeBytes, this.forceOwnership);
  20105. }
  20106. }
  20107. class Mf {
  20108. constructor() {
  20109. this.kind = "PersistentMultipleTab";
  20110. }
  20111. toJSON() {
  20112. return {
  20113. kind: this.kind
  20114. };
  20115. }
  20116. /**
  20117. * @internal
  20118. */ _initialize(t) {
  20119. this._onlineComponentProvider = new Pa, this._offlineComponentProvider = new Ra(this._onlineComponentProvider, null == t ? void 0 : t.cacheSizeBytes);
  20120. }
  20121. }
  20122. /**
  20123. * Creates an instance of `PersistentSingleTabManager`.
  20124. *
  20125. * @param settings Configures the created tab manager.
  20126. */ function $f(t) {
  20127. return new kf(null == t ? void 0 : t.forceOwnership);
  20128. }
  20129. /**
  20130. * Creates an instance of `PersistentMultipleTabManager`.
  20131. */ function Of() {
  20132. return new Mf;
  20133. }
  20134. /**
  20135. * @license
  20136. * Copyright 2022 Google LLC
  20137. *
  20138. * Licensed under the Apache License, Version 2.0 (the "License");
  20139. * you may not use this file except in compliance with the License.
  20140. * You may obtain a copy of the License at
  20141. *
  20142. * http://www.apache.org/licenses/LICENSE-2.0
  20143. *
  20144. * Unless required by applicable law or agreed to in writing, software
  20145. * distributed under the License is distributed on an "AS IS" BASIS,
  20146. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20147. * See the License for the specific language governing permissions and
  20148. * limitations under the License.
  20149. */ const Ff = {
  20150. maxAttempts: 5
  20151. };
  20152. /**
  20153. * @license
  20154. * Copyright 2020 Google LLC
  20155. *
  20156. * Licensed under the Apache License, Version 2.0 (the "License");
  20157. * you may not use this file except in compliance with the License.
  20158. * You may obtain a copy of the License at
  20159. *
  20160. * http://www.apache.org/licenses/LICENSE-2.0
  20161. *
  20162. * Unless required by applicable law or agreed to in writing, software
  20163. * distributed under the License is distributed on an "AS IS" BASIS,
  20164. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20165. * See the License for the specific language governing permissions and
  20166. * limitations under the License.
  20167. */
  20168. /**
  20169. * A write batch, used to perform multiple writes as a single atomic unit.
  20170. *
  20171. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  20172. * provides methods for adding writes to the write batch. None of the writes
  20173. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  20174. * called.
  20175. */
  20176. class Bf {
  20177. /** @hideconstructor */
  20178. constructor(t, e) {
  20179. this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1,
  20180. this._dataReader = Zh(t);
  20181. }
  20182. set(t, e, n) {
  20183. this._verifyNotCommitted();
  20184. const s = Lf(t, this._firestore), i = Hl(s.converter, e, n), r = tl(this._dataReader, "WriteBatch.set", s._key, i, null !== s.converter, n);
  20185. return this._mutations.push(r.toMutation(s._key, Fs.none())), this;
  20186. }
  20187. update(t, e, n, ...s) {
  20188. this._verifyNotCommitted();
  20189. const i = Lf(t, this._firestore);
  20190. // For Compat types, we have to "extract" the underlying types before
  20191. // performing validation.
  20192. let r;
  20193. return r = "string" == typeof (e = util.getModularInstance(e)) || e instanceof Kh ? cl(this._dataReader, "WriteBatch.update", i._key, e, n, s) : ul(this._dataReader, "WriteBatch.update", i._key, e),
  20194. this._mutations.push(r.toMutation(i._key, Fs.exists(!0))), this;
  20195. }
  20196. /**
  20197. * Deletes the document referred to by the provided {@link DocumentReference}.
  20198. *
  20199. * @param documentRef - A reference to the document to be deleted.
  20200. * @returns This `WriteBatch` instance. Used for chaining method calls.
  20201. */ delete(t) {
  20202. this._verifyNotCommitted();
  20203. const e = Lf(t, this._firestore);
  20204. return this._mutations = this._mutations.concat(new Ys(e._key, Fs.none())), this;
  20205. }
  20206. /**
  20207. * Commits all of the writes in this write batch as a single atomic unit.
  20208. *
  20209. * The result of these writes will only be reflected in document reads that
  20210. * occur after the returned promise resolves. If the client is offline, the
  20211. * write fails. If you would like to see local modifications or buffer writes
  20212. * until the client is online, use the full Firestore SDK.
  20213. *
  20214. * @returns A `Promise` resolved once all of the writes in the batch have been
  20215. * successfully written to the backend as an atomic unit (note that it won't
  20216. * resolve while you're offline).
  20217. */ commit() {
  20218. return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();
  20219. }
  20220. _verifyNotCommitted() {
  20221. if (this._committed) throw new U(q.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
  20222. }
  20223. }
  20224. function Lf(t, e) {
  20225. if ((t = util.getModularInstance(t)).firestore !== e) throw new U(q.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
  20226. return t;
  20227. }
  20228. /**
  20229. * @license
  20230. * Copyright 2020 Google LLC
  20231. *
  20232. * Licensed under the Apache License, Version 2.0 (the "License");
  20233. * you may not use this file except in compliance with the License.
  20234. * You may obtain a copy of the License at
  20235. *
  20236. * http://www.apache.org/licenses/LICENSE-2.0
  20237. *
  20238. * Unless required by applicable law or agreed to in writing, software
  20239. * distributed under the License is distributed on an "AS IS" BASIS,
  20240. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20241. * See the License for the specific language governing permissions and
  20242. * limitations under the License.
  20243. */
  20244. // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
  20245. // legacy SDK.
  20246. /**
  20247. * A reference to a transaction.
  20248. *
  20249. * The `Transaction` object passed to a transaction's `updateFunction` provides
  20250. * the methods to read and write data within the transaction context. See
  20251. * {@link runTransaction}.
  20252. */
  20253. /**
  20254. * @license
  20255. * Copyright 2020 Google LLC
  20256. *
  20257. * Licensed under the Apache License, Version 2.0 (the "License");
  20258. * you may not use this file except in compliance with the License.
  20259. * You may obtain a copy of the License at
  20260. *
  20261. * http://www.apache.org/licenses/LICENSE-2.0
  20262. *
  20263. * Unless required by applicable law or agreed to in writing, software
  20264. * distributed under the License is distributed on an "AS IS" BASIS,
  20265. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20266. * See the License for the specific language governing permissions and
  20267. * limitations under the License.
  20268. */
  20269. /**
  20270. * A reference to a transaction.
  20271. *
  20272. * The `Transaction` object passed to a transaction's `updateFunction` provides
  20273. * the methods to read and write data within the transaction context. See
  20274. * {@link runTransaction}.
  20275. */
  20276. class qf extends class {
  20277. /** @hideconstructor */
  20278. constructor(t, e) {
  20279. this._firestore = t, this._transaction = e, this._dataReader = Zh(t);
  20280. }
  20281. /**
  20282. * Reads the document referenced by the provided {@link DocumentReference}.
  20283. *
  20284. * @param documentRef - A reference to the document to be read.
  20285. * @returns A `DocumentSnapshot` with the read data.
  20286. */ get(t) {
  20287. const e = Lf(t, this._firestore), n = new Jl(this._firestore);
  20288. return this._transaction.lookup([ e._key ]).then((t => {
  20289. if (!t || 1 !== t.length) return O();
  20290. const s = t[0];
  20291. if (s.isFoundDocument()) return new pl(this._firestore, n, s.key, s, e.converter);
  20292. if (s.isNoDocument()) return new pl(this._firestore, n, e._key, null, e.converter);
  20293. throw O();
  20294. }));
  20295. }
  20296. set(t, e, n) {
  20297. const s = Lf(t, this._firestore), i = Hl(s.converter, e, n), r = tl(this._dataReader, "Transaction.set", s._key, i, null !== s.converter, n);
  20298. return this._transaction.set(s._key, r), this;
  20299. }
  20300. update(t, e, n, ...s) {
  20301. const i = Lf(t, this._firestore);
  20302. // For Compat types, we have to "extract" the underlying types before
  20303. // performing validation.
  20304. let r;
  20305. return r = "string" == typeof (e = util.getModularInstance(e)) || e instanceof Kh ? cl(this._dataReader, "Transaction.update", i._key, e, n, s) : ul(this._dataReader, "Transaction.update", i._key, e),
  20306. this._transaction.update(i._key, r), this;
  20307. }
  20308. /**
  20309. * Deletes the document referred to by the provided {@link DocumentReference}.
  20310. *
  20311. * @param documentRef - A reference to the document to be deleted.
  20312. * @returns This `Transaction` instance. Used for chaining method calls.
  20313. */ delete(t) {
  20314. const e = Lf(t, this._firestore);
  20315. return this._transaction.delete(e._key), this;
  20316. }
  20317. } {
  20318. // This class implements the same logic as the Transaction API in the Lite SDK
  20319. // but is subclassed in order to return its own DocumentSnapshot types.
  20320. /** @hideconstructor */
  20321. constructor(t, e) {
  20322. super(t, e), this._firestore = t;
  20323. }
  20324. /**
  20325. * Reads the document referenced by the provided {@link DocumentReference}.
  20326. *
  20327. * @param documentRef - A reference to the document to be read.
  20328. * @returns A `DocumentSnapshot` with the read data.
  20329. */ get(t) {
  20330. const e = Lf(t, this._firestore), n = new hf(this._firestore);
  20331. return super.get(t).then((t => new sf(this._firestore, n, e._key, t._document, new nf(
  20332. /* hasPendingWrites= */ !1,
  20333. /* fromCache= */ !1), e.converter)));
  20334. }
  20335. }
  20336. /**
  20337. * Executes the given `updateFunction` and then attempts to commit the changes
  20338. * applied within the transaction. If any document read within the transaction
  20339. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  20340. * commit after 5 attempts, the transaction fails.
  20341. *
  20342. * The maximum number of writes allowed in a single transaction is 500.
  20343. *
  20344. * @param firestore - A reference to the Firestore database to run this
  20345. * transaction against.
  20346. * @param updateFunction - The function to execute within the transaction
  20347. * context.
  20348. * @param options - An options object to configure maximum number of attempts to
  20349. * commit.
  20350. * @returns If the transaction completed successfully or was explicitly aborted
  20351. * (the `updateFunction` returned a failed promise), the promise returned by the
  20352. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  20353. * rejected promise with the corresponding failure error is returned.
  20354. */ function Uf(t, e, n) {
  20355. t = uh(t, vh);
  20356. const s = Object.assign(Object.assign({}, Ff), n);
  20357. !function(t) {
  20358. if (t.maxAttempts < 1) throw new U(q.INVALID_ARGUMENT, "Max attempts must be at least 1");
  20359. }(s);
  20360. return function(t, e, n) {
  20361. const s = new K;
  20362. return t.asyncQueue.enqueueAndForget((async () => {
  20363. const i = await Ua(t);
  20364. new Ca(t.asyncQueue, i, n, e, s).run();
  20365. })), s.promise;
  20366. }(bh(t), (n => e(new qf(t, n))), s);
  20367. }
  20368. /**
  20369. * @license
  20370. * Copyright 2020 Google LLC
  20371. *
  20372. * Licensed under the Apache License, Version 2.0 (the "License");
  20373. * you may not use this file except in compliance with the License.
  20374. * You may obtain a copy of the License at
  20375. *
  20376. * http://www.apache.org/licenses/LICENSE-2.0
  20377. *
  20378. * Unless required by applicable law or agreed to in writing, software
  20379. * distributed under the License is distributed on an "AS IS" BASIS,
  20380. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20381. * See the License for the specific language governing permissions and
  20382. * limitations under the License.
  20383. */
  20384. /**
  20385. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  20386. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  20387. */ function Kf() {
  20388. return new el("deleteField");
  20389. }
  20390. /**
  20391. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  20392. * include a server-generated timestamp in the written data.
  20393. */ function Gf() {
  20394. return new sl("serverTimestamp");
  20395. }
  20396. /**
  20397. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  20398. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  20399. * value that already exists on the server. Each specified element that doesn't
  20400. * already exist in the array will be added to the end. If the field being
  20401. * modified is not already an array it will be overwritten with an array
  20402. * containing exactly the specified elements.
  20403. *
  20404. * @param elements - The elements to union into the array.
  20405. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20406. * `updateDoc()`.
  20407. */ function Qf(...t) {
  20408. // NOTE: We don't actually parse the data until it's used in set() or
  20409. // update() since we'd need the Firestore instance to do this.
  20410. return new il("arrayUnion", t);
  20411. }
  20412. /**
  20413. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  20414. * updateDoc:1} that tells the server to remove the given elements from any
  20415. * array value that already exists on the server. All instances of each element
  20416. * specified will be removed from the array. If the field being modified is not
  20417. * already an array it will be overwritten with an empty array.
  20418. *
  20419. * @param elements - The elements to remove from the array.
  20420. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20421. * `updateDoc()`
  20422. */ function jf(...t) {
  20423. // NOTE: We don't actually parse the data until it's used in set() or
  20424. // update() since we'd need the Firestore instance to do this.
  20425. return new rl("arrayRemove", t);
  20426. }
  20427. /**
  20428. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  20429. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  20430. * the given value.
  20431. *
  20432. * If either the operand or the current field value uses floating point
  20433. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  20434. * integers, values outside of JavaScript's safe number range
  20435. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  20436. * precision loss. Furthermore, once processed by the Firestore backend, all
  20437. * integer operations are capped between -2^63 and 2^63-1.
  20438. *
  20439. * If the current field value is not of type `number`, or if the field does not
  20440. * yet exist, the transformation sets the field to the given value.
  20441. *
  20442. * @param n - The value to increment by.
  20443. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20444. * `updateDoc()`
  20445. */ function zf(t) {
  20446. return new ol("increment", t);
  20447. }
  20448. /**
  20449. * @license
  20450. * Copyright 2020 Google LLC
  20451. *
  20452. * Licensed under the Apache License, Version 2.0 (the "License");
  20453. * you may not use this file except in compliance with the License.
  20454. * You may obtain a copy of the License at
  20455. *
  20456. * http://www.apache.org/licenses/LICENSE-2.0
  20457. *
  20458. * Unless required by applicable law or agreed to in writing, software
  20459. * distributed under the License is distributed on an "AS IS" BASIS,
  20460. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20461. * See the License for the specific language governing permissions and
  20462. * limitations under the License.
  20463. */
  20464. /**
  20465. * Creates a write batch, used for performing multiple writes as a single
  20466. * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}
  20467. * is 500.
  20468. *
  20469. * Unlike transactions, write batches are persisted offline and therefore are
  20470. * preferable when you don't need to condition your writes on read data.
  20471. *
  20472. * @returns A {@link WriteBatch} that can be used to atomically execute multiple
  20473. * writes.
  20474. */ function Wf(t) {
  20475. return bh(t = uh(t, vh)), new Bf(t, (e => Ef(t, e)));
  20476. }
  20477. /**
  20478. * @license
  20479. * Copyright 2021 Google LLC
  20480. *
  20481. * Licensed under the Apache License, Version 2.0 (the "License");
  20482. * you may not use this file except in compliance with the License.
  20483. * You may obtain a copy of the License at
  20484. *
  20485. * http://www.apache.org/licenses/LICENSE-2.0
  20486. *
  20487. * Unless required by applicable law or agreed to in writing, software
  20488. * distributed under the License is distributed on an "AS IS" BASIS,
  20489. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20490. * See the License for the specific language governing permissions and
  20491. * limitations under the License.
  20492. */ function Hf(t, e) {
  20493. var n;
  20494. const s = bh(t = uh(t, vh));
  20495. if (!s._uninitializedComponentsProvider || "memory" === (null === (n = s._uninitializedComponentsProvider) || void 0 === n ? void 0 : n._offlineKind))
  20496. // PORTING NOTE: We don't return an error if the user has not enabled
  20497. // persistence since `enableIndexeddbPersistence()` can fail on the Web.
  20498. return M("Cannot enable indexes when persistence is disabled"), Promise.resolve();
  20499. const i = function(t) {
  20500. const e = "string" == typeof t ? function(t) {
  20501. try {
  20502. return JSON.parse(t);
  20503. } catch (t) {
  20504. throw new U(q.INVALID_ARGUMENT, "Failed to parse JSON: " + (null == t ? void 0 : t.message));
  20505. }
  20506. }(t) : t, n = [];
  20507. if (Array.isArray(e.indexes)) for (const t of e.indexes) {
  20508. const e = Jf(t, "collectionGroup"), s = [];
  20509. if (Array.isArray(t.fields)) for (const e of t.fields) {
  20510. const t = ml("setIndexConfiguration", Jf(e, "fieldPath"));
  20511. "CONTAINS" === e.arrayConfig ? s.push(new _t(t, 2 /* IndexKind.CONTAINS */)) : "ASCENDING" === e.order ? s.push(new _t(t, 0 /* IndexKind.ASCENDING */)) : "DESCENDING" === e.order && s.push(new _t(t, 1 /* IndexKind.DESCENDING */));
  20512. }
  20513. n.push(new lt(lt.UNKNOWN_ID, e, s, gt.empty()));
  20514. }
  20515. return n;
  20516. }(e);
  20517. return Za(s, i);
  20518. }
  20519. function Jf(t, e) {
  20520. if ("string" != typeof t[e]) throw new U(q.INVALID_ARGUMENT, "Missing string value for: " + e);
  20521. return t[e];
  20522. }
  20523. /**
  20524. * Cloud Firestore
  20525. *
  20526. * @packageDocumentation
  20527. */ !function(t, e = !0) {
  20528. !function(t) {
  20529. S = t;
  20530. }(app.SDK_VERSION), app._registerComponent(new component.Component("firestore", ((t, {instanceIdentifier: n, options: s}) => {
  20531. const i = t.getProvider("app").getImmediate(), r = new vh(new z(t.getProvider("auth-internal")), new Y(t.getProvider("app-check-internal")), function(t, e) {
  20532. if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new U(q.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
  20533. return new Oe(t.options.projectId, e);
  20534. }(i, n), i);
  20535. return s = Object.assign({
  20536. useFetchStreams: e
  20537. }, s), r._setSettings(s), r;
  20538. }), "PUBLIC").setMultipleInstances(!0)), app.registerVersion(b, "3.13.0", t),
  20539. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  20540. app.registerVersion(b, "3.13.0", "cjs2017");
  20541. }();
  20542. exports.AbstractUserDataWriter = Wl;
  20543. exports.AggregateField = Lh;
  20544. exports.AggregateQuerySnapshot = qh;
  20545. exports.Bytes = Uh;
  20546. exports.CACHE_SIZE_UNLIMITED = Ah;
  20547. exports.CollectionReference = wh;
  20548. exports.DocumentReference = fh;
  20549. exports.DocumentSnapshot = sf;
  20550. exports.FieldPath = Kh;
  20551. exports.FieldValue = Qh;
  20552. exports.Firestore = vh;
  20553. exports.FirestoreError = U;
  20554. exports.GeoPoint = jh;
  20555. exports.LoadBundleTask = Eh;
  20556. exports.Query = dh;
  20557. exports.QueryCompositeFilterConstraint = Vl;
  20558. exports.QueryConstraint = vl;
  20559. exports.QueryDocumentSnapshot = rf;
  20560. exports.QueryEndAtConstraint = Bl;
  20561. exports.QueryFieldFilterConstraint = Pl;
  20562. exports.QueryLimitConstraint = Nl;
  20563. exports.QueryOrderByConstraint = Cl;
  20564. exports.QuerySnapshot = of;
  20565. exports.QueryStartAtConstraint = $l;
  20566. exports.SnapshotMetadata = nf;
  20567. exports.Timestamp = it;
  20568. exports.Transaction = qf;
  20569. exports.WriteBatch = Bf;
  20570. exports._DatabaseId = Oe;
  20571. exports._DocumentKey = ht;
  20572. exports._EmptyAppCheckTokenProvider = X;
  20573. exports._EmptyAuthCredentialsProvider = Q;
  20574. exports._FieldPath = at;
  20575. exports._TestingHooks = ci;
  20576. exports._cast = uh;
  20577. exports._debugAssert = B;
  20578. exports._isBase64Available = be;
  20579. exports._logWarn = M;
  20580. exports._validateIsNotUsedTogether = sh;
  20581. exports.addDoc = pf;
  20582. exports.aggregateFieldEqual = tf;
  20583. exports.aggregateQuerySnapshotEqual = ef;
  20584. exports.and = Dl;
  20585. exports.arrayRemove = jf;
  20586. exports.arrayUnion = Qf;
  20587. exports.average = Xl;
  20588. exports.clearIndexedDbPersistence = xh;
  20589. exports.collection = _h;
  20590. exports.collectionGroup = mh;
  20591. exports.connectFirestoreEmulator = lh;
  20592. exports.count = Zl;
  20593. exports.deleteDoc = yf;
  20594. exports.deleteField = Kf;
  20595. exports.disableNetwork = Mh;
  20596. exports.doc = gh;
  20597. exports.documentId = Gh;
  20598. exports.enableIndexedDbPersistence = Sh;
  20599. exports.enableMultiTabIndexedDbPersistence = Dh;
  20600. exports.enableNetwork = kh;
  20601. exports.endAt = ql;
  20602. exports.endBefore = Ll;
  20603. exports.ensureFirestoreConfigured = bh;
  20604. exports.executeWrite = Ef;
  20605. exports.getAggregateFromServer = Rf;
  20606. exports.getCountFromServer = vf;
  20607. exports.getDoc = af;
  20608. exports.getDocFromCache = lf;
  20609. exports.getDocFromServer = ff;
  20610. exports.getDocs = df;
  20611. exports.getDocsFromCache = wf;
  20612. exports.getDocsFromServer = _f;
  20613. exports.getFirestore = Ph;
  20614. exports.increment = zf;
  20615. exports.initializeFirestore = Rh;
  20616. exports.limit = kl;
  20617. exports.limitToLast = Ml;
  20618. exports.loadBundle = Oh;
  20619. exports.memoryEagerGarbageCollector = Df;
  20620. exports.memoryLocalCache = xf;
  20621. exports.memoryLruGarbageCollector = Cf;
  20622. exports.namedQuery = Fh;
  20623. exports.onSnapshot = If;
  20624. exports.onSnapshotsInSync = Tf;
  20625. exports.or = Sl;
  20626. exports.orderBy = xl;
  20627. exports.persistentLocalCache = Nf;
  20628. exports.persistentMultipleTabManager = Of;
  20629. exports.persistentSingleTabManager = $f;
  20630. exports.query = Rl;
  20631. exports.queryEqual = ph;
  20632. exports.refEqual = yh;
  20633. exports.runTransaction = Uf;
  20634. exports.serverTimestamp = Gf;
  20635. exports.setDoc = mf;
  20636. exports.setIndexConfiguration = Hf;
  20637. exports.setLogLevel = x;
  20638. exports.snapshotEqual = cf;
  20639. exports.startAfter = Fl;
  20640. exports.startAt = Ol;
  20641. exports.sum = Yl;
  20642. exports.terminate = $h;
  20643. exports.updateDoc = gf;
  20644. exports.waitForPendingWrites = Nh;
  20645. exports.where = bl;
  20646. exports.writeBatch = Wf;
  20647. //# sourceMappingURL=index.cjs.js.map