index.esm5.js 911 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160
  1. import { __extends as t, __awaiter as e, __generator as n, __spreadArray as r } from "tslib";
  2. import { SDK_VERSION as i, _registerComponent as o, registerVersion as u, _getProvider, getApp as a, _removeServiceInstance as s } from "@firebase/app";
  3. import { Component as c } from "@firebase/component";
  4. import { Logger as l, LogLevel as h } from "@firebase/logger";
  5. import { FirebaseError as f, getUA as d, isSafari as p, getModularInstance as v, isIndexedDBAvailable as m, createMockUserToken as y, deepEqual as g, getDefaultEmulatorHostnameAndPort as w } from "@firebase/util";
  6. import { Integer as b, XhrIo as I, EventType as E, ErrorCode as T, createWebChannelTransport as S, getStatEventTarget as _, FetchXmlHttpFactory as D, WebChannel as C, Event as x, Stat as N, Md5 as A } from "@firebase/webchannel-wrapper";
  7. var k = "@firebase/firestore", O = /** @class */ function() {
  8. function t(t) {
  9. this.uid = t;
  10. }
  11. return t.prototype.isAuthenticated = function() {
  12. return null != this.uid;
  13. },
  14. /**
  15. * Returns a key representing this user, suitable for inclusion in a
  16. * dictionary.
  17. */
  18. t.prototype.toKey = function() {
  19. return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
  20. }, t.prototype.isEqual = function(t) {
  21. return t.uid === this.uid;
  22. }, t;
  23. }();
  24. /**
  25. * @license
  26. * Copyright 2017 Google LLC
  27. *
  28. * Licensed under the Apache License, Version 2.0 (the "License");
  29. * you may not use this file except in compliance with the License.
  30. * You may obtain a copy of the License at
  31. *
  32. * http://www.apache.org/licenses/LICENSE-2.0
  33. *
  34. * Unless required by applicable law or agreed to in writing, software
  35. * distributed under the License is distributed on an "AS IS" BASIS,
  36. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37. * See the License for the specific language governing permissions and
  38. * limitations under the License.
  39. */
  40. /**
  41. * Simple wrapper around a nullable UID. Mostly exists to make code more
  42. * readable.
  43. */
  44. /** A user with a null UID. */ O.UNAUTHENTICATED = new O(null),
  45. // TODO(mikelehen): Look into getting a proper uid-equivalent for
  46. // non-FirebaseAuth providers.
  47. O.GOOGLE_CREDENTIALS = new O("google-credentials-uid"), O.FIRST_PARTY = new O("first-party-uid"),
  48. O.MOCK_USER = new O("mock-user");
  49. /**
  50. * @license
  51. * Copyright 2017 Google LLC
  52. *
  53. * Licensed under the Apache License, Version 2.0 (the "License");
  54. * you may not use this file except in compliance with the License.
  55. * You may obtain a copy of the License at
  56. *
  57. * http://www.apache.org/licenses/LICENSE-2.0
  58. *
  59. * Unless required by applicable law or agreed to in writing, software
  60. * distributed under the License is distributed on an "AS IS" BASIS,
  61. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  62. * See the License for the specific language governing permissions and
  63. * limitations under the License.
  64. */
  65. var F = "9.23.0", P = new l("@firebase/firestore");
  66. /**
  67. * @license
  68. * Copyright 2017 Google LLC
  69. *
  70. * Licensed under the Apache License, Version 2.0 (the "License");
  71. * you may not use this file except in compliance with the License.
  72. * You may obtain a copy of the License at
  73. *
  74. * http://www.apache.org/licenses/LICENSE-2.0
  75. *
  76. * Unless required by applicable law or agreed to in writing, software
  77. * distributed under the License is distributed on an "AS IS" BASIS,
  78. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  79. * See the License for the specific language governing permissions and
  80. * limitations under the License.
  81. */
  82. // Helper methods are needed because variables can't be exported as read/write
  83. function R() {
  84. return P.logLevel;
  85. }
  86. /**
  87. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  88. *
  89. * @param logLevel - The verbosity you set for activity and error logging. Can
  90. * be any of the following values:
  91. *
  92. * <ul>
  93. * <li>`debug` for the most verbose logging level, primarily for
  94. * debugging.</li>
  95. * <li>`error` to log errors only.</li>
  96. * <li><code>`silent` to turn off logging.</li>
  97. * </ul>
  98. */ function V(t) {
  99. P.setLogLevel(t);
  100. }
  101. function M(t) {
  102. for (var e = [], n = 1; n < arguments.length; n++) e[n - 1] = arguments[n];
  103. if (P.logLevel <= h.DEBUG) {
  104. var i = e.map(B);
  105. P.debug.apply(P, r([ "Firestore (".concat(F, "): ").concat(t) ], i, !1));
  106. }
  107. }
  108. function L(t) {
  109. for (var e = [], n = 1; n < arguments.length; n++) e[n - 1] = arguments[n];
  110. if (P.logLevel <= h.ERROR) {
  111. var i = e.map(B);
  112. P.error.apply(P, r([ "Firestore (".concat(F, "): ").concat(t) ], i, !1));
  113. }
  114. }
  115. /**
  116. * @internal
  117. */ function q(t) {
  118. for (var e = [], n = 1; n < arguments.length; n++) e[n - 1] = arguments[n];
  119. if (P.logLevel <= h.WARN) {
  120. var i = e.map(B);
  121. P.warn.apply(P, r([ "Firestore (".concat(F, "): ").concat(t) ], i, !1));
  122. }
  123. }
  124. /**
  125. * Converts an additional log parameter to a string representation.
  126. */ function B(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. */ var e;
  151. }
  152. /**
  153. * @license
  154. * Copyright 2017 Google LLC
  155. *
  156. * Licensed under the Apache License, Version 2.0 (the "License");
  157. * you may not use this file except in compliance with the License.
  158. * You may obtain a copy of the License at
  159. *
  160. * http://www.apache.org/licenses/LICENSE-2.0
  161. *
  162. * Unless required by applicable law or agreed to in writing, software
  163. * distributed under the License is distributed on an "AS IS" BASIS,
  164. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  165. * See the License for the specific language governing permissions and
  166. * limitations under the License.
  167. */
  168. /**
  169. * Unconditionally fails, throwing an Error with the given message.
  170. * Messages are stripped in production builds.
  171. *
  172. * Returns `never` and can be used in expressions:
  173. * @example
  174. * let futureVar = fail('not implemented yet');
  175. */ function U(t) {
  176. void 0 === t && (t = "Unexpected state");
  177. // Log the failure in addition to throw an exception, just in case the
  178. // exception is swallowed.
  179. var e = "FIRESTORE (".concat(F, ") 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 L(e), new Error(e)
  184. /**
  185. * Fails if the given assertion condition is false, throwing an Error with the
  186. * given message if it did.
  187. *
  188. * Messages are stripped in production builds.
  189. */;
  190. }
  191. function z(t, e) {
  192. t || U();
  193. }
  194. /**
  195. * Fails if the given assertion condition is false, throwing an Error with the
  196. * given message if it did.
  197. *
  198. * The code of callsites invoking this function are stripped out in production
  199. * builds. Any side-effects of code within the debugAssert() invocation will not
  200. * happen in this case.
  201. *
  202. * @internal
  203. */ function G(t, e) {
  204. t || U();
  205. }
  206. /**
  207. * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
  208. * instance of `T` before casting.
  209. */ function j(t,
  210. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  211. e) {
  212. return t;
  213. }
  214. /**
  215. * @license
  216. * Copyright 2017 Google LLC
  217. *
  218. * Licensed under the Apache License, Version 2.0 (the "License");
  219. * you may not use this file except in compliance with the License.
  220. * You may obtain a copy of the License at
  221. *
  222. * http://www.apache.org/licenses/LICENSE-2.0
  223. *
  224. * Unless required by applicable law or agreed to in writing, software
  225. * distributed under the License is distributed on an "AS IS" BASIS,
  226. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  227. * See the License for the specific language governing permissions and
  228. * limitations under the License.
  229. */ var K = {
  230. // Causes are copied from:
  231. // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  232. /** Not an error; returned on success. */
  233. OK: "ok",
  234. /** The operation was cancelled (typically by the caller). */
  235. CANCELLED: "cancelled",
  236. /** Unknown error or an error from a different error domain. */
  237. UNKNOWN: "unknown",
  238. /**
  239. * Client specified an invalid argument. Note that this differs from
  240. * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
  241. * problematic regardless of the state of the system (e.g., a malformed file
  242. * name).
  243. */
  244. INVALID_ARGUMENT: "invalid-argument",
  245. /**
  246. * Deadline expired before operation could complete. For operations that
  247. * change the state of the system, this error may be returned even if the
  248. * operation has completed successfully. For example, a successful response
  249. * from a server could have been delayed long enough for the deadline to
  250. * expire.
  251. */
  252. DEADLINE_EXCEEDED: "deadline-exceeded",
  253. /** Some requested entity (e.g., file or directory) was not found. */
  254. NOT_FOUND: "not-found",
  255. /**
  256. * Some entity that we attempted to create (e.g., file or directory) already
  257. * exists.
  258. */
  259. ALREADY_EXISTS: "already-exists",
  260. /**
  261. * The caller does not have permission to execute the specified operation.
  262. * PERMISSION_DENIED must not be used for rejections caused by exhausting
  263. * some resource (use RESOURCE_EXHAUSTED instead for those errors).
  264. * PERMISSION_DENIED must not be used if the caller can not be identified
  265. * (use UNAUTHENTICATED instead for those errors).
  266. */
  267. PERMISSION_DENIED: "permission-denied",
  268. /**
  269. * The request does not have valid authentication credentials for the
  270. * operation.
  271. */
  272. UNAUTHENTICATED: "unauthenticated",
  273. /**
  274. * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  275. * entire file system is out of space.
  276. */
  277. RESOURCE_EXHAUSTED: "resource-exhausted",
  278. /**
  279. * Operation was rejected because the system is not in a state required for
  280. * the operation's execution. For example, directory to be deleted may be
  281. * non-empty, an rmdir operation is applied to a non-directory, etc.
  282. *
  283. * A litmus test that may help a service implementor in deciding
  284. * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  285. * (a) Use UNAVAILABLE if the client can retry just the failing call.
  286. * (b) Use ABORTED if the client should retry at a higher-level
  287. * (e.g., restarting a read-modify-write sequence).
  288. * (c) Use FAILED_PRECONDITION if the client should not retry until
  289. * the system state has been explicitly fixed. E.g., if an "rmdir"
  290. * fails because the directory is non-empty, FAILED_PRECONDITION
  291. * should be returned since the client should not retry unless
  292. * they have first fixed up the directory by deleting files from it.
  293. * (d) Use FAILED_PRECONDITION if the client performs conditional
  294. * REST Get/Update/Delete on a resource and the resource on the
  295. * server does not match the condition. E.g., conflicting
  296. * read-modify-write on the same resource.
  297. */
  298. FAILED_PRECONDITION: "failed-precondition",
  299. /**
  300. * The operation was aborted, typically due to a concurrency issue like
  301. * sequencer check failures, transaction aborts, etc.
  302. *
  303. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  304. * and UNAVAILABLE.
  305. */
  306. ABORTED: "aborted",
  307. /**
  308. * Operation was attempted past the valid range. E.g., seeking or reading
  309. * past end of file.
  310. *
  311. * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
  312. * if the system state changes. For example, a 32-bit file system will
  313. * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
  314. * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  315. * an offset past the current file size.
  316. *
  317. * There is a fair bit of overlap between FAILED_PRECONDITION and
  318. * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  319. * when it applies so that callers who are iterating through a space can
  320. * easily look for an OUT_OF_RANGE error to detect when they are done.
  321. */
  322. OUT_OF_RANGE: "out-of-range",
  323. /** Operation is not implemented or not supported/enabled in this service. */
  324. UNIMPLEMENTED: "unimplemented",
  325. /**
  326. * Internal errors. Means some invariants expected by underlying System has
  327. * been broken. If you see one of these errors, Something is very broken.
  328. */
  329. INTERNAL: "internal",
  330. /**
  331. * The service is currently unavailable. This is a most likely a transient
  332. * condition and may be corrected by retrying with a backoff.
  333. *
  334. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  335. * and UNAVAILABLE.
  336. */
  337. UNAVAILABLE: "unavailable",
  338. /** Unrecoverable data loss or corruption. */
  339. DATA_LOSS: "data-loss"
  340. }, Q = /** @class */ function(e) {
  341. /** @hideconstructor */
  342. function n(
  343. /**
  344. * The backend error code associated with this error.
  345. */
  346. t,
  347. /**
  348. * A custom error description.
  349. */
  350. n) {
  351. var r = this;
  352. return (r = e.call(this, t, n) || this).code = t, r.message = n,
  353. // HACK: We write a toString property directly because Error is not a real
  354. // class and so inheritance does not work correctly. We could alternatively
  355. // do the same "back-door inheritance" trick that FirebaseError does.
  356. r.toString = function() {
  357. return "".concat(r.name, ": [code=").concat(r.code, "]: ").concat(r.message);
  358. }, r;
  359. }
  360. return t(n, e), n;
  361. }(f), W = function() {
  362. var t = this;
  363. this.promise = new Promise((function(e, n) {
  364. t.resolve = e, t.reject = n;
  365. }));
  366. }, H = function(t, e) {
  367. this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", "Bearer ".concat(t));
  368. }, Y = /** @class */ function() {
  369. function t() {}
  370. return t.prototype.getToken = function() {
  371. return Promise.resolve(null);
  372. }, t.prototype.invalidateToken = function() {}, t.prototype.start = function(t, e) {
  373. // Fire with initial user.
  374. t.enqueueRetryable((function() {
  375. return e(O.UNAUTHENTICATED);
  376. }));
  377. }, t.prototype.shutdown = function() {}, t;
  378. }(), X = /** @class */ function() {
  379. function t(t) {
  380. this.token = t,
  381. /**
  382. * Stores the listener registered with setChangeListener()
  383. * This isn't actually necessary since the UID never changes, but we use this
  384. * to verify the listen contract is adhered to in tests.
  385. */
  386. this.changeListener = null;
  387. }
  388. return t.prototype.getToken = function() {
  389. return Promise.resolve(this.token);
  390. }, t.prototype.invalidateToken = function() {}, t.prototype.start = function(t, e) {
  391. var n = this;
  392. this.changeListener = e,
  393. // Fire with initial user.
  394. t.enqueueRetryable((function() {
  395. return e(n.token.user);
  396. }));
  397. }, t.prototype.shutdown = function() {
  398. this.changeListener = null;
  399. }, t;
  400. }(), J = /** @class */ function() {
  401. function t(t) {
  402. this.t = t,
  403. /** Tracks the current User. */
  404. this.currentUser = O.UNAUTHENTICATED,
  405. /**
  406. * Counter used to detect if the token changed while a getToken request was
  407. * outstanding.
  408. */
  409. this.i = 0, this.forceRefresh = !1, this.auth = null;
  410. }
  411. return t.prototype.start = function(t, r) {
  412. var i = this, o = this.i, u = function(t) {
  413. return i.i !== o ? (o = i.i, r(t)) : Promise.resolve();
  414. }, a = new W;
  415. this.o = function() {
  416. i.i++, i.currentUser = i.u(), a.resolve(), a = new W, t.enqueueRetryable((function() {
  417. return u(i.currentUser);
  418. }));
  419. };
  420. var s = function() {
  421. var r = a;
  422. t.enqueueRetryable((function() {
  423. return e(i, void 0, void 0, (function() {
  424. return n(this, (function(t) {
  425. switch (t.label) {
  426. case 0:
  427. return [ 4 /*yield*/ , r.promise ];
  428. case 1:
  429. return t.sent(), [ 4 /*yield*/ , u(this.currentUser) ];
  430. case 2:
  431. return t.sent(), [ 2 /*return*/ ];
  432. }
  433. }));
  434. }));
  435. }));
  436. }, c = function(t) {
  437. M("FirebaseAuthCredentialsProvider", "Auth detected"), i.auth = t, i.auth.addAuthTokenListener(i.o),
  438. s();
  439. };
  440. this.t.onInit((function(t) {
  441. return c(t);
  442. })),
  443. // Our users can initialize Auth right after Firestore, so we give it
  444. // a chance to register itself with the component framework before we
  445. // determine whether to start up in unauthenticated mode.
  446. setTimeout((function() {
  447. if (!i.auth) {
  448. var t = i.t.getImmediate({
  449. optional: !0
  450. });
  451. t ? c(t) : (
  452. // If auth is still not available, proceed with `null` user
  453. M("FirebaseAuthCredentialsProvider", "Auth not yet detected"), a.resolve(), a = new W);
  454. }
  455. }), 0), s();
  456. }, t.prototype.getToken = function() {
  457. var t = this, e = this.i, n = this.forceRefresh;
  458. // Take note of the current value of the tokenCounter so that this method
  459. // can fail (with an ABORTED error) if there is a token change while the
  460. // request is outstanding.
  461. return this.forceRefresh = !1, this.auth ? this.auth.getToken(n).then((function(n) {
  462. // Cancel the request since the token changed while the request was
  463. // outstanding so the response is potentially for a previous user (which
  464. // user, we can't be sure).
  465. return t.i !== e ? (M("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."),
  466. t.getToken()) : n ? (z("string" == typeof n.accessToken), new H(n.accessToken, t.currentUser)) : null;
  467. })) : Promise.resolve(null);
  468. }, t.prototype.invalidateToken = function() {
  469. this.forceRefresh = !0;
  470. }, t.prototype.shutdown = function() {
  471. this.auth && this.auth.removeAuthTokenListener(this.o);
  472. },
  473. // Auth.getUid() can return null even with a user logged in. It is because
  474. // getUid() is synchronous, but the auth code populating Uid is asynchronous.
  475. // This method should only be called in the AuthTokenListener callback
  476. // to guarantee to get the actual user.
  477. t.prototype.u = function() {
  478. var t = this.auth && this.auth.getUid();
  479. return z(null === t || "string" == typeof t), new O(t);
  480. }, t;
  481. }(), Z = /** @class */ function() {
  482. function t(t, e, n) {
  483. this.h = t, this.l = e, this.m = n, this.type = "FirstParty", this.user = O.FIRST_PARTY,
  484. this.g = new Map
  485. /**
  486. * Gets an authorization token, using a provided factory function, or return
  487. * null.
  488. */;
  489. }
  490. return t.prototype.p = function() {
  491. return this.m ? this.m() : null;
  492. }, Object.defineProperty(t.prototype, "headers", {
  493. get: function() {
  494. this.g.set("X-Goog-AuthUser", this.h);
  495. // Use array notation to prevent minification
  496. var t = this.p();
  497. return t && this.g.set("Authorization", t), this.l && this.g.set("X-Goog-Iam-Authorization-Token", this.l),
  498. this.g;
  499. },
  500. enumerable: !1,
  501. configurable: !0
  502. }), t;
  503. }(), $ = /** @class */ function() {
  504. function t(t, e, n) {
  505. this.h = t, this.l = e, this.m = n;
  506. }
  507. return t.prototype.getToken = function() {
  508. return Promise.resolve(new Z(this.h, this.l, this.m));
  509. }, t.prototype.start = function(t, e) {
  510. // Fire with initial uid.
  511. t.enqueueRetryable((function() {
  512. return e(O.FIRST_PARTY);
  513. }));
  514. }, t.prototype.shutdown = function() {}, t.prototype.invalidateToken = function() {},
  515. t;
  516. }(), tt = function(t) {
  517. this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
  518. }, et = /** @class */ function() {
  519. function t(t) {
  520. this.I = t, this.forceRefresh = !1, this.appCheck = null, this.T = null;
  521. }
  522. return t.prototype.start = function(t, e) {
  523. var n = this, r = function(t) {
  524. null != t.error && M("FirebaseAppCheckTokenProvider", "Error getting App Check token; using placeholder token instead. Error: ".concat(t.error.message));
  525. var r = t.token !== n.T;
  526. return n.T = t.token, M("FirebaseAppCheckTokenProvider", "Received ".concat(r ? "new" : "existing", " token.")),
  527. r ? e(t.token) : Promise.resolve();
  528. };
  529. this.o = function(e) {
  530. t.enqueueRetryable((function() {
  531. return r(e);
  532. }));
  533. };
  534. var i = function(t) {
  535. M("FirebaseAppCheckTokenProvider", "AppCheck detected"), n.appCheck = t, n.appCheck.addTokenListener(n.o);
  536. };
  537. this.I.onInit((function(t) {
  538. return i(t);
  539. })),
  540. // Our users can initialize AppCheck after Firestore, so we give it
  541. // a chance to register itself with the component framework.
  542. setTimeout((function() {
  543. if (!n.appCheck) {
  544. var t = n.I.getImmediate({
  545. optional: !0
  546. });
  547. t ? i(t) :
  548. // If AppCheck is still not available, proceed without it.
  549. M("FirebaseAppCheckTokenProvider", "AppCheck not yet detected");
  550. }
  551. }), 0);
  552. }, t.prototype.getToken = function() {
  553. var t = this, e = this.forceRefresh;
  554. return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(e).then((function(e) {
  555. return e ? (z("string" == typeof e.token), t.T = e.token, new tt(e.token)) : null;
  556. })) : Promise.resolve(null);
  557. }, t.prototype.invalidateToken = function() {
  558. this.forceRefresh = !0;
  559. }, t.prototype.shutdown = function() {
  560. this.appCheck && this.appCheck.removeTokenListener(this.o);
  561. }, t;
  562. }(), nt = /** @class */ function() {
  563. function t() {}
  564. return t.prototype.getToken = function() {
  565. return Promise.resolve(new tt(""));
  566. }, t.prototype.invalidateToken = function() {}, t.prototype.start = function(t, e) {},
  567. t.prototype.shutdown = function() {}, t;
  568. }();
  569. /** An error returned by a Firestore operation. */
  570. /**
  571. * Builds a CredentialsProvider depending on the type of
  572. * the credentials passed in.
  573. */
  574. /**
  575. * @license
  576. * Copyright 2020 Google LLC
  577. *
  578. * Licensed under the Apache License, Version 2.0 (the "License");
  579. * you may not use this file except in compliance with the License.
  580. * You may obtain a copy of the License at
  581. *
  582. * http://www.apache.org/licenses/LICENSE-2.0
  583. *
  584. * Unless required by applicable law or agreed to in writing, software
  585. * distributed under the License is distributed on an "AS IS" BASIS,
  586. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  587. * See the License for the specific language governing permissions and
  588. * limitations under the License.
  589. */
  590. /**
  591. * Generates `nBytes` of random bytes.
  592. *
  593. * If `nBytes < 0` , an error will be thrown.
  594. */
  595. function rt(t) {
  596. // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
  597. var e =
  598. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  599. "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);
  600. if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else
  601. // Falls back to Math.random
  602. for (var r = 0; r < t; r++) n[r] = Math.floor(256 * Math.random());
  603. return n;
  604. }
  605. /**
  606. * @license
  607. * Copyright 2017 Google LLC
  608. *
  609. * Licensed under the Apache License, Version 2.0 (the "License");
  610. * you may not use this file except in compliance with the License.
  611. * You may obtain a copy of the License at
  612. *
  613. * http://www.apache.org/licenses/LICENSE-2.0
  614. *
  615. * Unless required by applicable law or agreed to in writing, software
  616. * distributed under the License is distributed on an "AS IS" BASIS,
  617. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  618. * See the License for the specific language governing permissions and
  619. * limitations under the License.
  620. */ var it = /** @class */ function() {
  621. function t() {}
  622. return t.A = function() {
  623. for (
  624. // Alphanumeric characters
  625. var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length, n = ""
  626. // The largest byte value that is a multiple of `char.length`.
  627. ; n.length < 20; ) for (var r = rt(40), i = 0; i < r.length; ++i)
  628. // Only accept values that are [0, maxMultiple), this ensures they can
  629. // be evenly mapped to indices of `chars` via a modulo operation.
  630. n.length < 20 && r[i] < e && (n += t.charAt(r[i] % t.length));
  631. return n;
  632. }, t;
  633. }();
  634. function ot(t, e) {
  635. return t < e ? -1 : t > e ? 1 : 0;
  636. }
  637. /** Helper to compare arrays using isEqual(). */ function ut(t, e, n) {
  638. return t.length === e.length && t.every((function(t, r) {
  639. return n(t, e[r]);
  640. }));
  641. }
  642. /**
  643. * Returns the immediate lexicographically-following string. This is useful to
  644. * construct an inclusive range for indexeddb iterators.
  645. */ function at(t) {
  646. // Return the input string, with an additional NUL byte appended.
  647. return t + "\0";
  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. */
  665. // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
  666. /**
  667. * A `Timestamp` represents a point in time independent of any time zone or
  668. * calendar, represented as seconds and fractions of seconds at nanosecond
  669. * resolution in UTC Epoch time.
  670. *
  671. * It is encoded using the Proleptic Gregorian Calendar which extends the
  672. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  673. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  674. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  675. * 9999-12-31T23:59:59.999999999Z.
  676. *
  677. * For examples and further specifications, refer to the
  678. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  679. */ var st = /** @class */ function() {
  680. /**
  681. * Creates a new timestamp.
  682. *
  683. * @param seconds - The number of seconds of UTC time since Unix epoch
  684. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  685. * 9999-12-31T23:59:59Z inclusive.
  686. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  687. * resolution. Negative second values with fractions must still have
  688. * non-negative nanoseconds values that count forward in time. Must be
  689. * from 0 to 999,999,999 inclusive.
  690. */
  691. function t(
  692. /**
  693. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  694. */
  695. t,
  696. /**
  697. * The fractions of a second at nanosecond resolution.*
  698. */
  699. e) {
  700. if (this.seconds = t, this.nanoseconds = e, e < 0) throw new Q(K.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  701. if (e >= 1e9) throw new Q(K.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  702. if (t < -62135596800) throw new Q(K.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  703. // This will break in the year 10,000.
  704. if (t >= 253402300800) throw new Q(K.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  705. }
  706. /**
  707. * Creates a new timestamp with the current date, with millisecond precision.
  708. *
  709. * @returns a new timestamp representing the current date.
  710. */ return t.now = function() {
  711. return t.fromMillis(Date.now());
  712. },
  713. /**
  714. * Creates a new timestamp from the given date.
  715. *
  716. * @param date - The date to initialize the `Timestamp` from.
  717. * @returns A new `Timestamp` representing the same point in time as the given
  718. * date.
  719. */
  720. t.fromDate = function(e) {
  721. return t.fromMillis(e.getTime());
  722. },
  723. /**
  724. * Creates a new timestamp from the given number of milliseconds.
  725. *
  726. * @param milliseconds - Number of milliseconds since Unix epoch
  727. * 1970-01-01T00:00:00Z.
  728. * @returns A new `Timestamp` representing the same point in time as the given
  729. * number of milliseconds.
  730. */
  731. t.fromMillis = function(e) {
  732. var n = Math.floor(e / 1e3);
  733. return new t(n, Math.floor(1e6 * (e - 1e3 * n)));
  734. },
  735. /**
  736. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  737. * causes a loss of precision since `Date` objects only support millisecond
  738. * precision.
  739. *
  740. * @returns JavaScript `Date` object representing the same point in time as
  741. * this `Timestamp`, with millisecond precision.
  742. */
  743. t.prototype.toDate = function() {
  744. return new Date(this.toMillis());
  745. },
  746. /**
  747. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  748. * epoch). This operation causes a loss of precision.
  749. *
  750. * @returns The point in time corresponding to this timestamp, represented as
  751. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  752. */
  753. t.prototype.toMillis = function() {
  754. return 1e3 * this.seconds + this.nanoseconds / 1e6;
  755. }, t.prototype._compareTo = function(t) {
  756. return this.seconds === t.seconds ? ot(this.nanoseconds, t.nanoseconds) : ot(this.seconds, t.seconds);
  757. },
  758. /**
  759. * Returns true if this `Timestamp` is equal to the provided one.
  760. *
  761. * @param other - The `Timestamp` to compare against.
  762. * @returns true if this `Timestamp` is equal to the provided one.
  763. */
  764. t.prototype.isEqual = function(t) {
  765. return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
  766. },
  767. /** Returns a textual representation of this `Timestamp`. */ t.prototype.toString = function() {
  768. return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
  769. },
  770. /** Returns a JSON-serializable representation of this `Timestamp`. */ t.prototype.toJSON = function() {
  771. return {
  772. seconds: this.seconds,
  773. nanoseconds: this.nanoseconds
  774. };
  775. },
  776. /**
  777. * Converts this object to a primitive string, which allows `Timestamp` objects
  778. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  779. */
  780. t.prototype.valueOf = function() {
  781. // This method returns a string of the form <seconds>.<nanoseconds> where
  782. // <seconds> is translated to have a non-negative value and both <seconds>
  783. // and <nanoseconds> are left-padded with zeroes to be a consistent length.
  784. // Strings with this format then have a lexiographical ordering that matches
  785. // the expected ordering. The <seconds> translation is done to avoid having
  786. // a leading negative sign (i.e. a leading '-' character) in its string
  787. // representation, which would affect its lexiographical ordering.
  788. var t = this.seconds - -62135596800;
  789. // Note: Up to 12 decimal digits are required to represent all valid
  790. // 'seconds' values.
  791. return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
  792. }, t;
  793. }(), ct = /** @class */ function() {
  794. function t(t) {
  795. this.timestamp = t;
  796. }
  797. return t.fromTimestamp = function(e) {
  798. return new t(e);
  799. }, t.min = function() {
  800. return new t(new st(0, 0));
  801. }, t.max = function() {
  802. return new t(new st(253402300799, 999999999));
  803. }, t.prototype.compareTo = function(t) {
  804. return this.timestamp._compareTo(t.timestamp);
  805. }, t.prototype.isEqual = function(t) {
  806. return this.timestamp.isEqual(t.timestamp);
  807. },
  808. /** Returns a number representation of the version for use in spec tests. */ t.prototype.toMicroseconds = function() {
  809. // Convert to microseconds.
  810. return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
  811. }, t.prototype.toString = function() {
  812. return "SnapshotVersion(" + this.timestamp.toString() + ")";
  813. }, t.prototype.toTimestamp = function() {
  814. return this.timestamp;
  815. }, t;
  816. }(), lt = /** @class */ function() {
  817. function t(t, e, n) {
  818. void 0 === e ? e = 0 : e > t.length && U(), void 0 === n ? n = t.length - e : n > t.length - e && U(),
  819. this.segments = t, this.offset = e, this.len = n;
  820. }
  821. return Object.defineProperty(t.prototype, "length", {
  822. get: function() {
  823. return this.len;
  824. },
  825. enumerable: !1,
  826. configurable: !0
  827. }), t.prototype.isEqual = function(e) {
  828. return 0 === t.comparator(this, e);
  829. }, t.prototype.child = function(e) {
  830. var n = this.segments.slice(this.offset, this.limit());
  831. return e instanceof t ? e.forEach((function(t) {
  832. n.push(t);
  833. })) : n.push(e), this.construct(n);
  834. },
  835. /** The index of one past the last segment of the path. */ t.prototype.limit = function() {
  836. return this.offset + this.length;
  837. }, t.prototype.popFirst = function(t) {
  838. return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);
  839. }, t.prototype.popLast = function() {
  840. return this.construct(this.segments, this.offset, this.length - 1);
  841. }, t.prototype.firstSegment = function() {
  842. return this.segments[this.offset];
  843. }, t.prototype.lastSegment = function() {
  844. return this.get(this.length - 1);
  845. }, t.prototype.get = function(t) {
  846. return this.segments[this.offset + t];
  847. }, t.prototype.isEmpty = function() {
  848. return 0 === this.length;
  849. }, t.prototype.isPrefixOf = function(t) {
  850. if (t.length < this.length) return !1;
  851. for (var e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  852. return !0;
  853. }, t.prototype.isImmediateParentOf = function(t) {
  854. if (this.length + 1 !== t.length) return !1;
  855. for (var e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  856. return !0;
  857. }, t.prototype.forEach = function(t) {
  858. for (var e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);
  859. }, t.prototype.toArray = function() {
  860. return this.segments.slice(this.offset, this.limit());
  861. }, t.comparator = function(t, e) {
  862. for (var n = Math.min(t.length, e.length), r = 0; r < n; r++) {
  863. var i = t.get(r), o = e.get(r);
  864. if (i < o) return -1;
  865. if (i > o) return 1;
  866. }
  867. return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
  868. }, t;
  869. }(), ht = /** @class */ function(e) {
  870. function n() {
  871. return null !== e && e.apply(this, arguments) || this;
  872. }
  873. return t(n, e), n.prototype.construct = function(t, e, r) {
  874. return new n(t, e, r);
  875. }, n.prototype.canonicalString = function() {
  876. // NOTE: The client is ignorant of any path segments containing escape
  877. // sequences (e.g. __id123__) and just passes them through raw (they exist
  878. // for legacy reasons and should not be used frequently).
  879. return this.toArray().join("/");
  880. }, n.prototype.toString = function() {
  881. return this.canonicalString();
  882. },
  883. /**
  884. * Creates a resource path from the given slash-delimited string. If multiple
  885. * arguments are provided, all components are combined. Leading and trailing
  886. * slashes from all components are ignored.
  887. */
  888. n.fromString = function() {
  889. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  890. // NOTE: The client is ignorant of any path segments containing escape
  891. // sequences (e.g. __id123__) and just passes them through raw (they exist
  892. // for legacy reasons and should not be used frequently).
  893. for (var r = [], i = 0, o = t; i < o.length; i++) {
  894. var u = o[i];
  895. if (u.indexOf("//") >= 0) throw new Q(K.INVALID_ARGUMENT, "Invalid segment (".concat(u, "). Paths must not contain // in them."));
  896. // Strip leading and traling slashed.
  897. r.push.apply(r, u.split("/").filter((function(t) {
  898. return t.length > 0;
  899. })));
  900. }
  901. return new n(r);
  902. }, n.emptyPath = function() {
  903. return new n([]);
  904. }, n;
  905. }(lt), ft = /^[_a-zA-Z][_a-zA-Z0-9]*$/, dt = /** @class */ function(e) {
  906. function n() {
  907. return null !== e && e.apply(this, arguments) || this;
  908. }
  909. return t(n, e), n.prototype.construct = function(t, e, r) {
  910. return new n(t, e, r);
  911. },
  912. /**
  913. * Returns true if the string could be used as a segment in a field path
  914. * without escaping.
  915. */
  916. n.isValidIdentifier = function(t) {
  917. return ft.test(t);
  918. }, n.prototype.canonicalString = function() {
  919. return this.toArray().map((function(t) {
  920. return t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), n.isValidIdentifier(t) || (t = "`" + t + "`"),
  921. t;
  922. })).join(".");
  923. }, n.prototype.toString = function() {
  924. return this.canonicalString();
  925. },
  926. /**
  927. * Returns true if this field references the key of a document.
  928. */
  929. n.prototype.isKeyField = function() {
  930. return 1 === this.length && "__name__" === this.get(0);
  931. },
  932. /**
  933. * The field designating the key of a document.
  934. */
  935. n.keyField = function() {
  936. return new n([ "__name__" ]);
  937. },
  938. /**
  939. * Parses a field string from the given server-formatted string.
  940. *
  941. * - Splitting the empty string is not allowed (for now at least).
  942. * - Empty segments within the string (e.g. if there are two consecutive
  943. * separators) are not allowed.
  944. *
  945. * TODO(b/37244157): we should make this more strict. Right now, it allows
  946. * non-identifier path components, even if they aren't escaped.
  947. */
  948. n.fromServerFormat = function(t) {
  949. for (var e = [], r = "", i = 0, o = function() {
  950. if (0 === r.length) throw new Q(K.INVALID_ARGUMENT, "Invalid field path (".concat(t, "). Paths must not be empty, begin with '.', end with '.', or contain '..'"));
  951. e.push(r), r = "";
  952. }, u = !1; i < t.length; ) {
  953. var a = t[i];
  954. if ("\\" === a) {
  955. if (i + 1 === t.length) throw new Q(K.INVALID_ARGUMENT, "Path has trailing escape character: " + t);
  956. var s = t[i + 1];
  957. if ("\\" !== s && "." !== s && "`" !== s) throw new Q(K.INVALID_ARGUMENT, "Path has invalid escape sequence: " + t);
  958. r += s, i += 2;
  959. } else "`" === a ? (u = !u, i++) : "." !== a || u ? (r += a, i++) : (o(), i++);
  960. }
  961. if (o(), u) throw new Q(K.INVALID_ARGUMENT, "Unterminated ` in path: " + t);
  962. return new n(e);
  963. }, n.emptyPath = function() {
  964. return new n([]);
  965. }, n;
  966. }(lt), pt = /** @class */ function() {
  967. function t(t) {
  968. this.path = t;
  969. }
  970. return t.fromPath = function(e) {
  971. return new t(ht.fromString(e));
  972. }, t.fromName = function(e) {
  973. return new t(ht.fromString(e).popFirst(5));
  974. }, t.empty = function() {
  975. return new t(ht.emptyPath());
  976. }, Object.defineProperty(t.prototype, "collectionGroup", {
  977. get: function() {
  978. return this.path.popLast().lastSegment();
  979. },
  980. enumerable: !1,
  981. configurable: !0
  982. }),
  983. /** Returns true if the document is in the specified collectionId. */ t.prototype.hasCollectionId = function(t) {
  984. return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
  985. },
  986. /** Returns the collection group (i.e. the name of the parent collection) for this key. */ t.prototype.getCollectionGroup = function() {
  987. return this.path.get(this.path.length - 2);
  988. },
  989. /** Returns the fully qualified path to the parent collection. */ t.prototype.getCollectionPath = function() {
  990. return this.path.popLast();
  991. }, t.prototype.isEqual = function(t) {
  992. return null !== t && 0 === ht.comparator(this.path, t.path);
  993. }, t.prototype.toString = function() {
  994. return this.path.toString();
  995. }, t.comparator = function(t, e) {
  996. return ht.comparator(t.path, e.path);
  997. }, t.isDocumentKey = function(t) {
  998. return t.length % 2 == 0;
  999. },
  1000. /**
  1001. * Creates and returns a new document key with the given segments.
  1002. *
  1003. * @param segments - The segments of the path to the document
  1004. * @returns A new instance of DocumentKey
  1005. */
  1006. t.fromSegments = function(e) {
  1007. return new t(new ht(e.slice()));
  1008. }, t;
  1009. }(), vt = function(
  1010. /**
  1011. * The index ID. Returns -1 if the index ID is not available (e.g. the index
  1012. * has not yet been persisted).
  1013. */
  1014. t,
  1015. /** The collection ID this index applies to. */
  1016. e,
  1017. /** The field segments for this index. */
  1018. n,
  1019. /** Shows how up-to-date the index is for the current user. */
  1020. r) {
  1021. this.indexId = t, this.collectionGroup = e, this.fields = n, this.indexState = r;
  1022. };
  1023. /**
  1024. * @license
  1025. * Copyright 2017 Google LLC
  1026. *
  1027. * Licensed under the Apache License, Version 2.0 (the "License");
  1028. * you may not use this file except in compliance with the License.
  1029. * You may obtain a copy of the License at
  1030. *
  1031. * http://www.apache.org/licenses/LICENSE-2.0
  1032. *
  1033. * Unless required by applicable law or agreed to in writing, software
  1034. * distributed under the License is distributed on an "AS IS" BASIS,
  1035. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1036. * See the License for the specific language governing permissions and
  1037. * limitations under the License.
  1038. */
  1039. /**
  1040. * A version of a document in Firestore. This corresponds to the version
  1041. * timestamp, such as update_time or read_time.
  1042. */
  1043. /** An ID for an index that has not yet been added to persistence. */
  1044. /** Returns the ArrayContains/ArrayContainsAny segment for this index. */
  1045. function mt(t) {
  1046. return t.fields.find((function(t) {
  1047. return 2 /* IndexKind.CONTAINS */ === t.kind;
  1048. }));
  1049. }
  1050. /** Returns all directional (ascending/descending) segments for this index. */ function yt(t) {
  1051. return t.fields.filter((function(t) {
  1052. return 2 /* IndexKind.CONTAINS */ !== t.kind;
  1053. }));
  1054. }
  1055. /**
  1056. * Returns the order of the document key component for the given index.
  1057. *
  1058. * PORTING NOTE: This is only used in the Web IndexedDb implementation.
  1059. */
  1060. /**
  1061. * Compares indexes by collection group and segments. Ignores update time and
  1062. * index ID.
  1063. */ function gt(t, e) {
  1064. var n = ot(t.collectionGroup, e.collectionGroup);
  1065. if (0 !== n) return n;
  1066. for (var r = 0; r < Math.min(t.fields.length, e.fields.length); ++r) if (0 !== (n = bt(t.fields[r], e.fields[r]))) return n;
  1067. return ot(t.fields.length, e.fields.length);
  1068. }
  1069. /** Returns a debug representation of the field index */ vt.UNKNOWN_ID = -1;
  1070. /** An index component consisting of field path and index type. */
  1071. var wt = function(
  1072. /** The field path of the component. */
  1073. t,
  1074. /** The fields sorting order. */
  1075. e) {
  1076. this.fieldPath = t, this.kind = e;
  1077. };
  1078. function bt(t, e) {
  1079. var n = dt.comparator(t.fieldPath, e.fieldPath);
  1080. return 0 !== n ? n : ot(t.kind, e.kind);
  1081. }
  1082. /**
  1083. * Stores the "high water mark" that indicates how updated the Index is for the
  1084. * current user.
  1085. */ var It = /** @class */ function() {
  1086. function t(
  1087. /**
  1088. * Indicates when the index was last updated (relative to other indexes).
  1089. */
  1090. t,
  1091. /** The the latest indexed read time, document and batch id. */
  1092. e) {
  1093. this.sequenceNumber = t, this.offset = e
  1094. /** The state of an index that has not yet been backfilled. */;
  1095. }
  1096. return t.empty = function() {
  1097. return new t(0, St.min());
  1098. }, t;
  1099. }();
  1100. /**
  1101. * Creates an offset that matches all documents with a read time higher than
  1102. * `readTime`.
  1103. */ function Et(t, e) {
  1104. // We want to create an offset that matches all documents with a read time
  1105. // greater than the provided read time. To do so, we technically need to
  1106. // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use
  1107. // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use
  1108. // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches
  1109. // all valid document IDs.
  1110. var n = t.toTimestamp().seconds, r = t.toTimestamp().nanoseconds + 1, i = ct.fromTimestamp(1e9 === r ? new st(n + 1, 0) : new st(n, r));
  1111. return new St(i, pt.empty(), e);
  1112. }
  1113. /** Creates a new offset based on the provided document. */ function Tt(t) {
  1114. return new St(t.readTime, t.key, -1);
  1115. }
  1116. /**
  1117. * Stores the latest read time, document and batch ID that were processed for an
  1118. * index.
  1119. */ var St = /** @class */ function() {
  1120. function t(
  1121. /**
  1122. * The latest read time version that has been indexed by Firestore for this
  1123. * field index.
  1124. */
  1125. t,
  1126. /**
  1127. * The key of the last document that was indexed for this query. Use
  1128. * `DocumentKey.empty()` if no document has been indexed.
  1129. */
  1130. e,
  1131. /*
  1132. * The largest mutation batch id that's been processed by Firestore.
  1133. */
  1134. n) {
  1135. this.readTime = t, this.documentKey = e, this.largestBatchId = n
  1136. /** Returns an offset that sorts before all regular offsets. */;
  1137. }
  1138. return t.min = function() {
  1139. return new t(ct.min(), pt.empty(), -1);
  1140. },
  1141. /** Returns an offset that sorts after all regular offsets. */ t.max = function() {
  1142. return new t(ct.max(), pt.empty(), -1);
  1143. }, t;
  1144. }();
  1145. function _t(t, e) {
  1146. var n = t.readTime.compareTo(e.readTime);
  1147. return 0 !== n ? n : 0 !== (n = pt.comparator(t.documentKey, e.documentKey)) ? n : ot(t.largestBatchId, e.largestBatchId);
  1148. }
  1149. /**
  1150. * @license
  1151. * Copyright 2020 Google LLC
  1152. *
  1153. * Licensed under the Apache License, Version 2.0 (the "License");
  1154. * you may not use this file except in compliance with the License.
  1155. * You may obtain a copy of the License at
  1156. *
  1157. * http://www.apache.org/licenses/LICENSE-2.0
  1158. *
  1159. * Unless required by applicable law or agreed to in writing, software
  1160. * distributed under the License is distributed on an "AS IS" BASIS,
  1161. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1162. * See the License for the specific language governing permissions and
  1163. * limitations under the License.
  1164. */ var Dt = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.", Ct = /** @class */ function() {
  1165. function t() {
  1166. this.onCommittedListeners = [];
  1167. }
  1168. return t.prototype.addOnCommittedListener = function(t) {
  1169. this.onCommittedListeners.push(t);
  1170. }, t.prototype.raiseOnCommittedEvent = function() {
  1171. this.onCommittedListeners.forEach((function(t) {
  1172. return t();
  1173. }));
  1174. }, t;
  1175. }();
  1176. /**
  1177. * A base class representing a persistence transaction, encapsulating both the
  1178. * transaction's sequence numbers as well as a list of onCommitted listeners.
  1179. *
  1180. * When you call Persistence.runTransaction(), it will create a transaction and
  1181. * pass it to your callback. You then pass it to any method that operates
  1182. * on persistence.
  1183. */
  1184. /**
  1185. * @license
  1186. * Copyright 2017 Google LLC
  1187. *
  1188. * Licensed under the Apache License, Version 2.0 (the "License");
  1189. * you may not use this file except in compliance with the License.
  1190. * You may obtain a copy of the License at
  1191. *
  1192. * http://www.apache.org/licenses/LICENSE-2.0
  1193. *
  1194. * Unless required by applicable law or agreed to in writing, software
  1195. * distributed under the License is distributed on an "AS IS" BASIS,
  1196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1197. * See the License for the specific language governing permissions and
  1198. * limitations under the License.
  1199. */
  1200. /**
  1201. * Verifies the error thrown by a LocalStore operation. If a LocalStore
  1202. * operation fails because the primary lease has been taken by another client,
  1203. * we ignore the error (the persistence layer will immediately call
  1204. * `applyPrimaryLease` to propagate the primary state change). All other errors
  1205. * are re-thrown.
  1206. *
  1207. * @param err - An error returned by a LocalStore operation.
  1208. * @returns A Promise that resolves after we recovered, or the original error.
  1209. */
  1210. function xt(t) {
  1211. return e(this, void 0, void 0, (function() {
  1212. return n(this, (function(e) {
  1213. if (t.code !== K.FAILED_PRECONDITION || t.message !== Dt) throw t;
  1214. return M("LocalStore", "Unexpectedly lost primary lease"), [ 2 /*return*/ ];
  1215. }));
  1216. }));
  1217. }
  1218. /**
  1219. * @license
  1220. * Copyright 2017 Google LLC
  1221. *
  1222. * Licensed under the Apache License, Version 2.0 (the "License");
  1223. * you may not use this file except in compliance with the License.
  1224. * You may obtain a copy of the License at
  1225. *
  1226. * http://www.apache.org/licenses/LICENSE-2.0
  1227. *
  1228. * Unless required by applicable law or agreed to in writing, software
  1229. * distributed under the License is distributed on an "AS IS" BASIS,
  1230. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1231. * See the License for the specific language governing permissions and
  1232. * limitations under the License.
  1233. */
  1234. /**
  1235. * PersistencePromise is essentially a re-implementation of Promise except
  1236. * it has a .next() method instead of .then() and .next() and .catch() callbacks
  1237. * are executed synchronously when a PersistencePromise resolves rather than
  1238. * asynchronously (Promise implementations use setImmediate() or similar).
  1239. *
  1240. * This is necessary to interoperate with IndexedDB which will automatically
  1241. * commit transactions if control is returned to the event loop without
  1242. * synchronously initiating another operation on the transaction.
  1243. *
  1244. * NOTE: .then() and .catch() only allow a single consumer, unlike normal
  1245. * Promises.
  1246. */ var Nt = /** @class */ function() {
  1247. function t(t) {
  1248. var e = this;
  1249. // NOTE: next/catchCallback will always point to our own wrapper functions,
  1250. // not the user's raw next() or catch() callbacks.
  1251. this.nextCallback = null, this.catchCallback = null,
  1252. // When the operation resolves, we'll set result or error and mark isDone.
  1253. this.result = void 0, this.error = void 0, this.isDone = !1,
  1254. // Set to true when .then() or .catch() are called and prevents additional
  1255. // chaining.
  1256. this.callbackAttached = !1, t((function(t) {
  1257. e.isDone = !0, e.result = t, e.nextCallback &&
  1258. // value should be defined unless T is Void, but we can't express
  1259. // that in the type system.
  1260. e.nextCallback(t);
  1261. }), (function(t) {
  1262. e.isDone = !0, e.error = t, e.catchCallback && e.catchCallback(t);
  1263. }));
  1264. }
  1265. return t.prototype.catch = function(t) {
  1266. return this.next(void 0, t);
  1267. }, t.prototype.next = function(e, n) {
  1268. var r = this;
  1269. return this.callbackAttached && U(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(n, this.error) : this.wrapSuccess(e, this.result) : new t((function(t, i) {
  1270. r.nextCallback = function(n) {
  1271. r.wrapSuccess(e, n).next(t, i);
  1272. }, r.catchCallback = function(e) {
  1273. r.wrapFailure(n, e).next(t, i);
  1274. };
  1275. }));
  1276. }, t.prototype.toPromise = function() {
  1277. var t = this;
  1278. return new Promise((function(e, n) {
  1279. t.next(e, n);
  1280. }));
  1281. }, t.prototype.wrapUserFunction = function(e) {
  1282. try {
  1283. var n = e();
  1284. return n instanceof t ? n : t.resolve(n);
  1285. } catch (e) {
  1286. return t.reject(e);
  1287. }
  1288. }, t.prototype.wrapSuccess = function(e, n) {
  1289. return e ? this.wrapUserFunction((function() {
  1290. return e(n);
  1291. })) : t.resolve(n);
  1292. }, t.prototype.wrapFailure = function(e, n) {
  1293. return e ? this.wrapUserFunction((function() {
  1294. return e(n);
  1295. })) : t.reject(n);
  1296. }, t.resolve = function(e) {
  1297. return new t((function(t, n) {
  1298. t(e);
  1299. }));
  1300. }, t.reject = function(e) {
  1301. return new t((function(t, n) {
  1302. n(e);
  1303. }));
  1304. }, t.waitFor = function(
  1305. // Accept all Promise types in waitFor().
  1306. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1307. e) {
  1308. return new t((function(t, n) {
  1309. var r = 0, i = 0, o = !1;
  1310. e.forEach((function(e) {
  1311. ++r, e.next((function() {
  1312. ++i, o && i === r && t();
  1313. }), (function(t) {
  1314. return n(t);
  1315. }));
  1316. })), o = !0, i === r && t();
  1317. }));
  1318. },
  1319. /**
  1320. * Given an array of predicate functions that asynchronously evaluate to a
  1321. * boolean, implements a short-circuiting `or` between the results. Predicates
  1322. * will be evaluated until one of them returns `true`, then stop. The final
  1323. * result will be whether any of them returned `true`.
  1324. */
  1325. t.or = function(e) {
  1326. for (var n = t.resolve(!1), r = function(e) {
  1327. n = n.next((function(n) {
  1328. return n ? t.resolve(n) : e();
  1329. }));
  1330. }, i = 0, o = e; i < o.length; i++) {
  1331. r(o[i]);
  1332. }
  1333. return n;
  1334. }, t.forEach = function(t, e) {
  1335. var n = this, r = [];
  1336. return t.forEach((function(t, i) {
  1337. r.push(e.call(n, t, i));
  1338. })), this.waitFor(r);
  1339. },
  1340. /**
  1341. * Concurrently map all array elements through asynchronous function.
  1342. */
  1343. t.mapArray = function(e, n) {
  1344. return new t((function(t, r) {
  1345. for (var i = e.length, o = new Array(i), u = 0, a = function(a) {
  1346. var s = a;
  1347. n(e[s]).next((function(e) {
  1348. o[s] = e, ++u === i && t(o);
  1349. }), (function(t) {
  1350. return r(t);
  1351. }));
  1352. }, s = 0; s < i; s++) a(s);
  1353. }));
  1354. },
  1355. /**
  1356. * An alternative to recursive PersistencePromise calls, that avoids
  1357. * potential memory problems from unbounded chains of promises.
  1358. *
  1359. * The `action` will be called repeatedly while `condition` is true.
  1360. */
  1361. t.doWhile = function(e, n) {
  1362. return new t((function(t, r) {
  1363. var i = function() {
  1364. !0 === e() ? n().next((function() {
  1365. i();
  1366. }), r) : t();
  1367. };
  1368. i();
  1369. }));
  1370. }, t;
  1371. }(), At = /** @class */ function() {
  1372. function t(t, e) {
  1373. var n = this;
  1374. this.action = t, this.transaction = e, this.aborted = !1,
  1375. /**
  1376. * A `Promise` that resolves with the result of the IndexedDb transaction.
  1377. */
  1378. this.v = new W, this.transaction.oncomplete = function() {
  1379. n.v.resolve();
  1380. }, this.transaction.onabort = function() {
  1381. e.error ? n.v.reject(new Ft(t, e.error)) : n.v.resolve();
  1382. }, this.transaction.onerror = function(e) {
  1383. var r = Lt(e.target.error);
  1384. n.v.reject(new Ft(t, r));
  1385. };
  1386. }
  1387. return t.open = function(e, n, r, i) {
  1388. try {
  1389. return new t(n, e.transaction(i, r));
  1390. } catch (e) {
  1391. throw new Ft(n, e);
  1392. }
  1393. }, Object.defineProperty(t.prototype, "R", {
  1394. get: function() {
  1395. return this.v.promise;
  1396. },
  1397. enumerable: !1,
  1398. configurable: !0
  1399. }), t.prototype.abort = function(t) {
  1400. t && this.v.reject(t), this.aborted || (M("SimpleDb", "Aborting transaction:", t ? t.message : "Client-initiated abort"),
  1401. this.aborted = !0, this.transaction.abort());
  1402. }, t.prototype.P = function() {
  1403. // If the browser supports V3 IndexedDB, we invoke commit() explicitly to
  1404. // speed up index DB processing if the event loop remains blocks.
  1405. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1406. var t = this.transaction;
  1407. this.aborted || "function" != typeof t.commit || t.commit();
  1408. },
  1409. /**
  1410. * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
  1411. * operations performed on the SimpleDbStore happen within the context of this
  1412. * transaction and it cannot be used anymore once the transaction is
  1413. * completed.
  1414. *
  1415. * Note that we can't actually enforce that the KeyType and ValueType are
  1416. * correct, but they allow type safety through the rest of the consuming code.
  1417. */
  1418. t.prototype.store = function(t) {
  1419. var e = this.transaction.objectStore(t);
  1420. return new Rt(e);
  1421. }, t;
  1422. }(), kt = /** @class */ function() {
  1423. /*
  1424. * Creates a new SimpleDb wrapper for IndexedDb database `name`.
  1425. *
  1426. * Note that `version` must not be a downgrade. IndexedDB does not support
  1427. * downgrading the schema version. We currently do not support any way to do
  1428. * versioning outside of IndexedDB's versioning mechanism, as only
  1429. * version-upgrade transactions are allowed to do things like create
  1430. * objectstores.
  1431. */
  1432. function t(e, n, r) {
  1433. this.name = e, this.version = n, this.V = r,
  1434. // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the
  1435. // bug we're checking for should exist in iOS >= 12.2 and < 13, but for
  1436. // whatever reason it's much harder to hit after 12.2 so we only proactively
  1437. // log on 12.2.
  1438. 12.2 === t.S(d()) && L("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.");
  1439. }
  1440. /** Deletes the specified database. */ return t.delete = function(t) {
  1441. return M("SimpleDb", "Removing database:", t), Vt(window.indexedDB.deleteDatabase(t)).toPromise();
  1442. },
  1443. /** Returns true if IndexedDB is available in the current environment. */ t.D = function() {
  1444. if (!m()) return !1;
  1445. if (t.C()) return !0;
  1446. // We extensively use indexed array values and compound keys,
  1447. // which IE and Edge do not support. However, they still have indexedDB
  1448. // defined on the window, so we need to check for them here and make sure
  1449. // to return that persistence is not enabled for those browsers.
  1450. // For tracking support of this feature, see here:
  1451. // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/
  1452. // Check the UA string to find out the browser.
  1453. var e = d(), n = t.S(e), r = 0 < n && n < 10, i = t.N(e), o = 0 < i && i < 4.5;
  1454. // IE 10
  1455. // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
  1456. // IE 11
  1457. // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
  1458. // Edge
  1459. // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,
  1460. // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
  1461. // iOS Safari: Disable for users running iOS version < 10.
  1462. return !(e.indexOf("MSIE ") > 0 || e.indexOf("Trident/") > 0 || e.indexOf("Edge/") > 0 || r || o);
  1463. },
  1464. /**
  1465. * Returns true if the backing IndexedDB store is the Node IndexedDBShim
  1466. * (see https://github.com/axemclion/IndexedDBShim).
  1467. */
  1468. t.C = function() {
  1469. var t;
  1470. return "undefined" != typeof process && "YES" === (null === (t = process.env) || void 0 === t ? void 0 : t.k);
  1471. },
  1472. /** Helper to get a typed SimpleDbStore from a transaction. */ t.M = function(t, e) {
  1473. return t.store(e);
  1474. },
  1475. // visible for testing
  1476. /** Parse User Agent to determine iOS version. Returns -1 if not found. */
  1477. t.S = function(t) {
  1478. var e = t.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = e ? e[1].split("_").slice(0, 2).join(".") : "-1";
  1479. return Number(n);
  1480. },
  1481. // visible for testing
  1482. /** Parse User Agent to determine Android version. Returns -1 if not found. */
  1483. t.N = function(t) {
  1484. var e = t.match(/Android ([\d.]+)/i), n = e ? e[1].split(".").slice(0, 2).join(".") : "-1";
  1485. return Number(n);
  1486. },
  1487. /**
  1488. * Opens the specified database, creating or upgrading it if necessary.
  1489. */
  1490. t.prototype.$ = function(t) {
  1491. return e(this, void 0, void 0, (function() {
  1492. var e, r = this;
  1493. return n(this, (function(n) {
  1494. switch (n.label) {
  1495. case 0:
  1496. return this.db ? [ 3 /*break*/ , 2 ] : (M("SimpleDb", "Opening database:", this.name),
  1497. e = this, [ 4 /*yield*/ , new Promise((function(e, n) {
  1498. // TODO(mikelehen): Investigate browser compatibility.
  1499. // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
  1500. // suggests IE9 and older WebKit browsers handle upgrade
  1501. // differently. They expect setVersion, as described here:
  1502. // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion
  1503. var i = indexedDB.open(r.name, r.version);
  1504. i.onsuccess = function(t) {
  1505. var n = t.target.result;
  1506. e(n);
  1507. }, i.onblocked = function() {
  1508. n(new Ft(t, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."));
  1509. }, i.onerror = function(e) {
  1510. var r = e.target.error;
  1511. "VersionError" === r.name ? n(new Q(K.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" === r.name ? n(new Q(K.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: " + r)) : n(new Ft(t, r));
  1512. }, i.onupgradeneeded = function(t) {
  1513. M("SimpleDb", 'Database "' + r.name + '" requires upgrade from version:', t.oldVersion);
  1514. var e = t.target.result;
  1515. r.V.O(e, i.transaction, t.oldVersion, r.version).next((function() {
  1516. M("SimpleDb", "Database upgrade to version " + r.version + " complete");
  1517. }));
  1518. };
  1519. })) ]);
  1520. case 1:
  1521. e.db = n.sent(), n.label = 2;
  1522. case 2:
  1523. return [ 2 /*return*/ , (this.F && (this.db.onversionchange = function(t) {
  1524. return r.F(t);
  1525. }), this.db) ];
  1526. }
  1527. }));
  1528. }));
  1529. }, t.prototype.B = function(t) {
  1530. this.F = t, this.db && (this.db.onversionchange = function(e) {
  1531. return t(e);
  1532. });
  1533. }, t.prototype.runTransaction = function(t, r, i, o) {
  1534. return e(this, void 0, void 0, (function() {
  1535. var e, u, a, s, c;
  1536. return n(this, (function(l) {
  1537. switch (l.label) {
  1538. case 0:
  1539. e = "readonly" === r, u = 0, a = function() {
  1540. var r, a, c, l, h, f;
  1541. return n(this, (function(n) {
  1542. switch (n.label) {
  1543. case 0:
  1544. ++u, n.label = 1;
  1545. case 1:
  1546. return n.trys.push([ 1, 4, , 5 ]), [ 4 /*yield*/ , s.$(t) ];
  1547. case 2:
  1548. // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
  1549. // fire), but still return the original transactionFnResult back to the
  1550. // caller.
  1551. return s.db = n.sent(), r = At.open(s.db, t, e ? "readonly" : "readwrite", i), a = o(r).next((function(t) {
  1552. return r.P(), t;
  1553. })).catch((function(t) {
  1554. // Abort the transaction if there was an error.
  1555. return r.abort(t), Nt.reject(t);
  1556. })).toPromise(), c = {}, a.catch((function() {})), [ 4 /*yield*/ , r.R ];
  1557. case 3:
  1558. return [ 2 /*return*/ , (c.value = (
  1559. // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
  1560. // fire), but still return the original transactionFnResult back to the
  1561. // caller.
  1562. n.sent(), a), c) ];
  1563. case 4:
  1564. // TODO(schmidt-sebastian): We could probably be smarter about this and
  1565. // not retry exceptions that are likely unrecoverable (such as quota
  1566. // exceeded errors).
  1567. // Note: We cannot use an instanceof check for FirestoreException, since the
  1568. // exception is wrapped in a generic error by our async/await handling.
  1569. return l = n.sent(), f = "FirebaseError" !== (h = l).name && u < 3, M("SimpleDb", "Transaction failed with error:", h.message, "Retrying:", f),
  1570. s.close(), f ? [ 3 /*break*/ , 5 ] : [ 2 /*return*/ , {
  1571. value: Promise.reject(h)
  1572. } ];
  1573. case 5:
  1574. return [ 2 /*return*/ ];
  1575. }
  1576. }));
  1577. }, s = this, l.label = 1;
  1578. case 1:
  1579. return [ 5 /*yield**/ , a() ];
  1580. case 2:
  1581. if ("object" == typeof (c = l.sent())) return [ 2 /*return*/ , c.value ];
  1582. l.label = 3;
  1583. case 3:
  1584. return [ 3 /*break*/ , 1 ];
  1585. case 4:
  1586. return [ 2 /*return*/ ];
  1587. }
  1588. }));
  1589. }));
  1590. }, t.prototype.close = function() {
  1591. this.db && this.db.close(), this.db = void 0;
  1592. }, t;
  1593. }(), Ot = /** @class */ function() {
  1594. function t(t) {
  1595. this.L = t, this.q = !1, this.U = null;
  1596. }
  1597. return Object.defineProperty(t.prototype, "isDone", {
  1598. get: function() {
  1599. return this.q;
  1600. },
  1601. enumerable: !1,
  1602. configurable: !0
  1603. }), Object.defineProperty(t.prototype, "K", {
  1604. get: function() {
  1605. return this.U;
  1606. },
  1607. enumerable: !1,
  1608. configurable: !0
  1609. }), Object.defineProperty(t.prototype, "cursor", {
  1610. set: function(t) {
  1611. this.L = t;
  1612. },
  1613. enumerable: !1,
  1614. configurable: !0
  1615. }),
  1616. /**
  1617. * This function can be called to stop iteration at any point.
  1618. */
  1619. t.prototype.done = function() {
  1620. this.q = !0;
  1621. },
  1622. /**
  1623. * This function can be called to skip to that next key, which could be
  1624. * an index or a primary key.
  1625. */
  1626. t.prototype.G = function(t) {
  1627. this.U = t;
  1628. },
  1629. /**
  1630. * Delete the current cursor value from the object store.
  1631. *
  1632. * NOTE: You CANNOT do this with a keysOnly query.
  1633. */
  1634. t.prototype.delete = function() {
  1635. return Vt(this.L.delete());
  1636. }, t;
  1637. }(), Ft = /** @class */ function(e) {
  1638. function n(t, n) {
  1639. var r = this;
  1640. return (r = e.call(this, K.UNAVAILABLE, "IndexedDB transaction '".concat(t, "' failed: ").concat(n)) || this).name = "IndexedDbTransactionError",
  1641. r;
  1642. }
  1643. return t(n, e), n;
  1644. }(Q);
  1645. /**
  1646. * @license
  1647. * Copyright 2017 Google LLC
  1648. *
  1649. * Licensed under the Apache License, Version 2.0 (the "License");
  1650. * you may not use this file except in compliance with the License.
  1651. * You may obtain a copy of the License at
  1652. *
  1653. * http://www.apache.org/licenses/LICENSE-2.0
  1654. *
  1655. * Unless required by applicable law or agreed to in writing, software
  1656. * distributed under the License is distributed on an "AS IS" BASIS,
  1657. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1658. * See the License for the specific language governing permissions and
  1659. * limitations under the License.
  1660. */
  1661. // References to `window` are guarded by SimpleDb.isAvailable()
  1662. /* eslint-disable no-restricted-globals */
  1663. /**
  1664. * Wraps an IDBTransaction and exposes a store() method to get a handle to a
  1665. * specific object store.
  1666. */
  1667. /** Verifies whether `e` is an IndexedDbTransactionError. */ function Pt(t) {
  1668. // Use name equality, as instanceof checks on errors don't work with errors
  1669. // that wrap other errors.
  1670. return "IndexedDbTransactionError" === t.name;
  1671. }
  1672. /**
  1673. * A wrapper around an IDBObjectStore providing an API that:
  1674. *
  1675. * 1) Has generic KeyType / ValueType parameters to provide strongly-typed
  1676. * methods for acting against the object store.
  1677. * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every
  1678. * method return a PersistencePromise instead.
  1679. * 3) Provides a higher-level API to avoid needing to do excessive wrapping of
  1680. * intermediate IndexedDB types (IDBCursorWithValue, etc.)
  1681. */ var Rt = /** @class */ function() {
  1682. function t(t) {
  1683. this.store = t;
  1684. }
  1685. return t.prototype.put = function(t, e) {
  1686. var n;
  1687. return void 0 !== e ? (M("SimpleDb", "PUT", this.store.name, t, e), n = this.store.put(e, t)) : (M("SimpleDb", "PUT", this.store.name, "<auto-key>", t),
  1688. n = this.store.put(t)), Vt(n);
  1689. },
  1690. /**
  1691. * Adds a new value into an Object Store and returns the new key. Similar to
  1692. * IndexedDb's `add()`, this method will fail on primary key collisions.
  1693. *
  1694. * @param value - The object to write.
  1695. * @returns The key of the value to add.
  1696. */
  1697. t.prototype.add = function(t) {
  1698. return M("SimpleDb", "ADD", this.store.name, t, t), Vt(this.store.add(t));
  1699. },
  1700. /**
  1701. * Gets the object with the specified key from the specified store, or null
  1702. * if no object exists with the specified key.
  1703. *
  1704. * @key The key of the object to get.
  1705. * @returns The object with the specified key or null if no object exists.
  1706. */
  1707. t.prototype.get = function(t) {
  1708. var e = this;
  1709. // We're doing an unsafe cast to ValueType.
  1710. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1711. return Vt(this.store.get(t)).next((function(n) {
  1712. // Normalize nonexistence to null.
  1713. return void 0 === n && (n = null), M("SimpleDb", "GET", e.store.name, t, n), n;
  1714. }));
  1715. }, t.prototype.delete = function(t) {
  1716. return M("SimpleDb", "DELETE", this.store.name, t), Vt(this.store.delete(t));
  1717. },
  1718. /**
  1719. * If we ever need more of the count variants, we can add overloads. For now,
  1720. * all we need is to count everything in a store.
  1721. *
  1722. * Returns the number of rows in the store.
  1723. */
  1724. t.prototype.count = function() {
  1725. return M("SimpleDb", "COUNT", this.store.name), Vt(this.store.count());
  1726. }, t.prototype.j = function(t, e) {
  1727. var n = this.options(t, e);
  1728. // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly
  1729. // 20% faster. Unfortunately, getAll() does not support custom indices.
  1730. if (n.index || "function" != typeof this.store.getAll) {
  1731. var r = this.cursor(n), i = [];
  1732. return this.W(r, (function(t, e) {
  1733. i.push(e);
  1734. })).next((function() {
  1735. return i;
  1736. }));
  1737. }
  1738. var o = this.store.getAll(n.range);
  1739. return new Nt((function(t, e) {
  1740. o.onerror = function(t) {
  1741. e(t.target.error);
  1742. }, o.onsuccess = function(e) {
  1743. t(e.target.result);
  1744. };
  1745. }));
  1746. },
  1747. /**
  1748. * Loads the first `count` elements from the provided index range. Loads all
  1749. * elements if no limit is provided.
  1750. */
  1751. t.prototype.H = function(t, e) {
  1752. var n = this.store.getAll(t, null === e ? void 0 : e);
  1753. return new Nt((function(t, e) {
  1754. n.onerror = function(t) {
  1755. e(t.target.error);
  1756. }, n.onsuccess = function(e) {
  1757. t(e.target.result);
  1758. };
  1759. }));
  1760. }, t.prototype.J = function(t, e) {
  1761. M("SimpleDb", "DELETE ALL", this.store.name);
  1762. var n = this.options(t, e);
  1763. n.Y = !1;
  1764. var r = this.cursor(n);
  1765. return this.W(r, (function(t, e, n) {
  1766. return n.delete();
  1767. }));
  1768. }, t.prototype.X = function(t, e) {
  1769. var n;
  1770. e ? n = t : (n = {}, e = t);
  1771. var r = this.cursor(n);
  1772. return this.W(r, e);
  1773. },
  1774. /**
  1775. * Iterates over a store, but waits for the given callback to complete for
  1776. * each entry before iterating the next entry. This allows the callback to do
  1777. * asynchronous work to determine if this iteration should continue.
  1778. *
  1779. * The provided callback should return `true` to continue iteration, and
  1780. * `false` otherwise.
  1781. */
  1782. t.prototype.Z = function(t) {
  1783. var e = this.cursor({});
  1784. return new Nt((function(n, r) {
  1785. e.onerror = function(t) {
  1786. var e = Lt(t.target.error);
  1787. r(e);
  1788. }, e.onsuccess = function(e) {
  1789. var r = e.target.result;
  1790. r ? t(r.primaryKey, r.value).next((function(t) {
  1791. t ? r.continue() : n();
  1792. })) : n();
  1793. };
  1794. }));
  1795. }, t.prototype.W = function(t, e) {
  1796. var n = [];
  1797. return new Nt((function(r, i) {
  1798. t.onerror = function(t) {
  1799. i(t.target.error);
  1800. }, t.onsuccess = function(t) {
  1801. var i = t.target.result;
  1802. if (i) {
  1803. var o = new Ot(i), u = e(i.primaryKey, i.value, o);
  1804. if (u instanceof Nt) {
  1805. var a = u.catch((function(t) {
  1806. return o.done(), Nt.reject(t);
  1807. }));
  1808. n.push(a);
  1809. }
  1810. o.isDone ? r() : null === o.K ? i.continue() : i.continue(o.K);
  1811. } else r();
  1812. };
  1813. })).next((function() {
  1814. return Nt.waitFor(n);
  1815. }));
  1816. }, t.prototype.options = function(t, e) {
  1817. var n;
  1818. return void 0 !== t && ("string" == typeof t ? n = t : e = t), {
  1819. index: n,
  1820. range: e
  1821. };
  1822. }, t.prototype.cursor = function(t) {
  1823. var e = "next";
  1824. if (t.reverse && (e = "prev"), t.index) {
  1825. var n = this.store.index(t.index);
  1826. return t.Y ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);
  1827. }
  1828. return this.store.openCursor(t.range, e);
  1829. }, t;
  1830. }();
  1831. /**
  1832. * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror
  1833. * handlers to resolve / reject the PersistencePromise as appropriate.
  1834. */ function Vt(t) {
  1835. return new Nt((function(e, n) {
  1836. t.onsuccess = function(t) {
  1837. var n = t.target.result;
  1838. e(n);
  1839. }, t.onerror = function(t) {
  1840. var e = Lt(t.target.error);
  1841. n(e);
  1842. };
  1843. }));
  1844. }
  1845. // Guard so we only report the error once.
  1846. var Mt = !1;
  1847. function Lt(t) {
  1848. var e = kt.S(d());
  1849. if (e >= 12.2 && e < 13) {
  1850. var n = "An internal error was encountered in the Indexed Database server";
  1851. if (t.message.indexOf(n) >= 0) {
  1852. // Wrap error in a more descriptive one.
  1853. var r = new Q("internal", "IOS_INDEXEDDB_BUG1: IndexedDb has thrown '".concat(n, "'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround."));
  1854. return Mt || (Mt = !0,
  1855. // Throw a global exception outside of this promise chain, for the user to
  1856. // potentially catch.
  1857. setTimeout((function() {
  1858. throw r;
  1859. }), 0)), r;
  1860. }
  1861. }
  1862. return t;
  1863. }
  1864. /** This class is responsible for the scheduling of Index Backfiller. */ var qt = /** @class */ function() {
  1865. function t(t, e) {
  1866. this.asyncQueue = t, this.tt = e, this.task = null;
  1867. }
  1868. return t.prototype.start = function() {
  1869. this.et(15e3);
  1870. }, t.prototype.stop = function() {
  1871. this.task && (this.task.cancel(), this.task = null);
  1872. }, Object.defineProperty(t.prototype, "started", {
  1873. get: function() {
  1874. return null !== this.task;
  1875. },
  1876. enumerable: !1,
  1877. configurable: !0
  1878. }), t.prototype.et = function(t) {
  1879. var r = this;
  1880. M("IndexBackiller", "Scheduled in ".concat(t, "ms")), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */ , t, (function() {
  1881. return e(r, void 0, void 0, (function() {
  1882. var t, e, r, i;
  1883. return n(this, (function(n) {
  1884. switch (n.label) {
  1885. case 0:
  1886. this.task = null, n.label = 1;
  1887. case 1:
  1888. return n.trys.push([ 1, 3, , 7 ]), t = M, e = [ "IndexBackiller" ], r = "Documents written: ".concat,
  1889. [ 4 /*yield*/ , this.tt.nt() ];
  1890. case 2:
  1891. return t.apply(void 0, e.concat([ r.apply("Documents written: ", [ n.sent() ]) ])),
  1892. [ 3 /*break*/ , 7 ];
  1893. case 3:
  1894. return Pt(i = n.sent()) ? (M("IndexBackiller", "Ignoring IndexedDB error during index backfill: ", i),
  1895. [ 3 /*break*/ , 6 ]) : [ 3 /*break*/ , 4 ];
  1896. case 4:
  1897. return [ 4 /*yield*/ , xt(i) ];
  1898. case 5:
  1899. n.sent(), n.label = 6;
  1900. case 6:
  1901. return [ 3 /*break*/ , 7 ];
  1902. case 7:
  1903. return [ 4 /*yield*/ , this.et(6e4) ];
  1904. case 8:
  1905. return n.sent(), [ 2 /*return*/ ];
  1906. }
  1907. }));
  1908. }));
  1909. }));
  1910. }, t;
  1911. }(), Bt = /** @class */ function() {
  1912. function t(
  1913. /**
  1914. * LocalStore provides access to IndexManager and LocalDocumentView.
  1915. * These properties will update when the user changes. Consequently,
  1916. * making a local copy of IndexManager and LocalDocumentView will require
  1917. * updates over time. The simpler solution is to rely on LocalStore to have
  1918. * an up-to-date references to IndexManager and LocalDocumentStore.
  1919. */
  1920. t, e) {
  1921. this.localStore = t, this.persistence = e;
  1922. }
  1923. return t.prototype.nt = function(t) {
  1924. return void 0 === t && (t = 50), e(this, void 0, void 0, (function() {
  1925. var e = this;
  1926. return n(this, (function(n) {
  1927. return [ 2 /*return*/ , this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (function(n) {
  1928. return e.st(n, t);
  1929. })) ];
  1930. }));
  1931. }));
  1932. },
  1933. /** Writes index entries until the cap is reached. Returns the number of documents processed. */ t.prototype.st = function(t, e) {
  1934. var n = this, r = new Set, i = e, o = !0;
  1935. return Nt.doWhile((function() {
  1936. return !0 === o && i > 0;
  1937. }), (function() {
  1938. return n.localStore.indexManager.getNextCollectionGroupToUpdate(t).next((function(e) {
  1939. if (null !== e && !r.has(e)) return M("IndexBackiller", "Processing collection: ".concat(e)),
  1940. n.it(t, e, i).next((function(t) {
  1941. i -= t, r.add(e);
  1942. }));
  1943. o = !1;
  1944. }));
  1945. })).next((function() {
  1946. return e - i;
  1947. }));
  1948. },
  1949. /**
  1950. * Writes entries for the provided collection group. Returns the number of documents processed.
  1951. */
  1952. t.prototype.it = function(t, e, n) {
  1953. var r = this;
  1954. // Use the earliest offset of all field indexes to query the local cache.
  1955. return this.localStore.indexManager.getMinOffsetFromCollectionGroup(t, e).next((function(i) {
  1956. return r.localStore.localDocuments.getNextDocuments(t, e, i, n).next((function(n) {
  1957. var o = n.changes;
  1958. return r.localStore.indexManager.updateIndexEntries(t, o).next((function() {
  1959. return r.rt(i, n);
  1960. })).next((function(n) {
  1961. return M("IndexBackiller", "Updating offset: ".concat(n)), r.localStore.indexManager.updateCollectionGroup(t, e, n);
  1962. })).next((function() {
  1963. return o.size;
  1964. }));
  1965. }));
  1966. }));
  1967. },
  1968. /** Returns the next offset based on the provided documents. */ t.prototype.rt = function(t, e) {
  1969. var n = t;
  1970. return e.changes.forEach((function(t, e) {
  1971. var r = Tt(e);
  1972. _t(r, n) > 0 && (n = r);
  1973. })), new St(n.readTime, n.documentKey, Math.max(e.batchId, t.largestBatchId));
  1974. }, t;
  1975. }(), Ut = /** @class */ function() {
  1976. function t(t, e) {
  1977. var n = this;
  1978. this.previousValue = t, e && (e.sequenceNumberHandler = function(t) {
  1979. return n.ot(t);
  1980. }, this.ut = function(t) {
  1981. return e.writeSequenceNumber(t);
  1982. });
  1983. }
  1984. return t.prototype.ot = function(t) {
  1985. return this.previousValue = Math.max(t, this.previousValue), this.previousValue;
  1986. }, t.prototype.next = function() {
  1987. var t = ++this.previousValue;
  1988. return this.ut && this.ut(t), t;
  1989. }, t;
  1990. }();
  1991. /** Implements the steps for backfilling indexes. */
  1992. /**
  1993. * Returns whether a variable is either undefined or null.
  1994. */
  1995. function zt(t) {
  1996. return null == t;
  1997. }
  1998. /** Returns whether the value represents -0. */ function Gt(t) {
  1999. // Detect if the value is -0.0. Based on polyfill from
  2000. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  2001. return 0 === t && 1 / t == -1 / 0;
  2002. }
  2003. /**
  2004. * Returns whether a value is an integer and in the safe integer range
  2005. * @param value - The value to test for being an integer and in the safe range
  2006. */ function jt(t) {
  2007. return "number" == typeof t && Number.isInteger(t) && !Gt(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;
  2008. }
  2009. /**
  2010. * @license
  2011. * Copyright 2017 Google LLC
  2012. *
  2013. * Licensed under the Apache License, Version 2.0 (the "License");
  2014. * you may not use this file except in compliance with the License.
  2015. * You may obtain a copy of the License at
  2016. *
  2017. * http://www.apache.org/licenses/LICENSE-2.0
  2018. *
  2019. * Unless required by applicable law or agreed to in writing, software
  2020. * distributed under the License is distributed on an "AS IS" BASIS,
  2021. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2022. * See the License for the specific language governing permissions and
  2023. * limitations under the License.
  2024. */
  2025. /**
  2026. * Encodes a resource path into a IndexedDb-compatible string form.
  2027. */ function Kt(t) {
  2028. for (var e = "", n = 0; n < t.length; n++) e.length > 0 && (e = Wt(e)), e = Qt(t.get(n), e);
  2029. return Wt(e);
  2030. }
  2031. /** Encodes a single segment of a resource path into the given result */ function Qt(t, e) {
  2032. for (var n = e, r = t.length, i = 0; i < r; i++) {
  2033. var o = t.charAt(i);
  2034. switch (o) {
  2035. case "\0":
  2036. n += "";
  2037. break;
  2038. case "":
  2039. n += "";
  2040. break;
  2041. default:
  2042. n += o;
  2043. }
  2044. }
  2045. return n;
  2046. }
  2047. /** Encodes a path separator into the given result */ function Wt(t) {
  2048. return t + "";
  2049. }
  2050. /**
  2051. * Decodes the given IndexedDb-compatible string form of a resource path into
  2052. * a ResourcePath instance. Note that this method is not suitable for use with
  2053. * decoding resource names from the server; those are One Platform format
  2054. * strings.
  2055. */ function Ht(t) {
  2056. // Event the empty path must encode as a path of at least length 2. A path
  2057. // with exactly 2 must be the empty path.
  2058. var e = t.length;
  2059. if (z(e >= 2), 2 === e) return z("" === t.charAt(0) && "" === t.charAt(1)), ht.emptyPath();
  2060. // Escape characters cannot exist past the second-to-last position in the
  2061. // source value.
  2062. for (var n = e - 2, r = [], i = "", o = 0; o < e; ) {
  2063. // The last two characters of a valid encoded path must be a separator, so
  2064. // there must be an end to this segment.
  2065. var u = t.indexOf("", o);
  2066. switch ((u < 0 || u > n) && U(), t.charAt(u + 1)) {
  2067. case "":
  2068. var a = t.substring(o, u), s = void 0;
  2069. 0 === i.length ?
  2070. // Avoid copying for the common case of a segment that excludes \0
  2071. // and \001
  2072. s = a : (s = i += a, i = ""), r.push(s);
  2073. break;
  2074. case "":
  2075. i += t.substring(o, u), i += "\0";
  2076. break;
  2077. case "":
  2078. // The escape character can be used in the output to encode itself.
  2079. i += t.substring(o, u + 1);
  2080. break;
  2081. default:
  2082. U();
  2083. }
  2084. o = u + 2;
  2085. }
  2086. return new ht(r);
  2087. }
  2088. /**
  2089. * @license
  2090. * Copyright 2022 Google LLC
  2091. *
  2092. * Licensed under the Apache License, Version 2.0 (the "License");
  2093. * you may not use this file except in compliance with the License.
  2094. * You may obtain a copy of the License at
  2095. *
  2096. * http://www.apache.org/licenses/LICENSE-2.0
  2097. *
  2098. * Unless required by applicable law or agreed to in writing, software
  2099. * distributed under the License is distributed on an "AS IS" BASIS,
  2100. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2101. * See the License for the specific language governing permissions and
  2102. * limitations under the License.
  2103. */ Ut.ct = -1;
  2104. var Yt = [ "userId", "batchId" ];
  2105. /**
  2106. * @license
  2107. * Copyright 2022 Google LLC
  2108. *
  2109. * Licensed under the Apache License, Version 2.0 (the "License");
  2110. * you may not use this file except in compliance with the License.
  2111. * You may obtain a copy of the License at
  2112. *
  2113. * http://www.apache.org/licenses/LICENSE-2.0
  2114. *
  2115. * Unless required by applicable law or agreed to in writing, software
  2116. * distributed under the License is distributed on an "AS IS" BASIS,
  2117. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2118. * See the License for the specific language governing permissions and
  2119. * limitations under the License.
  2120. */
  2121. /**
  2122. * Name of the IndexedDb object store.
  2123. *
  2124. * Note that the name 'owner' is chosen to ensure backwards compatibility with
  2125. * older clients that only supported single locked access to the persistence
  2126. * layer.
  2127. */
  2128. /**
  2129. * Creates a [userId, encodedPath] key for use in the DbDocumentMutations
  2130. * index to iterate over all at document mutations for a given path or lower.
  2131. */ function Xt(t, e) {
  2132. return [ t, Kt(e) ];
  2133. }
  2134. /**
  2135. * Creates a full index key of [userId, encodedPath, batchId] for inserting
  2136. * and deleting into the DbDocumentMutations index.
  2137. */ function Jt(t, e, n) {
  2138. return [ t, Kt(e), n ];
  2139. }
  2140. /**
  2141. * Because we store all the useful information for this store in the key,
  2142. * there is no useful information to store as the value. The raw (unencoded)
  2143. * path cannot be stored because IndexedDb doesn't store prototype
  2144. * information.
  2145. */ var Zt = {}, $t = [ "prefixPath", "collectionGroup", "readTime", "documentId" ], te = [ "prefixPath", "collectionGroup", "documentId" ], ee = [ "collectionGroup", "readTime", "prefixPath", "documentId" ], ne = [ "canonicalId", "targetId" ], re = [ "targetId", "path" ], ie = [ "path", "targetId" ], oe = [ "collectionId", "parent" ], ue = [ "indexId", "uid" ], ae = [ "uid", "sequenceNumber" ], se = [ "indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey" ], ce = [ "indexId", "uid", "orderedDocumentKey" ], le = [ "userId", "collectionPath", "documentId" ], he = [ "userId", "collectionPath", "largestBatchId" ], fe = [ "userId", "collectionGroup", "largestBatchId" ], de = r(r([], r(r([], r(r([], r(r([], [ "mutationQueues", "mutations", "documentMutations", "remoteDocuments", "targets", "owner", "targetGlobal", "targetDocuments" ], !1), [ "clientMetadata" ], !1), !0), [ "remoteDocumentGlobal" ], !1), !0), [ "collectionParents" ], !1), !0), [ "bundles", "namedQueries" ], !1), pe = r(r([], de, !0), [ "documentOverlays" ], !1), ve = [ "mutationQueues", "mutations", "documentMutations", "remoteDocumentsV14", "targets", "owner", "targetGlobal", "targetDocuments", "clientMetadata", "remoteDocumentGlobal", "collectionParents", "bundles", "namedQueries", "documentOverlays" ], me = ve, ye = r(r([], me, !0), [ "indexConfiguration", "indexState", "indexEntries" ], !1), ge = /** @class */ function(e) {
  2146. function n(t, n) {
  2147. var r = this;
  2148. return (r = e.call(this) || this).ht = t, r.currentSequenceNumber = n, r;
  2149. }
  2150. return t(n, e), n;
  2151. }(Ct);
  2152. /**
  2153. * @license
  2154. * Copyright 2020 Google LLC
  2155. *
  2156. * Licensed under the Apache License, Version 2.0 (the "License");
  2157. * you may not use this file except in compliance with the License.
  2158. * You may obtain a copy of the License at
  2159. *
  2160. * http://www.apache.org/licenses/LICENSE-2.0
  2161. *
  2162. * Unless required by applicable law or agreed to in writing, software
  2163. * distributed under the License is distributed on an "AS IS" BASIS,
  2164. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2165. * See the License for the specific language governing permissions and
  2166. * limitations under the License.
  2167. */ function we(t, e) {
  2168. var n = j(t);
  2169. return kt.M(n.ht, e);
  2170. }
  2171. /**
  2172. * @license
  2173. * Copyright 2017 Google LLC
  2174. *
  2175. * Licensed under the Apache License, Version 2.0 (the "License");
  2176. * you may not use this file except in compliance with the License.
  2177. * You may obtain a copy of the License at
  2178. *
  2179. * http://www.apache.org/licenses/LICENSE-2.0
  2180. *
  2181. * Unless required by applicable law or agreed to in writing, software
  2182. * distributed under the License is distributed on an "AS IS" BASIS,
  2183. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2184. * See the License for the specific language governing permissions and
  2185. * limitations under the License.
  2186. */ function be(t) {
  2187. var e = 0;
  2188. for (var n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;
  2189. return e;
  2190. }
  2191. function Ie(t, e) {
  2192. for (var n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);
  2193. }
  2194. function Ee(t) {
  2195. for (var e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
  2196. return !0;
  2197. }
  2198. /**
  2199. * @license
  2200. * Copyright 2017 Google LLC
  2201. *
  2202. * Licensed under the Apache License, Version 2.0 (the "License");
  2203. * you may not use this file except in compliance with the License.
  2204. * You may obtain a copy of the License at
  2205. *
  2206. * http://www.apache.org/licenses/LICENSE-2.0
  2207. *
  2208. * Unless required by applicable law or agreed to in writing, software
  2209. * distributed under the License is distributed on an "AS IS" BASIS,
  2210. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2211. * See the License for the specific language governing permissions and
  2212. * limitations under the License.
  2213. */
  2214. // An immutable sorted map implementation, based on a Left-leaning Red-Black
  2215. // tree.
  2216. var Te = /** @class */ function() {
  2217. function t(t, e) {
  2218. this.comparator = t, this.root = e || _e.EMPTY;
  2219. }
  2220. // Returns a copy of the map, with the specified key/value added or replaced.
  2221. return t.prototype.insert = function(e, n) {
  2222. return new t(this.comparator, this.root.insert(e, n, this.comparator).copy(null, null, _e.BLACK, null, null));
  2223. },
  2224. // Returns a copy of the map, with the specified key removed.
  2225. t.prototype.remove = function(e) {
  2226. return new t(this.comparator, this.root.remove(e, this.comparator).copy(null, null, _e.BLACK, null, null));
  2227. },
  2228. // Returns the value of the node with the given key, or null.
  2229. t.prototype.get = function(t) {
  2230. for (var e = this.root; !e.isEmpty(); ) {
  2231. var n = this.comparator(t, e.key);
  2232. if (0 === n) return e.value;
  2233. n < 0 ? e = e.left : n > 0 && (e = e.right);
  2234. }
  2235. return null;
  2236. },
  2237. // Returns the index of the element in this sorted map, or -1 if it doesn't
  2238. // exist.
  2239. t.prototype.indexOf = function(t) {
  2240. for (
  2241. // Number of nodes that were pruned when descending right
  2242. var e = 0, n = this.root; !n.isEmpty(); ) {
  2243. var r = this.comparator(t, n.key);
  2244. if (0 === r) return e + n.left.size;
  2245. r < 0 ? n = n.left : (
  2246. // Count all nodes left of the node plus the node itself
  2247. e += n.left.size + 1, n = n.right);
  2248. }
  2249. // Node not found
  2250. return -1;
  2251. }, t.prototype.isEmpty = function() {
  2252. return this.root.isEmpty();
  2253. }, Object.defineProperty(t.prototype, "size", {
  2254. // Returns the total number of nodes in the map.
  2255. get: function() {
  2256. return this.root.size;
  2257. },
  2258. enumerable: !1,
  2259. configurable: !0
  2260. }),
  2261. // Returns the minimum key in the map.
  2262. t.prototype.minKey = function() {
  2263. return this.root.minKey();
  2264. },
  2265. // Returns the maximum key in the map.
  2266. t.prototype.maxKey = function() {
  2267. return this.root.maxKey();
  2268. },
  2269. // Traverses the map in key order and calls the specified action function
  2270. // for each key/value pair. If action returns true, traversal is aborted.
  2271. // Returns the first truthy value returned by action, or the last falsey
  2272. // value returned by action.
  2273. t.prototype.inorderTraversal = function(t) {
  2274. return this.root.inorderTraversal(t);
  2275. }, t.prototype.forEach = function(t) {
  2276. this.inorderTraversal((function(e, n) {
  2277. return t(e, n), !1;
  2278. }));
  2279. }, t.prototype.toString = function() {
  2280. var t = [];
  2281. return this.inorderTraversal((function(e, n) {
  2282. return t.push("".concat(e, ":").concat(n)), !1;
  2283. })), "{".concat(t.join(", "), "}");
  2284. },
  2285. // Traverses the map in reverse key order and calls the specified action
  2286. // function for each key/value pair. If action returns true, traversal is
  2287. // aborted.
  2288. // Returns the first truthy value returned by action, or the last falsey
  2289. // value returned by action.
  2290. t.prototype.reverseTraversal = function(t) {
  2291. return this.root.reverseTraversal(t);
  2292. },
  2293. // Returns an iterator over the SortedMap.
  2294. t.prototype.getIterator = function() {
  2295. return new Se(this.root, null, this.comparator, !1);
  2296. }, t.prototype.getIteratorFrom = function(t) {
  2297. return new Se(this.root, t, this.comparator, !1);
  2298. }, t.prototype.getReverseIterator = function() {
  2299. return new Se(this.root, null, this.comparator, !0);
  2300. }, t.prototype.getReverseIteratorFrom = function(t) {
  2301. return new Se(this.root, t, this.comparator, !0);
  2302. }, t;
  2303. }(), Se = /** @class */ function() {
  2304. function t(t, e, n, r) {
  2305. this.isReverse = r, this.nodeStack = [];
  2306. for (var i = 1; !t.isEmpty(); ) if (i = e ? n(t.key, e) : 1,
  2307. // flip the comparison if we're going in reverse
  2308. e && r && (i *= -1), i < 0)
  2309. // This node is less than our start key. ignore it
  2310. t = this.isReverse ? t.left : t.right; else {
  2311. if (0 === i) {
  2312. // This node is exactly equal to our start key. Push it on the stack,
  2313. // but stop iterating;
  2314. this.nodeStack.push(t);
  2315. break;
  2316. }
  2317. // This node is greater than our start key, add it to the stack and move
  2318. // to the next one
  2319. this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;
  2320. }
  2321. }
  2322. return t.prototype.getNext = function() {
  2323. var t = this.nodeStack.pop(), e = {
  2324. key: t.key,
  2325. value: t.value
  2326. };
  2327. 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),
  2328. t = t.left;
  2329. return e;
  2330. }, t.prototype.hasNext = function() {
  2331. return this.nodeStack.length > 0;
  2332. }, t.prototype.peek = function() {
  2333. if (0 === this.nodeStack.length) return null;
  2334. var t = this.nodeStack[this.nodeStack.length - 1];
  2335. return {
  2336. key: t.key,
  2337. value: t.value
  2338. };
  2339. }, t;
  2340. }(), _e = /** @class */ function() {
  2341. function t(e, n, r, i, o) {
  2342. this.key = e, this.value = n, this.color = null != r ? r : t.RED, this.left = null != i ? i : t.EMPTY,
  2343. this.right = null != o ? o : t.EMPTY, this.size = this.left.size + 1 + this.right.size;
  2344. }
  2345. // Returns a copy of the current node, optionally replacing pieces of it.
  2346. return t.prototype.copy = function(e, n, r, i, o) {
  2347. return new t(null != e ? e : this.key, null != n ? n : this.value, null != r ? r : this.color, null != i ? i : this.left, null != o ? o : this.right);
  2348. }, t.prototype.isEmpty = function() {
  2349. return !1;
  2350. },
  2351. // Traverses the tree in key order and calls the specified action function
  2352. // for each node. If action returns true, traversal is aborted.
  2353. // Returns the first truthy value returned by action, or the last falsey
  2354. // value returned by action.
  2355. t.prototype.inorderTraversal = function(t) {
  2356. return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);
  2357. },
  2358. // Traverses the tree in reverse key order and calls the specified action
  2359. // function for each node. If action returns true, traversal is aborted.
  2360. // Returns the first truthy value returned by action, or the last falsey
  2361. // value returned by action.
  2362. t.prototype.reverseTraversal = function(t) {
  2363. return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);
  2364. },
  2365. // Returns the minimum node in the tree.
  2366. t.prototype.min = function() {
  2367. return this.left.isEmpty() ? this : this.left.min();
  2368. },
  2369. // Returns the maximum key in the tree.
  2370. t.prototype.minKey = function() {
  2371. return this.min().key;
  2372. },
  2373. // Returns the maximum key in the tree.
  2374. t.prototype.maxKey = function() {
  2375. return this.right.isEmpty() ? this.key : this.right.maxKey();
  2376. },
  2377. // Returns new tree, with the key/value added.
  2378. t.prototype.insert = function(t, e, n) {
  2379. var r = this, i = n(t, r.key);
  2380. return (r = i < 0 ? r.copy(null, null, null, r.left.insert(t, e, n), null) : 0 === i ? r.copy(null, e, null, null, null) : r.copy(null, null, null, null, r.right.insert(t, e, n))).fixUp();
  2381. }, t.prototype.removeMin = function() {
  2382. if (this.left.isEmpty()) return t.EMPTY;
  2383. var e = this;
  2384. return e.left.isRed() || e.left.left.isRed() || (e = e.moveRedLeft()), (e = e.copy(null, null, null, e.left.removeMin(), null)).fixUp();
  2385. },
  2386. // Returns new tree, with the specified item removed.
  2387. t.prototype.remove = function(e, n) {
  2388. var r, i = this;
  2389. if (n(e, i.key) < 0) i.left.isEmpty() || i.left.isRed() || i.left.left.isRed() || (i = i.moveRedLeft()),
  2390. i = i.copy(null, null, null, i.left.remove(e, n), null); else {
  2391. if (i.left.isRed() && (i = i.rotateRight()), i.right.isEmpty() || i.right.isRed() || i.right.left.isRed() || (i = i.moveRedRight()),
  2392. 0 === n(e, i.key)) {
  2393. if (i.right.isEmpty()) return t.EMPTY;
  2394. r = i.right.min(), i = i.copy(r.key, r.value, null, null, i.right.removeMin());
  2395. }
  2396. i = i.copy(null, null, null, null, i.right.remove(e, n));
  2397. }
  2398. return i.fixUp();
  2399. }, t.prototype.isRed = function() {
  2400. return this.color;
  2401. },
  2402. // Returns new tree after performing any needed rotations.
  2403. t.prototype.fixUp = function() {
  2404. var t = this;
  2405. return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()),
  2406. t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;
  2407. }, t.prototype.moveRedLeft = function() {
  2408. var t = this.colorFlip();
  2409. return t.right.left.isRed() && (t = (t = (t = t.copy(null, null, null, null, t.right.rotateRight())).rotateLeft()).colorFlip()),
  2410. t;
  2411. }, t.prototype.moveRedRight = function() {
  2412. var t = this.colorFlip();
  2413. return t.left.left.isRed() && (t = (t = t.rotateRight()).colorFlip()), t;
  2414. }, t.prototype.rotateLeft = function() {
  2415. var e = this.copy(null, null, t.RED, null, this.right.left);
  2416. return this.right.copy(null, null, this.color, e, null);
  2417. }, t.prototype.rotateRight = function() {
  2418. var e = this.copy(null, null, t.RED, this.left.right, null);
  2419. return this.left.copy(null, null, this.color, null, e);
  2420. }, t.prototype.colorFlip = function() {
  2421. var t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);
  2422. return this.copy(null, null, !this.color, t, e);
  2423. },
  2424. // For testing.
  2425. t.prototype.checkMaxDepth = function() {
  2426. var t = this.check();
  2427. return Math.pow(2, t) <= this.size + 1;
  2428. },
  2429. // In a balanced RB tree, the black-depth (number of black nodes) from root to
  2430. // leaves is equal on both sides. This function verifies that or asserts.
  2431. t.prototype.check = function() {
  2432. if (this.isRed() && this.left.isRed()) throw U();
  2433. if (this.right.isRed()) throw U();
  2434. var t = this.left.check();
  2435. if (t !== this.right.check()) throw U();
  2436. return t + (this.isRed() ? 0 : 1);
  2437. }, t;
  2438. }();
  2439. // end SortedMap
  2440. // An iterator over an LLRBNode.
  2441. // end LLRBNode
  2442. // Empty node is shared between all LLRB trees.
  2443. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2444. _e.EMPTY = null, _e.RED = !0, _e.BLACK = !1,
  2445. // end LLRBEmptyNode
  2446. _e.EMPTY = new (/** @class */ function() {
  2447. function t() {
  2448. this.size = 0;
  2449. }
  2450. return Object.defineProperty(t.prototype, "key", {
  2451. get: function() {
  2452. throw U();
  2453. },
  2454. enumerable: !1,
  2455. configurable: !0
  2456. }), Object.defineProperty(t.prototype, "value", {
  2457. get: function() {
  2458. throw U();
  2459. },
  2460. enumerable: !1,
  2461. configurable: !0
  2462. }), Object.defineProperty(t.prototype, "color", {
  2463. get: function() {
  2464. throw U();
  2465. },
  2466. enumerable: !1,
  2467. configurable: !0
  2468. }), Object.defineProperty(t.prototype, "left", {
  2469. get: function() {
  2470. throw U();
  2471. },
  2472. enumerable: !1,
  2473. configurable: !0
  2474. }), Object.defineProperty(t.prototype, "right", {
  2475. get: function() {
  2476. throw U();
  2477. },
  2478. enumerable: !1,
  2479. configurable: !0
  2480. }),
  2481. // Returns a copy of the current node.
  2482. t.prototype.copy = function(t, e, n, r, i) {
  2483. return this;
  2484. },
  2485. // Returns a copy of the tree, with the specified key/value added.
  2486. t.prototype.insert = function(t, e, n) {
  2487. return new _e(t, e);
  2488. },
  2489. // Returns a copy of the tree, with the specified key removed.
  2490. t.prototype.remove = function(t, e) {
  2491. return this;
  2492. }, t.prototype.isEmpty = function() {
  2493. return !0;
  2494. }, t.prototype.inorderTraversal = function(t) {
  2495. return !1;
  2496. }, t.prototype.reverseTraversal = function(t) {
  2497. return !1;
  2498. }, t.prototype.minKey = function() {
  2499. return null;
  2500. }, t.prototype.maxKey = function() {
  2501. return null;
  2502. }, t.prototype.isRed = function() {
  2503. return !1;
  2504. },
  2505. // For testing.
  2506. t.prototype.checkMaxDepth = function() {
  2507. return !0;
  2508. }, t.prototype.check = function() {
  2509. return 0;
  2510. }, t;
  2511. }());
  2512. /**
  2513. * @license
  2514. * Copyright 2017 Google LLC
  2515. *
  2516. * Licensed under the Apache License, Version 2.0 (the "License");
  2517. * you may not use this file except in compliance with the License.
  2518. * You may obtain a copy of the License at
  2519. *
  2520. * http://www.apache.org/licenses/LICENSE-2.0
  2521. *
  2522. * Unless required by applicable law or agreed to in writing, software
  2523. * distributed under the License is distributed on an "AS IS" BASIS,
  2524. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2525. * See the License for the specific language governing permissions and
  2526. * limitations under the License.
  2527. */
  2528. /**
  2529. * SortedSet is an immutable (copy-on-write) collection that holds elements
  2530. * in order specified by the provided comparator.
  2531. *
  2532. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  2533. * be equal!
  2534. */
  2535. var De = /** @class */ function() {
  2536. function t(t) {
  2537. this.comparator = t, this.data = new Te(this.comparator);
  2538. }
  2539. return t.prototype.has = function(t) {
  2540. return null !== this.data.get(t);
  2541. }, t.prototype.first = function() {
  2542. return this.data.minKey();
  2543. }, t.prototype.last = function() {
  2544. return this.data.maxKey();
  2545. }, Object.defineProperty(t.prototype, "size", {
  2546. get: function() {
  2547. return this.data.size;
  2548. },
  2549. enumerable: !1,
  2550. configurable: !0
  2551. }), t.prototype.indexOf = function(t) {
  2552. return this.data.indexOf(t);
  2553. },
  2554. /** Iterates elements in order defined by "comparator" */ t.prototype.forEach = function(t) {
  2555. this.data.inorderTraversal((function(e, n) {
  2556. return t(e), !1;
  2557. }));
  2558. },
  2559. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */ t.prototype.forEachInRange = function(t, e) {
  2560. for (var n = this.data.getIteratorFrom(t[0]); n.hasNext(); ) {
  2561. var r = n.getNext();
  2562. if (this.comparator(r.key, t[1]) >= 0) return;
  2563. e(r.key);
  2564. }
  2565. },
  2566. /**
  2567. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  2568. */
  2569. t.prototype.forEachWhile = function(t, e) {
  2570. var n;
  2571. for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) if (!t(n.getNext().key)) return;
  2572. },
  2573. /** Finds the least element greater than or equal to `elem`. */ t.prototype.firstAfterOrEqual = function(t) {
  2574. var e = this.data.getIteratorFrom(t);
  2575. return e.hasNext() ? e.getNext().key : null;
  2576. }, t.prototype.getIterator = function() {
  2577. return new Ce(this.data.getIterator());
  2578. }, t.prototype.getIteratorFrom = function(t) {
  2579. return new Ce(this.data.getIteratorFrom(t));
  2580. },
  2581. /** Inserts or updates an element */ t.prototype.add = function(t) {
  2582. return this.copy(this.data.remove(t).insert(t, !0));
  2583. },
  2584. /** Deletes an element */ t.prototype.delete = function(t) {
  2585. return this.has(t) ? this.copy(this.data.remove(t)) : this;
  2586. }, t.prototype.isEmpty = function() {
  2587. return this.data.isEmpty();
  2588. }, t.prototype.unionWith = function(t) {
  2589. var e = this;
  2590. // Make sure `result` always refers to the larger one of the two sets.
  2591. return e.size < t.size && (e = t, t = this), t.forEach((function(t) {
  2592. e = e.add(t);
  2593. })), e;
  2594. }, t.prototype.isEqual = function(e) {
  2595. if (!(e instanceof t)) return !1;
  2596. if (this.size !== e.size) return !1;
  2597. for (var n = this.data.getIterator(), r = e.data.getIterator(); n.hasNext(); ) {
  2598. var i = n.getNext().key, o = r.getNext().key;
  2599. if (0 !== this.comparator(i, o)) return !1;
  2600. }
  2601. return !0;
  2602. }, t.prototype.toArray = function() {
  2603. var t = [];
  2604. return this.forEach((function(e) {
  2605. t.push(e);
  2606. })), t;
  2607. }, t.prototype.toString = function() {
  2608. var t = [];
  2609. return this.forEach((function(e) {
  2610. return t.push(e);
  2611. })), "SortedSet(" + t.toString() + ")";
  2612. }, t.prototype.copy = function(e) {
  2613. var n = new t(this.comparator);
  2614. return n.data = e, n;
  2615. }, t;
  2616. }(), Ce = /** @class */ function() {
  2617. function t(t) {
  2618. this.iter = t;
  2619. }
  2620. return t.prototype.getNext = function() {
  2621. return this.iter.getNext().key;
  2622. }, t.prototype.hasNext = function() {
  2623. return this.iter.hasNext();
  2624. }, t;
  2625. }();
  2626. /**
  2627. * Compares two sorted sets for equality using their natural ordering. The
  2628. * method computes the intersection and invokes `onAdd` for every element that
  2629. * is in `after` but not `before`. `onRemove` is invoked for every element in
  2630. * `before` but missing from `after`.
  2631. *
  2632. * The method creates a copy of both `before` and `after` and runs in O(n log
  2633. * n), where n is the size of the two lists.
  2634. *
  2635. * @param before - The elements that exist in the original set.
  2636. * @param after - The elements to diff against the original set.
  2637. * @param comparator - The comparator for the elements in before and after.
  2638. * @param onAdd - A function to invoke for every element that is part of `
  2639. * after` but not `before`.
  2640. * @param onRemove - A function to invoke for every element that is part of
  2641. * `before` but not `after`.
  2642. */
  2643. /**
  2644. * Returns the next element from the iterator or `undefined` if none available.
  2645. */
  2646. function xe(t) {
  2647. return t.hasNext() ? t.getNext() : void 0;
  2648. }
  2649. /**
  2650. * @license
  2651. * Copyright 2020 Google LLC
  2652. *
  2653. * Licensed under the Apache License, Version 2.0 (the "License");
  2654. * you may not use this file except in compliance with the License.
  2655. * You may obtain a copy of the License at
  2656. *
  2657. * http://www.apache.org/licenses/LICENSE-2.0
  2658. *
  2659. * Unless required by applicable law or agreed to in writing, software
  2660. * distributed under the License is distributed on an "AS IS" BASIS,
  2661. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2662. * See the License for the specific language governing permissions and
  2663. * limitations under the License.
  2664. */
  2665. /**
  2666. * Provides a set of fields that can be used to partially patch a document.
  2667. * FieldMask is used in conjunction with ObjectValue.
  2668. * Examples:
  2669. * foo - Overwrites foo entirely with the provided value. If foo is not
  2670. * present in the companion ObjectValue, the field is deleted.
  2671. * foo.bar - Overwrites only the field bar of the object foo.
  2672. * If foo is not an object, foo is replaced with an object
  2673. * containing foo
  2674. */ var Ne = /** @class */ function() {
  2675. function t(t) {
  2676. this.fields = t,
  2677. // TODO(dimond): validation of FieldMask
  2678. // Sort the field mask to support `FieldMask.isEqual()` and assert below.
  2679. t.sort(dt.comparator);
  2680. }
  2681. return t.empty = function() {
  2682. return new t([]);
  2683. },
  2684. /**
  2685. * Returns a new FieldMask object that is the result of adding all the given
  2686. * fields paths to this field mask.
  2687. */
  2688. t.prototype.unionWith = function(e) {
  2689. for (var n = new De(dt.comparator), r = 0, i = this.fields; r < i.length; r++) {
  2690. var o = i[r];
  2691. n = n.add(o);
  2692. }
  2693. for (var u = 0, a = e; u < a.length; u++) {
  2694. var s = a[u];
  2695. n = n.add(s);
  2696. }
  2697. return new t(n.toArray());
  2698. },
  2699. /**
  2700. * Verifies that `fieldPath` is included by at least one field in this field
  2701. * mask.
  2702. *
  2703. * This is an O(n) operation, where `n` is the size of the field mask.
  2704. */
  2705. t.prototype.covers = function(t) {
  2706. for (var e = 0, n = this.fields; e < n.length; e++) {
  2707. if (n[e].isPrefixOf(t)) return !0;
  2708. }
  2709. return !1;
  2710. }, t.prototype.isEqual = function(t) {
  2711. return ut(this.fields, t.fields, (function(t, e) {
  2712. return t.isEqual(e);
  2713. }));
  2714. }, t;
  2715. }(), Ae = /** @class */ function(e) {
  2716. function n() {
  2717. var t = this;
  2718. return (t = e.apply(this, arguments) || this).name = "Base64DecodeError", t;
  2719. }
  2720. return t(n, e), n;
  2721. }(Error);
  2722. /**
  2723. * @license
  2724. * Copyright 2023 Google LLC
  2725. *
  2726. * Licensed under the Apache License, Version 2.0 (the "License");
  2727. * you may not use this file except in compliance with the License.
  2728. * You may obtain a copy of the License at
  2729. *
  2730. * http://www.apache.org/licenses/LICENSE-2.0
  2731. *
  2732. * Unless required by applicable law or agreed to in writing, software
  2733. * distributed under the License is distributed on an "AS IS" BASIS,
  2734. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2735. * See the License for the specific language governing permissions and
  2736. * limitations under the License.
  2737. */
  2738. /**
  2739. * An error encountered while decoding base64 string.
  2740. */
  2741. /**
  2742. * @license
  2743. * Copyright 2020 Google LLC
  2744. *
  2745. * Licensed under the Apache License, Version 2.0 (the "License");
  2746. * you may not use this file except in compliance with the License.
  2747. * You may obtain a copy of the License at
  2748. *
  2749. * http://www.apache.org/licenses/LICENSE-2.0
  2750. *
  2751. * Unless required by applicable law or agreed to in writing, software
  2752. * distributed under the License is distributed on an "AS IS" BASIS,
  2753. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2754. * See the License for the specific language governing permissions and
  2755. * limitations under the License.
  2756. */
  2757. /** Converts a Base64 encoded string to a binary string. */
  2758. /** True if and only if the Base64 conversion functions are available. */
  2759. function ke() {
  2760. return "undefined" != typeof atob;
  2761. }
  2762. /**
  2763. * @license
  2764. * Copyright 2020 Google LLC
  2765. *
  2766. * Licensed under the Apache License, Version 2.0 (the "License");
  2767. * you may not use this file except in compliance with the License.
  2768. * You may obtain a copy of the License at
  2769. *
  2770. * http://www.apache.org/licenses/LICENSE-2.0
  2771. *
  2772. * Unless required by applicable law or agreed to in writing, software
  2773. * distributed under the License is distributed on an "AS IS" BASIS,
  2774. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2775. * See the License for the specific language governing permissions and
  2776. * limitations under the License.
  2777. */
  2778. /**
  2779. * Immutable class that represents a "proto" byte string.
  2780. *
  2781. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  2782. * sent on the wire. This class abstracts away this differentiation by holding
  2783. * the proto byte string in a common class that must be converted into a string
  2784. * before being sent as a proto.
  2785. * @internal
  2786. */ var Oe = /** @class */ function() {
  2787. function t(t) {
  2788. this.binaryString = t;
  2789. }
  2790. return t.fromBase64String = function(e) {
  2791. var n = function(t) {
  2792. try {
  2793. return atob(t);
  2794. } catch (t) {
  2795. // Check that `DOMException` is defined before using it to avoid
  2796. // "ReferenceError: Property 'DOMException' doesn't exist" in react-native.
  2797. // (https://github.com/firebase/firebase-js-sdk/issues/7115)
  2798. throw "undefined" != typeof DOMException && t instanceof DOMException ? new Ae("Invalid base64 string: " + t) : t;
  2799. }
  2800. }(e);
  2801. return new t(n);
  2802. }, t.fromUint8Array = function(e) {
  2803. // TODO(indexing); Remove the copy of the byte string here as this method
  2804. // is frequently called during indexing.
  2805. var n =
  2806. /**
  2807. * Helper function to convert an Uint8array to a binary string.
  2808. */
  2809. function(t) {
  2810. for (var e = "", n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);
  2811. return e;
  2812. }(e);
  2813. return new t(n);
  2814. }, t.prototype[Symbol.iterator] = function() {
  2815. var t = this, e = 0;
  2816. return {
  2817. next: function() {
  2818. return e < t.binaryString.length ? {
  2819. value: t.binaryString.charCodeAt(e++),
  2820. done: !1
  2821. } : {
  2822. value: void 0,
  2823. done: !0
  2824. };
  2825. }
  2826. };
  2827. }, t.prototype.toBase64 = function() {
  2828. return t = this.binaryString, btoa(t);
  2829. var t;
  2830. }, t.prototype.toUint8Array = function() {
  2831. return function(t) {
  2832. for (var e = new Uint8Array(t.length), n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  2833. return e;
  2834. }(this.binaryString);
  2835. }, t.prototype.approximateByteSize = function() {
  2836. return 2 * this.binaryString.length;
  2837. }, t.prototype.compareTo = function(t) {
  2838. return ot(this.binaryString, t.binaryString);
  2839. }, t.prototype.isEqual = function(t) {
  2840. return this.binaryString === t.binaryString;
  2841. }, t;
  2842. }();
  2843. Oe.EMPTY_BYTE_STRING = new Oe("");
  2844. var Fe = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  2845. /**
  2846. * Converts the possible Proto values for a timestamp value into a "seconds and
  2847. * nanos" representation.
  2848. */ function Pe(t) {
  2849. // The json interface (for the browser) will return an iso timestamp string,
  2850. // while the proto js library (for node) will return a
  2851. // google.protobuf.Timestamp instance.
  2852. if (z(!!t), "string" == typeof t) {
  2853. // The date string can have higher precision (nanos) than the Date class
  2854. // (millis), so we do some custom parsing here.
  2855. // Parse the nanos right out of the string.
  2856. var e = 0, n = Fe.exec(t);
  2857. if (z(!!n), n[1]) {
  2858. // Pad the fraction out to 9 digits (nanos).
  2859. var r = n[1];
  2860. r = (r + "000000000").substr(0, 9), e = Number(r);
  2861. }
  2862. // Parse the date to get the seconds.
  2863. var i = new Date(t);
  2864. return {
  2865. seconds: Math.floor(i.getTime() / 1e3),
  2866. nanos: e
  2867. };
  2868. }
  2869. return {
  2870. seconds: Re(t.seconds),
  2871. nanos: Re(t.nanos)
  2872. };
  2873. }
  2874. /**
  2875. * Converts the possible Proto types for numbers into a JavaScript number.
  2876. * Returns 0 if the value is not numeric.
  2877. */ function Re(t) {
  2878. // TODO(bjornick): Handle int64 greater than 53 bits.
  2879. return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0;
  2880. }
  2881. /** Converts the possible Proto types for Blobs into a ByteString. */ function Ve(t) {
  2882. return "string" == typeof t ? Oe.fromBase64String(t) : Oe.fromUint8Array(t);
  2883. }
  2884. /**
  2885. * @license
  2886. * Copyright 2020 Google LLC
  2887. *
  2888. * Licensed under the Apache License, Version 2.0 (the "License");
  2889. * you may not use this file except in compliance with the License.
  2890. * You may obtain a copy of the License at
  2891. *
  2892. * http://www.apache.org/licenses/LICENSE-2.0
  2893. *
  2894. * Unless required by applicable law or agreed to in writing, software
  2895. * distributed under the License is distributed on an "AS IS" BASIS,
  2896. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2897. * See the License for the specific language governing permissions and
  2898. * limitations under the License.
  2899. */
  2900. /**
  2901. * Represents a locally-applied ServerTimestamp.
  2902. *
  2903. * Server Timestamps are backed by MapValues that contain an internal field
  2904. * `__type__` with a value of `server_timestamp`. The previous value and local
  2905. * write time are stored in its `__previous_value__` and `__local_write_time__`
  2906. * fields respectively.
  2907. *
  2908. * Notes:
  2909. * - ServerTimestampValue instances are created as the result of applying a
  2910. * transform. They can only exist in the local view of a document. Therefore
  2911. * they do not need to be parsed or serialized.
  2912. * - When evaluated locally (e.g. for snapshot.data()), they by default
  2913. * evaluate to `null`. This behavior can be configured by passing custom
  2914. * FieldValueOptions to value().
  2915. * - With respect to other ServerTimestampValues, they sort by their
  2916. * localWriteTime.
  2917. */ function Me(t) {
  2918. var e, n;
  2919. 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);
  2920. }
  2921. /**
  2922. * Creates a new ServerTimestamp proto value (using the internal format).
  2923. */
  2924. /**
  2925. * Returns the value of the field before this ServerTimestamp was set.
  2926. *
  2927. * Preserving the previous values allows the user to display the last resoled
  2928. * value until the backend responds with the timestamp.
  2929. */ function Le(t) {
  2930. var e = t.mapValue.fields.__previous_value__;
  2931. return Me(e) ? Le(e) : e;
  2932. }
  2933. /**
  2934. * Returns the local time at which this timestamp was first set.
  2935. */ function qe(t) {
  2936. var e = Pe(t.mapValue.fields.__local_write_time__.timestampValue);
  2937. return new st(e.seconds, e.nanos);
  2938. }
  2939. /**
  2940. * @license
  2941. * Copyright 2017 Google LLC
  2942. *
  2943. * Licensed under the Apache License, Version 2.0 (the "License");
  2944. * you may not use this file except in compliance with the License.
  2945. * You may obtain a copy of the License at
  2946. *
  2947. * http://www.apache.org/licenses/LICENSE-2.0
  2948. *
  2949. * Unless required by applicable law or agreed to in writing, software
  2950. * distributed under the License is distributed on an "AS IS" BASIS,
  2951. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2952. * See the License for the specific language governing permissions and
  2953. * limitations under the License.
  2954. */ var Be =
  2955. /**
  2956. * Constructs a DatabaseInfo using the provided host, databaseId and
  2957. * persistenceKey.
  2958. *
  2959. * @param databaseId - The database to use.
  2960. * @param appId - The Firebase App Id.
  2961. * @param persistenceKey - A unique identifier for this Firestore's local
  2962. * storage (used in conjunction with the databaseId).
  2963. * @param host - The Firestore backend host to connect to.
  2964. * @param ssl - Whether to use SSL when connecting.
  2965. * @param forceLongPolling - Whether to use the forceLongPolling option
  2966. * when using WebChannel as the network transport.
  2967. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  2968. * option when using WebChannel as the network transport.
  2969. * @param longPollingOptions Options that configure long-polling.
  2970. * @param useFetchStreams Whether to use the Fetch API instead of
  2971. * XMLHTTPRequest
  2972. */
  2973. function(t, e, n, r, i, o, u, a, s) {
  2974. this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = r, this.ssl = i,
  2975. this.forceLongPolling = o, this.autoDetectLongPolling = u, this.longPollingOptions = a,
  2976. this.useFetchStreams = s;
  2977. }, Ue = /** @class */ function() {
  2978. function t(t, e) {
  2979. this.projectId = t, this.database = e || "(default)";
  2980. }
  2981. return t.empty = function() {
  2982. return new t("", "");
  2983. }, Object.defineProperty(t.prototype, "isDefaultDatabase", {
  2984. get: function() {
  2985. return "(default)" === this.database;
  2986. },
  2987. enumerable: !1,
  2988. configurable: !0
  2989. }), t.prototype.isEqual = function(e) {
  2990. return e instanceof t && e.projectId === this.projectId && e.database === this.database;
  2991. }, t;
  2992. }(), ze = {
  2993. mapValue: {
  2994. fields: {
  2995. __type__: {
  2996. stringValue: "__max__"
  2997. }
  2998. }
  2999. }
  3000. }, Ge = {
  3001. nullValue: "NULL_VALUE"
  3002. };
  3003. /** The default database name for a project. */
  3004. /**
  3005. * Represents the database ID a Firestore client is associated with.
  3006. * @internal
  3007. */
  3008. /** Extracts the backend's type order for the provided value. */
  3009. function je(t) {
  3010. 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 ? Me(t) ? 4 /* TypeOrder.ServerTimestampValue */ : un(t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : U();
  3011. }
  3012. /** Tests `left` and `right` for equality based on the backend semantics. */ function Ke(t, e) {
  3013. if (t === e) return !0;
  3014. var n = je(t);
  3015. if (n !== je(e)) return !1;
  3016. switch (n) {
  3017. case 0 /* TypeOrder.NullValue */ :
  3018. case 9007199254740991 /* TypeOrder.MaxValue */ :
  3019. return !0;
  3020. case 1 /* TypeOrder.BooleanValue */ :
  3021. return t.booleanValue === e.booleanValue;
  3022. case 4 /* TypeOrder.ServerTimestampValue */ :
  3023. return qe(t).isEqual(qe(e));
  3024. case 3 /* TypeOrder.TimestampValue */ :
  3025. return function(t, e) {
  3026. if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length)
  3027. // Use string equality for ISO 8601 timestamps
  3028. return t.timestampValue === e.timestampValue;
  3029. var n = Pe(t.timestampValue), r = Pe(e.timestampValue);
  3030. return n.seconds === r.seconds && n.nanos === r.nanos;
  3031. }(t, e);
  3032. case 5 /* TypeOrder.StringValue */ :
  3033. return t.stringValue === e.stringValue;
  3034. case 6 /* TypeOrder.BlobValue */ :
  3035. return function(t, e) {
  3036. return Ve(t.bytesValue).isEqual(Ve(e.bytesValue));
  3037. }(t, e);
  3038. case 7 /* TypeOrder.RefValue */ :
  3039. return t.referenceValue === e.referenceValue;
  3040. case 8 /* TypeOrder.GeoPointValue */ :
  3041. return function(t, e) {
  3042. return Re(t.geoPointValue.latitude) === Re(e.geoPointValue.latitude) && Re(t.geoPointValue.longitude) === Re(e.geoPointValue.longitude);
  3043. }(t, e);
  3044. case 2 /* TypeOrder.NumberValue */ :
  3045. return function(t, e) {
  3046. if ("integerValue" in t && "integerValue" in e) return Re(t.integerValue) === Re(e.integerValue);
  3047. if ("doubleValue" in t && "doubleValue" in e) {
  3048. var n = Re(t.doubleValue), r = Re(e.doubleValue);
  3049. return n === r ? Gt(n) === Gt(r) : isNaN(n) && isNaN(r);
  3050. }
  3051. return !1;
  3052. }(t, e);
  3053. case 9 /* TypeOrder.ArrayValue */ :
  3054. return ut(t.arrayValue.values || [], e.arrayValue.values || [], Ke);
  3055. case 10 /* TypeOrder.ObjectValue */ :
  3056. return function(t, e) {
  3057. var n = t.mapValue.fields || {}, r = e.mapValue.fields || {};
  3058. if (be(n) !== be(r)) return !1;
  3059. for (var i in n) if (n.hasOwnProperty(i) && (void 0 === r[i] || !Ke(n[i], r[i]))) return !1;
  3060. return !0;
  3061. }(t, e);
  3062. default:
  3063. return U();
  3064. }
  3065. }
  3066. function Qe(t, e) {
  3067. return void 0 !== (t.values || []).find((function(t) {
  3068. return Ke(t, e);
  3069. }));
  3070. }
  3071. function We(t, e) {
  3072. if (t === e) return 0;
  3073. var n = je(t), r = je(e);
  3074. if (n !== r) return ot(n, r);
  3075. switch (n) {
  3076. case 0 /* TypeOrder.NullValue */ :
  3077. case 9007199254740991 /* TypeOrder.MaxValue */ :
  3078. return 0;
  3079. case 1 /* TypeOrder.BooleanValue */ :
  3080. return ot(t.booleanValue, e.booleanValue);
  3081. case 2 /* TypeOrder.NumberValue */ :
  3082. return function(t, e) {
  3083. var n = Re(t.integerValue || t.doubleValue), r = Re(e.integerValue || e.doubleValue);
  3084. return n < r ? -1 : n > r ? 1 : n === r ? 0 :
  3085. // one or both are NaN.
  3086. isNaN(n) ? isNaN(r) ? 0 : -1 : 1;
  3087. }(t, e);
  3088. case 3 /* TypeOrder.TimestampValue */ :
  3089. return He(t.timestampValue, e.timestampValue);
  3090. case 4 /* TypeOrder.ServerTimestampValue */ :
  3091. return He(qe(t), qe(e));
  3092. case 5 /* TypeOrder.StringValue */ :
  3093. return ot(t.stringValue, e.stringValue);
  3094. case 6 /* TypeOrder.BlobValue */ :
  3095. return function(t, e) {
  3096. var n = Ve(t), r = Ve(e);
  3097. return n.compareTo(r);
  3098. }(t.bytesValue, e.bytesValue);
  3099. case 7 /* TypeOrder.RefValue */ :
  3100. return function(t, e) {
  3101. for (var n = t.split("/"), r = e.split("/"), i = 0; i < n.length && i < r.length; i++) {
  3102. var o = ot(n[i], r[i]);
  3103. if (0 !== o) return o;
  3104. }
  3105. return ot(n.length, r.length);
  3106. }(t.referenceValue, e.referenceValue);
  3107. case 8 /* TypeOrder.GeoPointValue */ :
  3108. return function(t, e) {
  3109. var n = ot(Re(t.latitude), Re(e.latitude));
  3110. return 0 !== n ? n : ot(Re(t.longitude), Re(e.longitude));
  3111. }(t.geoPointValue, e.geoPointValue);
  3112. case 9 /* TypeOrder.ArrayValue */ :
  3113. return function(t, e) {
  3114. for (var n = t.values || [], r = e.values || [], i = 0; i < n.length && i < r.length; ++i) {
  3115. var o = We(n[i], r[i]);
  3116. if (o) return o;
  3117. }
  3118. return ot(n.length, r.length);
  3119. }(t.arrayValue, e.arrayValue);
  3120. case 10 /* TypeOrder.ObjectValue */ :
  3121. return function(t, e) {
  3122. if (t === ze.mapValue && e === ze.mapValue) return 0;
  3123. if (t === ze.mapValue) return 1;
  3124. if (e === ze.mapValue) return -1;
  3125. var n = t.fields || {}, r = Object.keys(n), i = e.fields || {}, o = Object.keys(i);
  3126. // Even though MapValues are likely sorted correctly based on their insertion
  3127. // order (e.g. when received from the backend), local modifications can bring
  3128. // elements out of order. We need to re-sort the elements to ensure that
  3129. // canonical IDs are independent of insertion order.
  3130. r.sort(), o.sort();
  3131. for (var u = 0; u < r.length && u < o.length; ++u) {
  3132. var a = ot(r[u], o[u]);
  3133. if (0 !== a) return a;
  3134. var s = We(n[r[u]], i[o[u]]);
  3135. if (0 !== s) return s;
  3136. }
  3137. return ot(r.length, o.length);
  3138. }(t.mapValue, e.mapValue);
  3139. default:
  3140. throw U();
  3141. }
  3142. }
  3143. function He(t, e) {
  3144. if ("string" == typeof t && "string" == typeof e && t.length === e.length) return ot(t, e);
  3145. var n = Pe(t), r = Pe(e), i = ot(n.seconds, r.seconds);
  3146. return 0 !== i ? i : ot(n.nanos, r.nanos);
  3147. }
  3148. function Ye(t) {
  3149. return Xe(t);
  3150. }
  3151. function Xe(t) {
  3152. 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) {
  3153. var e = Pe(t);
  3154. return "time(".concat(e.seconds, ",").concat(e.nanos, ")");
  3155. }(t.timestampValue) : "stringValue" in t ? t.stringValue : "bytesValue" in t ? Ve(t.bytesValue).toBase64() : "referenceValue" in t ? (n = t.referenceValue,
  3156. pt.fromName(n).toString()) : "geoPointValue" in t ? "geo(".concat((e = t.geoPointValue).latitude, ",").concat(e.longitude, ")") : "arrayValue" in t ? function(t) {
  3157. for (var e = "[", n = !0, r = 0, i = t.values || []; r < i.length; r++) {
  3158. n ? n = !1 : e += ",", e += Xe(i[r]);
  3159. }
  3160. return e + "]";
  3161. }(t.arrayValue) : "mapValue" in t ? function(t) {
  3162. for (
  3163. // Iteration order in JavaScript is not guaranteed. To ensure that we generate
  3164. // matching canonical IDs for identical maps, we need to sort the keys.
  3165. var e = "{", n = !0, r = 0, i = Object.keys(t.fields || {}).sort(); r < i.length; r++) {
  3166. var o = i[r];
  3167. n ? n = !1 : e += ",", e += "".concat(o, ":").concat(Xe(t.fields[o]));
  3168. }
  3169. return e + "}";
  3170. }(t.mapValue) : U();
  3171. var e, n;
  3172. }
  3173. function Je(t) {
  3174. switch (je(t)) {
  3175. case 0 /* TypeOrder.NullValue */ :
  3176. case 1 /* TypeOrder.BooleanValue */ :
  3177. return 4;
  3178. case 2 /* TypeOrder.NumberValue */ :
  3179. return 8;
  3180. case 3 /* TypeOrder.TimestampValue */ :
  3181. case 8 /* TypeOrder.GeoPointValue */ :
  3182. // GeoPoints are made up of two distinct numbers (latitude + longitude)
  3183. return 16;
  3184. case 4 /* TypeOrder.ServerTimestampValue */ :
  3185. var e = Le(t);
  3186. return e ? 16 + Je(e) : 16;
  3187. case 5 /* TypeOrder.StringValue */ :
  3188. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:
  3189. // "JavaScript's String type is [...] a set of elements of 16-bit unsigned
  3190. // integer values"
  3191. return 2 * t.stringValue.length;
  3192. case 6 /* TypeOrder.BlobValue */ :
  3193. return Ve(t.bytesValue).approximateByteSize();
  3194. case 7 /* TypeOrder.RefValue */ :
  3195. return t.referenceValue.length;
  3196. case 9 /* TypeOrder.ArrayValue */ :
  3197. return (t.arrayValue.values || []).reduce((function(t, e) {
  3198. return t + Je(e);
  3199. }), 0);
  3200. case 10 /* TypeOrder.ObjectValue */ :
  3201. return function(t) {
  3202. var e = 0;
  3203. return Ie(t.fields, (function(t, n) {
  3204. e += t.length + Je(n);
  3205. })), e;
  3206. }(t.mapValue);
  3207. default:
  3208. throw U();
  3209. }
  3210. }
  3211. /** Returns a reference value for the provided database and key. */ function Ze(t, e) {
  3212. return {
  3213. referenceValue: "projects/".concat(t.projectId, "/databases/").concat(t.database, "/documents/").concat(e.path.canonicalString())
  3214. };
  3215. }
  3216. /** Returns true if `value` is an IntegerValue . */ function $e(t) {
  3217. return !!t && "integerValue" in t;
  3218. }
  3219. /** Returns true if `value` is a DoubleValue. */
  3220. /** Returns true if `value` is an ArrayValue. */ function tn(t) {
  3221. return !!t && "arrayValue" in t;
  3222. }
  3223. /** Returns true if `value` is a NullValue. */ function en(t) {
  3224. return !!t && "nullValue" in t;
  3225. }
  3226. /** Returns true if `value` is NaN. */ function nn(t) {
  3227. return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
  3228. }
  3229. /** Returns true if `value` is a MapValue. */ function rn(t) {
  3230. return !!t && "mapValue" in t;
  3231. }
  3232. /** Creates a deep copy of `source`. */ function on(t) {
  3233. if (t.geoPointValue) return {
  3234. geoPointValue: Object.assign({}, t.geoPointValue)
  3235. };
  3236. if (t.timestampValue && "object" == typeof t.timestampValue) return {
  3237. timestampValue: Object.assign({}, t.timestampValue)
  3238. };
  3239. if (t.mapValue) {
  3240. var e = {
  3241. mapValue: {
  3242. fields: {}
  3243. }
  3244. };
  3245. return Ie(t.mapValue.fields, (function(t, n) {
  3246. return e.mapValue.fields[t] = on(n);
  3247. })), e;
  3248. }
  3249. if (t.arrayValue) {
  3250. for (var n = {
  3251. arrayValue: {
  3252. values: []
  3253. }
  3254. }, r = 0; r < (t.arrayValue.values || []).length; ++r) n.arrayValue.values[r] = on(t.arrayValue.values[r]);
  3255. return n;
  3256. }
  3257. return Object.assign({}, t);
  3258. }
  3259. /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function un(t) {
  3260. return "__max__" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;
  3261. }
  3262. /** Returns the lowest value for the given value type (inclusive). */ function an(t) {
  3263. return "nullValue" in t ? Ge : "booleanValue" in t ? {
  3264. booleanValue: !1
  3265. } : "integerValue" in t || "doubleValue" in t ? {
  3266. doubleValue: NaN
  3267. } : "timestampValue" in t ? {
  3268. timestampValue: {
  3269. seconds: Number.MIN_SAFE_INTEGER
  3270. }
  3271. } : "stringValue" in t ? {
  3272. stringValue: ""
  3273. } : "bytesValue" in t ? {
  3274. bytesValue: ""
  3275. } : "referenceValue" in t ? Ze(Ue.empty(), pt.empty()) : "geoPointValue" in t ? {
  3276. geoPointValue: {
  3277. latitude: -90,
  3278. longitude: -180
  3279. }
  3280. } : "arrayValue" in t ? {
  3281. arrayValue: {}
  3282. } : "mapValue" in t ? {
  3283. mapValue: {}
  3284. } : U();
  3285. }
  3286. /** Returns the largest value for the given value type (exclusive). */ function sn(t) {
  3287. return "nullValue" in t ? {
  3288. booleanValue: !1
  3289. } : "booleanValue" in t ? {
  3290. doubleValue: NaN
  3291. } : "integerValue" in t || "doubleValue" in t ? {
  3292. timestampValue: {
  3293. seconds: Number.MIN_SAFE_INTEGER
  3294. }
  3295. } : "timestampValue" in t ? {
  3296. stringValue: ""
  3297. } : "stringValue" in t ? {
  3298. bytesValue: ""
  3299. } : "bytesValue" in t ? Ze(Ue.empty(), pt.empty()) : "referenceValue" in t ? {
  3300. geoPointValue: {
  3301. latitude: -90,
  3302. longitude: -180
  3303. }
  3304. } : "geoPointValue" in t ? {
  3305. arrayValue: {}
  3306. } : "arrayValue" in t ? {
  3307. mapValue: {}
  3308. } : "mapValue" in t ? ze : U();
  3309. }
  3310. function cn(t, e) {
  3311. var n = We(t.value, e.value);
  3312. return 0 !== n ? n : t.inclusive && !e.inclusive ? -1 : !t.inclusive && e.inclusive ? 1 : 0;
  3313. }
  3314. function ln(t, e) {
  3315. var n = We(t.value, e.value);
  3316. return 0 !== n ? n : t.inclusive && !e.inclusive ? 1 : !t.inclusive && e.inclusive ? -1 : 0;
  3317. }
  3318. /**
  3319. * @license
  3320. * Copyright 2017 Google LLC
  3321. *
  3322. * Licensed under the Apache License, Version 2.0 (the "License");
  3323. * you may not use this file except in compliance with the License.
  3324. * You may obtain a copy of the License at
  3325. *
  3326. * http://www.apache.org/licenses/LICENSE-2.0
  3327. *
  3328. * Unless required by applicable law or agreed to in writing, software
  3329. * distributed under the License is distributed on an "AS IS" BASIS,
  3330. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3331. * See the License for the specific language governing permissions and
  3332. * limitations under the License.
  3333. */
  3334. /**
  3335. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  3336. * ability to add and remove fields (via the ObjectValueBuilder).
  3337. */ var hn = /** @class */ function() {
  3338. function t(t) {
  3339. this.value = t;
  3340. }
  3341. return t.empty = function() {
  3342. return new t({
  3343. mapValue: {}
  3344. });
  3345. },
  3346. /**
  3347. * Returns the value at the given path or null.
  3348. *
  3349. * @param path - the path to search
  3350. * @returns The value at the path or null if the path is not set.
  3351. */
  3352. t.prototype.field = function(t) {
  3353. if (t.isEmpty()) return this.value;
  3354. for (var e = this.value, n = 0; n < t.length - 1; ++n) if (!rn(e = (e.mapValue.fields || {})[t.get(n)])) return null;
  3355. return (e = (e.mapValue.fields || {})[t.lastSegment()]) || null;
  3356. },
  3357. /**
  3358. * Sets the field to the provided value.
  3359. *
  3360. * @param path - The field path to set.
  3361. * @param value - The value to set.
  3362. */
  3363. t.prototype.set = function(t, e) {
  3364. this.getFieldsMap(t.popLast())[t.lastSegment()] = on(e);
  3365. },
  3366. /**
  3367. * Sets the provided fields to the provided values.
  3368. *
  3369. * @param data - A map of fields to values (or null for deletes).
  3370. */
  3371. t.prototype.setAll = function(t) {
  3372. var e = this, n = dt.emptyPath(), r = {}, i = [];
  3373. t.forEach((function(t, o) {
  3374. if (!n.isImmediateParentOf(o)) {
  3375. // Insert the accumulated changes at this parent location
  3376. var u = e.getFieldsMap(n);
  3377. e.applyChanges(u, r, i), r = {}, i = [], n = o.popLast();
  3378. }
  3379. t ? r[o.lastSegment()] = on(t) : i.push(o.lastSegment());
  3380. }));
  3381. var o = this.getFieldsMap(n);
  3382. this.applyChanges(o, r, i);
  3383. },
  3384. /**
  3385. * Removes the field at the specified path. If there is no field at the
  3386. * specified path, nothing is changed.
  3387. *
  3388. * @param path - The field path to remove.
  3389. */
  3390. t.prototype.delete = function(t) {
  3391. var e = this.field(t.popLast());
  3392. rn(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];
  3393. }, t.prototype.isEqual = function(t) {
  3394. return Ke(this.value, t.value);
  3395. },
  3396. /**
  3397. * Returns the map that contains the leaf element of `path`. If the parent
  3398. * entry does not yet exist, or if it is not a map, a new map will be created.
  3399. */
  3400. t.prototype.getFieldsMap = function(t) {
  3401. var e = this.value;
  3402. e.mapValue.fields || (e.mapValue = {
  3403. fields: {}
  3404. });
  3405. for (var n = 0; n < t.length; ++n) {
  3406. var r = e.mapValue.fields[t.get(n)];
  3407. rn(r) && r.mapValue.fields || (r = {
  3408. mapValue: {
  3409. fields: {}
  3410. }
  3411. }, e.mapValue.fields[t.get(n)] = r), e = r;
  3412. }
  3413. return e.mapValue.fields;
  3414. },
  3415. /**
  3416. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  3417. * entries.
  3418. */
  3419. t.prototype.applyChanges = function(t, e, n) {
  3420. Ie(e, (function(e, n) {
  3421. return t[e] = n;
  3422. }));
  3423. for (var r = 0, i = n; r < i.length; r++) {
  3424. var o = i[r];
  3425. delete t[o];
  3426. }
  3427. }, t.prototype.clone = function() {
  3428. return new t(on(this.value));
  3429. }, t;
  3430. }();
  3431. /**
  3432. * Returns a FieldMask built from all fields in a MapValue.
  3433. */ function fn(t) {
  3434. var e = [];
  3435. return Ie(t.fields, (function(t, n) {
  3436. var r = new dt([ t ]);
  3437. if (rn(n)) {
  3438. var i = fn(n.mapValue).fields;
  3439. if (0 === i.length)
  3440. // Preserve the empty map by adding it to the FieldMask.
  3441. e.push(r); else
  3442. // For nested and non-empty ObjectValues, add the FieldPath of the
  3443. // leaf nodes.
  3444. for (var o = 0, u = i; o < u.length; o++) {
  3445. var a = u[o];
  3446. e.push(r.child(a));
  3447. }
  3448. } else
  3449. // For nested and non-empty ObjectValues, add the FieldPath of the leaf
  3450. // nodes.
  3451. e.push(r);
  3452. })), new Ne(e)
  3453. /**
  3454. * @license
  3455. * Copyright 2017 Google LLC
  3456. *
  3457. * Licensed under the Apache License, Version 2.0 (the "License");
  3458. * you may not use this file except in compliance with the License.
  3459. * You may obtain a copy of the License at
  3460. *
  3461. * http://www.apache.org/licenses/LICENSE-2.0
  3462. *
  3463. * Unless required by applicable law or agreed to in writing, software
  3464. * distributed under the License is distributed on an "AS IS" BASIS,
  3465. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3466. * See the License for the specific language governing permissions and
  3467. * limitations under the License.
  3468. */
  3469. /**
  3470. * Represents a document in Firestore with a key, version, data and whether it
  3471. * has local mutations applied to it.
  3472. *
  3473. * Documents can transition between states via `convertToFoundDocument()`,
  3474. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  3475. * not transition to one of these states even after all mutations have been
  3476. * applied, `isValidDocument()` returns false and the document should be removed
  3477. * from all views.
  3478. */;
  3479. }
  3480. var dn = /** @class */ function() {
  3481. function t(t, e, n, r, i, o, u) {
  3482. this.key = t, this.documentType = e, this.version = n, this.readTime = r, this.createTime = i,
  3483. this.data = o, this.documentState = u
  3484. /**
  3485. * Creates a document with no known version or data, but which can serve as
  3486. * base document for mutations.
  3487. */;
  3488. }
  3489. return t.newInvalidDocument = function(e) {
  3490. return new t(e, 0 /* DocumentType.INVALID */ ,
  3491. /* version */ ct.min(),
  3492. /* readTime */ ct.min(),
  3493. /* createTime */ ct.min(), hn.empty(), 0 /* DocumentState.SYNCED */);
  3494. },
  3495. /**
  3496. * Creates a new document that is known to exist with the given data at the
  3497. * given version.
  3498. */
  3499. t.newFoundDocument = function(e, n, r, i) {
  3500. return new t(e, 1 /* DocumentType.FOUND_DOCUMENT */ ,
  3501. /* version */ n,
  3502. /* readTime */ ct.min(),
  3503. /* createTime */ r, i, 0 /* DocumentState.SYNCED */);
  3504. },
  3505. /** Creates a new document that is known to not exist at the given version. */ t.newNoDocument = function(e, n) {
  3506. return new t(e, 2 /* DocumentType.NO_DOCUMENT */ ,
  3507. /* version */ n,
  3508. /* readTime */ ct.min(),
  3509. /* createTime */ ct.min(), hn.empty(), 0 /* DocumentState.SYNCED */);
  3510. },
  3511. /**
  3512. * Creates a new document that is known to exist at the given version but
  3513. * whose data is not known (e.g. a document that was updated without a known
  3514. * base document).
  3515. */
  3516. t.newUnknownDocument = function(e, n) {
  3517. return new t(e, 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3518. /* version */ n,
  3519. /* readTime */ ct.min(),
  3520. /* createTime */ ct.min(), hn.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
  3521. },
  3522. /**
  3523. * Changes the document type to indicate that it exists and that its version
  3524. * and data are known.
  3525. */
  3526. t.prototype.convertToFoundDocument = function(t, e) {
  3527. // If a document is switching state from being an invalid or deleted
  3528. // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
  3529. // update from Watch or due to applying a local set mutation on top
  3530. // of a deleted document, our best guess about its createTime would be the
  3531. // version at which the document transitioned to a FOUND_DOCUMENT.
  3532. return !this.createTime.isEqual(ct.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t),
  3533. this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e,
  3534. this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3535. },
  3536. /**
  3537. * Changes the document type to indicate that it doesn't exist at the given
  3538. * version.
  3539. */
  3540. t.prototype.convertToNoDocument = function(t) {
  3541. return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ ,
  3542. this.data = hn.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3543. },
  3544. /**
  3545. * Changes the document type to indicate that it exists at a given version but
  3546. * that its data is not known (e.g. a document that was updated without a known
  3547. * base document).
  3548. */
  3549. t.prototype.convertToUnknownDocument = function(t) {
  3550. return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3551. this.data = hn.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ ,
  3552. this;
  3553. }, t.prototype.setHasCommittedMutations = function() {
  3554. return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;
  3555. }, t.prototype.setHasLocalMutations = function() {
  3556. return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = ct.min(),
  3557. this;
  3558. }, t.prototype.setReadTime = function(t) {
  3559. return this.readTime = t, this;
  3560. }, Object.defineProperty(t.prototype, "hasLocalMutations", {
  3561. get: function() {
  3562. return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;
  3563. },
  3564. enumerable: !1,
  3565. configurable: !0
  3566. }), Object.defineProperty(t.prototype, "hasCommittedMutations", {
  3567. get: function() {
  3568. return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;
  3569. },
  3570. enumerable: !1,
  3571. configurable: !0
  3572. }), Object.defineProperty(t.prototype, "hasPendingWrites", {
  3573. get: function() {
  3574. return this.hasLocalMutations || this.hasCommittedMutations;
  3575. },
  3576. enumerable: !1,
  3577. configurable: !0
  3578. }), t.prototype.isValidDocument = function() {
  3579. return 0 /* DocumentType.INVALID */ !== this.documentType;
  3580. }, t.prototype.isFoundDocument = function() {
  3581. return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;
  3582. }, t.prototype.isNoDocument = function() {
  3583. return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;
  3584. }, t.prototype.isUnknownDocument = function() {
  3585. return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;
  3586. }, t.prototype.isEqual = function(e) {
  3587. return e instanceof t && this.key.isEqual(e.key) && this.version.isEqual(e.version) && this.documentType === e.documentType && this.documentState === e.documentState && this.data.isEqual(e.data);
  3588. }, t.prototype.mutableCopy = function() {
  3589. return new t(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  3590. }, t.prototype.toString = function() {
  3591. return "Document(".concat(this.key, ", ").concat(this.version, ", ").concat(JSON.stringify(this.data.value), ", {createTime: ").concat(this.createTime, "}), {documentType: ").concat(this.documentType, "}), {documentState: ").concat(this.documentState, "})");
  3592. }, t;
  3593. }(), pn = function(t, e) {
  3594. this.position = t, this.inclusive = e;
  3595. };
  3596. /**
  3597. * Compares the value for field `field` in the provided documents. Throws if
  3598. * the field does not exist in both documents.
  3599. */
  3600. /**
  3601. * @license
  3602. * Copyright 2022 Google LLC
  3603. *
  3604. * Licensed under the Apache License, Version 2.0 (the "License");
  3605. * you may not use this file except in compliance with the License.
  3606. * You may obtain a copy of the License at
  3607. *
  3608. * http://www.apache.org/licenses/LICENSE-2.0
  3609. *
  3610. * Unless required by applicable law or agreed to in writing, software
  3611. * distributed under the License is distributed on an "AS IS" BASIS,
  3612. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3613. * See the License for the specific language governing permissions and
  3614. * limitations under the License.
  3615. */
  3616. /**
  3617. * Represents a bound of a query.
  3618. *
  3619. * The bound is specified with the given components representing a position and
  3620. * whether it's just before or just after the position (relative to whatever the
  3621. * query order is).
  3622. *
  3623. * The position represents a logical index position for a query. It's a prefix
  3624. * of values for the (potentially implicit) order by clauses of a query.
  3625. *
  3626. * Bound provides a function to determine whether a document comes before or
  3627. * after a bound. This is influenced by whether the position is just before or
  3628. * just after the provided values.
  3629. */ function vn(t, e, n) {
  3630. for (var r = 0, i = 0; i < t.position.length; i++) {
  3631. var o = e[i], u = t.position[i];
  3632. if (r = o.field.isKeyField() ? pt.comparator(pt.fromName(u.referenceValue), n.key) : We(u, n.data.field(o.field)),
  3633. "desc" /* Direction.DESCENDING */ === o.dir && (r *= -1), 0 !== r) break;
  3634. }
  3635. return r;
  3636. }
  3637. /**
  3638. * Returns true if a document sorts after a bound using the provided sort
  3639. * order.
  3640. */ function mn(t, e) {
  3641. if (null === t) return null === e;
  3642. if (null === e) return !1;
  3643. if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;
  3644. for (var n = 0; n < t.position.length; n++) if (!Ke(t.position[n], e.position[n])) return !1;
  3645. return !0;
  3646. }
  3647. /**
  3648. * @license
  3649. * Copyright 2022 Google LLC
  3650. *
  3651. * Licensed under the Apache License, Version 2.0 (the "License");
  3652. * you may not use this file except in compliance with the License.
  3653. * You may obtain a copy of the License at
  3654. *
  3655. * http://www.apache.org/licenses/LICENSE-2.0
  3656. *
  3657. * Unless required by applicable law or agreed to in writing, software
  3658. * distributed under the License is distributed on an "AS IS" BASIS,
  3659. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3660. * See the License for the specific language governing permissions and
  3661. * limitations under the License.
  3662. */
  3663. /**
  3664. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  3665. */ var yn = function(t, e /* Direction.ASCENDING */) {
  3666. void 0 === e && (e = "asc"), this.field = t, this.dir = e;
  3667. };
  3668. function gn(t, e) {
  3669. return t.dir === e.dir && t.field.isEqual(e.field);
  3670. }
  3671. /**
  3672. * @license
  3673. * Copyright 2022 Google LLC
  3674. *
  3675. * Licensed under the Apache License, Version 2.0 (the "License");
  3676. * you may not use this file except in compliance with the License.
  3677. * You may obtain a copy of the License at
  3678. *
  3679. * http://www.apache.org/licenses/LICENSE-2.0
  3680. *
  3681. * Unless required by applicable law or agreed to in writing, software
  3682. * distributed under the License is distributed on an "AS IS" BASIS,
  3683. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3684. * See the License for the specific language governing permissions and
  3685. * limitations under the License.
  3686. */ var wn = function() {}, bn = /** @class */ function(e) {
  3687. function n(t, n, r) {
  3688. var i = this;
  3689. return (i = e.call(this) || this).field = t, i.op = n, i.value = r, i;
  3690. }
  3691. /**
  3692. * Creates a filter based on the provided arguments.
  3693. */ return t(n, e), n.create = function(t, e, r) {
  3694. return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, r) : new An(t, e, r) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new Pn(t, r) : "in" /* Operator.IN */ === e ? new Rn(t, r) : "not-in" /* Operator.NOT_IN */ === e ? new Vn(t, r) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new Mn(t, r) : new n(t, e, r);
  3695. }, n.createKeyFieldInFilter = function(t, e, n) {
  3696. return "in" /* Operator.IN */ === e ? new kn(t, n) : new On(t, n);
  3697. }, n.prototype.matches = function(t) {
  3698. var e = t.data.field(this.field);
  3699. // Types do not have to match in NOT_EQUAL filters.
  3700. return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(We(e, this.value)) : null !== e && je(this.value) === je(e) && this.matchesComparison(We(e, this.value));
  3701. // Only compare types with matching backend order (such as double and int).
  3702. }, n.prototype.matchesComparison = function(t) {
  3703. switch (this.op) {
  3704. case "<" /* Operator.LESS_THAN */ :
  3705. return t < 0;
  3706. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  3707. return t <= 0;
  3708. case "==" /* Operator.EQUAL */ :
  3709. return 0 === t;
  3710. case "!=" /* Operator.NOT_EQUAL */ :
  3711. return 0 !== t;
  3712. case ">" /* Operator.GREATER_THAN */ :
  3713. return t > 0;
  3714. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  3715. return t >= 0;
  3716. default:
  3717. return U();
  3718. }
  3719. }, n.prototype.isInequality = function() {
  3720. 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;
  3721. }, n.prototype.getFlattenedFilters = function() {
  3722. return [ this ];
  3723. }, n.prototype.getFilters = function() {
  3724. return [ this ];
  3725. }, n.prototype.getFirstInequalityField = function() {
  3726. return this.isInequality() ? this.field : null;
  3727. }, n;
  3728. }(wn), In = /** @class */ function(e) {
  3729. function n(t, n) {
  3730. var r = this;
  3731. return (r = e.call(this) || this).filters = t, r.op = n, r.lt = null, r;
  3732. }
  3733. /**
  3734. * Creates a filter based on the provided arguments.
  3735. */ return t(n, e), n.create = function(t, e) {
  3736. return new n(t, e);
  3737. }, n.prototype.matches = function(t) {
  3738. return En(this) ? void 0 === this.filters.find((function(e) {
  3739. return !e.matches(t);
  3740. })) : void 0 !== this.filters.find((function(e) {
  3741. return e.matches(t);
  3742. }));
  3743. }, n.prototype.getFlattenedFilters = function() {
  3744. return null !== this.lt || (this.lt = this.filters.reduce((function(t, e) {
  3745. return t.concat(e.getFlattenedFilters());
  3746. }), [])), this.lt;
  3747. },
  3748. // Returns a mutable copy of `this.filters`
  3749. n.prototype.getFilters = function() {
  3750. return Object.assign([], this.filters);
  3751. }, n.prototype.getFirstInequalityField = function() {
  3752. var t = this.ft((function(t) {
  3753. return t.isInequality();
  3754. }));
  3755. return null !== t ? t.field : null;
  3756. },
  3757. // Performs a depth-first search to find and return the first FieldFilter in the composite filter
  3758. // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
  3759. // predicate.
  3760. n.prototype.ft = function(t) {
  3761. for (var e = 0, n = this.getFlattenedFilters(); e < n.length; e++) {
  3762. var r = n[e];
  3763. if (t(r)) return r;
  3764. }
  3765. return null;
  3766. }, n;
  3767. }(wn);
  3768. function En(t) {
  3769. return "and" /* CompositeOperator.AND */ === t.op;
  3770. }
  3771. function Tn(t) {
  3772. return "or" /* CompositeOperator.OR */ === t.op;
  3773. }
  3774. /**
  3775. * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.
  3776. */ function Sn(t) {
  3777. return _n(t) && En(t);
  3778. }
  3779. /**
  3780. * Returns true if this filter does not contain any composite filters. Returns false otherwise.
  3781. */ function _n(t) {
  3782. for (var e = 0, n = t.filters; e < n.length; e++) {
  3783. if (n[e] instanceof In) return !1;
  3784. }
  3785. return !0;
  3786. }
  3787. function Dn(t) {
  3788. if (t instanceof bn)
  3789. // TODO(b/29183165): Technically, this won't be unique if two values have
  3790. // the same description, such as the int 3 and the string "3". So we should
  3791. // add the types in here somehow, too.
  3792. return t.field.canonicalString() + t.op.toString() + Ye(t.value);
  3793. if (Sn(t))
  3794. // Older SDK versions use an implicit AND operation between their filters.
  3795. // In the new SDK versions, the developer may use an explicit AND filter.
  3796. // To stay consistent with the old usages, we add a special case to ensure
  3797. // the canonical ID for these two are the same. For example:
  3798. // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same
  3799. // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`.
  3800. return t.filters.map((function(t) {
  3801. return Dn(t);
  3802. })).join(",");
  3803. // filter instanceof CompositeFilter
  3804. var e = t.filters.map((function(t) {
  3805. return Dn(t);
  3806. })).join(",");
  3807. return "".concat(t.op, "(").concat(e, ")");
  3808. }
  3809. function Cn(t, e) {
  3810. return t instanceof bn ? function(t, e) {
  3811. return e instanceof bn && t.op === e.op && t.field.isEqual(e.field) && Ke(t.value, e.value);
  3812. }(t, e) : t instanceof In ? function(t, e) {
  3813. return e instanceof In && t.op === e.op && t.filters.length === e.filters.length && t.filters.reduce((function(t, n, r) {
  3814. return t && Cn(n, e.filters[r]);
  3815. }), !0);
  3816. }(t, e) : void U();
  3817. }
  3818. function xn(t, e) {
  3819. var n = t.filters.concat(e);
  3820. return In.create(n, t.op);
  3821. }
  3822. /** Returns a debug description for `filter`. */ function Nn(t) {
  3823. return t instanceof bn ? function(t) {
  3824. return "".concat(t.field.canonicalString(), " ").concat(t.op, " ").concat(Ye(t.value));
  3825. }(t) : t instanceof In ? function(t) {
  3826. return t.op.toString() + " {" + t.getFilters().map(Nn).join(" ,") + "}";
  3827. }(t) : "Filter";
  3828. }
  3829. var An = /** @class */ function(e) {
  3830. function n(t, n, r) {
  3831. var i = this;
  3832. return (i = e.call(this, t, n, r) || this).key = pt.fromName(r.referenceValue),
  3833. i;
  3834. }
  3835. return t(n, e), n.prototype.matches = function(t) {
  3836. var e = pt.comparator(t.key, this.key);
  3837. return this.matchesComparison(e);
  3838. }, n;
  3839. }(bn), kn = /** @class */ function(e) {
  3840. function n(t, n) {
  3841. var r = this;
  3842. return (r = e.call(this, t, "in" /* Operator.IN */ , n) || this).keys = Fn("in" /* Operator.IN */ , n),
  3843. r;
  3844. }
  3845. return t(n, e), n.prototype.matches = function(t) {
  3846. return this.keys.some((function(e) {
  3847. return e.isEqual(t.key);
  3848. }));
  3849. }, n;
  3850. }(bn), On = /** @class */ function(e) {
  3851. function n(t, n) {
  3852. var r = this;
  3853. return (r = e.call(this, t, "not-in" /* Operator.NOT_IN */ , n) || this).keys = Fn("not-in" /* Operator.NOT_IN */ , n),
  3854. r;
  3855. }
  3856. return t(n, e), n.prototype.matches = function(t) {
  3857. return !this.keys.some((function(e) {
  3858. return e.isEqual(t.key);
  3859. }));
  3860. }, n;
  3861. }(bn);
  3862. /** Filter that matches on key fields within an array. */ function Fn(t, e) {
  3863. var n;
  3864. return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((function(t) {
  3865. return pt.fromName(t.referenceValue);
  3866. }));
  3867. }
  3868. /** A Filter that implements the array-contains operator. */ var Pn = /** @class */ function(e) {
  3869. function n(t, n) {
  3870. return e.call(this, t, "array-contains" /* Operator.ARRAY_CONTAINS */ , n) || this;
  3871. }
  3872. return t(n, e), n.prototype.matches = function(t) {
  3873. var e = t.data.field(this.field);
  3874. return tn(e) && Qe(e.arrayValue, this.value);
  3875. }, n;
  3876. }(bn), Rn = /** @class */ function(e) {
  3877. function n(t, n) {
  3878. return e.call(this, t, "in" /* Operator.IN */ , n) || this;
  3879. }
  3880. return t(n, e), n.prototype.matches = function(t) {
  3881. var e = t.data.field(this.field);
  3882. return null !== e && Qe(this.value.arrayValue, e);
  3883. }, n;
  3884. }(bn), Vn = /** @class */ function(e) {
  3885. function n(t, n) {
  3886. return e.call(this, t, "not-in" /* Operator.NOT_IN */ , n) || this;
  3887. }
  3888. return t(n, e), n.prototype.matches = function(t) {
  3889. if (Qe(this.value.arrayValue, {
  3890. nullValue: "NULL_VALUE"
  3891. })) return !1;
  3892. var e = t.data.field(this.field);
  3893. return null !== e && !Qe(this.value.arrayValue, e);
  3894. }, n;
  3895. }(bn), Mn = /** @class */ function(e) {
  3896. function n(t, n) {
  3897. return e.call(this, t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , n) || this;
  3898. }
  3899. return t(n, e), n.prototype.matches = function(t) {
  3900. var e = this, n = t.data.field(this.field);
  3901. return !(!tn(n) || !n.arrayValue.values) && n.arrayValue.values.some((function(t) {
  3902. return Qe(e.value.arrayValue, t);
  3903. }));
  3904. }, n;
  3905. }(bn), Ln = function(t, e, n, r, i, o, u) {
  3906. void 0 === e && (e = null), void 0 === n && (n = []), void 0 === r && (r = []),
  3907. void 0 === i && (i = null), void 0 === o && (o = null), void 0 === u && (u = null),
  3908. this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = r, this.limit = i,
  3909. this.startAt = o, this.endAt = u, this.dt = null;
  3910. };
  3911. /** A Filter that implements the IN operator. */
  3912. /**
  3913. * Initializes a Target with a path and optional additional query constraints.
  3914. * Path must currently be empty if this is a collection group query.
  3915. *
  3916. * NOTE: you should always construct `Target` from `Query.toTarget` instead of
  3917. * using this factory method, because `Query` provides an implicit `orderBy`
  3918. * property.
  3919. */
  3920. function qn(t, e, n, r, i, o, u) {
  3921. return void 0 === e && (e = null), void 0 === n && (n = []), void 0 === r && (r = []),
  3922. void 0 === i && (i = null), void 0 === o && (o = null), void 0 === u && (u = null),
  3923. new Ln(t, e, n, r, i, o, u);
  3924. }
  3925. function Bn(t) {
  3926. var e = j(t);
  3927. if (null === e.dt) {
  3928. var n = e.path.canonicalString();
  3929. null !== e.collectionGroup && (n += "|cg:" + e.collectionGroup), n += "|f:", n += e.filters.map((function(t) {
  3930. return Dn(t);
  3931. })).join(","), n += "|ob:", n += e.orderBy.map((function(t) {
  3932. return function(t) {
  3933. // TODO(b/29183165): Make this collision robust.
  3934. return t.field.canonicalString() + t.dir;
  3935. }(t);
  3936. })).join(","), zt(e.limit) || (n += "|l:", n += e.limit), e.startAt && (n += "|lb:",
  3937. n += e.startAt.inclusive ? "b:" : "a:", n += e.startAt.position.map((function(t) {
  3938. return Ye(t);
  3939. })).join(",")), e.endAt && (n += "|ub:", n += e.endAt.inclusive ? "a:" : "b:", n += e.endAt.position.map((function(t) {
  3940. return Ye(t);
  3941. })).join(",")), e.dt = n;
  3942. }
  3943. return e.dt;
  3944. }
  3945. function Un(t, e) {
  3946. if (t.limit !== e.limit) return !1;
  3947. if (t.orderBy.length !== e.orderBy.length) return !1;
  3948. for (var n = 0; n < t.orderBy.length; n++) if (!gn(t.orderBy[n], e.orderBy[n])) return !1;
  3949. if (t.filters.length !== e.filters.length) return !1;
  3950. for (var r = 0; r < t.filters.length; r++) if (!Cn(t.filters[r], e.filters[r])) return !1;
  3951. return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!mn(t.startAt, e.startAt) && mn(t.endAt, e.endAt);
  3952. }
  3953. function zn(t) {
  3954. return pt.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  3955. }
  3956. /** Returns the field filters that target the given field path. */ function Gn(t, e) {
  3957. return t.filters.filter((function(t) {
  3958. return t instanceof bn && t.field.isEqual(e);
  3959. }));
  3960. }
  3961. /**
  3962. * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
  3963. * filters. Returns `null` if there are no such filters.
  3964. */
  3965. /**
  3966. * Returns the value to use as the lower bound for ascending index segment at
  3967. * the provided `fieldPath` (or the upper bound for an descending segment).
  3968. */ function jn(t, e, n) {
  3969. // Process all filters to find a value for the current field segment
  3970. for (var r = Ge, i = !0, o = 0, u = Gn(t, e); o < u.length; o++) {
  3971. var a = u[o], s = Ge, c = !0;
  3972. switch (a.op) {
  3973. case "<" /* Operator.LESS_THAN */ :
  3974. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  3975. s = an(a.value);
  3976. break;
  3977. case "==" /* Operator.EQUAL */ :
  3978. case "in" /* Operator.IN */ :
  3979. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  3980. s = a.value;
  3981. break;
  3982. case ">" /* Operator.GREATER_THAN */ :
  3983. s = a.value, c = !1;
  3984. break;
  3985. case "!=" /* Operator.NOT_EQUAL */ :
  3986. case "not-in" /* Operator.NOT_IN */ :
  3987. s = Ge;
  3988. // Remaining filters cannot be used as lower bounds.
  3989. }
  3990. cn({
  3991. value: r,
  3992. inclusive: i
  3993. }, {
  3994. value: s,
  3995. inclusive: c
  3996. }) < 0 && (r = s, i = c);
  3997. }
  3998. // If there is an additional bound, compare the values against the existing
  3999. // range to see if we can narrow the scope.
  4000. if (null !== n) for (var l = 0; l < t.orderBy.length; ++l) if (t.orderBy[l].field.isEqual(e)) {
  4001. var h = n.position[l];
  4002. cn({
  4003. value: r,
  4004. inclusive: i
  4005. }, {
  4006. value: h,
  4007. inclusive: n.inclusive
  4008. }) < 0 && (r = h, i = n.inclusive);
  4009. break;
  4010. }
  4011. return {
  4012. value: r,
  4013. inclusive: i
  4014. };
  4015. }
  4016. /**
  4017. * Returns the value to use as the upper bound for ascending index segment at
  4018. * the provided `fieldPath` (or the lower bound for a descending segment).
  4019. */ function Kn(t, e, n) {
  4020. // Process all filters to find a value for the current field segment
  4021. for (var r = ze, i = !0, o = 0, u = Gn(t, e); o < u.length; o++) {
  4022. var a = u[o], s = ze, c = !0;
  4023. switch (a.op) {
  4024. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  4025. case ">" /* Operator.GREATER_THAN */ :
  4026. s = sn(a.value), c = !1;
  4027. break;
  4028. case "==" /* Operator.EQUAL */ :
  4029. case "in" /* Operator.IN */ :
  4030. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  4031. s = a.value;
  4032. break;
  4033. case "<" /* Operator.LESS_THAN */ :
  4034. s = a.value, c = !1;
  4035. break;
  4036. case "!=" /* Operator.NOT_EQUAL */ :
  4037. case "not-in" /* Operator.NOT_IN */ :
  4038. s = ze;
  4039. // Remaining filters cannot be used as upper bounds.
  4040. }
  4041. ln({
  4042. value: r,
  4043. inclusive: i
  4044. }, {
  4045. value: s,
  4046. inclusive: c
  4047. }) > 0 && (r = s, i = c);
  4048. }
  4049. // If there is an additional bound, compare the values against the existing
  4050. // range to see if we can narrow the scope.
  4051. if (null !== n) for (var l = 0; l < t.orderBy.length; ++l) if (t.orderBy[l].field.isEqual(e)) {
  4052. var h = n.position[l];
  4053. ln({
  4054. value: r,
  4055. inclusive: i
  4056. }, {
  4057. value: h,
  4058. inclusive: n.inclusive
  4059. }) > 0 && (r = h, i = n.inclusive);
  4060. break;
  4061. }
  4062. return {
  4063. value: r,
  4064. inclusive: i
  4065. };
  4066. }
  4067. /** Returns the number of segments of a perfect index for this target. */
  4068. /**
  4069. * @license
  4070. * Copyright 2017 Google LLC
  4071. *
  4072. * Licensed under the Apache License, Version 2.0 (the "License");
  4073. * you may not use this file except in compliance with the License.
  4074. * You may obtain a copy of the License at
  4075. *
  4076. * http://www.apache.org/licenses/LICENSE-2.0
  4077. *
  4078. * Unless required by applicable law or agreed to in writing, software
  4079. * distributed under the License is distributed on an "AS IS" BASIS,
  4080. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4081. * See the License for the specific language governing permissions and
  4082. * limitations under the License.
  4083. */
  4084. /**
  4085. * Query encapsulates all the query attributes we support in the SDK. It can
  4086. * be run against the LocalStore, as well as be converted to a `Target` to
  4087. * query the RemoteStore results.
  4088. *
  4089. * Visible for testing.
  4090. */ var Qn =
  4091. /**
  4092. * Initializes a Query with a path and optional additional query constraints.
  4093. * Path must currently be empty if this is a collection group query.
  4094. */
  4095. function(t, e, n, r, i, o /* LimitType.First */ , u, a) {
  4096. void 0 === e && (e = null), void 0 === n && (n = []), void 0 === r && (r = []),
  4097. void 0 === i && (i = null), void 0 === o && (o = "F"), void 0 === u && (u = null),
  4098. void 0 === a && (a = null), this.path = t, this.collectionGroup = e, this.explicitOrderBy = n,
  4099. this.filters = r, this.limit = i, this.limitType = o, this.startAt = u, this.endAt = a,
  4100. this.wt = null,
  4101. // The corresponding `Target` of this `Query` instance.
  4102. this._t = null, this.startAt, this.endAt;
  4103. };
  4104. /** Creates a new Query instance with the options provided. */ function Wn(t, e, n, r, i, o, u, a) {
  4105. return new Qn(t, e, n, r, i, o, u, a);
  4106. }
  4107. /** Creates a new Query for a query that matches all documents at `path` */ function Hn(t) {
  4108. return new Qn(t);
  4109. }
  4110. /**
  4111. * Helper to convert a collection group query into a collection query at a
  4112. * specific path. This is used when executing collection group queries, since
  4113. * we have to split the query into a set of collection queries at multiple
  4114. * paths.
  4115. */
  4116. /**
  4117. * Returns true if this query does not specify any query constraints that
  4118. * could remove results.
  4119. */ function Yn(t) {
  4120. 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());
  4121. }
  4122. function Xn(t) {
  4123. return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;
  4124. }
  4125. function Jn(t) {
  4126. for (var e = 0, n = t.filters; e < n.length; e++) {
  4127. var r = n[e].getFirstInequalityField();
  4128. if (null !== r) return r;
  4129. }
  4130. return null;
  4131. }
  4132. /**
  4133. * Creates a new Query for a collection group query that matches all documents
  4134. * within the provided collection group.
  4135. */
  4136. /**
  4137. * Returns whether the query matches a collection group rather than a specific
  4138. * collection.
  4139. */ function Zn(t) {
  4140. return null !== t.collectionGroup;
  4141. }
  4142. /**
  4143. * Returns the implicit order by constraint that is used to execute the Query,
  4144. * which can be different from the order by constraints the user provided (e.g.
  4145. * the SDK and backend always orders by `__name__`).
  4146. */ function $n(t) {
  4147. var e = j(t);
  4148. if (null === e.wt) {
  4149. e.wt = [];
  4150. var n = Jn(e), r = Xn(e);
  4151. if (null !== n && null === r)
  4152. // In order to implicitly add key ordering, we must also add the
  4153. // inequality filter field for it to be a valid query.
  4154. // Note that the default inequality field and key ordering is ascending.
  4155. n.isKeyField() || e.wt.push(new yn(n)), e.wt.push(new yn(dt.keyField(), "asc" /* Direction.ASCENDING */)); else {
  4156. for (var i = !1, o = 0, u = e.explicitOrderBy; o < u.length; o++) {
  4157. var a = u[o];
  4158. e.wt.push(a), a.field.isKeyField() && (i = !0);
  4159. }
  4160. if (!i) {
  4161. // The order of the implicit key ordering always matches the last
  4162. // explicit order by
  4163. var s = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */;
  4164. e.wt.push(new yn(dt.keyField(), s));
  4165. }
  4166. }
  4167. }
  4168. return e.wt;
  4169. }
  4170. /**
  4171. * Converts this `Query` instance to it's corresponding `Target` representation.
  4172. */ function tr(t) {
  4173. var e = j(t);
  4174. if (!e._t) if ("F" /* LimitType.First */ === e.limitType) e._t = qn(e.path, e.collectionGroup, $n(e), e.filters, e.limit, e.startAt, e.endAt); else {
  4175. for (
  4176. // Flip the orderBy directions since we want the last results
  4177. var n = [], r = 0, i = $n(e); r < i.length; r++) {
  4178. var o = i[r], u = "desc" /* Direction.DESCENDING */ === o.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */;
  4179. n.push(new yn(o.field, u));
  4180. }
  4181. // We need to swap the cursors to match the now-flipped query ordering.
  4182. var a = e.endAt ? new pn(e.endAt.position, e.endAt.inclusive) : null, s = e.startAt ? new pn(e.startAt.position, e.startAt.inclusive) : null;
  4183. // Now return as a LimitType.First query.
  4184. e._t = qn(e.path, e.collectionGroup, n, e.filters, e.limit, a, s);
  4185. }
  4186. return e._t;
  4187. }
  4188. function er(t, e) {
  4189. e.getFirstInequalityField(), Jn(t);
  4190. var n = t.filters.concat([ e ]);
  4191. return new Qn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);
  4192. }
  4193. function nr(t, e, n) {
  4194. return new Qn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);
  4195. }
  4196. function rr(t, e) {
  4197. return Un(tr(t), tr(e)) && t.limitType === e.limitType;
  4198. }
  4199. // TODO(b/29183165): This is used to get a unique string from a query to, for
  4200. // example, use as a dictionary key, but the implementation is subject to
  4201. // collisions. Make it collision-free.
  4202. function ir(t) {
  4203. return "".concat(Bn(tr(t)), "|lt:").concat(t.limitType);
  4204. }
  4205. function or(t) {
  4206. return "Query(target=".concat(function(t) {
  4207. var e = t.path.canonicalString();
  4208. return null !== t.collectionGroup && (e += " collectionGroup=" + t.collectionGroup),
  4209. t.filters.length > 0 && (e += ", filters: [".concat(t.filters.map((function(t) {
  4210. return Nn(t);
  4211. })).join(", "), "]")), zt(t.limit) || (e += ", limit: " + t.limit), t.orderBy.length > 0 && (e += ", orderBy: [".concat(t.orderBy.map((function(t) {
  4212. return function(t) {
  4213. return "".concat(t.field.canonicalString(), " (").concat(t.dir, ")");
  4214. }(t);
  4215. })).join(", "), "]")), t.startAt && (e += ", startAt: ", e += t.startAt.inclusive ? "b:" : "a:",
  4216. e += t.startAt.position.map((function(t) {
  4217. return Ye(t);
  4218. })).join(",")), t.endAt && (e += ", endAt: ", e += t.endAt.inclusive ? "a:" : "b:",
  4219. e += t.endAt.position.map((function(t) {
  4220. return Ye(t);
  4221. })).join(",")), "Target(".concat(e, ")");
  4222. }(tr(t)), "; limitType=").concat(t.limitType, ")");
  4223. }
  4224. /** Returns whether `doc` matches the constraints of `query`. */ function ur(t, e) {
  4225. return e.isFoundDocument() && function(t, e) {
  4226. var n = e.key.path;
  4227. return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : pt.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);
  4228. }(t, e) && function(t, e) {
  4229. // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).
  4230. // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must
  4231. // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due
  4232. // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a".
  4233. // A document with content of {b:1} matches the filters, but does not match the orderBy because
  4234. // it's missing the field 'a'.
  4235. for (var n = 0, r = $n(t); n < r.length; n++) {
  4236. var i = r[n];
  4237. // order by key always matches
  4238. if (!i.field.isKeyField() && null === e.data.field(i.field)) return !1;
  4239. }
  4240. return !0;
  4241. }(t, e) && function(t, e) {
  4242. for (var n = 0, r = t.filters; n < r.length; n++) {
  4243. if (!r[n].matches(e)) return !1;
  4244. }
  4245. return !0;
  4246. }(t, e) && function(t, e) {
  4247. return !(t.startAt &&
  4248. /**
  4249. * Returns true if a document sorts before a bound using the provided sort
  4250. * order.
  4251. */
  4252. !function(t, e, n) {
  4253. var r = vn(t, e, n);
  4254. return t.inclusive ? r <= 0 : r < 0;
  4255. }(t.startAt, $n(t), e)) && !(t.endAt && !function(t, e, n) {
  4256. var r = vn(t, e, n);
  4257. return t.inclusive ? r >= 0 : r > 0;
  4258. }(t.endAt, $n(t), e));
  4259. }(t, e);
  4260. }
  4261. function ar(t) {
  4262. return t.collectionGroup || (t.path.length % 2 == 1 ? t.path.lastSegment() : t.path.get(t.path.length - 2));
  4263. }
  4264. /**
  4265. * Returns a new comparator function that can be used to compare two documents
  4266. * based on the Query's ordering constraint.
  4267. */ function sr(t) {
  4268. return function(e, n) {
  4269. for (var r = !1, i = 0, o = $n(t); i < o.length; i++) {
  4270. var u = o[i], a = cr(u, e, n);
  4271. if (0 !== a) return a;
  4272. r = r || u.field.isKeyField();
  4273. }
  4274. return 0;
  4275. };
  4276. }
  4277. function cr(t, e, n) {
  4278. var r = t.field.isKeyField() ? pt.comparator(e.key, n.key) : function(t, e, n) {
  4279. var r = e.data.field(t), i = n.data.field(t);
  4280. return null !== r && null !== i ? We(r, i) : U();
  4281. }(t.field, e, n);
  4282. switch (t.dir) {
  4283. case "asc" /* Direction.ASCENDING */ :
  4284. return r;
  4285. case "desc" /* Direction.DESCENDING */ :
  4286. return -1 * r;
  4287. default:
  4288. return U();
  4289. }
  4290. }
  4291. /**
  4292. * @license
  4293. * Copyright 2017 Google LLC
  4294. *
  4295. * Licensed under the Apache License, Version 2.0 (the "License");
  4296. * you may not use this file except in compliance with the License.
  4297. * You may obtain a copy of the License at
  4298. *
  4299. * http://www.apache.org/licenses/LICENSE-2.0
  4300. *
  4301. * Unless required by applicable law or agreed to in writing, software
  4302. * distributed under the License is distributed on an "AS IS" BASIS,
  4303. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4304. * See the License for the specific language governing permissions and
  4305. * limitations under the License.
  4306. */
  4307. /**
  4308. * A map implementation that uses objects as keys. Objects must have an
  4309. * associated equals function and must be immutable. Entries in the map are
  4310. * stored together with the key being produced from the mapKeyFn. This map
  4311. * automatically handles collisions of keys.
  4312. */ var lr = /** @class */ function() {
  4313. function t(t, e) {
  4314. this.mapKeyFn = t, this.equalsFn = e,
  4315. /**
  4316. * The inner map for a key/value pair. Due to the possibility of collisions we
  4317. * keep a list of entries that we do a linear search through to find an actual
  4318. * match. Note that collisions should be rare, so we still expect near
  4319. * constant time lookups in practice.
  4320. */
  4321. this.inner = {},
  4322. /** The number of entries stored in the map */
  4323. this.innerSize = 0
  4324. /** Get a value for this key, or undefined if it does not exist. */;
  4325. }
  4326. return t.prototype.get = function(t) {
  4327. var e = this.mapKeyFn(t), n = this.inner[e];
  4328. if (void 0 !== n) for (var r = 0, i = n; r < i.length; r++) {
  4329. var o = i[r], u = o[0], a = o[1];
  4330. if (this.equalsFn(u, t)) return a;
  4331. }
  4332. }, t.prototype.has = function(t) {
  4333. return void 0 !== this.get(t);
  4334. },
  4335. /** Put this key and value in the map. */ t.prototype.set = function(t, e) {
  4336. var n = this.mapKeyFn(t), r = this.inner[n];
  4337. if (void 0 === r) return this.inner[n] = [ [ t, e ] ], void this.innerSize++;
  4338. for (var i = 0; i < r.length; i++) if (this.equalsFn(r[i][0], t))
  4339. // This is updating an existing entry and does not increase `innerSize`.
  4340. return void (r[i] = [ t, e ]);
  4341. r.push([ t, e ]), this.innerSize++;
  4342. },
  4343. /**
  4344. * Remove this key from the map. Returns a boolean if anything was deleted.
  4345. */
  4346. t.prototype.delete = function(t) {
  4347. var e = this.mapKeyFn(t), n = this.inner[e];
  4348. if (void 0 === n) return !1;
  4349. for (var r = 0; r < n.length; r++) if (this.equalsFn(n[r][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(r, 1),
  4350. this.innerSize--, !0;
  4351. return !1;
  4352. }, t.prototype.forEach = function(t) {
  4353. Ie(this.inner, (function(e, n) {
  4354. for (var r = 0, i = n; r < i.length; r++) {
  4355. var o = i[r], u = o[0], a = o[1];
  4356. t(u, a);
  4357. }
  4358. }));
  4359. }, t.prototype.isEmpty = function() {
  4360. return Ee(this.inner);
  4361. }, t.prototype.size = function() {
  4362. return this.innerSize;
  4363. }, t;
  4364. }(), hr = new Te(pt.comparator);
  4365. /**
  4366. * @license
  4367. * Copyright 2017 Google LLC
  4368. *
  4369. * Licensed under the Apache License, Version 2.0 (the "License");
  4370. * you may not use this file except in compliance with the License.
  4371. * You may obtain a copy of the License at
  4372. *
  4373. * http://www.apache.org/licenses/LICENSE-2.0
  4374. *
  4375. * Unless required by applicable law or agreed to in writing, software
  4376. * distributed under the License is distributed on an "AS IS" BASIS,
  4377. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4378. * See the License for the specific language governing permissions and
  4379. * limitations under the License.
  4380. */ function fr() {
  4381. return hr;
  4382. }
  4383. var dr = new Te(pt.comparator);
  4384. function pr() {
  4385. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  4386. for (var n = dr, r = 0, i = t; r < i.length; r++) {
  4387. var o = i[r];
  4388. n = n.insert(o.key, o);
  4389. }
  4390. return n;
  4391. }
  4392. function vr(t) {
  4393. var e = dr;
  4394. return t.forEach((function(t, n) {
  4395. return e = e.insert(t, n.overlayedDocument);
  4396. })), e;
  4397. }
  4398. function mr() {
  4399. return gr();
  4400. }
  4401. function yr() {
  4402. return gr();
  4403. }
  4404. function gr() {
  4405. return new lr((function(t) {
  4406. return t.toString();
  4407. }), (function(t, e) {
  4408. return t.isEqual(e);
  4409. }));
  4410. }
  4411. var wr = new Te(pt.comparator), br = new De(pt.comparator);
  4412. function Ir() {
  4413. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  4414. for (var n = br, r = 0, i = t; r < i.length; r++) {
  4415. var o = i[r];
  4416. n = n.add(o);
  4417. }
  4418. return n;
  4419. }
  4420. var Er = new De(ot);
  4421. function Tr() {
  4422. return Er;
  4423. }
  4424. /**
  4425. * @license
  4426. * Copyright 2020 Google LLC
  4427. *
  4428. * Licensed under the Apache License, Version 2.0 (the "License");
  4429. * you may not use this file except in compliance with the License.
  4430. * You may obtain a copy of the License at
  4431. *
  4432. * http://www.apache.org/licenses/LICENSE-2.0
  4433. *
  4434. * Unless required by applicable law or agreed to in writing, software
  4435. * distributed under the License is distributed on an "AS IS" BASIS,
  4436. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4437. * See the License for the specific language governing permissions and
  4438. * limitations under the License.
  4439. */
  4440. /**
  4441. * Returns an DoubleValue for `value` that is encoded based the serializer's
  4442. * `useProto3Json` setting.
  4443. */ function Sr(t, e) {
  4444. if (t.useProto3Json) {
  4445. if (isNaN(e)) return {
  4446. doubleValue: "NaN"
  4447. };
  4448. if (e === 1 / 0) return {
  4449. doubleValue: "Infinity"
  4450. };
  4451. if (e === -1 / 0) return {
  4452. doubleValue: "-Infinity"
  4453. };
  4454. }
  4455. return {
  4456. doubleValue: Gt(e) ? "-0" : e
  4457. };
  4458. }
  4459. /**
  4460. * Returns an IntegerValue for `value`.
  4461. */ function _r(t) {
  4462. return {
  4463. integerValue: "" + t
  4464. };
  4465. }
  4466. /**
  4467. * Returns a value for a number that's appropriate to put into a proto.
  4468. * The return value is an IntegerValue if it can safely represent the value,
  4469. * otherwise a DoubleValue is returned.
  4470. */ function Dr(t, e) {
  4471. return jt(e) ? _r(e) : Sr(t, e);
  4472. }
  4473. /**
  4474. * @license
  4475. * Copyright 2018 Google LLC
  4476. *
  4477. * Licensed under the Apache License, Version 2.0 (the "License");
  4478. * you may not use this file except in compliance with the License.
  4479. * You may obtain a copy of the License at
  4480. *
  4481. * http://www.apache.org/licenses/LICENSE-2.0
  4482. *
  4483. * Unless required by applicable law or agreed to in writing, software
  4484. * distributed under the License is distributed on an "AS IS" BASIS,
  4485. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4486. * See the License for the specific language governing permissions and
  4487. * limitations under the License.
  4488. */
  4489. /** Used to represent a field transform on a mutation. */ var Cr = function() {
  4490. // Make sure that the structural type of `TransformOperation` is unique.
  4491. // See https://github.com/microsoft/TypeScript/issues/5451
  4492. this._ = void 0;
  4493. };
  4494. /**
  4495. * Computes the local transform result against the provided `previousValue`,
  4496. * optionally using the provided localWriteTime.
  4497. */ function xr(t, e, n) {
  4498. return t instanceof kr ? function(t, e) {
  4499. var n = {
  4500. fields: {
  4501. __type__: {
  4502. stringValue: "server_timestamp"
  4503. },
  4504. __local_write_time__: {
  4505. timestampValue: {
  4506. seconds: t.seconds,
  4507. nanos: t.nanoseconds
  4508. }
  4509. }
  4510. }
  4511. };
  4512. // We should avoid storing deeply nested server timestamp map values
  4513. // because we never use the intermediate "previous values".
  4514. // For example:
  4515. // previous: 42L, add: t1, result: t1 -> 42L
  4516. // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)
  4517. // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)
  4518. // `getPreviousValue` recursively traverses server timestamps to find the
  4519. // least recent Value.
  4520. return e && Me(e) && (e = Le(e)), e && (n.fields.__previous_value__ = e),
  4521. {
  4522. mapValue: n
  4523. };
  4524. }(n, e) : t instanceof Or ? Fr(t, e) : t instanceof Pr ? Rr(t, e) : function(t, e) {
  4525. // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit
  4526. // precision and resolves overflows by reducing precision, we do not
  4527. // manually cap overflows at 2^63.
  4528. var n = Ar(t, e), r = Mr(n) + Mr(t.gt);
  4529. return $e(n) && $e(t.gt) ? _r(r) : Sr(t.serializer, r);
  4530. }(t, e);
  4531. }
  4532. /**
  4533. * Computes a final transform result after the transform has been acknowledged
  4534. * by the server, potentially using the server-provided transformResult.
  4535. */ function Nr(t, e, n) {
  4536. // The server just sends null as the transform result for array operations,
  4537. // so we have to calculate a result the same as we do for local
  4538. // applications.
  4539. return t instanceof Or ? Fr(t, e) : t instanceof Pr ? Rr(t, e) : n;
  4540. }
  4541. /**
  4542. * If this transform operation is not idempotent, returns the base value to
  4543. * persist for this transform. If a base value is returned, the transform
  4544. * operation is always applied to this base value, even if document has
  4545. * already been updated.
  4546. *
  4547. * Base values provide consistent behavior for non-idempotent transforms and
  4548. * allow us to return the same latency-compensated value even if the backend
  4549. * has already applied the transform operation. The base value is null for
  4550. * idempotent transforms, as they can be re-played even if the backend has
  4551. * already applied them.
  4552. *
  4553. * @returns a base value to store along with the mutation, or null for
  4554. * idempotent transforms.
  4555. */ function Ar(t, e) {
  4556. return t instanceof Vr ? $e(n = e) || function(t) {
  4557. return !!t && "doubleValue" in t;
  4558. }(n) ? e : {
  4559. integerValue: 0
  4560. } : null;
  4561. var n;
  4562. }
  4563. /** Transforms a value into a server-generated timestamp. */ var kr = /** @class */ function(e) {
  4564. function n() {
  4565. return null !== e && e.apply(this, arguments) || this;
  4566. }
  4567. return t(n, e), n;
  4568. }(Cr), Or = /** @class */ function(e) {
  4569. function n(t) {
  4570. var n = this;
  4571. return (n = e.call(this) || this).elements = t, n;
  4572. }
  4573. return t(n, e), n;
  4574. }(Cr);
  4575. /** Transforms an array value via a union operation. */ function Fr(t, e) {
  4576. for (var n = Lr(e), r = function(t) {
  4577. n.some((function(e) {
  4578. return Ke(e, t);
  4579. })) || n.push(t);
  4580. }, i = 0, o = t.elements; i < o.length; i++) {
  4581. r(o[i]);
  4582. }
  4583. return {
  4584. arrayValue: {
  4585. values: n
  4586. }
  4587. };
  4588. }
  4589. /** Transforms an array value via a remove operation. */ var Pr = /** @class */ function(e) {
  4590. function n(t) {
  4591. var n = this;
  4592. return (n = e.call(this) || this).elements = t, n;
  4593. }
  4594. return t(n, e), n;
  4595. }(Cr);
  4596. function Rr(t, e) {
  4597. for (var n = Lr(e), r = function(t) {
  4598. n = n.filter((function(e) {
  4599. return !Ke(e, t);
  4600. }));
  4601. }, i = 0, o = t.elements; i < o.length; i++) {
  4602. r(o[i]);
  4603. }
  4604. return {
  4605. arrayValue: {
  4606. values: n
  4607. }
  4608. };
  4609. }
  4610. /**
  4611. * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
  4612. * transforms. Converts all field values to integers or doubles, but unlike the
  4613. * backend does not cap integer values at 2^63. Instead, JavaScript number
  4614. * arithmetic is used and precision loss can occur for values greater than 2^53.
  4615. */ var Vr = /** @class */ function(e) {
  4616. function n(t, n) {
  4617. var r = this;
  4618. return (r = e.call(this) || this).serializer = t, r.gt = n, r;
  4619. }
  4620. return t(n, e), n;
  4621. }(Cr);
  4622. function Mr(t) {
  4623. return Re(t.integerValue || t.doubleValue);
  4624. }
  4625. function Lr(t) {
  4626. return tn(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];
  4627. }
  4628. /**
  4629. * @license
  4630. * Copyright 2017 Google LLC
  4631. *
  4632. * Licensed under the Apache License, Version 2.0 (the "License");
  4633. * you may not use this file except in compliance with the License.
  4634. * You may obtain a copy of the License at
  4635. *
  4636. * http://www.apache.org/licenses/LICENSE-2.0
  4637. *
  4638. * Unless required by applicable law or agreed to in writing, software
  4639. * distributed under the License is distributed on an "AS IS" BASIS,
  4640. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4641. * See the License for the specific language governing permissions and
  4642. * limitations under the License.
  4643. */
  4644. /** A field path and the TransformOperation to perform upon it. */ var qr = function(t, e) {
  4645. this.field = t, this.transform = e;
  4646. };
  4647. /** The result of successfully applying a mutation to the backend. */
  4648. var Br = function(
  4649. /**
  4650. * The version at which the mutation was committed:
  4651. *
  4652. * - For most operations, this is the updateTime in the WriteResult.
  4653. * - For deletes, the commitTime of the WriteResponse (because deletes are
  4654. * not stored and have no updateTime).
  4655. *
  4656. * Note that these versions can be different: No-op writes will not change
  4657. * the updateTime even though the commitTime advances.
  4658. */
  4659. t,
  4660. /**
  4661. * The resulting fields returned from the backend after a mutation
  4662. * containing field transforms has been committed. Contains one FieldValue
  4663. * for each FieldTransform that was in the mutation.
  4664. *
  4665. * Will be empty if the mutation did not contain any field transforms.
  4666. */
  4667. e) {
  4668. this.version = t, this.transformResults = e;
  4669. }, Ur = /** @class */ function() {
  4670. function t(t, e) {
  4671. this.updateTime = t, this.exists = e
  4672. /** Creates a new empty Precondition. */;
  4673. }
  4674. return t.none = function() {
  4675. return new t;
  4676. },
  4677. /** Creates a new Precondition with an exists flag. */ t.exists = function(e) {
  4678. return new t(void 0, e);
  4679. },
  4680. /** Creates a new Precondition based on a version a document exists at. */ t.updateTime = function(e) {
  4681. return new t(e);
  4682. }, Object.defineProperty(t.prototype, "isNone", {
  4683. /** Returns whether this Precondition is empty. */ get: function() {
  4684. return void 0 === this.updateTime && void 0 === this.exists;
  4685. },
  4686. enumerable: !1,
  4687. configurable: !0
  4688. }), t.prototype.isEqual = function(t) {
  4689. return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
  4690. }, t;
  4691. }();
  4692. /**
  4693. * Encodes a precondition for a mutation. This follows the model that the
  4694. * backend accepts with the special case of an explicit "empty" precondition
  4695. * (meaning no precondition).
  4696. */
  4697. /** Returns true if the preconditions is valid for the given document. */ function zr(t, e) {
  4698. return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();
  4699. }
  4700. /**
  4701. * A mutation describes a self-contained change to a document. Mutations can
  4702. * create, replace, delete, and update subsets of documents.
  4703. *
  4704. * Mutations not only act on the value of the document but also its version.
  4705. *
  4706. * For local mutations (mutations that haven't been committed yet), we preserve
  4707. * the existing version for Set and Patch mutations. For Delete mutations, we
  4708. * reset the version to 0.
  4709. *
  4710. * Here's the expected transition table.
  4711. *
  4712. * MUTATION APPLIED TO RESULTS IN
  4713. *
  4714. * SetMutation Document(v3) Document(v3)
  4715. * SetMutation NoDocument(v3) Document(v0)
  4716. * SetMutation InvalidDocument(v0) Document(v0)
  4717. * PatchMutation Document(v3) Document(v3)
  4718. * PatchMutation NoDocument(v3) NoDocument(v3)
  4719. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  4720. * DeleteMutation Document(v3) NoDocument(v0)
  4721. * DeleteMutation NoDocument(v3) NoDocument(v0)
  4722. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  4723. *
  4724. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  4725. * the resulting version for Set and Patch mutations. As deletes have no
  4726. * explicit update time, we use the commitTime of the WriteResponse for
  4727. * Delete mutations.
  4728. *
  4729. * If a mutation is acknowledged by the backend but fails the precondition check
  4730. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  4731. * the updated version.
  4732. *
  4733. * Field transforms are used only with Patch and Set Mutations. We use the
  4734. * `updateTransforms` message to store transforms, rather than the `transforms`s
  4735. * messages.
  4736. *
  4737. * ## Subclassing Notes
  4738. *
  4739. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  4740. * applyToLocalView() to implement the actual behavior of applying the mutation
  4741. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  4742. * example).
  4743. */ var Gr = function() {};
  4744. /**
  4745. * A utility method to calculate a `Mutation` representing the overlay from the
  4746. * final state of the document, and a `FieldMask` representing the fields that
  4747. * are mutated by the local mutations.
  4748. */ function jr(t, e) {
  4749. if (!t.hasLocalMutations || e && 0 === e.fields.length) return null;
  4750. // mask is null when sets or deletes are applied to the current document.
  4751. if (null === e) return t.isNoDocument() ? new ni(t.key, Ur.none()) : new Yr(t.key, t.data, Ur.none());
  4752. for (var n = t.data, r = hn.empty(), i = new De(dt.comparator), o = 0, u = e.fields; o < u.length; o++) {
  4753. var a = u[o];
  4754. if (!i.has(a)) {
  4755. var s = n.field(a);
  4756. // If we are deleting a nested field, we take the immediate parent as
  4757. // the mask used to construct the resulting mutation.
  4758. // Justification: Nested fields can create parent fields implicitly. If
  4759. // only a leaf entry is deleted in later mutations, the parent field
  4760. // should still remain, but we may have lost this information.
  4761. // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).
  4762. // This leaves the final result (foo, {}). Despite the fact that `doc`
  4763. // has the correct result, `foo` is not in `mask`, and the resulting
  4764. // mutation would miss `foo`.
  4765. null === s && a.length > 1 && (a = a.popLast(), s = n.field(a)), null === s ? r.delete(a) : r.set(a, s),
  4766. i = i.add(a);
  4767. }
  4768. }
  4769. return new Xr(t.key, r, new Ne(i.toArray()), Ur.none());
  4770. }
  4771. /**
  4772. * Applies this mutation to the given document for the purposes of computing a
  4773. * new remote document. If the input document doesn't match the expected state
  4774. * (e.g. it is invalid or outdated), the document type may transition to
  4775. * unknown.
  4776. *
  4777. * @param mutation - The mutation to apply.
  4778. * @param document - The document to mutate. The input document can be an
  4779. * invalid document if the client has no knowledge of the pre-mutation state
  4780. * of the document.
  4781. * @param mutationResult - The result of applying the mutation from the backend.
  4782. */ function Kr(t, e, n) {
  4783. t instanceof Yr ? function(t, e, n) {
  4784. // Unlike setMutationApplyToLocalView, if we're applying a mutation to a
  4785. // remote document the server has accepted the mutation so the precondition
  4786. // must have held.
  4787. var r = t.value.clone(), i = Zr(t.fieldTransforms, e, n.transformResults);
  4788. r.setAll(i), e.convertToFoundDocument(n.version, r).setHasCommittedMutations();
  4789. }(t, e, n) : t instanceof Xr ? function(t, e, n) {
  4790. if (zr(t.precondition, e)) {
  4791. var r = Zr(t.fieldTransforms, e, n.transformResults), i = e.data;
  4792. i.setAll(Jr(t)), i.setAll(r), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();
  4793. } else e.convertToUnknownDocument(n.version);
  4794. }(t, e, n) : function(t, e, n) {
  4795. // Unlike applyToLocalView, if we're applying a mutation to a remote
  4796. // document the server has accepted the mutation so the precondition must
  4797. // have held.
  4798. e.convertToNoDocument(n.version).setHasCommittedMutations();
  4799. }(0, e, n);
  4800. }
  4801. /**
  4802. * Applies this mutation to the given document for the purposes of computing
  4803. * the new local view of a document. If the input document doesn't match the
  4804. * expected state, the document is not modified.
  4805. *
  4806. * @param mutation - The mutation to apply.
  4807. * @param document - The document to mutate. The input document can be an
  4808. * invalid document if the client has no knowledge of the pre-mutation state
  4809. * of the document.
  4810. * @param previousMask - The fields that have been updated before applying this mutation.
  4811. * @param localWriteTime - A timestamp indicating the local write time of the
  4812. * batch this mutation is a part of.
  4813. * @returns A `FieldMask` representing the fields that are changed by applying this mutation.
  4814. */ function Qr(t, e, n, r) {
  4815. return t instanceof Yr ? function(t, e, n, r) {
  4816. if (!zr(t.precondition, e))
  4817. // The mutation failed to apply (e.g. a document ID created with add()
  4818. // caused a name collision).
  4819. return n;
  4820. var i = t.value.clone(), o = $r(t.fieldTransforms, r, e);
  4821. return i.setAll(o), e.convertToFoundDocument(e.version, i).setHasLocalMutations(),
  4822. null;
  4823. // SetMutation overwrites all fields.
  4824. }(t, e, n, r) : t instanceof Xr ? function(t, e, n, r) {
  4825. if (!zr(t.precondition, e)) return n;
  4826. var i = $r(t.fieldTransforms, r, e), o = e.data;
  4827. return o.setAll(Jr(t)), o.setAll(i), e.convertToFoundDocument(e.version, o).setHasLocalMutations(),
  4828. null === n ? null : n.unionWith(t.fieldMask.fields).unionWith(t.fieldTransforms.map((function(t) {
  4829. return t.field;
  4830. })));
  4831. }(t, e, n, r) : function(t, e, n) {
  4832. return zr(t.precondition, e) ? (e.convertToNoDocument(e.version).setHasLocalMutations(),
  4833. null) : n;
  4834. }(t, e, n);
  4835. }
  4836. /**
  4837. * If this mutation is not idempotent, returns the base value to persist with
  4838. * this mutation. If a base value is returned, the mutation is always applied
  4839. * to this base value, even if document has already been updated.
  4840. *
  4841. * The base value is a sparse object that consists of only the document
  4842. * fields for which this mutation contains a non-idempotent transformation
  4843. * (e.g. a numeric increment). The provided value guarantees consistent
  4844. * behavior for non-idempotent transforms and allow us to return the same
  4845. * latency-compensated value even if the backend has already applied the
  4846. * mutation. The base value is null for idempotent mutations, as they can be
  4847. * re-played even if the backend has already applied them.
  4848. *
  4849. * @returns a base value to store along with the mutation, or null for
  4850. * idempotent mutations.
  4851. */ function Wr(t, e) {
  4852. for (var n = null, r = 0, i = t.fieldTransforms; r < i.length; r++) {
  4853. var o = i[r], u = e.data.field(o.field), a = Ar(o.transform, u || null);
  4854. null != a && (null === n && (n = hn.empty()), n.set(o.field, a));
  4855. }
  4856. return n || null;
  4857. }
  4858. function Hr(t, e) {
  4859. return t.type === e.type && !!t.key.isEqual(e.key) && !!t.precondition.isEqual(e.precondition) && !!function(t, e) {
  4860. return void 0 === t && void 0 === e || !(!t || !e) && ut(t, e, (function(t, e) {
  4861. return function(t, e) {
  4862. return t.field.isEqual(e.field) && function(t, e) {
  4863. return t instanceof Or && e instanceof Or || t instanceof Pr && e instanceof Pr ? ut(t.elements, e.elements, Ke) : t instanceof Vr && e instanceof Vr ? Ke(t.gt, e.gt) : t instanceof kr && e instanceof kr;
  4864. }(t.transform, e.transform);
  4865. }(t, e);
  4866. }));
  4867. }(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));
  4868. }
  4869. /**
  4870. * A mutation that creates or replaces the document at the given key with the
  4871. * object value contents.
  4872. */ var Yr = /** @class */ function(e) {
  4873. function n(t, n, r, i) {
  4874. void 0 === i && (i = []);
  4875. var o = this;
  4876. return (o = e.call(this) || this).key = t, o.value = n, o.precondition = r, o.fieldTransforms = i,
  4877. o.type = 0 /* MutationType.Set */ , o;
  4878. }
  4879. return t(n, e), n.prototype.getFieldMask = function() {
  4880. return null;
  4881. }, n;
  4882. }(Gr), Xr = /** @class */ function(e) {
  4883. function n(t, n, r, i, o) {
  4884. void 0 === o && (o = []);
  4885. var u = this;
  4886. return (u = e.call(this) || this).key = t, u.data = n, u.fieldMask = r, u.precondition = i,
  4887. u.fieldTransforms = o, u.type = 1 /* MutationType.Patch */ , u;
  4888. }
  4889. return t(n, e), n.prototype.getFieldMask = function() {
  4890. return this.fieldMask;
  4891. }, n;
  4892. }(Gr);
  4893. function Jr(t) {
  4894. var e = new Map;
  4895. return t.fieldMask.fields.forEach((function(n) {
  4896. if (!n.isEmpty()) {
  4897. var r = t.data.field(n);
  4898. e.set(n, r);
  4899. }
  4900. })), e
  4901. /**
  4902. * Creates a list of "transform results" (a transform result is a field value
  4903. * representing the result of applying a transform) for use after a mutation
  4904. * containing transforms has been acknowledged by the server.
  4905. *
  4906. * @param fieldTransforms - The field transforms to apply the result to.
  4907. * @param mutableDocument - The current state of the document after applying all
  4908. * previous mutations.
  4909. * @param serverTransformResults - The transform results received by the server.
  4910. * @returns The transform results list.
  4911. */;
  4912. }
  4913. function Zr(t, e, n) {
  4914. var r = new Map;
  4915. z(t.length === n.length);
  4916. for (var i = 0; i < n.length; i++) {
  4917. var o = t[i], u = o.transform, a = e.data.field(o.field);
  4918. r.set(o.field, Nr(u, a, n[i]));
  4919. }
  4920. return r;
  4921. }
  4922. /**
  4923. * Creates a list of "transform results" (a transform result is a field value
  4924. * representing the result of applying a transform) for use when applying a
  4925. * transform locally.
  4926. *
  4927. * @param fieldTransforms - The field transforms to apply the result to.
  4928. * @param localWriteTime - The local time of the mutation (used to
  4929. * generate ServerTimestampValues).
  4930. * @param mutableDocument - The document to apply transforms on.
  4931. * @returns The transform results list.
  4932. */ function $r(t, e, n) {
  4933. for (var r = new Map, i = 0, o = t; i < o.length; i++) {
  4934. var u = o[i], a = u.transform, s = n.data.field(u.field);
  4935. r.set(u.field, xr(a, s, e));
  4936. }
  4937. return r;
  4938. }
  4939. /** A mutation that deletes the document at the given key. */ var ti, ei, ni = /** @class */ function(e) {
  4940. function n(t, n) {
  4941. var r = this;
  4942. return (r = e.call(this) || this).key = t, r.precondition = n, r.type = 2 /* MutationType.Delete */ ,
  4943. r.fieldTransforms = [], r;
  4944. }
  4945. return t(n, e), n.prototype.getFieldMask = function() {
  4946. return null;
  4947. }, n;
  4948. }(Gr), ri = /** @class */ function(e) {
  4949. function n(t, n) {
  4950. var r = this;
  4951. return (r = e.call(this) || this).key = t, r.precondition = n, r.type = 3 /* MutationType.Verify */ ,
  4952. r.fieldTransforms = [], r;
  4953. }
  4954. return t(n, e), n.prototype.getFieldMask = function() {
  4955. return null;
  4956. }, n;
  4957. }(Gr), ii = /** @class */ function() {
  4958. /**
  4959. * @param batchId - The unique ID of this mutation batch.
  4960. * @param localWriteTime - The original write time of this mutation.
  4961. * @param baseMutations - Mutations that are used to populate the base
  4962. * values when this mutation is applied locally. This can be used to locally
  4963. * overwrite values that are persisted in the remote document cache. Base
  4964. * mutations are never sent to the backend.
  4965. * @param mutations - The user-provided mutations in this mutation batch.
  4966. * User-provided mutations are applied both locally and remotely on the
  4967. * backend.
  4968. */
  4969. function t(t, e, n, r) {
  4970. this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = r
  4971. /**
  4972. * Applies all the mutations in this MutationBatch to the specified document
  4973. * to compute the state of the remote document
  4974. *
  4975. * @param document - The document to apply mutations to.
  4976. * @param batchResult - The result of applying the MutationBatch to the
  4977. * backend.
  4978. */;
  4979. }
  4980. return t.prototype.applyToRemoteDocument = function(t, e) {
  4981. for (var n = e.mutationResults, r = 0; r < this.mutations.length; r++) {
  4982. var i = this.mutations[r];
  4983. i.key.isEqual(t.key) && Kr(i, t, n[r]);
  4984. }
  4985. },
  4986. /**
  4987. * Computes the local view of a document given all the mutations in this
  4988. * batch.
  4989. *
  4990. * @param document - The document to apply mutations to.
  4991. * @param mutatedFields - Fields that have been updated before applying this mutation batch.
  4992. * @returns A `FieldMask` representing all the fields that are mutated.
  4993. */
  4994. t.prototype.applyToLocalView = function(t, e) {
  4995. // First, apply the base state. This allows us to apply non-idempotent
  4996. // transform against a consistent set of values.
  4997. for (var n = 0, r = this.baseMutations; n < r.length; n++) {
  4998. var i = r[n];
  4999. i.key.isEqual(t.key) && (e = Qr(i, t, e, this.localWriteTime));
  5000. }
  5001. // Second, apply all user-provided mutations.
  5002. for (var o = 0, u = this.mutations; o < u.length; o++) {
  5003. var a = u[o];
  5004. a.key.isEqual(t.key) && (e = Qr(a, t, e, this.localWriteTime));
  5005. }
  5006. return e;
  5007. },
  5008. /**
  5009. * Computes the local view for all provided documents given the mutations in
  5010. * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
  5011. * replace all the mutation applications.
  5012. */
  5013. t.prototype.applyToLocalDocumentSet = function(t, e) {
  5014. var n = this, r = yr();
  5015. // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations
  5016. // directly (as done in `applyToLocalView()`), we can reduce the complexity
  5017. // to O(n).
  5018. return this.mutations.forEach((function(i) {
  5019. var o = t.get(i.key), u = o.overlayedDocument, a = n.applyToLocalView(u, o.mutatedFields), s = jr(u,
  5020. // Set mutatedFields to null if the document is only from local mutations.
  5021. // This creates a Set or Delete mutation, instead of trying to create a
  5022. // patch mutation as the overlay.
  5023. a = e.has(i.key) ? null : a);
  5024. // TODO(mutabledocuments): This method should take a MutableDocumentMap
  5025. // and we should remove this cast.
  5026. null !== s && r.set(i.key, s), u.isValidDocument() || u.convertToNoDocument(ct.min());
  5027. })), r;
  5028. }, t.prototype.keys = function() {
  5029. return this.mutations.reduce((function(t, e) {
  5030. return t.add(e.key);
  5031. }), Ir());
  5032. }, t.prototype.isEqual = function(t) {
  5033. return this.batchId === t.batchId && ut(this.mutations, t.mutations, (function(t, e) {
  5034. return Hr(t, e);
  5035. })) && ut(this.baseMutations, t.baseMutations, (function(t, e) {
  5036. return Hr(t, e);
  5037. }));
  5038. }, t;
  5039. }(), oi = /** @class */ function() {
  5040. function t(t, e, n,
  5041. /**
  5042. * A pre-computed mapping from each mutated document to the resulting
  5043. * version.
  5044. */
  5045. r) {
  5046. this.batch = t, this.commitVersion = e, this.mutationResults = n, this.docVersions = r
  5047. /**
  5048. * Creates a new MutationBatchResult for the given batch and results. There
  5049. * must be one result for each mutation in the batch. This static factory
  5050. * caches a document=&gt;version mapping (docVersions).
  5051. */;
  5052. }
  5053. return t.from = function(e, n, r) {
  5054. z(e.mutations.length === r.length);
  5055. for (var i = wr, o = e.mutations, u = 0; u < o.length; u++) i = i.insert(o[u].key, r[u].version);
  5056. return new t(e, n, r, i);
  5057. }, t;
  5058. }(), ui = /** @class */ function() {
  5059. function t(t, e) {
  5060. this.largestBatchId = t, this.mutation = e;
  5061. }
  5062. return t.prototype.getKey = function() {
  5063. return this.mutation.key;
  5064. }, t.prototype.isEqual = function(t) {
  5065. return null !== t && this.mutation === t.mutation;
  5066. }, t.prototype.toString = function() {
  5067. return "Overlay{\n largestBatchId: ".concat(this.largestBatchId, ",\n mutation: ").concat(this.mutation.toString(), "\n }");
  5068. }, t;
  5069. }(), ai = function(t, e, n) {
  5070. this.alias = t, this.yt = e, this.fieldPath = n;
  5071. }, si = function(t, e) {
  5072. this.count = t, this.unchangedNames = e;
  5073. };
  5074. /**
  5075. * Determines whether an error code represents a permanent error when received
  5076. * in response to a non-write operation.
  5077. *
  5078. * See isPermanentWriteError for classifying write errors.
  5079. */
  5080. function ci(t) {
  5081. switch (t) {
  5082. default:
  5083. return U();
  5084. case K.CANCELLED:
  5085. case K.UNKNOWN:
  5086. case K.DEADLINE_EXCEEDED:
  5087. case K.RESOURCE_EXHAUSTED:
  5088. case K.INTERNAL:
  5089. case K.UNAVAILABLE:
  5090. // Unauthenticated means something went wrong with our token and we need
  5091. // to retry with new credentials which will happen automatically.
  5092. case K.UNAUTHENTICATED:
  5093. return !1;
  5094. case K.INVALID_ARGUMENT:
  5095. case K.NOT_FOUND:
  5096. case K.ALREADY_EXISTS:
  5097. case K.PERMISSION_DENIED:
  5098. case K.FAILED_PRECONDITION:
  5099. // Aborted might be retried in some scenarios, but that is dependant on
  5100. // the context and should handled individually by the calling code.
  5101. // See https://cloud.google.com/apis/design/errors.
  5102. case K.ABORTED:
  5103. case K.OUT_OF_RANGE:
  5104. case K.UNIMPLEMENTED:
  5105. case K.DATA_LOSS:
  5106. return !0;
  5107. }
  5108. }
  5109. /**
  5110. * Determines whether an error code represents a permanent error when received
  5111. * in response to a write operation.
  5112. *
  5113. * Write operations must be handled specially because as of b/119437764, ABORTED
  5114. * errors on the write stream should be retried too (even though ABORTED errors
  5115. * are not generally retryable).
  5116. *
  5117. * Note that during the initial handshake on the write stream an ABORTED error
  5118. * signals that we should discard our stream token (i.e. it is permanent). This
  5119. * means a handshake error should be classified with isPermanentError, above.
  5120. */
  5121. /**
  5122. * Maps an error Code from GRPC status code number, like 0, 1, or 14. These
  5123. * are not the same as HTTP status codes.
  5124. *
  5125. * @returns The Code equivalent to the given GRPC status code. Fails if there
  5126. * is no match.
  5127. */ function li(t) {
  5128. if (void 0 === t)
  5129. // This shouldn't normally happen, but in certain error cases (like trying
  5130. // to send invalid proto messages) we may get an error with no GRPC code.
  5131. return L("GRPC error has no .code"), K.UNKNOWN;
  5132. switch (t) {
  5133. case ti.OK:
  5134. return K.OK;
  5135. case ti.CANCELLED:
  5136. return K.CANCELLED;
  5137. case ti.UNKNOWN:
  5138. return K.UNKNOWN;
  5139. case ti.DEADLINE_EXCEEDED:
  5140. return K.DEADLINE_EXCEEDED;
  5141. case ti.RESOURCE_EXHAUSTED:
  5142. return K.RESOURCE_EXHAUSTED;
  5143. case ti.INTERNAL:
  5144. return K.INTERNAL;
  5145. case ti.UNAVAILABLE:
  5146. return K.UNAVAILABLE;
  5147. case ti.UNAUTHENTICATED:
  5148. return K.UNAUTHENTICATED;
  5149. case ti.INVALID_ARGUMENT:
  5150. return K.INVALID_ARGUMENT;
  5151. case ti.NOT_FOUND:
  5152. return K.NOT_FOUND;
  5153. case ti.ALREADY_EXISTS:
  5154. return K.ALREADY_EXISTS;
  5155. case ti.PERMISSION_DENIED:
  5156. return K.PERMISSION_DENIED;
  5157. case ti.FAILED_PRECONDITION:
  5158. return K.FAILED_PRECONDITION;
  5159. case ti.ABORTED:
  5160. return K.ABORTED;
  5161. case ti.OUT_OF_RANGE:
  5162. return K.OUT_OF_RANGE;
  5163. case ti.UNIMPLEMENTED:
  5164. return K.UNIMPLEMENTED;
  5165. case ti.DATA_LOSS:
  5166. return K.DATA_LOSS;
  5167. default:
  5168. return U();
  5169. }
  5170. }
  5171. /**
  5172. * Converts an HTTP response's error status to the equivalent error code.
  5173. *
  5174. * @param status - An HTTP error response status ("FAILED_PRECONDITION",
  5175. * "UNKNOWN", etc.)
  5176. * @returns The equivalent Code. Non-matching responses are mapped to
  5177. * Code.UNKNOWN.
  5178. */ (ei = ti || (ti = {}))[ei.OK = 0] = "OK", ei[ei.CANCELLED = 1] = "CANCELLED",
  5179. ei[ei.UNKNOWN = 2] = "UNKNOWN", ei[ei.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT",
  5180. ei[ei.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", ei[ei.NOT_FOUND = 5] = "NOT_FOUND",
  5181. ei[ei.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", ei[ei.PERMISSION_DENIED = 7] = "PERMISSION_DENIED",
  5182. ei[ei.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", ei[ei.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED",
  5183. ei[ei.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", ei[ei.ABORTED = 10] = "ABORTED",
  5184. ei[ei.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", ei[ei.UNIMPLEMENTED = 12] = "UNIMPLEMENTED",
  5185. ei[ei.INTERNAL = 13] = "INTERNAL", ei[ei.UNAVAILABLE = 14] = "UNAVAILABLE", ei[ei.DATA_LOSS = 15] = "DATA_LOSS";
  5186. /**
  5187. * @license
  5188. * Copyright 2023 Google LLC
  5189. *
  5190. * Licensed under the Apache License, Version 2.0 (the "License");
  5191. * you may not use this file except in compliance with the License.
  5192. * You may obtain a copy of the License at
  5193. *
  5194. * http://www.apache.org/licenses/LICENSE-2.0
  5195. *
  5196. * Unless required by applicable law or agreed to in writing, software
  5197. * distributed under the License is distributed on an "AS IS" BASIS,
  5198. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5199. * See the License for the specific language governing permissions and
  5200. * limitations under the License.
  5201. */
  5202. /**
  5203. * Manages "testing hooks", hooks into the internals of the SDK to verify
  5204. * internal state and events during integration tests. Do not use this class
  5205. * except for testing purposes.
  5206. *
  5207. * There are two ways to retrieve the global singleton instance of this class:
  5208. * 1. The `instance` property, which returns null if the global singleton
  5209. * instance has not been created. Use this property if the caller should
  5210. * "do nothing" if there are no testing hooks registered, such as when
  5211. * delivering an event to notify registered callbacks.
  5212. * 2. The `getOrCreateInstance()` method, which creates the global singleton
  5213. * instance if it has not been created. Use this method if the instance is
  5214. * needed to, for example, register a callback.
  5215. *
  5216. * @internal
  5217. */
  5218. var hi = /** @class */ function() {
  5219. function t() {
  5220. this.onExistenceFilterMismatchCallbacks = new Map;
  5221. }
  5222. return Object.defineProperty(t, "instance", {
  5223. /**
  5224. * Returns the singleton instance of this class, or null if it has not been
  5225. * initialized.
  5226. */
  5227. get: function() {
  5228. return fi;
  5229. },
  5230. enumerable: !1,
  5231. configurable: !0
  5232. }),
  5233. /**
  5234. * Returns the singleton instance of this class, creating it if is has never
  5235. * been created before.
  5236. */
  5237. t.getOrCreateInstance = function() {
  5238. return null === fi && (fi = new t), fi;
  5239. },
  5240. /**
  5241. * Registers a callback to be notified when an existence filter mismatch
  5242. * occurs in the Watch listen stream.
  5243. *
  5244. * The relative order in which callbacks are notified is unspecified; do not
  5245. * rely on any particular ordering. If a given callback is registered multiple
  5246. * times then it will be notified multiple times, once per registration.
  5247. *
  5248. * @param callback the callback to invoke upon existence filter mismatch.
  5249. *
  5250. * @return a function that, when called, unregisters the given callback; only
  5251. * the first invocation of the returned function does anything; all subsequent
  5252. * invocations do nothing.
  5253. */
  5254. t.prototype.onExistenceFilterMismatch = function(t) {
  5255. var e = this, n = Symbol();
  5256. return this.onExistenceFilterMismatchCallbacks.set(n, t), function() {
  5257. return e.onExistenceFilterMismatchCallbacks.delete(n);
  5258. };
  5259. },
  5260. /**
  5261. * Invokes all currently-registered `onExistenceFilterMismatch` callbacks.
  5262. * @param info Information about the existence filter mismatch.
  5263. */
  5264. t.prototype.notifyOnExistenceFilterMismatch = function(t) {
  5265. this.onExistenceFilterMismatchCallbacks.forEach((function(e) {
  5266. return e(t);
  5267. }));
  5268. }, t;
  5269. }(), fi = null;
  5270. /** The global singleton instance of `TestingHooks`. */
  5271. /**
  5272. * @license
  5273. * Copyright 2023 Google LLC
  5274. *
  5275. * Licensed under the Apache License, Version 2.0 (the "License");
  5276. * you may not use this file except in compliance with the License.
  5277. * You may obtain a copy of the License at
  5278. *
  5279. * http://www.apache.org/licenses/LICENSE-2.0
  5280. *
  5281. * Unless required by applicable law or agreed to in writing, software
  5282. * distributed under the License is distributed on an "AS IS" BASIS,
  5283. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5284. * See the License for the specific language governing permissions and
  5285. * limitations under the License.
  5286. */
  5287. /**
  5288. * An instance of the Platform's 'TextEncoder' implementation.
  5289. */
  5290. function di() {
  5291. return new TextEncoder;
  5292. }
  5293. /**
  5294. * An instance of the Platform's 'TextDecoder' implementation.
  5295. */
  5296. /**
  5297. * @license
  5298. * Copyright 2022 Google LLC
  5299. *
  5300. * Licensed under the Apache License, Version 2.0 (the "License");
  5301. * you may not use this file except in compliance with the License.
  5302. * You may obtain a copy of the License at
  5303. *
  5304. * http://www.apache.org/licenses/LICENSE-2.0
  5305. *
  5306. * Unless required by applicable law or agreed to in writing, software
  5307. * distributed under the License is distributed on an "AS IS" BASIS,
  5308. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5309. * See the License for the specific language governing permissions and
  5310. * limitations under the License.
  5311. */ var pi = new b([ 4294967295, 4294967295 ], 0);
  5312. // Hash a string using md5 hashing algorithm.
  5313. function vi(t) {
  5314. var e = di().encode(t), n = new A;
  5315. return n.update(e), new Uint8Array(n.digest());
  5316. }
  5317. // Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using
  5318. // 2’s complement using little endian.
  5319. function mi(t) {
  5320. var e = new DataView(t.buffer), n = e.getUint32(0, /* littleEndian= */ !0), r = e.getUint32(4, /* littleEndian= */ !0), i = e.getUint32(8, /* littleEndian= */ !0), o = e.getUint32(12, /* littleEndian= */ !0);
  5321. return [ new b([ n, r ], 0), new b([ i, o ], 0) ];
  5322. }
  5323. var yi = /** @class */ function() {
  5324. function t(t, e, n) {
  5325. if (this.bitmap = t, this.padding = e, this.hashCount = n, e < 0 || e >= 8) throw new gi("Invalid padding: ".concat(e));
  5326. if (n < 0) throw new gi("Invalid hash count: ".concat(n));
  5327. if (t.length > 0 && 0 === this.hashCount)
  5328. // Only empty bloom filter can have 0 hash count.
  5329. throw new gi("Invalid hash count: ".concat(n));
  5330. if (0 === t.length && 0 !== e)
  5331. // Empty bloom filter should have 0 padding.
  5332. throw new gi("Invalid padding when bitmap length is 0: ".concat(e));
  5333. this.It = 8 * t.length - e,
  5334. // Set the bit count in Integer to avoid repetition in mightContain().
  5335. this.Tt = b.fromNumber(this.It);
  5336. }
  5337. // Calculate the ith hash value based on the hashed 64bit integers,
  5338. // and calculate its corresponding bit index in the bitmap to be checked.
  5339. return t.prototype.Et = function(t, e, n) {
  5340. // Calculate hashed value h(i) = h1 + (i * h2).
  5341. var r = t.add(e.multiply(b.fromNumber(n)));
  5342. // Wrap if hash value overflow 64bit.
  5343. return 1 === r.compare(pi) && (r = new b([ r.getBits(0), r.getBits(1) ], 0)),
  5344. r.modulo(this.Tt).toNumber();
  5345. },
  5346. // Return whether the bit on the given index in the bitmap is set to 1.
  5347. t.prototype.At = function(t) {
  5348. return 0 != (this.bitmap[Math.floor(t / 8)] & 1 << t % 8);
  5349. }, t.prototype.vt = function(t) {
  5350. // Empty bitmap should always return false on membership check.
  5351. if (0 === this.It) return !1;
  5352. for (var e = mi(vi(t)), n = e[0], r = e[1], i = 0; i < this.hashCount; i++) {
  5353. var o = this.Et(n, r, i);
  5354. if (!this.At(o)) return !1;
  5355. }
  5356. return !0;
  5357. },
  5358. /** Create bloom filter for testing purposes only. */ t.create = function(e, n, r) {
  5359. var i = e % 8 == 0 ? 0 : 8 - e % 8, o = new t(new Uint8Array(Math.ceil(e / 8)), i, n);
  5360. return r.forEach((function(t) {
  5361. return o.insert(t);
  5362. })), o;
  5363. }, t.prototype.insert = function(t) {
  5364. if (0 !== this.It) for (var e = mi(vi(t)), n = e[0], r = e[1], i = 0; i < this.hashCount; i++) {
  5365. var o = this.Et(n, r, i);
  5366. this.Rt(o);
  5367. }
  5368. }, t.prototype.Rt = function(t) {
  5369. var e = Math.floor(t / 8), n = t % 8;
  5370. this.bitmap[e] |= 1 << n;
  5371. }, t;
  5372. }(), gi = /** @class */ function(e) {
  5373. function n() {
  5374. var t = this;
  5375. return (t = e.apply(this, arguments) || this).name = "BloomFilterError", t;
  5376. }
  5377. return t(n, e), n;
  5378. }(Error), wi = /** @class */ function() {
  5379. function t(
  5380. /**
  5381. * The snapshot version this event brings us up to, or MIN if not set.
  5382. */
  5383. t,
  5384. /**
  5385. * A map from target to changes to the target. See TargetChange.
  5386. */
  5387. e,
  5388. /**
  5389. * A map of targets that is known to be inconsistent, and the purpose for
  5390. * re-listening. Listens for these targets should be re-established without
  5391. * resume tokens.
  5392. */
  5393. n,
  5394. /**
  5395. * A set of which documents have changed or been deleted, along with the
  5396. * doc's new values (if not deleted).
  5397. */
  5398. r,
  5399. /**
  5400. * A set of which document updates are due only to limbo resolution targets.
  5401. */
  5402. i) {
  5403. this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = r,
  5404. this.resolvedLimboDocuments = i;
  5405. }
  5406. /**
  5407. * HACK: Views require RemoteEvents in order to determine whether the view is
  5408. * CURRENT, but secondary tabs don't receive remote events. So this method is
  5409. * used to create a synthesized RemoteEvent that can be used to apply a
  5410. * CURRENT status change to a View, for queries executed in a different tab.
  5411. */
  5412. // PORTING NOTE: Multi-tab only
  5413. return t.createSynthesizedRemoteEventForCurrentChange = function(e, n, r) {
  5414. var i = new Map;
  5415. return i.set(e, bi.createSynthesizedTargetChangeForCurrentChange(e, n, r)), new t(ct.min(), i, new Te(ot), fr(), Ir());
  5416. }, t;
  5417. }(), bi = /** @class */ function() {
  5418. function t(
  5419. /**
  5420. * An opaque, server-assigned token that allows watching a query to be resumed
  5421. * after disconnecting without retransmitting all the data that matches the
  5422. * query. The resume token essentially identifies a point in time from which
  5423. * the server should resume sending results.
  5424. */
  5425. t,
  5426. /**
  5427. * The "current" (synced) status of this target. Note that "current"
  5428. * has special meaning in the RPC protocol that implies that a target is
  5429. * both up-to-date and consistent with the rest of the watch stream.
  5430. */
  5431. e,
  5432. /**
  5433. * The set of documents that were newly assigned to this target as part of
  5434. * this remote event.
  5435. */
  5436. n,
  5437. /**
  5438. * The set of documents that were already assigned to this target but received
  5439. * an update during this remote event.
  5440. */
  5441. r,
  5442. /**
  5443. * The set of documents that were removed from this target as part of this
  5444. * remote event.
  5445. */
  5446. i) {
  5447. this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = r,
  5448. this.removedDocuments = i
  5449. /**
  5450. * This method is used to create a synthesized TargetChanges that can be used to
  5451. * apply a CURRENT status change to a View (for queries executed in a different
  5452. * tab) or for new queries (to raise snapshots with correct CURRENT status).
  5453. */;
  5454. }
  5455. return t.createSynthesizedTargetChangeForCurrentChange = function(e, n, r) {
  5456. return new t(r, n, Ir(), Ir(), Ir());
  5457. }, t;
  5458. }(), Ii = function(
  5459. /** The new document applies to all of these targets. */
  5460. t,
  5461. /** The new document is removed from all of these targets. */
  5462. e,
  5463. /** The key of the document for this change. */
  5464. n,
  5465. /**
  5466. * The new document or NoDocument if it was deleted. Is null if the
  5467. * document went out of view without the server sending a new document.
  5468. */
  5469. r) {
  5470. this.Pt = t, this.removedTargetIds = e, this.key = n, this.bt = r;
  5471. }, Ei = function(t, e) {
  5472. this.targetId = t, this.Vt = e;
  5473. }, Ti = function(
  5474. /** What kind of change occurred to the watch target. */
  5475. t,
  5476. /** The target IDs that were added/removed/set. */
  5477. e,
  5478. /**
  5479. * An opaque, server-assigned token that allows watching a target to be
  5480. * resumed after disconnecting without retransmitting all the data that
  5481. * matches the target. The resume token essentially identifies a point in
  5482. * time from which the server should resume sending results.
  5483. */
  5484. n
  5485. /** An RPC error indicating why the watch failed. */ , r) {
  5486. void 0 === n && (n = Oe.EMPTY_BYTE_STRING), void 0 === r && (r = null), this.state = t,
  5487. this.targetIds = e, this.resumeToken = n, this.cause = r;
  5488. }, Si = /** @class */ function() {
  5489. function t() {
  5490. /**
  5491. * The number of pending responses (adds or removes) that we are waiting on.
  5492. * We only consider targets active that have no pending responses.
  5493. */
  5494. this.St = 0,
  5495. /**
  5496. * Keeps track of the document changes since the last raised snapshot.
  5497. *
  5498. * These changes are continuously updated as we receive document updates and
  5499. * always reflect the current set of changes against the last issued snapshot.
  5500. */
  5501. this.Dt = Ci(),
  5502. /** See public getters for explanations of these fields. */
  5503. this.Ct = Oe.EMPTY_BYTE_STRING, this.xt = !1,
  5504. /**
  5505. * Whether this target state should be included in the next snapshot. We
  5506. * initialize to true so that newly-added targets are included in the next
  5507. * RemoteEvent.
  5508. */
  5509. this.Nt = !0;
  5510. }
  5511. return Object.defineProperty(t.prototype, "current", {
  5512. /**
  5513. * Whether this target has been marked 'current'.
  5514. *
  5515. * 'Current' has special meaning in the RPC protocol: It implies that the
  5516. * Watch backend has sent us all changes up to the point at which the target
  5517. * was added and that the target is consistent with the rest of the watch
  5518. * stream.
  5519. */
  5520. get: function() {
  5521. return this.xt;
  5522. },
  5523. enumerable: !1,
  5524. configurable: !0
  5525. }), Object.defineProperty(t.prototype, "resumeToken", {
  5526. /** The last resume token sent to us for this target. */ get: function() {
  5527. return this.Ct;
  5528. },
  5529. enumerable: !1,
  5530. configurable: !0
  5531. }), Object.defineProperty(t.prototype, "kt", {
  5532. /** Whether this target has pending target adds or target removes. */ get: function() {
  5533. return 0 !== this.St;
  5534. },
  5535. enumerable: !1,
  5536. configurable: !0
  5537. }), Object.defineProperty(t.prototype, "Mt", {
  5538. /** Whether we have modified any state that should trigger a snapshot. */ get: function() {
  5539. return this.Nt;
  5540. },
  5541. enumerable: !1,
  5542. configurable: !0
  5543. }),
  5544. /**
  5545. * Applies the resume token to the TargetChange, but only when it has a new
  5546. * value. Empty resumeTokens are discarded.
  5547. */
  5548. t.prototype.$t = function(t) {
  5549. t.approximateByteSize() > 0 && (this.Nt = !0, this.Ct = t);
  5550. },
  5551. /**
  5552. * Creates a target change from the current set of changes.
  5553. *
  5554. * To reset the document changes after raising this snapshot, call
  5555. * `clearPendingChanges()`.
  5556. */
  5557. t.prototype.Ot = function() {
  5558. var t = Ir(), e = Ir(), n = Ir();
  5559. return this.Dt.forEach((function(r, i) {
  5560. switch (i) {
  5561. case 0 /* ChangeType.Added */ :
  5562. t = t.add(r);
  5563. break;
  5564. case 2 /* ChangeType.Modified */ :
  5565. e = e.add(r);
  5566. break;
  5567. case 1 /* ChangeType.Removed */ :
  5568. n = n.add(r);
  5569. break;
  5570. default:
  5571. U();
  5572. }
  5573. })), new bi(this.Ct, this.xt, t, e, n);
  5574. },
  5575. /**
  5576. * Resets the document changes and sets `hasPendingChanges` to false.
  5577. */
  5578. t.prototype.Ft = function() {
  5579. this.Nt = !1, this.Dt = Ci();
  5580. }, t.prototype.Bt = function(t, e) {
  5581. this.Nt = !0, this.Dt = this.Dt.insert(t, e);
  5582. }, t.prototype.Lt = function(t) {
  5583. this.Nt = !0, this.Dt = this.Dt.remove(t);
  5584. }, t.prototype.qt = function() {
  5585. this.St += 1;
  5586. }, t.prototype.Ut = function() {
  5587. this.St -= 1;
  5588. }, t.prototype.Kt = function() {
  5589. this.Nt = !0, this.xt = !0;
  5590. }, t;
  5591. }(), _i = /** @class */ function() {
  5592. function t(t) {
  5593. this.Gt = t,
  5594. /** The internal state of all tracked targets. */
  5595. this.Qt = new Map,
  5596. /** Keeps track of the documents to update since the last raised snapshot. */
  5597. this.jt = fr(),
  5598. /** A mapping of document keys to their set of target IDs. */
  5599. this.zt = Di(),
  5600. /**
  5601. * A map of targets with existence filter mismatches. These targets are
  5602. * known to be inconsistent and their listens needs to be re-established by
  5603. * RemoteStore.
  5604. */
  5605. this.Wt = new Te(ot)
  5606. /**
  5607. * Processes and adds the DocumentWatchChange to the current set of changes.
  5608. */;
  5609. }
  5610. return t.prototype.Ht = function(t) {
  5611. for (var e = 0, n = t.Pt; e < n.length; e++) {
  5612. var r = n[e];
  5613. t.bt && t.bt.isFoundDocument() ? this.Jt(r, t.bt) : this.Yt(r, t.key, t.bt);
  5614. }
  5615. for (var i = 0, o = t.removedTargetIds; i < o.length; i++) {
  5616. var u = o[i];
  5617. this.Yt(u, t.key, t.bt);
  5618. }
  5619. },
  5620. /** Processes and adds the WatchTargetChange to the current set of changes. */ t.prototype.Xt = function(t) {
  5621. var e = this;
  5622. this.forEachTarget(t, (function(n) {
  5623. var r = e.Zt(n);
  5624. switch (t.state) {
  5625. case 0 /* WatchTargetChangeState.NoChange */ :
  5626. e.te(n) && r.$t(t.resumeToken);
  5627. break;
  5628. case 1 /* WatchTargetChangeState.Added */ :
  5629. // We need to decrement the number of pending acks needed from watch
  5630. // for this targetId.
  5631. r.Ut(), r.kt ||
  5632. // We have a freshly added target, so we need to reset any state
  5633. // that we had previously. This can happen e.g. when remove and add
  5634. // back a target for existence filter mismatches.
  5635. r.Ft(), r.$t(t.resumeToken);
  5636. break;
  5637. case 2 /* WatchTargetChangeState.Removed */ :
  5638. // We need to keep track of removed targets to we can post-filter and
  5639. // remove any target changes.
  5640. // We need to decrement the number of pending acks needed from watch
  5641. // for this targetId.
  5642. r.Ut(), r.kt || e.removeTarget(n);
  5643. break;
  5644. case 3 /* WatchTargetChangeState.Current */ :
  5645. e.te(n) && (r.Kt(), r.$t(t.resumeToken));
  5646. break;
  5647. case 4 /* WatchTargetChangeState.Reset */ :
  5648. e.te(n) && (
  5649. // Reset the target and synthesizes removes for all existing
  5650. // documents. The backend will re-add any documents that still
  5651. // match the target before it sends the next global snapshot.
  5652. e.ee(n), r.$t(t.resumeToken));
  5653. break;
  5654. default:
  5655. U();
  5656. }
  5657. }));
  5658. },
  5659. /**
  5660. * Iterates over all targetIds that the watch change applies to: either the
  5661. * targetIds explicitly listed in the change or the targetIds of all currently
  5662. * active targets.
  5663. */
  5664. t.prototype.forEachTarget = function(t, e) {
  5665. var n = this;
  5666. t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Qt.forEach((function(t, r) {
  5667. n.te(r) && e(r);
  5668. }));
  5669. },
  5670. /**
  5671. * Handles existence filters and synthesizes deletes for filter mismatches.
  5672. * Targets that are invalidated by filter mismatches are added to
  5673. * `pendingTargetResets`.
  5674. */
  5675. t.prototype.ne = function(t) {
  5676. var e, n = t.targetId, r = t.Vt.count, i = this.se(n);
  5677. if (i) {
  5678. var o = i.target;
  5679. if (zn(o)) if (0 === r) {
  5680. // The existence filter told us the document does not exist. We deduce
  5681. // that this document does not exist and apply a deleted document to
  5682. // our updates. Without applying this deleted document there might be
  5683. // another query that will raise this document as part of a snapshot
  5684. // until it is resolved, essentially exposing inconsistency between
  5685. // queries.
  5686. var u = new pt(o.path);
  5687. this.Yt(n, u, dn.newNoDocument(u, ct.min()));
  5688. } else z(1 === r); else {
  5689. var a = this.ie(n);
  5690. // Existence filter mismatch. Mark the documents as being in limbo, and
  5691. // raise a snapshot with `isFromCache:true`.
  5692. if (a !== r) {
  5693. // Apply bloom filter to identify and mark removed documents.
  5694. var s = this.re(t, a);
  5695. if (0 /* BloomFilterApplicationStatus.Success */ !== s) {
  5696. // If bloom filter application fails, we reset the mapping and
  5697. // trigger re-run of the query.
  5698. this.ee(n);
  5699. var c = 2 /* BloomFilterApplicationStatus.FalsePositive */ === s ? "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ : "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */;
  5700. this.Wt = this.Wt.insert(n, c);
  5701. }
  5702. null === (e = hi.instance) || void 0 === e || e.notifyOnExistenceFilterMismatch(function(t, e, n) {
  5703. var r, i, o, u, a, s, c = {
  5704. localCacheCount: e,
  5705. existenceFilterCount: n.count
  5706. }, l = n.unchangedNames;
  5707. return l && (c.bloomFilter = {
  5708. applied: 0 /* BloomFilterApplicationStatus.Success */ === t,
  5709. hashCount: null !== (r = null == l ? void 0 : l.hashCount) && void 0 !== r ? r : 0,
  5710. bitmapLength: null !== (u = null === (o = null === (i = null == l ? void 0 : l.bits) || void 0 === i ? void 0 : i.bitmap) || void 0 === o ? void 0 : o.length) && void 0 !== u ? u : 0,
  5711. padding: null !== (s = null === (a = null == l ? void 0 : l.bits) || void 0 === a ? void 0 : a.padding) && void 0 !== s ? s : 0
  5712. }), c;
  5713. }(s, a, t.Vt));
  5714. }
  5715. }
  5716. }
  5717. },
  5718. /**
  5719. * Apply bloom filter to remove the deleted documents, and return the
  5720. * application status.
  5721. */
  5722. t.prototype.re = function(t, e) {
  5723. var n = t.Vt, r = n.unchangedNames, i = n.count;
  5724. if (!r || !r.bits) return 1 /* BloomFilterApplicationStatus.Skipped */;
  5725. var o, u, a = r.bits, s = a.bitmap, c = void 0 === s ? "" : s, l = a.padding, h = void 0 === l ? 0 : l, f = r.hashCount, d = void 0 === f ? 0 : f;
  5726. try {
  5727. o = Ve(c).toUint8Array();
  5728. } catch (t) {
  5729. if (t instanceof Ae) return q("Decoding the base64 bloom filter in existence filter failed (" + t.message + "); ignoring the bloom filter and falling back to full re-query."),
  5730. 1 /* BloomFilterApplicationStatus.Skipped */;
  5731. throw t;
  5732. }
  5733. try {
  5734. // BloomFilter throws error if the inputs are invalid.
  5735. u = new yi(o, h, d);
  5736. } catch (t) {
  5737. return q(t instanceof gi ? "BloomFilter error: " : "Applying bloom filter failed: ", t),
  5738. 1 /* BloomFilterApplicationStatus.Skipped */;
  5739. }
  5740. return 0 === u.It ? 1 /* BloomFilterApplicationStatus.Skipped */ : i !== e - this.oe(t.targetId, u) ? 2 /* BloomFilterApplicationStatus.FalsePositive */ : 0 /* BloomFilterApplicationStatus.Success */;
  5741. },
  5742. /**
  5743. * Filter out removed documents based on bloom filter membership result and
  5744. * return number of documents removed.
  5745. */
  5746. t.prototype.oe = function(t, e) {
  5747. var n = this, r = this.Gt.getRemoteKeysForTarget(t), i = 0;
  5748. return r.forEach((function(r) {
  5749. var o = n.Gt.ue(), u = "projects/".concat(o.projectId, "/databases/").concat(o.database, "/documents/").concat(r.path.canonicalString());
  5750. e.vt(u) || (n.Yt(t, r, /*updatedDocument=*/ null), i++);
  5751. })), i;
  5752. },
  5753. /**
  5754. * Converts the currently accumulated state into a remote event at the
  5755. * provided snapshot version. Resets the accumulated changes before returning.
  5756. */
  5757. t.prototype.ce = function(t) {
  5758. var e = this, n = new Map;
  5759. this.Qt.forEach((function(r, i) {
  5760. var o = e.se(i);
  5761. if (o) {
  5762. if (r.current && zn(o.target)) {
  5763. // Document queries for document that don't exist can produce an empty
  5764. // result set. To update our local cache, we synthesize a document
  5765. // delete if we have not previously received the document. This
  5766. // resolves the limbo state of the document, removing it from
  5767. // limboDocumentRefs.
  5768. // TODO(dimond): Ideally we would have an explicit lookup target
  5769. // instead resulting in an explicit delete message and we could
  5770. // remove this special logic.
  5771. var u = new pt(o.target.path);
  5772. null !== e.jt.get(u) || e.ae(i, u) || e.Yt(i, u, dn.newNoDocument(u, t));
  5773. }
  5774. r.Mt && (n.set(i, r.Ot()), r.Ft());
  5775. }
  5776. }));
  5777. var r = Ir();
  5778. // We extract the set of limbo-only document updates as the GC logic
  5779. // special-cases documents that do not appear in the target cache.
  5780. // TODO(gsoltis): Expand on this comment once GC is available in the JS
  5781. // client.
  5782. this.zt.forEach((function(t, n) {
  5783. var i = !0;
  5784. n.forEachWhile((function(t) {
  5785. var n = e.se(t);
  5786. return !n || "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ === n.purpose || (i = !1,
  5787. !1);
  5788. })), i && (r = r.add(t));
  5789. })), this.jt.forEach((function(e, n) {
  5790. return n.setReadTime(t);
  5791. }));
  5792. var i = new wi(t, n, this.Wt, this.jt, r);
  5793. return this.jt = fr(), this.zt = Di(), this.Wt = new Te(ot), i;
  5794. },
  5795. /**
  5796. * Adds the provided document to the internal list of document updates and
  5797. * its document key to the given target's mapping.
  5798. */
  5799. // Visible for testing.
  5800. t.prototype.Jt = function(t, e) {
  5801. if (this.te(t)) {
  5802. var n = this.ae(t, e.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;
  5803. 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));
  5804. }
  5805. },
  5806. /**
  5807. * Removes the provided document from the target mapping. If the
  5808. * document no longer matches the target, but the document's state is still
  5809. * known (e.g. we know that the document was deleted or we received the change
  5810. * that caused the filter mismatch), the new document can be provided
  5811. * to update the remote document cache.
  5812. */
  5813. // Visible for testing.
  5814. t.prototype.Yt = function(t, e, n) {
  5815. if (this.te(t)) {
  5816. var r = this.Zt(t);
  5817. this.ae(t, e) ? r.Bt(e, 1 /* ChangeType.Removed */) :
  5818. // The document may have entered and left the target before we raised a
  5819. // snapshot, so we can just ignore the change.
  5820. r.Lt(e), this.zt = this.zt.insert(e, this.he(e).delete(t)), n && (this.jt = this.jt.insert(e, n));
  5821. }
  5822. }, t.prototype.removeTarget = function(t) {
  5823. this.Qt.delete(t);
  5824. },
  5825. /**
  5826. * Returns the current count of documents in the target. This includes both
  5827. * the number of documents that the LocalStore considers to be part of the
  5828. * target as well as any accumulated changes.
  5829. */
  5830. t.prototype.ie = function(t) {
  5831. var e = this.Zt(t).Ot();
  5832. return this.Gt.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;
  5833. },
  5834. /**
  5835. * Increment the number of acks needed from watch before we can consider the
  5836. * server to be 'in-sync' with the client's active targets.
  5837. */
  5838. t.prototype.qt = function(t) {
  5839. this.Zt(t).qt();
  5840. }, t.prototype.Zt = function(t) {
  5841. var e = this.Qt.get(t);
  5842. return e || (e = new Si, this.Qt.set(t, e)), e;
  5843. }, t.prototype.he = function(t) {
  5844. var e = this.zt.get(t);
  5845. return e || (e = new De(ot), this.zt = this.zt.insert(t, e)), e;
  5846. },
  5847. /**
  5848. * Verifies that the user is still interested in this target (by calling
  5849. * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
  5850. * from watch.
  5851. */
  5852. t.prototype.te = function(t) {
  5853. var e = null !== this.se(t);
  5854. return e || M("WatchChangeAggregator", "Detected inactive target", t), e;
  5855. },
  5856. /**
  5857. * Returns the TargetData for an active target (i.e. a target that the user
  5858. * is still interested in that has no outstanding target change requests).
  5859. */
  5860. t.prototype.se = function(t) {
  5861. var e = this.Qt.get(t);
  5862. return e && e.kt ? null : this.Gt.le(t);
  5863. },
  5864. /**
  5865. * Resets the state of a Watch target to its initial state (e.g. sets
  5866. * 'current' to false, clears the resume token and removes its target mapping
  5867. * from all documents).
  5868. */
  5869. t.prototype.ee = function(t) {
  5870. var e = this;
  5871. this.Qt.set(t, new Si), this.Gt.getRemoteKeysForTarget(t).forEach((function(n) {
  5872. e.Yt(t, n, /*updatedDocument=*/ null);
  5873. }));
  5874. },
  5875. /**
  5876. * Returns whether the LocalStore considers the document to be part of the
  5877. * specified target.
  5878. */
  5879. t.prototype.ae = function(t, e) {
  5880. return this.Gt.getRemoteKeysForTarget(t).has(e);
  5881. }, t;
  5882. }();
  5883. function Di() {
  5884. return new Te(pt.comparator);
  5885. }
  5886. function Ci() {
  5887. return new Te(pt.comparator);
  5888. }
  5889. var xi = {
  5890. asc: "ASCENDING",
  5891. desc: "DESCENDING"
  5892. }, Ni = {
  5893. "<": "LESS_THAN",
  5894. "<=": "LESS_THAN_OR_EQUAL",
  5895. ">": "GREATER_THAN",
  5896. ">=": "GREATER_THAN_OR_EQUAL",
  5897. "==": "EQUAL",
  5898. "!=": "NOT_EQUAL",
  5899. "array-contains": "ARRAY_CONTAINS",
  5900. in: "IN",
  5901. "not-in": "NOT_IN",
  5902. "array-contains-any": "ARRAY_CONTAINS_ANY"
  5903. }, Ai = {
  5904. and: "AND",
  5905. or: "OR"
  5906. }, ki = function(t, e) {
  5907. this.databaseId = t, this.useProto3Json = e;
  5908. };
  5909. /**
  5910. * This class generates JsonObject values for the Datastore API suitable for
  5911. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  5912. *
  5913. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  5914. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  5915. * format.
  5916. *
  5917. * For a description of the Proto3 JSON format check
  5918. * https://developers.google.com/protocol-buffers/docs/proto3#json
  5919. *
  5920. * TODO(klimt): We can remove the databaseId argument if we keep the full
  5921. * resource name in documents.
  5922. */
  5923. /**
  5924. * Returns a value for a number (or null) that's appropriate to put into
  5925. * a google.protobuf.Int32Value proto.
  5926. * DO NOT USE THIS FOR ANYTHING ELSE.
  5927. * This method cheats. It's typed as returning "number" because that's what
  5928. * our generated proto interfaces say Int32Value must be. But GRPC actually
  5929. * expects a { value: <number> } struct.
  5930. */
  5931. function Oi(t, e) {
  5932. return t.useProto3Json || zt(e) ? e : {
  5933. value: e
  5934. };
  5935. }
  5936. /**
  5937. * Returns a number (or null) from a google.protobuf.Int32Value proto.
  5938. */
  5939. /**
  5940. * Returns a value for a Date that's appropriate to put into a proto.
  5941. */ function Fi(t, e) {
  5942. return t.useProto3Json ? "".concat(new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", ""), ".").concat(("000000000" + e.nanoseconds).slice(-9), "Z") : {
  5943. seconds: "" + e.seconds,
  5944. nanos: e.nanoseconds
  5945. };
  5946. }
  5947. /**
  5948. * Returns a value for bytes that's appropriate to put in a proto.
  5949. *
  5950. * Visible for testing.
  5951. */ function Pi(t, e) {
  5952. return t.useProto3Json ? e.toBase64() : e.toUint8Array();
  5953. }
  5954. /**
  5955. * Returns a ByteString based on the proto string value.
  5956. */ function Ri(t, e) {
  5957. return Fi(t, e.toTimestamp());
  5958. }
  5959. function Vi(t) {
  5960. return z(!!t), ct.fromTimestamp(function(t) {
  5961. var e = Pe(t);
  5962. return new st(e.seconds, e.nanos);
  5963. }(t));
  5964. }
  5965. function Mi(t, e) {
  5966. return function(t) {
  5967. return new ht([ "projects", t.projectId, "databases", t.database ]);
  5968. }(t).child("documents").child(e).canonicalString();
  5969. }
  5970. function Li(t) {
  5971. var e = ht.fromString(t);
  5972. return z(uo(e)), e;
  5973. }
  5974. function qi(t, e) {
  5975. return Mi(t.databaseId, e.path);
  5976. }
  5977. function Bi(t, e) {
  5978. var n = Li(e);
  5979. if (n.get(1) !== t.databaseId.projectId) throw new Q(K.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.databaseId.projectId);
  5980. if (n.get(3) !== t.databaseId.database) throw new Q(K.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.databaseId.database);
  5981. return new pt(ji(n));
  5982. }
  5983. function Ui(t, e) {
  5984. return Mi(t.databaseId, e);
  5985. }
  5986. function zi(t) {
  5987. var e = Li(t);
  5988. // In v1beta1 queries for collections at the root did not have a trailing
  5989. // "/documents". In v1 all resource paths contain "/documents". Preserve the
  5990. // ability to read the v1beta1 form for compatibility with queries persisted
  5991. // in the local target cache.
  5992. return 4 === e.length ? ht.emptyPath() : ji(e);
  5993. }
  5994. function Gi(t) {
  5995. return new ht([ "projects", t.databaseId.projectId, "databases", t.databaseId.database ]).canonicalString();
  5996. }
  5997. function ji(t) {
  5998. return z(t.length > 4 && "documents" === t.get(4)), t.popFirst(5)
  5999. /** Creates a Document proto from key and fields (but no create/update time) */;
  6000. }
  6001. function Ki(t, e, n) {
  6002. return {
  6003. name: qi(t, e),
  6004. fields: n.value.mapValue.fields
  6005. };
  6006. }
  6007. function Qi(t, e, n) {
  6008. var r = Bi(t, e.name), i = Vi(e.updateTime), o = e.createTime ? Vi(e.createTime) : ct.min(), u = new hn({
  6009. mapValue: {
  6010. fields: e.fields
  6011. }
  6012. }), a = dn.newFoundDocument(r, i, o, u);
  6013. return n && a.setHasCommittedMutations(), n ? a.setHasCommittedMutations() : a;
  6014. }
  6015. function Wi(t, e) {
  6016. var n;
  6017. if (e instanceof Yr) n = {
  6018. update: Ki(t, e.key, e.value)
  6019. }; else if (e instanceof ni) n = {
  6020. delete: qi(t, e.key)
  6021. }; else if (e instanceof Xr) n = {
  6022. update: Ki(t, e.key, e.data),
  6023. updateMask: oo(e.fieldMask)
  6024. }; else {
  6025. if (!(e instanceof ri)) return U();
  6026. n = {
  6027. verify: qi(t, e.key)
  6028. };
  6029. }
  6030. return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((function(t) {
  6031. return function(t, e) {
  6032. var n = e.transform;
  6033. if (n instanceof kr) return {
  6034. fieldPath: e.field.canonicalString(),
  6035. setToServerValue: "REQUEST_TIME"
  6036. };
  6037. if (n instanceof Or) return {
  6038. fieldPath: e.field.canonicalString(),
  6039. appendMissingElements: {
  6040. values: n.elements
  6041. }
  6042. };
  6043. if (n instanceof Pr) return {
  6044. fieldPath: e.field.canonicalString(),
  6045. removeAllFromArray: {
  6046. values: n.elements
  6047. }
  6048. };
  6049. if (n instanceof Vr) return {
  6050. fieldPath: e.field.canonicalString(),
  6051. increment: n.gt
  6052. };
  6053. throw U();
  6054. }(0, t);
  6055. }))), e.precondition.isNone || (n.currentDocument = function(t, e) {
  6056. return void 0 !== e.updateTime ? {
  6057. updateTime: Ri(t, e.updateTime)
  6058. } : void 0 !== e.exists ? {
  6059. exists: e.exists
  6060. } : U();
  6061. }(t, e.precondition)), n;
  6062. }
  6063. function Hi(t, e) {
  6064. var n = e.currentDocument ? function(t) {
  6065. return void 0 !== t.updateTime ? Ur.updateTime(Vi(t.updateTime)) : void 0 !== t.exists ? Ur.exists(t.exists) : Ur.none();
  6066. }(e.currentDocument) : Ur.none(), r = e.updateTransforms ? e.updateTransforms.map((function(e) {
  6067. return function(t, e) {
  6068. var n = null;
  6069. if ("setToServerValue" in e) z("REQUEST_TIME" === e.setToServerValue), n = new kr; else if ("appendMissingElements" in e) {
  6070. var r = e.appendMissingElements.values || [];
  6071. n = new Or(r);
  6072. } else if ("removeAllFromArray" in e) {
  6073. var i = e.removeAllFromArray.values || [];
  6074. n = new Pr(i);
  6075. } else "increment" in e ? n = new Vr(t, e.increment) : U();
  6076. var o = dt.fromServerFormat(e.fieldPath);
  6077. return new qr(o, n);
  6078. }(t, e);
  6079. })) : [];
  6080. if (e.update) {
  6081. e.update.name;
  6082. var i = Bi(t, e.update.name), o = new hn({
  6083. mapValue: {
  6084. fields: e.update.fields
  6085. }
  6086. });
  6087. if (e.updateMask) {
  6088. var u = function(t) {
  6089. var e = t.fieldPaths || [];
  6090. return new Ne(e.map((function(t) {
  6091. return dt.fromServerFormat(t);
  6092. })));
  6093. }(e.updateMask);
  6094. return new Xr(i, o, u, n, r);
  6095. }
  6096. return new Yr(i, o, n, r);
  6097. }
  6098. if (e.delete) {
  6099. var a = Bi(t, e.delete);
  6100. return new ni(a, n);
  6101. }
  6102. if (e.verify) {
  6103. var s = Bi(t, e.verify);
  6104. return new ri(s, n);
  6105. }
  6106. return U();
  6107. }
  6108. function Yi(t, e) {
  6109. return {
  6110. documents: [ Ui(t, e.path) ]
  6111. };
  6112. }
  6113. function Xi(t, e) {
  6114. // Dissect the path into parent, collectionId, and optional key filter.
  6115. var n = {
  6116. structuredQuery: {}
  6117. }, r = e.path;
  6118. null !== e.collectionGroup ? (n.parent = Ui(t, r), n.structuredQuery.from = [ {
  6119. collectionId: e.collectionGroup,
  6120. allDescendants: !0
  6121. } ]) : (n.parent = Ui(t, r.popLast()), n.structuredQuery.from = [ {
  6122. collectionId: r.lastSegment()
  6123. } ]);
  6124. var i = function(t) {
  6125. if (0 !== t.length) return io(In.create(t, "and" /* CompositeOperator.AND */));
  6126. }(e.filters);
  6127. i && (n.structuredQuery.where = i);
  6128. var o = function(t) {
  6129. if (0 !== t.length) return t.map((function(t) {
  6130. // visible for testing
  6131. return function(t) {
  6132. return {
  6133. field: no(t.field),
  6134. direction: $i(t.dir)
  6135. };
  6136. }(t);
  6137. }));
  6138. }(e.orderBy);
  6139. o && (n.structuredQuery.orderBy = o);
  6140. var u, a = Oi(t, e.limit);
  6141. return null !== a && (n.structuredQuery.limit = a), e.startAt && (n.structuredQuery.startAt = {
  6142. before: (u = e.startAt).inclusive,
  6143. values: u.position
  6144. }), e.endAt && (n.structuredQuery.endAt = function(t) {
  6145. return {
  6146. before: !t.inclusive,
  6147. values: t.position
  6148. };
  6149. }(e.endAt)), n;
  6150. }
  6151. function Ji(t) {
  6152. var e = zi(t.parent), n = t.structuredQuery, r = n.from ? n.from.length : 0, i = null;
  6153. if (r > 0) {
  6154. z(1 === r);
  6155. var o = n.from[0];
  6156. o.allDescendants ? i = o.collectionId : e = e.child(o.collectionId);
  6157. }
  6158. var u = [];
  6159. n.where && (u = function(t) {
  6160. var e = Zi(t);
  6161. return e instanceof In && Sn(e) ? e.getFilters() : [ e ];
  6162. }(n.where));
  6163. var a = [];
  6164. n.orderBy && (a = n.orderBy.map((function(t) {
  6165. return function(t) {
  6166. return new yn(ro(t.field),
  6167. // visible for testing
  6168. function(t) {
  6169. switch (t) {
  6170. case "ASCENDING":
  6171. return "asc" /* Direction.ASCENDING */;
  6172. case "DESCENDING":
  6173. return "desc" /* Direction.DESCENDING */;
  6174. default:
  6175. return;
  6176. }
  6177. }(t.direction));
  6178. }(t);
  6179. })));
  6180. var s = null;
  6181. n.limit && (s = function(t) {
  6182. var e;
  6183. return zt(e = "object" == typeof t ? t.value : t) ? null : e;
  6184. }(n.limit));
  6185. var c = null;
  6186. n.startAt && (c = function(t) {
  6187. var e = !!t.before, n = t.values || [];
  6188. return new pn(n, e);
  6189. }(n.startAt));
  6190. var l = null;
  6191. return n.endAt && (l = function(t) {
  6192. var e = !t.before, n = t.values || [];
  6193. return new pn(n, e);
  6194. }(n.endAt)), Wn(e, i, a, u, s, "F" /* LimitType.First */ , c, l);
  6195. }
  6196. function Zi(t) {
  6197. return void 0 !== t.unaryFilter ? function(t) {
  6198. switch (t.unaryFilter.op) {
  6199. case "IS_NAN":
  6200. var e = ro(t.unaryFilter.field);
  6201. return bn.create(e, "==" /* Operator.EQUAL */ , {
  6202. doubleValue: NaN
  6203. });
  6204. case "IS_NULL":
  6205. var n = ro(t.unaryFilter.field);
  6206. return bn.create(n, "==" /* Operator.EQUAL */ , {
  6207. nullValue: "NULL_VALUE"
  6208. });
  6209. case "IS_NOT_NAN":
  6210. var r = ro(t.unaryFilter.field);
  6211. return bn.create(r, "!=" /* Operator.NOT_EQUAL */ , {
  6212. doubleValue: NaN
  6213. });
  6214. case "IS_NOT_NULL":
  6215. var i = ro(t.unaryFilter.field);
  6216. return bn.create(i, "!=" /* Operator.NOT_EQUAL */ , {
  6217. nullValue: "NULL_VALUE"
  6218. });
  6219. default:
  6220. return U();
  6221. }
  6222. }(t) : void 0 !== t.fieldFilter ? function(t) {
  6223. return bn.create(ro(t.fieldFilter.field), function(t) {
  6224. switch (t) {
  6225. case "EQUAL":
  6226. return "==" /* Operator.EQUAL */;
  6227. case "NOT_EQUAL":
  6228. return "!=" /* Operator.NOT_EQUAL */;
  6229. case "GREATER_THAN":
  6230. return ">" /* Operator.GREATER_THAN */;
  6231. case "GREATER_THAN_OR_EQUAL":
  6232. return ">=" /* Operator.GREATER_THAN_OR_EQUAL */;
  6233. case "LESS_THAN":
  6234. return "<" /* Operator.LESS_THAN */;
  6235. case "LESS_THAN_OR_EQUAL":
  6236. return "<=" /* Operator.LESS_THAN_OR_EQUAL */;
  6237. case "ARRAY_CONTAINS":
  6238. return "array-contains" /* Operator.ARRAY_CONTAINS */;
  6239. case "IN":
  6240. return "in" /* Operator.IN */;
  6241. case "NOT_IN":
  6242. return "not-in" /* Operator.NOT_IN */;
  6243. case "ARRAY_CONTAINS_ANY":
  6244. return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */;
  6245. default:
  6246. return U();
  6247. }
  6248. }(t.fieldFilter.op), t.fieldFilter.value);
  6249. }(t) : void 0 !== t.compositeFilter ? function(t) {
  6250. return In.create(t.compositeFilter.filters.map((function(t) {
  6251. return Zi(t);
  6252. })), function(t) {
  6253. switch (t) {
  6254. case "AND":
  6255. return "and" /* CompositeOperator.AND */;
  6256. case "OR":
  6257. return "or" /* CompositeOperator.OR */;
  6258. default:
  6259. return U();
  6260. }
  6261. }(t.compositeFilter.op));
  6262. }(t) : U();
  6263. }
  6264. function $i(t) {
  6265. return xi[t];
  6266. }
  6267. function to(t) {
  6268. return Ni[t];
  6269. }
  6270. function eo(t) {
  6271. return Ai[t];
  6272. }
  6273. function no(t) {
  6274. return {
  6275. fieldPath: t.canonicalString()
  6276. };
  6277. }
  6278. function ro(t) {
  6279. return dt.fromServerFormat(t.fieldPath);
  6280. }
  6281. function io(t) {
  6282. return t instanceof bn ? function(t) {
  6283. if ("==" /* Operator.EQUAL */ === t.op) {
  6284. if (nn(t.value)) return {
  6285. unaryFilter: {
  6286. field: no(t.field),
  6287. op: "IS_NAN"
  6288. }
  6289. };
  6290. if (en(t.value)) return {
  6291. unaryFilter: {
  6292. field: no(t.field),
  6293. op: "IS_NULL"
  6294. }
  6295. };
  6296. } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) {
  6297. if (nn(t.value)) return {
  6298. unaryFilter: {
  6299. field: no(t.field),
  6300. op: "IS_NOT_NAN"
  6301. }
  6302. };
  6303. if (en(t.value)) return {
  6304. unaryFilter: {
  6305. field: no(t.field),
  6306. op: "IS_NOT_NULL"
  6307. }
  6308. };
  6309. }
  6310. return {
  6311. fieldFilter: {
  6312. field: no(t.field),
  6313. op: to(t.op),
  6314. value: t.value
  6315. }
  6316. };
  6317. }(t) : t instanceof In ? function(t) {
  6318. var e = t.getFilters().map((function(t) {
  6319. return io(t);
  6320. }));
  6321. return 1 === e.length ? e[0] : {
  6322. compositeFilter: {
  6323. op: eo(t.op),
  6324. filters: e
  6325. }
  6326. };
  6327. }(t) : U();
  6328. }
  6329. function oo(t) {
  6330. var e = [];
  6331. return t.fields.forEach((function(t) {
  6332. return e.push(t.canonicalString());
  6333. })), {
  6334. fieldPaths: e
  6335. };
  6336. }
  6337. function uo(t) {
  6338. // Resource names have at least 4 components (project ID, database ID)
  6339. return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2);
  6340. }
  6341. /**
  6342. * @license
  6343. * Copyright 2017 Google LLC
  6344. *
  6345. * Licensed under the Apache License, Version 2.0 (the "License");
  6346. * you may not use this file except in compliance with the License.
  6347. * You may obtain a copy of the License at
  6348. *
  6349. * http://www.apache.org/licenses/LICENSE-2.0
  6350. *
  6351. * Unless required by applicable law or agreed to in writing, software
  6352. * distributed under the License is distributed on an "AS IS" BASIS,
  6353. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6354. * See the License for the specific language governing permissions and
  6355. * limitations under the License.
  6356. */
  6357. /**
  6358. * An immutable set of metadata that the local store tracks for each target.
  6359. */ var ao = /** @class */ function() {
  6360. function t(
  6361. /** The target being listened to. */
  6362. t,
  6363. /**
  6364. * The target ID to which the target corresponds; Assigned by the
  6365. * LocalStore for user listens and by the SyncEngine for limbo watches.
  6366. */
  6367. e,
  6368. /** The purpose of the target. */
  6369. n,
  6370. /**
  6371. * The sequence number of the last transaction during which this target data
  6372. * was modified.
  6373. */
  6374. r,
  6375. /** The latest snapshot version seen for this target. */
  6376. i
  6377. /**
  6378. * The maximum snapshot version at which the associated view
  6379. * contained no limbo documents.
  6380. */ , o
  6381. /**
  6382. * An opaque, server-assigned token that allows watching a target to be
  6383. * resumed after disconnecting without retransmitting all the data that
  6384. * matches the target. The resume token essentially identifies a point in
  6385. * time from which the server should resume sending results.
  6386. */ , u
  6387. /**
  6388. * The number of documents that last matched the query at the resume token or
  6389. * read time. Documents are counted only when making a listen request with
  6390. * resume token or read time, otherwise, keep it null.
  6391. */ , a) {
  6392. void 0 === i && (i = ct.min()), void 0 === o && (o = ct.min()), void 0 === u && (u = Oe.EMPTY_BYTE_STRING),
  6393. void 0 === a && (a = null), this.target = t, this.targetId = e, this.purpose = n,
  6394. this.sequenceNumber = r, this.snapshotVersion = i, this.lastLimboFreeSnapshotVersion = o,
  6395. this.resumeToken = u, this.expectedCount = a;
  6396. }
  6397. /** Creates a new target data instance with an updated sequence number. */ return t.prototype.withSequenceNumber = function(e) {
  6398. return new t(this.target, this.targetId, this.purpose, e, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount);
  6399. },
  6400. /**
  6401. * Creates a new target data instance with an updated resume token and
  6402. * snapshot version.
  6403. */
  6404. t.prototype.withResumeToken = function(e, n) {
  6405. return new t(this.target, this.targetId, this.purpose, this.sequenceNumber, n, this.lastLimboFreeSnapshotVersion, e,
  6406. /* expectedCount= */ null);
  6407. },
  6408. /**
  6409. * Creates a new target data instance with an updated expected count.
  6410. */
  6411. t.prototype.withExpectedCount = function(e) {
  6412. return new t(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, e);
  6413. },
  6414. /**
  6415. * Creates a new target data instance with an updated last limbo free
  6416. * snapshot version number.
  6417. */
  6418. t.prototype.withLastLimboFreeSnapshotVersion = function(e) {
  6419. return new t(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, e, this.resumeToken, this.expectedCount);
  6420. }, t;
  6421. }(), so = function(t) {
  6422. this.fe = t;
  6423. };
  6424. /**
  6425. * @license
  6426. * Copyright 2017 Google LLC
  6427. *
  6428. * Licensed under the Apache License, Version 2.0 (the "License");
  6429. * you may not use this file except in compliance with the License.
  6430. * You may obtain a copy of the License at
  6431. *
  6432. * http://www.apache.org/licenses/LICENSE-2.0
  6433. *
  6434. * Unless required by applicable law or agreed to in writing, software
  6435. * distributed under the License is distributed on an "AS IS" BASIS,
  6436. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6437. * See the License for the specific language governing permissions and
  6438. * limitations under the License.
  6439. */
  6440. /** Serializer for values stored in the LocalStore. */
  6441. /** Encodes a document for storage locally. */ function co(t, e) {
  6442. var n = e.key, r = {
  6443. prefixPath: n.getCollectionPath().popLast().toArray(),
  6444. collectionGroup: n.collectionGroup,
  6445. documentId: n.path.lastSegment(),
  6446. readTime: lo(e.readTime),
  6447. hasCommittedMutations: e.hasCommittedMutations
  6448. };
  6449. if (e.isFoundDocument()) r.document = function(t, e) {
  6450. return {
  6451. name: qi(t, e.key),
  6452. fields: e.data.value.mapValue.fields,
  6453. updateTime: Fi(t, e.version.toTimestamp()),
  6454. createTime: Fi(t, e.createTime.toTimestamp())
  6455. };
  6456. }(t.fe, e); else if (e.isNoDocument()) r.noDocument = {
  6457. path: n.path.toArray(),
  6458. readTime: ho(e.version)
  6459. }; else {
  6460. if (!e.isUnknownDocument()) return U();
  6461. r.unknownDocument = {
  6462. path: n.path.toArray(),
  6463. version: ho(e.version)
  6464. };
  6465. }
  6466. return r;
  6467. }
  6468. function lo(t) {
  6469. var e = t.toTimestamp();
  6470. return [ e.seconds, e.nanoseconds ];
  6471. }
  6472. function ho(t) {
  6473. var e = t.toTimestamp();
  6474. return {
  6475. seconds: e.seconds,
  6476. nanoseconds: e.nanoseconds
  6477. };
  6478. }
  6479. function fo(t) {
  6480. var e = new st(t.seconds, t.nanoseconds);
  6481. return ct.fromTimestamp(e);
  6482. }
  6483. /** Encodes a batch of mutations into a DbMutationBatch for local storage. */
  6484. /** Decodes a DbMutationBatch into a MutationBatch */ function po(t, e) {
  6485. // Squash old transform mutations into existing patch or set mutations.
  6486. // The replacement of representing `transforms` with `update_transforms`
  6487. // on the SDK means that old `transform` mutations stored in IndexedDB need
  6488. // to be updated to `update_transforms`.
  6489. // TODO(b/174608374): Remove this code once we perform a schema migration.
  6490. for (var n = (e.baseMutations || []).map((function(e) {
  6491. return Hi(t.fe, e);
  6492. })), r = 0; r < e.mutations.length - 1; ++r) {
  6493. var i = e.mutations[r];
  6494. if (r + 1 < e.mutations.length && void 0 !== e.mutations[r + 1].transform) {
  6495. var o = e.mutations[r + 1];
  6496. i.updateTransforms = o.transform.fieldTransforms, e.mutations.splice(r + 1, 1),
  6497. ++r;
  6498. }
  6499. }
  6500. var u = e.mutations.map((function(e) {
  6501. return Hi(t.fe, e);
  6502. })), a = st.fromMillis(e.localWriteTimeMs);
  6503. return new ii(e.batchId, a, n, u);
  6504. }
  6505. /** Decodes a DbTarget into TargetData */ function vo(t) {
  6506. var e, n, r = fo(t.readTime), i = void 0 !== t.lastLimboFreeSnapshotVersion ? fo(t.lastLimboFreeSnapshotVersion) : ct.min();
  6507. return void 0 !== t.query.documents ? (z(1 === (n = t.query).documents.length),
  6508. e = tr(Hn(zi(n.documents[0])))) : e = function(t) {
  6509. return tr(Ji(t));
  6510. }(t.query), new ao(e, t.targetId, "TargetPurposeListen" /* TargetPurpose.Listen */ , t.lastListenSequenceNumber, r, i, Oe.fromBase64String(t.resumeToken))
  6511. /** Encodes TargetData into a DbTarget for storage locally. */;
  6512. }
  6513. function mo(t, e) {
  6514. var n, r = ho(e.snapshotVersion), i = ho(e.lastLimboFreeSnapshotVersion);
  6515. n = zn(e.target) ? Yi(t.fe, e.target) : Xi(t.fe, e.target);
  6516. // We can't store the resumeToken as a ByteString in IndexedDb, so we
  6517. // convert it to a base64 string for storage.
  6518. var o = e.resumeToken.toBase64();
  6519. // lastListenSequenceNumber is always 0 until we do real GC.
  6520. return {
  6521. targetId: e.targetId,
  6522. canonicalId: Bn(e.target),
  6523. readTime: r,
  6524. resumeToken: o,
  6525. lastListenSequenceNumber: e.sequenceNumber,
  6526. lastLimboFreeSnapshotVersion: i,
  6527. query: n
  6528. };
  6529. }
  6530. /**
  6531. * A helper function for figuring out what kind of query has been stored.
  6532. */
  6533. /**
  6534. * Encodes a `BundledQuery` from bundle proto to a Query object.
  6535. *
  6536. * This reconstructs the original query used to build the bundle being loaded,
  6537. * including features exists only in SDKs (for example: limit-to-last).
  6538. */ function yo(t) {
  6539. var e = Ji({
  6540. parent: t.parent,
  6541. structuredQuery: t.structuredQuery
  6542. });
  6543. return "LAST" === t.limitType ? nr(e, e.limit, "L" /* LimitType.Last */) : e;
  6544. }
  6545. /** Encodes a NamedQuery proto object to a NamedQuery model object. */
  6546. /** Encodes a DbDocumentOverlay object to an Overlay model object. */ function go(t, e) {
  6547. return new ui(e.largestBatchId, Hi(t.fe, e.overlayMutation));
  6548. }
  6549. /** Decodes an Overlay model object into a DbDocumentOverlay object. */
  6550. /**
  6551. * Returns the DbDocumentOverlayKey corresponding to the given user and
  6552. * document key.
  6553. */ function wo(t, e) {
  6554. var n = e.path.lastSegment();
  6555. return [ t, Kt(e.path.popLast()), n ];
  6556. }
  6557. function bo(t, e, n, r) {
  6558. return {
  6559. indexId: t,
  6560. uid: e.uid || "",
  6561. sequenceNumber: n,
  6562. readTime: ho(r.readTime),
  6563. documentKey: Kt(r.documentKey.path),
  6564. largestBatchId: r.largestBatchId
  6565. };
  6566. }
  6567. /**
  6568. * @license
  6569. * Copyright 2020 Google LLC
  6570. *
  6571. * Licensed under the Apache License, Version 2.0 (the "License");
  6572. * you may not use this file except in compliance with the License.
  6573. * You may obtain a copy of the License at
  6574. *
  6575. * http://www.apache.org/licenses/LICENSE-2.0
  6576. *
  6577. * Unless required by applicable law or agreed to in writing, software
  6578. * distributed under the License is distributed on an "AS IS" BASIS,
  6579. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6580. * See the License for the specific language governing permissions and
  6581. * limitations under the License.
  6582. */ var Io = /** @class */ function() {
  6583. function t() {}
  6584. return t.prototype.getBundleMetadata = function(t, e) {
  6585. return Eo(t).get(e).next((function(t) {
  6586. if (t) return {
  6587. id: (e = t).bundleId,
  6588. createTime: fo(e.createTime),
  6589. version: e.version
  6590. };
  6591. /** Encodes a DbBundle to a BundleMetadata object. */ var e;
  6592. /** Encodes a BundleMetadata to a DbBundle. */ }));
  6593. }, t.prototype.saveBundleMetadata = function(t, e) {
  6594. return Eo(t).put({
  6595. bundleId: (n = e).id,
  6596. createTime: ho(Vi(n.createTime)),
  6597. version: n.version
  6598. });
  6599. var n;
  6600. /** Encodes a DbNamedQuery to a NamedQuery. */ }, t.prototype.getNamedQuery = function(t, e) {
  6601. return To(t).get(e).next((function(t) {
  6602. if (t) return {
  6603. name: (e = t).name,
  6604. query: yo(e.bundledQuery),
  6605. readTime: fo(e.readTime)
  6606. };
  6607. var e;
  6608. /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ }));
  6609. }, t.prototype.saveNamedQuery = function(t, e) {
  6610. return To(t).put(function(t) {
  6611. return {
  6612. name: t.name,
  6613. readTime: ho(Vi(t.readTime)),
  6614. bundledQuery: t.bundledQuery
  6615. };
  6616. }(e));
  6617. }, t;
  6618. }();
  6619. /**
  6620. * Helper to get a typed SimpleDbStore for the bundles object store.
  6621. */ function Eo(t) {
  6622. return we(t, "bundles");
  6623. }
  6624. /**
  6625. * Helper to get a typed SimpleDbStore for the namedQueries object store.
  6626. */ function To(t) {
  6627. return we(t, "namedQueries");
  6628. }
  6629. /**
  6630. * @license
  6631. * Copyright 2022 Google LLC
  6632. *
  6633. * Licensed under the Apache License, Version 2.0 (the "License");
  6634. * you may not use this file except in compliance with the License.
  6635. * You may obtain a copy of the License at
  6636. *
  6637. * http://www.apache.org/licenses/LICENSE-2.0
  6638. *
  6639. * Unless required by applicable law or agreed to in writing, software
  6640. * distributed under the License is distributed on an "AS IS" BASIS,
  6641. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6642. * See the License for the specific language governing permissions and
  6643. * limitations under the License.
  6644. */
  6645. /**
  6646. * Implementation of DocumentOverlayCache using IndexedDb.
  6647. */ var So = /** @class */ function() {
  6648. /**
  6649. * @param serializer - The document serializer.
  6650. * @param userId - The userId for which we are accessing overlays.
  6651. */
  6652. function t(t, e) {
  6653. this.serializer = t, this.userId = e;
  6654. }
  6655. return t.de = function(e, n) {
  6656. return new t(e, n.uid || "");
  6657. }, t.prototype.getOverlay = function(t, e) {
  6658. var n = this;
  6659. return _o(t).get(wo(this.userId, e)).next((function(t) {
  6660. return t ? go(n.serializer, t) : null;
  6661. }));
  6662. }, t.prototype.getOverlays = function(t, e) {
  6663. var n = this, r = mr();
  6664. return Nt.forEach(e, (function(e) {
  6665. return n.getOverlay(t, e).next((function(t) {
  6666. null !== t && r.set(e, t);
  6667. }));
  6668. })).next((function() {
  6669. return r;
  6670. }));
  6671. }, t.prototype.saveOverlays = function(t, e, n) {
  6672. var r = this, i = [];
  6673. return n.forEach((function(n, o) {
  6674. var u = new ui(e, o);
  6675. i.push(r.we(t, u));
  6676. })), Nt.waitFor(i);
  6677. }, t.prototype.removeOverlaysForBatchId = function(t, e, n) {
  6678. var r = this, i = new Set;
  6679. // Get the set of unique collection paths.
  6680. e.forEach((function(t) {
  6681. return i.add(Kt(t.getCollectionPath()));
  6682. }));
  6683. var o = [];
  6684. return i.forEach((function(e) {
  6685. var i = IDBKeyRange.bound([ r.userId, e, n ], [ r.userId, e, n + 1 ],
  6686. /*lowerOpen=*/ !1,
  6687. /*upperOpen=*/ !0);
  6688. o.push(_o(t).J("collectionPathOverlayIndex", i));
  6689. })), Nt.waitFor(o);
  6690. }, t.prototype.getOverlaysForCollection = function(t, e, n) {
  6691. var r = this, i = mr(), o = Kt(e), u = IDBKeyRange.bound([ this.userId, o, n ], [ this.userId, o, Number.POSITIVE_INFINITY ],
  6692. /*lowerOpen=*/ !0);
  6693. return _o(t).j("collectionPathOverlayIndex", u).next((function(t) {
  6694. for (var e = 0, n = t; e < n.length; e++) {
  6695. var o = n[e], u = go(r.serializer, o);
  6696. i.set(u.getKey(), u);
  6697. }
  6698. return i;
  6699. }));
  6700. }, t.prototype.getOverlaysForCollectionGroup = function(t, e, n, r) {
  6701. var i, o = this, u = mr(), a = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, Number.POSITIVE_INFINITY ],
  6702. /*lowerOpen=*/ !0);
  6703. return _o(t).X({
  6704. index: "collectionGroupOverlayIndex",
  6705. range: a
  6706. }, (function(t, e, n) {
  6707. // We do not want to return partial batch overlays, even if the size
  6708. // of the result set exceeds the given `count` argument. Therefore, we
  6709. // continue to aggregate results even after the result size exceeds
  6710. // `count` if there are more overlays from the `currentBatchId`.
  6711. var a = go(o.serializer, e);
  6712. u.size() < r || a.largestBatchId === i ? (u.set(a.getKey(), a), i = a.largestBatchId) : n.done();
  6713. })).next((function() {
  6714. return u;
  6715. }));
  6716. }, t.prototype.we = function(t, e) {
  6717. return _o(t).put(function(t, e, n) {
  6718. var r = wo(e, n.mutation.key);
  6719. return r[0], {
  6720. userId: e,
  6721. collectionPath: r[1],
  6722. documentId: r[2],
  6723. collectionGroup: n.mutation.key.getCollectionGroup(),
  6724. largestBatchId: n.largestBatchId,
  6725. overlayMutation: Wi(t.fe, n.mutation)
  6726. };
  6727. }(this.serializer, this.userId, e));
  6728. }, t;
  6729. }();
  6730. /**
  6731. * Helper to get a typed SimpleDbStore for the document overlay object store.
  6732. */ function _o(t) {
  6733. return we(t, "documentOverlays");
  6734. }
  6735. /**
  6736. * @license
  6737. * Copyright 2021 Google LLC
  6738. *
  6739. * Licensed under the Apache License, Version 2.0 (the "License");
  6740. * you may not use this file except in compliance with the License.
  6741. * You may obtain a copy of the License at
  6742. *
  6743. * http://www.apache.org/licenses/LICENSE-2.0
  6744. *
  6745. * Unless required by applicable law or agreed to in writing, software
  6746. * distributed under the License is distributed on an "AS IS" BASIS,
  6747. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6748. * See the License for the specific language governing permissions and
  6749. * limitations under the License.
  6750. */
  6751. // Note: This code is copied from the backend. Code that is not used by
  6752. // Firestore was removed.
  6753. /** Firestore index value writer. */ var Do = /** @class */ function() {
  6754. function t() {}
  6755. // The write methods below short-circuit writing terminators for values
  6756. // containing a (terminating) truncated value.
  6757. // As an example, consider the resulting encoding for:
  6758. // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM)
  6759. // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC)
  6760. // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC)
  6761. /** Writes an index value. */ return t.prototype._e = function(t, e) {
  6762. this.me(t, e),
  6763. // Write separator to split index values
  6764. // (see go/firestore-storage-format#encodings).
  6765. e.ge();
  6766. }, t.prototype.me = function(t, e) {
  6767. if ("nullValue" in t) this.ye(e, 5); else if ("booleanValue" in t) this.ye(e, 10),
  6768. e.pe(t.booleanValue ? 1 : 0); else if ("integerValue" in t) this.ye(e, 15), e.pe(Re(t.integerValue)); else if ("doubleValue" in t) {
  6769. var n = Re(t.doubleValue);
  6770. isNaN(n) ? this.ye(e, 13) : (this.ye(e, 15), Gt(n) ?
  6771. // -0.0, 0 and 0.0 are all considered the same
  6772. e.pe(0) : e.pe(n));
  6773. } else if ("timestampValue" in t) {
  6774. var r = t.timestampValue;
  6775. this.ye(e, 20), "string" == typeof r ? e.Ie(r) : (e.Ie("".concat(r.seconds || "")),
  6776. e.pe(r.nanos || 0));
  6777. } else if ("stringValue" in t) this.Te(t.stringValue, e), this.Ee(e); else if ("bytesValue" in t) this.ye(e, 30),
  6778. e.Ae(Ve(t.bytesValue)), this.Ee(e); else if ("referenceValue" in t) this.ve(t.referenceValue, e); else if ("geoPointValue" in t) {
  6779. var i = t.geoPointValue;
  6780. this.ye(e, 45), e.pe(i.latitude || 0), e.pe(i.longitude || 0);
  6781. } else "mapValue" in t ? un(t) ? this.ye(e, Number.MAX_SAFE_INTEGER) : (this.Re(t.mapValue, e),
  6782. this.Ee(e)) : "arrayValue" in t ? (this.Pe(t.arrayValue, e), this.Ee(e)) : U();
  6783. }, t.prototype.Te = function(t, e) {
  6784. this.ye(e, 25), this.be(t, e);
  6785. }, t.prototype.be = function(t, e) {
  6786. e.Ie(t);
  6787. }, t.prototype.Re = function(t, e) {
  6788. var n = t.fields || {};
  6789. this.ye(e, 55);
  6790. for (var r = 0, i = Object.keys(n); r < i.length; r++) {
  6791. var o = i[r];
  6792. this.Te(o, e), this.me(n[o], e);
  6793. }
  6794. }, t.prototype.Pe = function(t, e) {
  6795. var n = t.values || [];
  6796. this.ye(e, 50);
  6797. for (var r = 0, i = n; r < i.length; r++) {
  6798. var o = i[r];
  6799. this.me(o, e);
  6800. }
  6801. }, t.prototype.ve = function(t, e) {
  6802. var n = this;
  6803. this.ye(e, 37), pt.fromName(t).path.forEach((function(t) {
  6804. n.ye(e, 60), n.be(t, e);
  6805. }));
  6806. }, t.prototype.ye = function(t, e) {
  6807. t.pe(e);
  6808. }, t.prototype.Ee = function(t) {
  6809. // While the SDK does not implement truncation, the truncation marker is
  6810. // used to terminate all variable length values (which are strings, bytes,
  6811. // references, arrays and maps).
  6812. t.pe(2);
  6813. }, t;
  6814. }();
  6815. /**
  6816. * Counts the number of zeros in a byte.
  6817. *
  6818. * Visible for testing.
  6819. */
  6820. function Co(t) {
  6821. if (0 === t) return 8;
  6822. var e = 0;
  6823. return t >> 4 == 0 && (
  6824. // Test if the first four bits are zero.
  6825. e += 4, t <<= 4), t >> 6 == 0 && (
  6826. // Test if the first two (or next two) bits are zero.
  6827. e += 2, t <<= 2), t >> 7 == 0 && (
  6828. // Test if the remaining bit is zero.
  6829. e += 1), e
  6830. /** Counts the number of leading zeros in the given byte array. */
  6831. /**
  6832. * Returns the number of bytes required to store "value". Leading zero bytes
  6833. * are skipped.
  6834. */;
  6835. }
  6836. function xo(t) {
  6837. // This is just the number of bytes for the unsigned representation of the number.
  6838. var e = 64 - function(t) {
  6839. for (var e = 0, n = 0; n < 8; ++n) {
  6840. var r = Co(255 & t[n]);
  6841. if (e += r, 8 !== r) break;
  6842. }
  6843. return e;
  6844. }(t);
  6845. return Math.ceil(e / 8);
  6846. }
  6847. /**
  6848. * OrderedCodeWriter is a minimal-allocation implementation of the writing
  6849. * behavior defined by the backend.
  6850. *
  6851. * The code is ported from its Java counterpart.
  6852. */ Do.Ve = new Do;
  6853. var No = /** @class */ function() {
  6854. function t() {
  6855. this.buffer = new Uint8Array(1024), this.position = 0;
  6856. }
  6857. return t.prototype.Se = function(t) {
  6858. for (var e = t[Symbol.iterator](), n = e.next(); !n.done; ) this.De(n.value), n = e.next();
  6859. this.Ce();
  6860. }, t.prototype.xe = function(t) {
  6861. for (var e = t[Symbol.iterator](), n = e.next(); !n.done; ) this.Ne(n.value), n = e.next();
  6862. this.ke();
  6863. },
  6864. /** Writes utf8 bytes into this byte sequence, ascending. */ t.prototype.Me = function(t) {
  6865. for (var e = 0, n = t; e < n.length; e++) {
  6866. var r = n[e], i = r.charCodeAt(0);
  6867. if (i < 128) this.De(i); else if (i < 2048) this.De(960 | i >>> 6), this.De(128 | 63 & i); else if (r < "\ud800" || "\udbff" < r) this.De(480 | i >>> 12),
  6868. this.De(128 | 63 & i >>> 6), this.De(128 | 63 & i); else {
  6869. var o = r.codePointAt(0);
  6870. this.De(240 | o >>> 18), this.De(128 | 63 & o >>> 12), this.De(128 | 63 & o >>> 6),
  6871. this.De(128 | 63 & o);
  6872. }
  6873. }
  6874. this.Ce();
  6875. },
  6876. /** Writes utf8 bytes into this byte sequence, descending */ t.prototype.$e = function(t) {
  6877. for (var e = 0, n = t; e < n.length; e++) {
  6878. var r = n[e], i = r.charCodeAt(0);
  6879. if (i < 128) this.Ne(i); else if (i < 2048) this.Ne(960 | i >>> 6), this.Ne(128 | 63 & i); else if (r < "\ud800" || "\udbff" < r) this.Ne(480 | i >>> 12),
  6880. this.Ne(128 | 63 & i >>> 6), this.Ne(128 | 63 & i); else {
  6881. var o = r.codePointAt(0);
  6882. this.Ne(240 | o >>> 18), this.Ne(128 | 63 & o >>> 12), this.Ne(128 | 63 & o >>> 6),
  6883. this.Ne(128 | 63 & o);
  6884. }
  6885. }
  6886. this.ke();
  6887. }, t.prototype.Oe = function(t) {
  6888. // Values are encoded with a single byte length prefix, followed by the
  6889. // actual value in big-endian format with leading 0 bytes dropped.
  6890. var e = this.Fe(t), n = xo(e);
  6891. this.Be(1 + n), this.buffer[this.position++] = 255 & n;
  6892. // Write the length
  6893. for (var r = e.length - n; r < e.length; ++r) this.buffer[this.position++] = 255 & e[r];
  6894. }, t.prototype.Le = function(t) {
  6895. // Values are encoded with a single byte length prefix, followed by the
  6896. // inverted value in big-endian format with leading 0 bytes dropped.
  6897. var e = this.Fe(t), n = xo(e);
  6898. this.Be(1 + n), this.buffer[this.position++] = ~(255 & n);
  6899. // Write the length
  6900. for (var r = e.length - n; r < e.length; ++r) this.buffer[this.position++] = ~(255 & e[r]);
  6901. },
  6902. /**
  6903. * Writes the "infinity" byte sequence that sorts after all other byte
  6904. * sequences written in ascending order.
  6905. */
  6906. t.prototype.qe = function() {
  6907. this.Ue(255), this.Ue(255);
  6908. },
  6909. /**
  6910. * Writes the "infinity" byte sequence that sorts before all other byte
  6911. * sequences written in descending order.
  6912. */
  6913. t.prototype.Ke = function() {
  6914. this.Ge(255), this.Ge(255);
  6915. },
  6916. /**
  6917. * Resets the buffer such that it is the same as when it was newly
  6918. * constructed.
  6919. */
  6920. t.prototype.reset = function() {
  6921. this.position = 0;
  6922. }, t.prototype.seed = function(t) {
  6923. this.Be(t.length), this.buffer.set(t, this.position), this.position += t.length;
  6924. },
  6925. /** Makes a copy of the encoded bytes in this buffer. */ t.prototype.Qe = function() {
  6926. return this.buffer.slice(0, this.position);
  6927. },
  6928. /**
  6929. * Encodes `val` into an encoding so that the order matches the IEEE 754
  6930. * floating-point comparison results with the following exceptions:
  6931. * -0.0 < 0.0
  6932. * all non-NaN < NaN
  6933. * NaN = NaN
  6934. */
  6935. t.prototype.Fe = function(t) {
  6936. var e =
  6937. /** Converts a JavaScript number to a byte array (using big endian encoding). */
  6938. function(t) {
  6939. var e = new DataView(new ArrayBuffer(8));
  6940. return e.setFloat64(0, t, /* littleEndian= */ !1), new Uint8Array(e.buffer);
  6941. }(t), n = 0 != (128 & e[0]);
  6942. // Check if the first bit is set. We use a bit mask since value[0] is
  6943. // encoded as a number from 0 to 255.
  6944. // Revert the two complement to get natural ordering
  6945. e[0] ^= n ? 255 : 128;
  6946. for (var r = 1; r < e.length; ++r) e[r] ^= n ? 255 : 0;
  6947. return e;
  6948. },
  6949. /** Writes a single byte ascending to the buffer. */ t.prototype.De = function(t) {
  6950. var e = 255 & t;
  6951. 0 === e ? (this.Ue(0), this.Ue(255)) : 255 === e ? (this.Ue(255), this.Ue(0)) : this.Ue(e);
  6952. },
  6953. /** Writes a single byte descending to the buffer. */ t.prototype.Ne = function(t) {
  6954. var e = 255 & t;
  6955. 0 === e ? (this.Ge(0), this.Ge(255)) : 255 === e ? (this.Ge(255), this.Ge(0)) : this.Ge(t);
  6956. }, t.prototype.Ce = function() {
  6957. this.Ue(0), this.Ue(1);
  6958. }, t.prototype.ke = function() {
  6959. this.Ge(0), this.Ge(1);
  6960. }, t.prototype.Ue = function(t) {
  6961. this.Be(1), this.buffer[this.position++] = t;
  6962. }, t.prototype.Ge = function(t) {
  6963. this.Be(1), this.buffer[this.position++] = ~t;
  6964. }, t.prototype.Be = function(t) {
  6965. var e = t + this.position;
  6966. if (!(e <= this.buffer.length)) {
  6967. // Try doubling.
  6968. var n = 2 * this.buffer.length;
  6969. // Still not big enough? Just allocate the right size.
  6970. n < e && (n = e);
  6971. // Create the new buffer.
  6972. var r = new Uint8Array(n);
  6973. r.set(this.buffer), // copy old data
  6974. this.buffer = r;
  6975. }
  6976. }, t;
  6977. }(), Ao = /** @class */ function() {
  6978. function t(t) {
  6979. this.je = t;
  6980. }
  6981. return t.prototype.Ae = function(t) {
  6982. this.je.Se(t);
  6983. }, t.prototype.Ie = function(t) {
  6984. this.je.Me(t);
  6985. }, t.prototype.pe = function(t) {
  6986. this.je.Oe(t);
  6987. }, t.prototype.ge = function() {
  6988. this.je.qe();
  6989. }, t;
  6990. }(), ko = /** @class */ function() {
  6991. function t(t) {
  6992. this.je = t;
  6993. }
  6994. return t.prototype.Ae = function(t) {
  6995. this.je.xe(t);
  6996. }, t.prototype.Ie = function(t) {
  6997. this.je.$e(t);
  6998. }, t.prototype.pe = function(t) {
  6999. this.je.Le(t);
  7000. }, t.prototype.ge = function() {
  7001. this.je.Ke();
  7002. }, t;
  7003. }(), Oo = /** @class */ function() {
  7004. function t() {
  7005. this.je = new No, this.ze = new Ao(this.je), this.We = new ko(this.je);
  7006. }
  7007. return t.prototype.seed = function(t) {
  7008. this.je.seed(t);
  7009. }, t.prototype.He = function(t) {
  7010. return 0 /* IndexKind.ASCENDING */ === t ? this.ze : this.We;
  7011. }, t.prototype.Qe = function() {
  7012. return this.je.Qe();
  7013. }, t.prototype.reset = function() {
  7014. this.je.reset();
  7015. }, t;
  7016. }(), Fo = /** @class */ function() {
  7017. function t(t, e, n, r) {
  7018. this.indexId = t, this.documentKey = e, this.arrayValue = n, this.directionalValue = r
  7019. /**
  7020. * Returns an IndexEntry entry that sorts immediately after the current
  7021. * directional value.
  7022. */;
  7023. }
  7024. return t.prototype.Je = function() {
  7025. var e = this.directionalValue.length, n = 0 === e || 255 === this.directionalValue[e - 1] ? e + 1 : e, r = new Uint8Array(n);
  7026. return r.set(this.directionalValue, 0), n !== e ? r.set([ 0 ], this.directionalValue.length) : ++r[r.length - 1],
  7027. new t(this.indexId, this.documentKey, this.arrayValue, r);
  7028. }, t;
  7029. }();
  7030. function Po(t, e) {
  7031. var n = t.indexId - e.indexId;
  7032. return 0 !== n ? n : 0 !== (n = Ro(t.arrayValue, e.arrayValue)) ? n : 0 !== (n = Ro(t.directionalValue, e.directionalValue)) ? n : pt.comparator(t.documentKey, e.documentKey);
  7033. }
  7034. function Ro(t, e) {
  7035. for (var n = 0; n < t.length && n < e.length; ++n) {
  7036. var r = t[n] - e[n];
  7037. if (0 !== r) return r;
  7038. }
  7039. return t.length - e.length;
  7040. }
  7041. /**
  7042. * @license
  7043. * Copyright 2022 Google LLC
  7044. *
  7045. * Licensed under the Apache License, Version 2.0 (the "License");
  7046. * you may not use this file except in compliance with the License.
  7047. * You may obtain a copy of the License at
  7048. *
  7049. * http://www.apache.org/licenses/LICENSE-2.0
  7050. *
  7051. * Unless required by applicable law or agreed to in writing, software
  7052. * distributed under the License is distributed on an "AS IS" BASIS,
  7053. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7054. * See the License for the specific language governing permissions and
  7055. * limitations under the License.
  7056. */
  7057. /**
  7058. * A light query planner for Firestore.
  7059. *
  7060. * This class matches a `FieldIndex` against a Firestore Query `Target`. It
  7061. * determines whether a given index can be used to serve the specified target.
  7062. *
  7063. * The following table showcases some possible index configurations:
  7064. *
  7065. * Query | Index
  7066. * -----------------------------------------------------------------------------
  7067. * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC
  7068. * where('a', '==', 'a').where('b', '==', 'b') | a ASC
  7069. * where('a', '==', 'a').where('b', '==', 'b') | b DESC
  7070. * where('a', '>=', 'a').orderBy('a') | a ASC
  7071. * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC
  7072. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC
  7073. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC
  7074. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING
  7075. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS
  7076. */ var Vo = /** @class */ function() {
  7077. function t(t) {
  7078. this.collectionId = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(),
  7079. this.Ye = t.orderBy, this.Xe = [];
  7080. for (var e = 0, n = t.filters; e < n.length; e++) {
  7081. var r = n[e];
  7082. r.isInequality() ? this.Ze = r : this.Xe.push(r);
  7083. }
  7084. }
  7085. /**
  7086. * Returns whether the index can be used to serve the TargetIndexMatcher's
  7087. * target.
  7088. *
  7089. * An index is considered capable of serving the target when:
  7090. * - The target uses all index segments for its filters and orderBy clauses.
  7091. * The target can have additional filter and orderBy clauses, but not
  7092. * fewer.
  7093. * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also
  7094. * have a corresponding `CONTAINS` segment.
  7095. * - All directional index segments can be mapped to the target as a series of
  7096. * equality filters, a single inequality filter and a series of orderBy
  7097. * clauses.
  7098. * - The segments that represent the equality filters may appear out of order.
  7099. * - The optional segment for the inequality filter must appear after all
  7100. * equality segments.
  7101. * - The segments that represent that orderBy clause of the target must appear
  7102. * in order after all equality and inequality segments. Single orderBy
  7103. * clauses cannot be skipped, but a continuous orderBy suffix may be
  7104. * omitted.
  7105. */ return t.prototype.tn = function(t) {
  7106. z(t.collectionGroup === this.collectionId);
  7107. // If there is an array element, find a matching filter.
  7108. var e = mt(t);
  7109. if (void 0 !== e && !this.en(e)) return !1;
  7110. // Process all equalities first. Equalities can appear out of order.
  7111. for (var n = yt(t), r = new Set, i = 0, o = 0; i < n.length && this.en(n[i]); ++i) r = r.add(n[i].fieldPath.canonicalString());
  7112. // If we already have processed all segments, all segments are used to serve
  7113. // the equality filters and we do not need to map any segments to the
  7114. // target's inequality and orderBy clauses.
  7115. if (i === n.length) return !0;
  7116. if (void 0 !== this.Ze) {
  7117. // If there is an inequality filter and the field was not in one of the
  7118. // equality filters above, the next segment must match both the filter
  7119. // and the first orderBy clause.
  7120. if (!r.has(this.Ze.field.canonicalString())) {
  7121. var u = n[i];
  7122. if (!this.nn(this.Ze, u) || !this.sn(this.Ye[o++], u)) return !1;
  7123. }
  7124. ++i;
  7125. }
  7126. // All remaining segments need to represent the prefix of the target's
  7127. // orderBy.
  7128. for (;i < n.length; ++i) {
  7129. var a = n[i];
  7130. if (o >= this.Ye.length || !this.sn(this.Ye[o++], a)) return !1;
  7131. }
  7132. return !0;
  7133. }, t.prototype.en = function(t) {
  7134. for (var e = 0, n = this.Xe; e < n.length; e++) {
  7135. var r = n[e];
  7136. if (this.nn(r, t)) return !0;
  7137. }
  7138. return !1;
  7139. }, t.prototype.nn = function(t, e) {
  7140. if (void 0 === t || !t.field.isEqual(e.fieldPath)) return !1;
  7141. var n = "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op;
  7142. return 2 /* IndexKind.CONTAINS */ === e.kind === n;
  7143. }, t.prototype.sn = function(t, e) {
  7144. 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);
  7145. }, t;
  7146. }();
  7147. /**
  7148. * @license
  7149. * Copyright 2022 Google LLC
  7150. *
  7151. * Licensed under the Apache License, Version 2.0 (the "License");
  7152. * you may not use this file except in compliance with the License.
  7153. * You may obtain a copy of the License at
  7154. *
  7155. * http://www.apache.org/licenses/LICENSE-2.0
  7156. *
  7157. * Unless required by applicable law or agreed to in writing, software
  7158. * distributed under the License is distributed on an "AS IS" BASIS,
  7159. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7160. * See the License for the specific language governing permissions and
  7161. * limitations under the License.
  7162. */
  7163. /**
  7164. * Provides utility functions that help with boolean logic transformations needed for handling
  7165. * complex filters used in queries.
  7166. */
  7167. /**
  7168. * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in
  7169. * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given
  7170. * input into a disjunction of equality filters and returns the expanded filter.
  7171. */ function Mo(t) {
  7172. var e, n;
  7173. if (z(t instanceof bn || t instanceof In), t instanceof bn) {
  7174. if (t instanceof Rn) {
  7175. var r = (null === (n = null === (e = t.value.arrayValue) || void 0 === e ? void 0 : e.values) || void 0 === n ? void 0 : n.map((function(e) {
  7176. return bn.create(t.field, "==" /* Operator.EQUAL */ , e);
  7177. }))) || [];
  7178. return In.create(r, "or" /* CompositeOperator.OR */);
  7179. }
  7180. // We have reached other kinds of field filters.
  7181. return t;
  7182. }
  7183. // We have a composite filter.
  7184. var i = t.filters.map((function(t) {
  7185. return Mo(t);
  7186. }));
  7187. return In.create(i, t.op);
  7188. }
  7189. /**
  7190. * Given a composite filter, returns the list of terms in its disjunctive normal form.
  7191. *
  7192. * <p>Each element in the return value is one term of the resulting DNF. For instance: For the
  7193. * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list
  7194. * with two elements: a composite filter that performs (A && C), and a composite filter that
  7195. * performs (B && C).
  7196. *
  7197. * @param filter the composite filter to calculate DNF transform for.
  7198. * @return the terms in the DNF transform.
  7199. */ function Lo(t) {
  7200. if (0 === t.getFilters().length) return [];
  7201. var e = zo(Mo(t));
  7202. return z(Uo(e)), qo(e) || Bo(e) ? [ e ] : e.getFilters()
  7203. /** Returns true if the given filter is a single field filter. e.g. (a == 10). */;
  7204. }
  7205. function qo(t) {
  7206. return t instanceof bn;
  7207. }
  7208. /**
  7209. * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10
  7210. * && b == 20)
  7211. */ function Bo(t) {
  7212. return t instanceof In && Sn(t);
  7213. }
  7214. /**
  7215. * Returns whether or not the given filter is in disjunctive normal form (DNF).
  7216. *
  7217. * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical
  7218. * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.
  7219. *
  7220. * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form
  7221. */ function Uo(t) {
  7222. return qo(t) || Bo(t) ||
  7223. /**
  7224. * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and
  7225. * field filters. e.g. (a == 10) || (b==20 && c==30)
  7226. */
  7227. function(t) {
  7228. if (t instanceof In && Tn(t)) {
  7229. for (var e = 0, n = t.getFilters(); e < n.length; e++) {
  7230. var r = n[e];
  7231. if (!qo(r) && !Bo(r)) return !1;
  7232. }
  7233. return !0;
  7234. }
  7235. return !1;
  7236. }(t);
  7237. }
  7238. function zo(t) {
  7239. if (z(t instanceof bn || t instanceof In), t instanceof bn) return t;
  7240. if (1 === t.filters.length) return zo(t.filters[0]);
  7241. // Compute DNF for each of the subfilters first
  7242. var e = t.filters.map((function(t) {
  7243. return zo(t);
  7244. })), n = In.create(e, t.op);
  7245. return Uo(n = Ko(n)) ? n : (z(n instanceof In), z(En(n)), z(n.filters.length > 1),
  7246. n.filters.reduce((function(t, e) {
  7247. return Go(t, e);
  7248. })));
  7249. }
  7250. function Go(t, e) {
  7251. var n;
  7252. return z(t instanceof bn || t instanceof In), z(e instanceof bn || e instanceof In),
  7253. // FieldFilter FieldFilter
  7254. n = t instanceof bn ? e instanceof bn ? function(t, e) {
  7255. // Conjunction distribution for two field filters is the conjunction of them.
  7256. return In.create([ t, e ], "and" /* CompositeOperator.AND */);
  7257. }(t, e) : jo(t, e) : e instanceof bn ? jo(e, t) : function(t, e) {
  7258. // There are four cases:
  7259. // (A & B) & (C & D) --> (A & B & C & D)
  7260. // (A & B) & (C | D) --> (A & B & C) | (A & B & D)
  7261. // (A | B) & (C & D) --> (C & D & A) | (C & D & B)
  7262. // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)
  7263. // Case 1 is a merge.
  7264. if (z(t.filters.length > 0 && e.filters.length > 0), En(t) && En(e)) return xn(t, e.getFilters());
  7265. // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases
  7266. // we should take each element of the disjunction and distribute it over the other side, and
  7267. // return the disjunction of the distribution results.
  7268. var n = Tn(t) ? t : e, r = Tn(t) ? e : t, i = n.filters.map((function(t) {
  7269. return Go(t, r);
  7270. }));
  7271. return In.create(i, "or" /* CompositeOperator.OR */);
  7272. }(t, e), Ko(n);
  7273. }
  7274. function jo(t, e) {
  7275. // There are two cases:
  7276. // A & (B & C) --> (A & B & C)
  7277. // A & (B | C) --> (A & B) | (A & C)
  7278. if (En(e))
  7279. // Case 1
  7280. return xn(e, t.getFilters());
  7281. // Case 2
  7282. var n = e.filters.map((function(e) {
  7283. return Go(t, e);
  7284. }));
  7285. return In.create(n, "or" /* CompositeOperator.OR */);
  7286. }
  7287. /**
  7288. * Applies the associativity property to the given filter and returns the resulting filter.
  7289. *
  7290. * <ul>
  7291. * <li>A | (B | C) == (A | B) | C == (A | B | C)
  7292. * <li>A & (B & C) == (A & B) & C == (A & B & C)
  7293. * </ul>
  7294. *
  7295. * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic
  7296. */ function Ko(t) {
  7297. if (z(t instanceof bn || t instanceof In), t instanceof bn) return t;
  7298. var e = t.getFilters();
  7299. // If the composite filter only contains 1 filter, apply associativity to it.
  7300. if (1 === e.length) return Ko(e[0]);
  7301. // Associativity applied to a flat composite filter results is itself.
  7302. if (_n(t)) return t;
  7303. // First apply associativity to all subfilters. This will in turn recursively apply
  7304. // associativity to all nested composite filters and field filters.
  7305. var n = e.map((function(t) {
  7306. return Ko(t);
  7307. })), r = [];
  7308. // For composite subfilters that perform the same kind of logical operation as `compositeFilter`
  7309. // take out their filters and add them to `compositeFilter`. For example:
  7310. // compositeFilter = (A | (B | C | D))
  7311. // compositeSubfilter = (B | C | D)
  7312. // Result: (A | B | C | D)
  7313. // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been
  7314. // added to the top-level "compositeFilter".
  7315. return n.forEach((function(e) {
  7316. e instanceof bn ? r.push(e) : e instanceof In && (e.op === t.op ?
  7317. // compositeFilter: (A | (B | C))
  7318. // compositeSubfilter: (B | C)
  7319. // Result: (A | B | C)
  7320. r.push.apply(
  7321. // compositeFilter: (A | (B | C))
  7322. // compositeSubfilter: (B | C)
  7323. // Result: (A | B | C)
  7324. r, e.filters) :
  7325. // compositeFilter: (A | (B & C))
  7326. // compositeSubfilter: (B & C)
  7327. // Result: (A | (B & C))
  7328. r.push(e));
  7329. })), 1 === r.length ? r[0] : In.create(r, t.op)
  7330. /**
  7331. * @license
  7332. * Copyright 2019 Google LLC
  7333. *
  7334. * Licensed under the Apache License, Version 2.0 (the "License");
  7335. * you may not use this file except in compliance with the License.
  7336. * You may obtain a copy of the License at
  7337. *
  7338. * http://www.apache.org/licenses/LICENSE-2.0
  7339. *
  7340. * Unless required by applicable law or agreed to in writing, software
  7341. * distributed under the License is distributed on an "AS IS" BASIS,
  7342. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7343. * See the License for the specific language governing permissions and
  7344. * limitations under the License.
  7345. */
  7346. /**
  7347. * An in-memory implementation of IndexManager.
  7348. */;
  7349. }
  7350. var Qo = /** @class */ function() {
  7351. function t() {
  7352. this.rn = new Wo;
  7353. }
  7354. return t.prototype.addToCollectionParentIndex = function(t, e) {
  7355. return this.rn.add(e), Nt.resolve();
  7356. }, t.prototype.getCollectionParents = function(t, e) {
  7357. return Nt.resolve(this.rn.getEntries(e));
  7358. }, t.prototype.addFieldIndex = function(t, e) {
  7359. // Field indices are not supported with memory persistence.
  7360. return Nt.resolve();
  7361. }, t.prototype.deleteFieldIndex = function(t, e) {
  7362. // Field indices are not supported with memory persistence.
  7363. return Nt.resolve();
  7364. }, t.prototype.getDocumentsMatchingTarget = function(t, e) {
  7365. // Field indices are not supported with memory persistence.
  7366. return Nt.resolve(null);
  7367. }, t.prototype.getIndexType = function(t, e) {
  7368. // Field indices are not supported with memory persistence.
  7369. return Nt.resolve(0 /* IndexType.NONE */);
  7370. }, t.prototype.getFieldIndexes = function(t, e) {
  7371. // Field indices are not supported with memory persistence.
  7372. return Nt.resolve([]);
  7373. }, t.prototype.getNextCollectionGroupToUpdate = function(t) {
  7374. // Field indices are not supported with memory persistence.
  7375. return Nt.resolve(null);
  7376. }, t.prototype.getMinOffset = function(t, e) {
  7377. return Nt.resolve(St.min());
  7378. }, t.prototype.getMinOffsetFromCollectionGroup = function(t, e) {
  7379. return Nt.resolve(St.min());
  7380. }, t.prototype.updateCollectionGroup = function(t, e, n) {
  7381. // Field indices are not supported with memory persistence.
  7382. return Nt.resolve();
  7383. }, t.prototype.updateIndexEntries = function(t, e) {
  7384. // Field indices are not supported with memory persistence.
  7385. return Nt.resolve();
  7386. }, t;
  7387. }(), Wo = /** @class */ function() {
  7388. function t() {
  7389. this.index = {};
  7390. }
  7391. // Returns false if the entry already existed.
  7392. return t.prototype.add = function(t) {
  7393. var e = t.lastSegment(), n = t.popLast(), r = this.index[e] || new De(ht.comparator), i = !r.has(n);
  7394. return this.index[e] = r.add(n), i;
  7395. }, t.prototype.has = function(t) {
  7396. var e = t.lastSegment(), n = t.popLast(), r = this.index[e];
  7397. return r && r.has(n);
  7398. }, t.prototype.getEntries = function(t) {
  7399. return (this.index[t] || new De(ht.comparator)).toArray();
  7400. }, t;
  7401. }(), Ho = new Uint8Array(0), Yo = /** @class */ function() {
  7402. function t(t, e) {
  7403. this.user = t, this.databaseId = e,
  7404. /**
  7405. * An in-memory copy of the index entries we've already written since the SDK
  7406. * launched. Used to avoid re-writing the same entry repeatedly.
  7407. *
  7408. * This is *NOT* a complete cache of what's in persistence and so can never be
  7409. * used to satisfy reads.
  7410. */
  7411. this.on = new Wo,
  7412. /**
  7413. * Maps from a target to its equivalent list of sub-targets. Each sub-target
  7414. * contains only one term from the target's disjunctive normal form (DNF).
  7415. */
  7416. this.un = new lr((function(t) {
  7417. return Bn(t);
  7418. }), (function(t, e) {
  7419. return Un(t, e);
  7420. })), this.uid = t.uid || ""
  7421. /**
  7422. * Adds a new entry to the collection parent index.
  7423. *
  7424. * Repeated calls for the same collectionPath should be avoided within a
  7425. * transaction as IndexedDbIndexManager only caches writes once a transaction
  7426. * has been committed.
  7427. */;
  7428. }
  7429. return t.prototype.addToCollectionParentIndex = function(t, e) {
  7430. var n = this;
  7431. if (!this.on.has(e)) {
  7432. var r = e.lastSegment(), i = e.popLast();
  7433. t.addOnCommittedListener((function() {
  7434. // Add the collection to the in memory cache only if the transaction was
  7435. // successfully committed.
  7436. n.on.add(e);
  7437. }));
  7438. var o = {
  7439. collectionId: r,
  7440. parent: Kt(i)
  7441. };
  7442. return Xo(t).put(o);
  7443. }
  7444. return Nt.resolve();
  7445. }, t.prototype.getCollectionParents = function(t, e) {
  7446. var n = [], r = IDBKeyRange.bound([ e, "" ], [ at(e), "" ],
  7447. /*lowerOpen=*/ !1,
  7448. /*upperOpen=*/ !0);
  7449. return Xo(t).j(r).next((function(t) {
  7450. for (var r = 0, i = t; r < i.length; r++) {
  7451. var o = i[r];
  7452. // This collectionId guard shouldn't be necessary (and isn't as long
  7453. // as we're running in a real browser), but there's a bug in
  7454. // indexeddbshim that breaks our range in our tests running in node:
  7455. // https://github.com/axemclion/IndexedDBShim/issues/334
  7456. if (o.collectionId !== e) break;
  7457. n.push(Ht(o.parent));
  7458. }
  7459. return n;
  7460. }));
  7461. }, t.prototype.addFieldIndex = function(t, e) {
  7462. var n = this, r = Zo(t), i = function(t) {
  7463. return {
  7464. indexId: t.indexId,
  7465. collectionGroup: t.collectionGroup,
  7466. fields: t.fields.map((function(t) {
  7467. return [ t.fieldPath.canonicalString(), t.kind ];
  7468. }))
  7469. };
  7470. }(e);
  7471. // TODO(indexing): Verify that the auto-incrementing index ID works in
  7472. // Safari & Firefox.
  7473. delete i.indexId;
  7474. // `indexId` is auto-populated by IndexedDb
  7475. var o = r.add(i);
  7476. if (e.indexState) {
  7477. var u = $o(t);
  7478. return o.next((function(t) {
  7479. u.put(bo(t, n.user, e.indexState.sequenceNumber, e.indexState.offset));
  7480. }));
  7481. }
  7482. return o.next();
  7483. }, t.prototype.deleteFieldIndex = function(t, e) {
  7484. var n = Zo(t), r = $o(t), i = Jo(t);
  7485. return n.delete(e.indexId).next((function() {
  7486. return r.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7487. /*lowerOpen=*/ !1,
  7488. /*upperOpen=*/ !0));
  7489. })).next((function() {
  7490. return i.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7491. /*lowerOpen=*/ !1,
  7492. /*upperOpen=*/ !0));
  7493. }));
  7494. }, t.prototype.getDocumentsMatchingTarget = function(t, e) {
  7495. var n = this, r = Jo(t), i = !0, o = new Map;
  7496. return Nt.forEach(this.cn(e), (function(e) {
  7497. return n.an(t, e).next((function(t) {
  7498. i && (i = !!t), o.set(e, t);
  7499. }));
  7500. })).next((function() {
  7501. if (i) {
  7502. var t = Ir(), u = [];
  7503. return Nt.forEach(o, (function(i, o) {
  7504. var a;
  7505. M("IndexedDbIndexManager", "Using index ".concat((a = i, "id=".concat(a.indexId, "|cg=").concat(a.collectionGroup, "|f=").concat(a.fields.map((function(t) {
  7506. return "".concat(t.fieldPath, ":").concat(t.kind);
  7507. })).join(","))), " to execute ").concat(Bn(e)));
  7508. var s = function(t, e) {
  7509. var n = mt(e);
  7510. if (void 0 === n) return null;
  7511. for (var r = 0, i = Gn(t, n.fieldPath); r < i.length; r++) {
  7512. var o = i[r];
  7513. switch (o.op) {
  7514. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  7515. return o.value.arrayValue.values || [];
  7516. case "array-contains" /* Operator.ARRAY_CONTAINS */ :
  7517. return [ o.value ];
  7518. // Remaining filters are not array filters.
  7519. }
  7520. }
  7521. return null;
  7522. }(o, i), c = function(t, e) {
  7523. for (var n = new Map, r = 0, i = yt(e); r < i.length; r++) for (var o = i[r], u = 0, a = Gn(t, o.fieldPath); u < a.length; u++) {
  7524. var s = a[u];
  7525. switch (s.op) {
  7526. case "==" /* Operator.EQUAL */ :
  7527. case "in" /* Operator.IN */ :
  7528. // Encode equality prefix, which is encoded in the index value before
  7529. // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
  7530. // `value != 'ab'`).
  7531. n.set(o.fieldPath.canonicalString(), s.value);
  7532. break;
  7533. case "not-in" /* Operator.NOT_IN */ :
  7534. case "!=" /* Operator.NOT_EQUAL */ :
  7535. // NotIn/NotEqual is always a suffix. There cannot be any remaining
  7536. // segments and hence we can return early here.
  7537. return n.set(o.fieldPath.canonicalString(), s.value), Array.from(n.values());
  7538. // Remaining filters cannot be used as notIn bounds.
  7539. }
  7540. }
  7541. return null;
  7542. }(o, i), l = function(t, e) {
  7543. // For each segment, retrieve a lower bound if there is a suitable filter or
  7544. // startAt.
  7545. for (var n = [], r = !0, i = 0, o = yt(e); i < o.length; i++) {
  7546. var u = o[i], a = 0 /* IndexKind.ASCENDING */ === u.kind ? jn(t, u.fieldPath, t.startAt) : Kn(t, u.fieldPath, t.startAt);
  7547. n.push(a.value), r && (r = a.inclusive);
  7548. }
  7549. return new pn(n, r);
  7550. }(o, i), h = function(t, e) {
  7551. // For each segment, retrieve an upper bound if there is a suitable filter or
  7552. // endAt.
  7553. for (var n = [], r = !0, i = 0, o = yt(e); i < o.length; i++) {
  7554. var u = o[i], a = 0 /* IndexKind.ASCENDING */ === u.kind ? Kn(t, u.fieldPath, t.endAt) : jn(t, u.fieldPath, t.endAt);
  7555. n.push(a.value), r && (r = a.inclusive);
  7556. }
  7557. return new pn(n, r);
  7558. }(o, i), f = n.hn(i, o, l), d = n.hn(i, o, h), p = n.ln(i, o, c), v = n.fn(i.indexId, s, f, l.inclusive, d, h.inclusive, p);
  7559. return Nt.forEach(v, (function(n) {
  7560. return r.H(n, e.limit).next((function(e) {
  7561. e.forEach((function(e) {
  7562. var n = pt.fromSegments(e.documentKey);
  7563. t.has(n) || (t = t.add(n), u.push(n));
  7564. }));
  7565. }));
  7566. }));
  7567. })).next((function() {
  7568. return u;
  7569. }));
  7570. }
  7571. return Nt.resolve(null);
  7572. }));
  7573. }, t.prototype.cn = function(t) {
  7574. var e = this.un.get(t);
  7575. return e || (e = 0 === t.filters.length ? [ t ] : Lo(In.create(t.filters, "and" /* CompositeOperator.AND */)).map((function(e) {
  7576. return qn(t.path, t.collectionGroup, t.orderBy, e.getFilters(), t.limit, t.startAt, t.endAt);
  7577. })), this.un.set(t, e), e);
  7578. },
  7579. /**
  7580. * Constructs a key range query on `DbIndexEntryStore` that unions all
  7581. * bounds.
  7582. */
  7583. t.prototype.fn = function(t, e, n, r, i, o, u) {
  7584. for (var a = this, s = (null != e ? e.length : 1) * Math.max(n.length, i.length), c = s / (null != e ? e.length : 1), l = [], h = function(s) {
  7585. var h = e ? f.dn(e[s / c]) : Ho, d = f.wn(t, h, n[s % c], r), p = f._n(t, h, i[s % c], o), v = u.map((function(e) {
  7586. return a.wn(t, h, e,
  7587. /* inclusive= */ !0);
  7588. }));
  7589. l.push.apply(l, f.createRange(d, p, v));
  7590. }, f = this, d = 0
  7591. // The number of total index scans we union together. This is similar to a
  7592. // distributed normal form, but adapted for array values. We create a single
  7593. // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter
  7594. // combined with the values from the query bounds.
  7595. ; d < s; ++d) h(d);
  7596. return l;
  7597. },
  7598. /** Generates the lower bound for `arrayValue` and `directionalValue`. */ t.prototype.wn = function(t, e, n, r) {
  7599. var i = new Fo(t, pt.empty(), e, n);
  7600. return r ? i : i.Je();
  7601. },
  7602. /** Generates the upper bound for `arrayValue` and `directionalValue`. */ t.prototype._n = function(t, e, n, r) {
  7603. var i = new Fo(t, pt.empty(), e, n);
  7604. return r ? i.Je() : i;
  7605. }, t.prototype.an = function(t, e) {
  7606. var n = new Vo(e), r = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment();
  7607. return this.getFieldIndexes(t, r).next((function(t) {
  7608. for (
  7609. // Return the index with the most number of segments.
  7610. var e = null, r = 0, i = t; r < i.length; r++) {
  7611. var o = i[r];
  7612. n.tn(o) && (!e || o.fields.length > e.fields.length) && (e = o);
  7613. }
  7614. return e;
  7615. }));
  7616. }, t.prototype.getIndexType = function(t, e) {
  7617. var n = this, r = 2 /* IndexType.FULL */ , i = this.cn(e);
  7618. return Nt.forEach(i, (function(e) {
  7619. return n.an(t, e).next((function(t) {
  7620. t ? 0 /* IndexType.NONE */ !== r && t.fields.length < function(t) {
  7621. for (var e = new De(dt.comparator), n = !1, r = 0, i = t.filters; r < i.length; r++) for (var o = 0, u = i[r].getFlattenedFilters(); o < u.length; o++) {
  7622. var a = u[o];
  7623. // __name__ is not an explicit segment of any index, so we don't need to
  7624. // count it.
  7625. a.field.isKeyField() || (
  7626. // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
  7627. // For instance, it is possible to have an index for "a ARRAY a ASC". Even
  7628. // though these are on the same field, they should be counted as two
  7629. // separate segments in an index.
  7630. "array-contains" /* Operator.ARRAY_CONTAINS */ === a.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === a.op ? n = !0 : e = e.add(a.field));
  7631. }
  7632. for (var s = 0, c = t.orderBy; s < c.length; s++) {
  7633. var l = c[s];
  7634. // __name__ is not an explicit segment of any index, so we don't need to
  7635. // count it.
  7636. l.field.isKeyField() || (e = e.add(l.field));
  7637. }
  7638. return e.size + (n ? 1 : 0);
  7639. }(e) && (r = 1 /* IndexType.PARTIAL */) : r = 0 /* IndexType.NONE */;
  7640. }));
  7641. })).next((function() {
  7642. // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider
  7643. // OR queries that have a `limit` to have a partial index. For such queries we perform sorting
  7644. // and apply the limit in memory as a post-processing step.
  7645. return function(t) {
  7646. return null !== t.limit;
  7647. }(e) && i.length > 1 && 2 /* IndexType.FULL */ === r ? 1 /* IndexType.PARTIAL */ : r;
  7648. }));
  7649. },
  7650. /**
  7651. * Returns the byte encoded form of the directional values in the field index.
  7652. * Returns `null` if the document does not have all fields specified in the
  7653. * index.
  7654. */
  7655. t.prototype.mn = function(t, e) {
  7656. for (var n = new Oo, r = 0, i = yt(t); r < i.length; r++) {
  7657. var o = i[r], u = e.data.field(o.fieldPath);
  7658. if (null == u) return null;
  7659. var a = n.He(o.kind);
  7660. Do.Ve._e(u, a);
  7661. }
  7662. return n.Qe();
  7663. },
  7664. /** Encodes a single value to the ascending index format. */ t.prototype.dn = function(t) {
  7665. var e = new Oo;
  7666. return Do.Ve._e(t, e.He(0 /* IndexKind.ASCENDING */)), e.Qe();
  7667. },
  7668. /**
  7669. * Returns an encoded form of the document key that sorts based on the key
  7670. * ordering of the field index.
  7671. */
  7672. t.prototype.gn = function(t, e) {
  7673. var n = new Oo;
  7674. return Do.Ve._e(Ze(this.databaseId, e), n.He(function(t) {
  7675. var e = yt(t);
  7676. return 0 === e.length ? 0 /* IndexKind.ASCENDING */ : e[e.length - 1].kind;
  7677. }(t))), n.Qe();
  7678. },
  7679. /**
  7680. * Encodes the given field values according to the specification in `target`.
  7681. * For IN queries, a list of possible values is returned.
  7682. */
  7683. t.prototype.ln = function(t, e, n) {
  7684. if (null === n) return [];
  7685. var r = [];
  7686. r.push(new Oo);
  7687. for (var i = 0, o = 0, u = yt(t); o < u.length; o++) for (var a = u[o], s = n[i++], c = 0, l = r; c < l.length; c++) {
  7688. var h = l[c];
  7689. if (this.yn(e, a.fieldPath) && tn(s)) r = this.pn(r, a, s); else {
  7690. var f = h.He(a.kind);
  7691. Do.Ve._e(s, f);
  7692. }
  7693. }
  7694. return this.In(r);
  7695. },
  7696. /**
  7697. * Encodes the given bounds according to the specification in `target`. For IN
  7698. * queries, a list of possible values is returned.
  7699. */
  7700. t.prototype.hn = function(t, e, n) {
  7701. return this.ln(t, e, n.position);
  7702. },
  7703. /** Returns the byte representation for the provided encoders. */ t.prototype.In = function(t) {
  7704. for (var e = [], n = 0; n < t.length; ++n) e[n] = t[n].Qe();
  7705. return e;
  7706. },
  7707. /**
  7708. * Creates a separate encoder for each element of an array.
  7709. *
  7710. * The method appends each value to all existing encoders (e.g. filter("a",
  7711. * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A
  7712. * list of new encoders is returned.
  7713. */
  7714. t.prototype.pn = function(t, e, n) {
  7715. for (var i = r([], t, !0), o = [], u = 0, a = n.arrayValue.values || []; u < a.length; u++) for (var s = a[u], c = 0, l = i; c < l.length; c++) {
  7716. var h = l[c], f = new Oo;
  7717. f.seed(h.Qe()), Do.Ve._e(s, f.He(e.kind)), o.push(f);
  7718. }
  7719. return o;
  7720. }, t.prototype.yn = function(t, e) {
  7721. return !!t.filters.find((function(t) {
  7722. return t instanceof bn && t.field.isEqual(e) && ("in" /* Operator.IN */ === t.op || "not-in" /* Operator.NOT_IN */ === t.op);
  7723. }));
  7724. }, t.prototype.getFieldIndexes = function(t, e) {
  7725. var n = this, r = Zo(t), i = $o(t);
  7726. return (e ? r.j("collectionGroupIndex", IDBKeyRange.bound(e, e)) : r.j()).next((function(t) {
  7727. var e = [];
  7728. return Nt.forEach(t, (function(t) {
  7729. return i.get([ t.indexId, n.uid ]).next((function(n) {
  7730. e.push(function(t, e) {
  7731. var n = e ? new It(e.sequenceNumber, new St(fo(e.readTime), new pt(Ht(e.documentKey)), e.largestBatchId)) : It.empty(), r = t.fields.map((function(t) {
  7732. var e = t[0], n = t[1];
  7733. return new wt(dt.fromServerFormat(e), n);
  7734. }));
  7735. return new vt(t.indexId, t.collectionGroup, r, n);
  7736. }(t, n));
  7737. }));
  7738. })).next((function() {
  7739. return e;
  7740. }));
  7741. }));
  7742. }, t.prototype.getNextCollectionGroupToUpdate = function(t) {
  7743. return this.getFieldIndexes(t).next((function(t) {
  7744. return 0 === t.length ? null : (t.sort((function(t, e) {
  7745. var n = t.indexState.sequenceNumber - e.indexState.sequenceNumber;
  7746. return 0 !== n ? n : ot(t.collectionGroup, e.collectionGroup);
  7747. })), t[0].collectionGroup);
  7748. }));
  7749. }, t.prototype.updateCollectionGroup = function(t, e, n) {
  7750. var r = this, i = Zo(t), o = $o(t);
  7751. return this.Tn(t).next((function(t) {
  7752. return i.j("collectionGroupIndex", IDBKeyRange.bound(e, e)).next((function(e) {
  7753. return Nt.forEach(e, (function(e) {
  7754. return o.put(bo(e.indexId, r.user, t, n));
  7755. }));
  7756. }));
  7757. }));
  7758. }, t.prototype.updateIndexEntries = function(t, e) {
  7759. var n = this, r = new Map;
  7760. // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as
  7761. // it could be used across different IndexedDB transactions. As any cached
  7762. // data might be invalidated by other multi-tab clients, we can only trust
  7763. // data within a single IndexedDB transaction. We therefore add a cache
  7764. // here.
  7765. return Nt.forEach(e, (function(e, i) {
  7766. var o = r.get(e.collectionGroup);
  7767. return (o ? Nt.resolve(o) : n.getFieldIndexes(t, e.collectionGroup)).next((function(o) {
  7768. return r.set(e.collectionGroup, o), Nt.forEach(o, (function(r) {
  7769. return n.En(t, e, r).next((function(e) {
  7770. var o = n.An(i, r);
  7771. return e.isEqual(o) ? Nt.resolve() : n.vn(t, i, r, e, o);
  7772. }));
  7773. }));
  7774. }));
  7775. }));
  7776. }, t.prototype.Rn = function(t, e, n, r) {
  7777. return Jo(t).put({
  7778. indexId: r.indexId,
  7779. uid: this.uid,
  7780. arrayValue: r.arrayValue,
  7781. directionalValue: r.directionalValue,
  7782. orderedDocumentKey: this.gn(n, e.key),
  7783. documentKey: e.key.path.toArray()
  7784. });
  7785. }, t.prototype.Pn = function(t, e, n, r) {
  7786. return Jo(t).delete([ r.indexId, this.uid, r.arrayValue, r.directionalValue, this.gn(n, e.key), e.key.path.toArray() ]);
  7787. }, t.prototype.En = function(t, e, n) {
  7788. var r = Jo(t), i = new De(Po);
  7789. return r.X({
  7790. index: "documentKeyIndex",
  7791. range: IDBKeyRange.only([ n.indexId, this.uid, this.gn(n, e) ])
  7792. }, (function(t, r) {
  7793. i = i.add(new Fo(n.indexId, e, r.arrayValue, r.directionalValue));
  7794. })).next((function() {
  7795. return i;
  7796. }));
  7797. },
  7798. /** Creates the index entries for the given document. */ t.prototype.An = function(t, e) {
  7799. var n = new De(Po), r = this.mn(e, t);
  7800. if (null == r) return n;
  7801. var i = mt(e);
  7802. if (null != i) {
  7803. var o = t.data.field(i.fieldPath);
  7804. if (tn(o)) for (var u = 0, a = o.arrayValue.values || []; u < a.length; u++) {
  7805. var s = a[u];
  7806. n = n.add(new Fo(e.indexId, t.key, this.dn(s), r));
  7807. }
  7808. } else n = n.add(new Fo(e.indexId, t.key, Ho, r));
  7809. return n;
  7810. },
  7811. /**
  7812. * Updates the index entries for the provided document by deleting entries
  7813. * that are no longer referenced in `newEntries` and adding all newly added
  7814. * entries.
  7815. */
  7816. t.prototype.vn = function(t, e, n, r, i) {
  7817. var o = this;
  7818. M("IndexedDbIndexManager", "Updating index entries for document '%s'", e.key);
  7819. var u = [];
  7820. return function(t, e, n, r, i) {
  7821. // Walk through the two sets at the same time, using the ordering defined by
  7822. // `comparator`.
  7823. for (var o = t.getIterator(), u = e.getIterator(), a = xe(o), s = xe(u); a || s; ) {
  7824. var c = !1, l = !1;
  7825. if (a && s) {
  7826. var h = n(a, s);
  7827. h < 0 ?
  7828. // The element was removed if the next element in our ordered
  7829. // walkthrough is only in `before`.
  7830. l = !0 : h > 0 && (
  7831. // The element was added if the next element in our ordered walkthrough
  7832. // is only in `after`.
  7833. c = !0);
  7834. } else null != a ? l = !0 : c = !0;
  7835. c ? (r(s), s = xe(u)) : l ? (i(a), a = xe(o)) : (a = xe(o), s = xe(u));
  7836. }
  7837. }(r, i, Po, (
  7838. /* onAdd= */ function(r) {
  7839. u.push(o.Rn(t, e, n, r));
  7840. }), (
  7841. /* onRemove= */ function(r) {
  7842. u.push(o.Pn(t, e, n, r));
  7843. })), Nt.waitFor(u);
  7844. }, t.prototype.Tn = function(t) {
  7845. var e = 1;
  7846. return $o(t).X({
  7847. index: "sequenceNumberIndex",
  7848. reverse: !0,
  7849. range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])
  7850. }, (function(t, n, r) {
  7851. r.done(), e = n.sequenceNumber + 1;
  7852. })).next((function() {
  7853. return e;
  7854. }));
  7855. },
  7856. /**
  7857. * Returns a new set of IDB ranges that splits the existing range and excludes
  7858. * any values that match the `notInValue` from these ranges. As an example,
  7859. * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.
  7860. */
  7861. t.prototype.createRange = function(t, e, n) {
  7862. // The notIn values need to be sorted and unique so that we can return a
  7863. // sorted set of non-overlapping ranges.
  7864. n = n.sort((function(t, e) {
  7865. return Po(t, e);
  7866. })).filter((function(t, e, n) {
  7867. return !e || 0 !== Po(t, n[e - 1]);
  7868. }));
  7869. var r = [];
  7870. r.push(t);
  7871. for (var i = 0, o = n; i < o.length; i++) {
  7872. var u = o[i], a = Po(u, t), s = Po(u, e);
  7873. if (0 === a)
  7874. // `notInValue` is the lower bound. We therefore need to raise the bound
  7875. // to the next value.
  7876. r[0] = t.Je(); else if (a > 0 && s < 0)
  7877. // `notInValue` is in the middle of the range
  7878. r.push(u), r.push(u.Je()); else if (s > 0)
  7879. // `notInValue` (and all following values) are out of the range
  7880. break;
  7881. }
  7882. r.push(e);
  7883. for (var c = [], l = 0; l < r.length; l += 2) {
  7884. // If we encounter two bounds that will create an unmatchable key range,
  7885. // then we return an empty set of key ranges.
  7886. if (this.bn(r[l], r[l + 1])) return [];
  7887. var h = [ r[l].indexId, this.uid, r[l].arrayValue, r[l].directionalValue, Ho, [] ], f = [ r[l + 1].indexId, this.uid, r[l + 1].arrayValue, r[l + 1].directionalValue, Ho, [] ];
  7888. c.push(IDBKeyRange.bound(h, f));
  7889. }
  7890. return c;
  7891. }, t.prototype.bn = function(t, e) {
  7892. // If lower bound is greater than the upper bound, then the key
  7893. // range can never be matched.
  7894. return Po(t, e) > 0;
  7895. }, t.prototype.getMinOffsetFromCollectionGroup = function(t, e) {
  7896. return this.getFieldIndexes(t, e).next(tu);
  7897. }, t.prototype.getMinOffset = function(t, e) {
  7898. var n = this;
  7899. return Nt.mapArray(this.cn(e), (function(e) {
  7900. return n.an(t, e).next((function(t) {
  7901. return t || U();
  7902. }));
  7903. })).next(tu);
  7904. }, t;
  7905. }();
  7906. /**
  7907. * Internal implementation of the collection-parent index exposed by MemoryIndexManager.
  7908. * Also used for in-memory caching by IndexedDbIndexManager and initial index population
  7909. * in indexeddb_schema.ts
  7910. */
  7911. /**
  7912. * Helper to get a typed SimpleDbStore for the collectionParents
  7913. * document store.
  7914. */
  7915. function Xo(t) {
  7916. return we(t, "collectionParents");
  7917. }
  7918. /**
  7919. * Helper to get a typed SimpleDbStore for the index entry object store.
  7920. */ function Jo(t) {
  7921. return we(t, "indexEntries");
  7922. }
  7923. /**
  7924. * Helper to get a typed SimpleDbStore for the index configuration object store.
  7925. */ function Zo(t) {
  7926. return we(t, "indexConfiguration");
  7927. }
  7928. /**
  7929. * Helper to get a typed SimpleDbStore for the index state object store.
  7930. */ function $o(t) {
  7931. return we(t, "indexState");
  7932. }
  7933. function tu(t) {
  7934. z(0 !== t.length);
  7935. for (var e = t[0].indexState.offset, n = e.largestBatchId, r = 1; r < t.length; r++) {
  7936. var i = t[r].indexState.offset;
  7937. _t(i, e) < 0 && (e = i), n < i.largestBatchId && (n = i.largestBatchId);
  7938. }
  7939. return new St(e.readTime, e.documentKey, n);
  7940. }
  7941. /**
  7942. * @license
  7943. * Copyright 2018 Google LLC
  7944. *
  7945. * Licensed under the Apache License, Version 2.0 (the "License");
  7946. * you may not use this file except in compliance with the License.
  7947. * You may obtain a copy of the License at
  7948. *
  7949. * http://www.apache.org/licenses/LICENSE-2.0
  7950. *
  7951. * Unless required by applicable law or agreed to in writing, software
  7952. * distributed under the License is distributed on an "AS IS" BASIS,
  7953. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7954. * See the License for the specific language governing permissions and
  7955. * limitations under the License.
  7956. */ var eu = {
  7957. didRun: !1,
  7958. sequenceNumbersCollected: 0,
  7959. targetsRemoved: 0,
  7960. documentsRemoved: 0
  7961. }, nu = /** @class */ function() {
  7962. function t(
  7963. // When we attempt to collect, we will only do so if the cache size is greater than this
  7964. // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.
  7965. t,
  7966. // The percentage of sequence numbers that we will attempt to collect
  7967. e,
  7968. // A cap on the total number of sequence numbers that will be collected. This prevents
  7969. // us from collecting a huge number of sequence numbers if the cache has grown very large.
  7970. n) {
  7971. this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;
  7972. }
  7973. return t.withCacheSize = function(e) {
  7974. return new t(e, t.DEFAULT_COLLECTION_PERCENTILE, t.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);
  7975. }, t;
  7976. }();
  7977. /**
  7978. * @license
  7979. * Copyright 2020 Google LLC
  7980. *
  7981. * Licensed under the Apache License, Version 2.0 (the "License");
  7982. * you may not use this file except in compliance with the License.
  7983. * You may obtain a copy of the License at
  7984. *
  7985. * http://www.apache.org/licenses/LICENSE-2.0
  7986. *
  7987. * Unless required by applicable law or agreed to in writing, software
  7988. * distributed under the License is distributed on an "AS IS" BASIS,
  7989. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7990. * See the License for the specific language governing permissions and
  7991. * limitations under the License.
  7992. */
  7993. /**
  7994. * Delete a mutation batch and the associated document mutations.
  7995. * @returns A PersistencePromise of the document mutations that were removed.
  7996. */
  7997. function ru(t, e, n) {
  7998. var r = t.store("mutations"), i = t.store("documentMutations"), o = [], u = IDBKeyRange.only(n.batchId), a = 0, s = r.X({
  7999. range: u
  8000. }, (function(t, e, n) {
  8001. return a++, n.delete();
  8002. }));
  8003. o.push(s.next((function() {
  8004. z(1 === a);
  8005. })));
  8006. for (var c = [], l = 0, h = n.mutations; l < h.length; l++) {
  8007. var f = h[l], d = Jt(e, f.key.path, n.batchId);
  8008. o.push(i.delete(d)), c.push(f.key);
  8009. }
  8010. return Nt.waitFor(o).next((function() {
  8011. return c;
  8012. }));
  8013. }
  8014. /**
  8015. * Returns an approximate size for the given document.
  8016. */ function iu(t) {
  8017. if (!t) return 0;
  8018. var e;
  8019. if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {
  8020. if (!t.noDocument) throw U();
  8021. e = t.noDocument;
  8022. }
  8023. return JSON.stringify(e).length;
  8024. }
  8025. /**
  8026. * @license
  8027. * Copyright 2017 Google LLC
  8028. *
  8029. * Licensed under the Apache License, Version 2.0 (the "License");
  8030. * you may not use this file except in compliance with the License.
  8031. * You may obtain a copy of the License at
  8032. *
  8033. * http://www.apache.org/licenses/LICENSE-2.0
  8034. *
  8035. * Unless required by applicable law or agreed to in writing, software
  8036. * distributed under the License is distributed on an "AS IS" BASIS,
  8037. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8038. * See the License for the specific language governing permissions and
  8039. * limitations under the License.
  8040. */
  8041. /** A mutation queue for a specific user, backed by IndexedDB. */ nu.DEFAULT_COLLECTION_PERCENTILE = 10,
  8042. nu.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, nu.DEFAULT = new nu(41943040, nu.DEFAULT_COLLECTION_PERCENTILE, nu.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),
  8043. nu.DISABLED = new nu(-1, 0, 0);
  8044. var ou = /** @class */ function() {
  8045. function t(
  8046. /**
  8047. * The normalized userId (e.g. null UID => "" userId) used to store /
  8048. * retrieve mutations.
  8049. */
  8050. t, e, n, r) {
  8051. this.userId = t, this.serializer = e, this.indexManager = n, this.referenceDelegate = r,
  8052. /**
  8053. * Caches the document keys for pending mutation batches. If the mutation
  8054. * has been removed from IndexedDb, the cached value may continue to
  8055. * be used to retrieve the batch's document keys. To remove a cached value
  8056. * locally, `removeCachedMutationKeys()` should be invoked either directly
  8057. * or through `removeMutationBatches()`.
  8058. *
  8059. * With multi-tab, when the primary client acknowledges or rejects a mutation,
  8060. * this cache is used by secondary clients to invalidate the local
  8061. * view of the documents that were previously affected by the mutation.
  8062. */
  8063. // PORTING NOTE: Multi-tab only.
  8064. this.Vn = {}
  8065. /**
  8066. * Creates a new mutation queue for the given user.
  8067. * @param user - The user for which to create a mutation queue.
  8068. * @param serializer - The serializer to use when persisting to IndexedDb.
  8069. */;
  8070. }
  8071. return t.de = function(e, n, r, i) {
  8072. // TODO(mcg): Figure out what constraints there are on userIDs
  8073. // In particular, are there any reserved characters? are empty ids allowed?
  8074. // For the moment store these together in the same mutations table assuming
  8075. // that empty userIDs aren't allowed.
  8076. return z("" !== e.uid), new t(e.isAuthenticated() ? e.uid : "", n, r, i);
  8077. }, t.prototype.checkEmpty = function(t) {
  8078. var e = !0, n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8079. return au(t).X({
  8080. index: "userMutationsIndex",
  8081. range: n
  8082. }, (function(t, n, r) {
  8083. e = !1, r.done();
  8084. })).next((function() {
  8085. return e;
  8086. }));
  8087. }, t.prototype.addMutationBatch = function(t, e, n, r) {
  8088. var i = this, o = su(t), u = au(t);
  8089. // The IndexedDb implementation in Chrome (and Firefox) does not handle
  8090. // compound indices that include auto-generated keys correctly. To ensure
  8091. // that the index entry is added correctly in all browsers, we perform two
  8092. // writes: The first write is used to retrieve the next auto-generated Batch
  8093. // ID, and the second write populates the index and stores the actual
  8094. // mutation batch.
  8095. // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972
  8096. // We write an empty object to obtain key
  8097. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8098. return u.add({}).next((function(a) {
  8099. z("number" == typeof a);
  8100. for (var s = new ii(a, e, n, r), c = function(t, e, n) {
  8101. var r = n.baseMutations.map((function(e) {
  8102. return Wi(t.fe, e);
  8103. })), i = n.mutations.map((function(e) {
  8104. return Wi(t.fe, e);
  8105. }));
  8106. return {
  8107. userId: e,
  8108. batchId: n.batchId,
  8109. localWriteTimeMs: n.localWriteTime.toMillis(),
  8110. baseMutations: r,
  8111. mutations: i
  8112. };
  8113. }(i.serializer, i.userId, s), l = [], h = new De((function(t, e) {
  8114. return ot(t.canonicalString(), e.canonicalString());
  8115. })), f = 0, d = r; f < d.length; f++) {
  8116. var p = d[f], v = Jt(i.userId, p.key.path, a);
  8117. h = h.add(p.key.path.popLast()), l.push(u.put(c)), l.push(o.put(v, Zt));
  8118. }
  8119. return h.forEach((function(e) {
  8120. l.push(i.indexManager.addToCollectionParentIndex(t, e));
  8121. })), t.addOnCommittedListener((function() {
  8122. i.Vn[a] = s.keys();
  8123. })), Nt.waitFor(l).next((function() {
  8124. return s;
  8125. }));
  8126. }));
  8127. }, t.prototype.lookupMutationBatch = function(t, e) {
  8128. var n = this;
  8129. return au(t).get(e).next((function(t) {
  8130. return t ? (z(t.userId === n.userId), po(n.serializer, t)) : null;
  8131. }));
  8132. },
  8133. /**
  8134. * Returns the document keys for the mutation batch with the given batchId.
  8135. * For primary clients, this method returns `null` after
  8136. * `removeMutationBatches()` has been called. Secondary clients return a
  8137. * cached result until `removeCachedMutationKeys()` is invoked.
  8138. */
  8139. // PORTING NOTE: Multi-tab only.
  8140. t.prototype.Sn = function(t, e) {
  8141. var n = this;
  8142. return this.Vn[e] ? Nt.resolve(this.Vn[e]) : this.lookupMutationBatch(t, e).next((function(t) {
  8143. if (t) {
  8144. var r = t.keys();
  8145. return n.Vn[e] = r, r;
  8146. }
  8147. return null;
  8148. }));
  8149. }, t.prototype.getNextMutationBatchAfterBatchId = function(t, e) {
  8150. var n = this, r = e + 1, i = IDBKeyRange.lowerBound([ this.userId, r ]), o = null;
  8151. return au(t).X({
  8152. index: "userMutationsIndex",
  8153. range: i
  8154. }, (function(t, e, i) {
  8155. e.userId === n.userId && (z(e.batchId >= r), o = po(n.serializer, e)), i.done();
  8156. })).next((function() {
  8157. return o;
  8158. }));
  8159. }, t.prototype.getHighestUnacknowledgedBatchId = function(t) {
  8160. var e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]), n = -1;
  8161. return au(t).X({
  8162. index: "userMutationsIndex",
  8163. range: e,
  8164. reverse: !0
  8165. }, (function(t, e, r) {
  8166. n = e.batchId, r.done();
  8167. })).next((function() {
  8168. return n;
  8169. }));
  8170. }, t.prototype.getAllMutationBatches = function(t) {
  8171. var e = this, n = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8172. return au(t).j("userMutationsIndex", n).next((function(t) {
  8173. return t.map((function(t) {
  8174. return po(e.serializer, t);
  8175. }));
  8176. }));
  8177. }, t.prototype.getAllMutationBatchesAffectingDocumentKey = function(t, e) {
  8178. var n = this, r = Xt(this.userId, e.path), i = IDBKeyRange.lowerBound(r), o = [];
  8179. // Scan the document-mutation index starting with a prefix starting with
  8180. // the given documentKey.
  8181. return su(t).X({
  8182. range: i
  8183. }, (function(r, i, u) {
  8184. var a = r[0], s = r[1], c = r[2], l = Ht(s);
  8185. // Only consider rows matching exactly the specific key of
  8186. // interest. Note that because we order by path first, and we
  8187. // order terminators before path separators, we'll encounter all
  8188. // the index rows for documentKey contiguously. In particular, all
  8189. // the rows for documentKey will occur before any rows for
  8190. // documents nested in a subcollection beneath documentKey so we
  8191. // can stop as soon as we hit any such row.
  8192. if (a === n.userId && e.path.isEqual(l))
  8193. // Look up the mutation batch in the store.
  8194. return au(t).get(c).next((function(t) {
  8195. if (!t) throw U();
  8196. z(t.userId === n.userId), o.push(po(n.serializer, t));
  8197. }));
  8198. u.done();
  8199. })).next((function() {
  8200. return o;
  8201. }));
  8202. }, t.prototype.getAllMutationBatchesAffectingDocumentKeys = function(t, e) {
  8203. var n = this, r = new De(ot), i = [];
  8204. return e.forEach((function(e) {
  8205. var o = Xt(n.userId, e.path), u = IDBKeyRange.lowerBound(o), a = su(t).X({
  8206. range: u
  8207. }, (function(t, i, o) {
  8208. var u = t[0], a = t[1], s = t[2], c = Ht(a);
  8209. // Only consider rows matching exactly the specific key of
  8210. // interest. Note that because we order by path first, and we
  8211. // order terminators before path separators, we'll encounter all
  8212. // the index rows for documentKey contiguously. In particular, all
  8213. // the rows for documentKey will occur before any rows for
  8214. // documents nested in a subcollection beneath documentKey so we
  8215. // can stop as soon as we hit any such row.
  8216. u === n.userId && e.path.isEqual(c) ? r = r.add(s) : o.done();
  8217. }));
  8218. i.push(a);
  8219. })), Nt.waitFor(i).next((function() {
  8220. return n.Dn(t, r);
  8221. }));
  8222. }, t.prototype.getAllMutationBatchesAffectingQuery = function(t, e) {
  8223. var n = this, r = e.path, i = r.length + 1, o = Xt(this.userId, r), u = IDBKeyRange.lowerBound(o), a = new De(ot);
  8224. return su(t).X({
  8225. range: u
  8226. }, (function(t, e, o) {
  8227. var u = t[0], s = t[1], c = t[2], l = Ht(s);
  8228. u === n.userId && r.isPrefixOf(l) ?
  8229. // Rows with document keys more than one segment longer than the
  8230. // query path can't be matches. For example, a query on 'rooms'
  8231. // can't match the document /rooms/abc/messages/xyx.
  8232. // TODO(mcg): we'll need a different scanner when we implement
  8233. // ancestor queries.
  8234. l.length === i && (a = a.add(c)) : o.done();
  8235. })).next((function() {
  8236. return n.Dn(t, a);
  8237. }));
  8238. }, t.prototype.Dn = function(t, e) {
  8239. var n = this, r = [], i = [];
  8240. // TODO(rockwood): Implement this using iterate.
  8241. return e.forEach((function(e) {
  8242. i.push(au(t).get(e).next((function(t) {
  8243. if (null === t) throw U();
  8244. z(t.userId === n.userId), r.push(po(n.serializer, t));
  8245. })));
  8246. })), Nt.waitFor(i).next((function() {
  8247. return r;
  8248. }));
  8249. }, t.prototype.removeMutationBatch = function(t, e) {
  8250. var n = this;
  8251. return ru(t.ht, this.userId, e).next((function(r) {
  8252. return t.addOnCommittedListener((function() {
  8253. n.Cn(e.batchId);
  8254. })), Nt.forEach(r, (function(e) {
  8255. return n.referenceDelegate.markPotentiallyOrphaned(t, e);
  8256. }));
  8257. }));
  8258. },
  8259. /**
  8260. * Clears the cached keys for a mutation batch. This method should be
  8261. * called by secondary clients after they process mutation updates.
  8262. *
  8263. * Note that this method does not have to be called from primary clients as
  8264. * the corresponding cache entries are cleared when an acknowledged or
  8265. * rejected batch is removed from the mutation queue.
  8266. */
  8267. // PORTING NOTE: Multi-tab only
  8268. t.prototype.Cn = function(t) {
  8269. delete this.Vn[t];
  8270. }, t.prototype.performConsistencyCheck = function(t) {
  8271. var e = this;
  8272. return this.checkEmpty(t).next((function(n) {
  8273. if (!n) return Nt.resolve();
  8274. // Verify that there are no entries in the documentMutations index if
  8275. // the queue is empty.
  8276. var r = IDBKeyRange.lowerBound([ e.userId ]), i = [];
  8277. return su(t).X({
  8278. range: r
  8279. }, (function(t, n, r) {
  8280. if (t[0] === e.userId) {
  8281. var o = Ht(t[1]);
  8282. i.push(o);
  8283. } else r.done();
  8284. })).next((function() {
  8285. z(0 === i.length);
  8286. }));
  8287. }));
  8288. }, t.prototype.containsKey = function(t, e) {
  8289. return uu(t, this.userId, e);
  8290. },
  8291. // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
  8292. /** Returns the mutation queue's metadata from IndexedDb. */
  8293. t.prototype.xn = function(t) {
  8294. var e = this;
  8295. return cu(t).get(this.userId).next((function(t) {
  8296. return t || {
  8297. userId: e.userId,
  8298. lastAcknowledgedBatchId: -1,
  8299. lastStreamToken: ""
  8300. };
  8301. }));
  8302. }, t;
  8303. }();
  8304. /**
  8305. * @returns true if the mutation queue for the given user contains a pending
  8306. * mutation for the given key.
  8307. */ function uu(t, e, n) {
  8308. var r = Xt(e, n.path), i = r[1], o = IDBKeyRange.lowerBound(r), u = !1;
  8309. return su(t).X({
  8310. range: o,
  8311. Y: !0
  8312. }, (function(t, n, r) {
  8313. var o = t[0], a = t[1];
  8314. /*batchID*/ t[2], o === e && a === i && (u = !0),
  8315. r.done();
  8316. })).next((function() {
  8317. return u;
  8318. }));
  8319. }
  8320. /** Returns true if any mutation queue contains the given document. */
  8321. /**
  8322. * Helper to get a typed SimpleDbStore for the mutations object store.
  8323. */ function au(t) {
  8324. return we(t, "mutations");
  8325. }
  8326. /**
  8327. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8328. */ function su(t) {
  8329. return we(t, "documentMutations");
  8330. }
  8331. /**
  8332. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8333. */ function cu(t) {
  8334. return we(t, "mutationQueues");
  8335. }
  8336. /**
  8337. * @license
  8338. * Copyright 2017 Google LLC
  8339. *
  8340. * Licensed under the Apache License, Version 2.0 (the "License");
  8341. * you may not use this file except in compliance with the License.
  8342. * You may obtain a copy of the License at
  8343. *
  8344. * http://www.apache.org/licenses/LICENSE-2.0
  8345. *
  8346. * Unless required by applicable law or agreed to in writing, software
  8347. * distributed under the License is distributed on an "AS IS" BASIS,
  8348. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8349. * See the License for the specific language governing permissions and
  8350. * limitations under the License.
  8351. */
  8352. /** Offset to ensure non-overlapping target ids. */
  8353. /**
  8354. * Generates monotonically increasing target IDs for sending targets to the
  8355. * watch stream.
  8356. *
  8357. * The client constructs two generators, one for the target cache, and one for
  8358. * for the sync engine (to generate limbo documents targets). These
  8359. * generators produce non-overlapping IDs (by using even and odd IDs
  8360. * respectively).
  8361. *
  8362. * By separating the target ID space, the query cache can generate target IDs
  8363. * that persist across client restarts, while sync engine can independently
  8364. * generate in-memory target IDs that are transient and can be reused after a
  8365. * restart.
  8366. */ var lu = /** @class */ function() {
  8367. function t(t) {
  8368. this.Nn = t;
  8369. }
  8370. return t.prototype.next = function() {
  8371. return this.Nn += 2, this.Nn;
  8372. }, t.kn = function() {
  8373. // The target cache generator must return '2' in its first call to `next()`
  8374. // as there is no differentiation in the protocol layer between an unset
  8375. // number and the number '0'. If we were to sent a target with target ID
  8376. // '0', the backend would consider it unset and replace it with its own ID.
  8377. return new t(0);
  8378. }, t.Mn = function() {
  8379. // Sync engine assigns target IDs for limbo document detection.
  8380. return new t(-1);
  8381. }, t;
  8382. }(), hu = /** @class */ function() {
  8383. function t(t, e) {
  8384. this.referenceDelegate = t, this.serializer = e;
  8385. }
  8386. // PORTING NOTE: We don't cache global metadata for the target cache, since
  8387. // some of it (in particular `highestTargetId`) can be modified by secondary
  8388. // tabs. We could perhaps be more granular (and e.g. still cache
  8389. // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go
  8390. // to IndexedDb whenever we need to read metadata. We can revisit if it turns
  8391. // out to have a meaningful performance impact.
  8392. return t.prototype.allocateTargetId = function(t) {
  8393. var e = this;
  8394. return this.$n(t).next((function(n) {
  8395. var r = new lu(n.highestTargetId);
  8396. return n.highestTargetId = r.next(), e.On(t, n).next((function() {
  8397. return n.highestTargetId;
  8398. }));
  8399. }));
  8400. }, t.prototype.getLastRemoteSnapshotVersion = function(t) {
  8401. return this.$n(t).next((function(t) {
  8402. return ct.fromTimestamp(new st(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds));
  8403. }));
  8404. }, t.prototype.getHighestSequenceNumber = function(t) {
  8405. return this.$n(t).next((function(t) {
  8406. return t.highestListenSequenceNumber;
  8407. }));
  8408. }, t.prototype.setTargetsMetadata = function(t, e, n) {
  8409. var r = this;
  8410. return this.$n(t).next((function(i) {
  8411. return i.highestListenSequenceNumber = e, n && (i.lastRemoteSnapshotVersion = n.toTimestamp()),
  8412. e > i.highestListenSequenceNumber && (i.highestListenSequenceNumber = e), r.On(t, i);
  8413. }));
  8414. }, t.prototype.addTargetData = function(t, e) {
  8415. var n = this;
  8416. return this.Fn(t, e).next((function() {
  8417. return n.$n(t).next((function(r) {
  8418. return r.targetCount += 1, n.Bn(e, r), n.On(t, r);
  8419. }));
  8420. }));
  8421. }, t.prototype.updateTargetData = function(t, e) {
  8422. return this.Fn(t, e);
  8423. }, t.prototype.removeTargetData = function(t, e) {
  8424. var n = this;
  8425. return this.removeMatchingKeysForTargetId(t, e.targetId).next((function() {
  8426. return fu(t).delete(e.targetId);
  8427. })).next((function() {
  8428. return n.$n(t);
  8429. })).next((function(e) {
  8430. return z(e.targetCount > 0), e.targetCount -= 1, n.On(t, e);
  8431. }));
  8432. },
  8433. /**
  8434. * Drops any targets with sequence number less than or equal to the upper bound, excepting those
  8435. * present in `activeTargetIds`. Document associations for the removed targets are also removed.
  8436. * Returns the number of targets removed.
  8437. */
  8438. t.prototype.removeTargets = function(t, e, n) {
  8439. var r = this, i = 0, o = [];
  8440. return fu(t).X((function(u, a) {
  8441. var s = vo(a);
  8442. s.sequenceNumber <= e && null === n.get(s.targetId) && (i++, o.push(r.removeTargetData(t, s)));
  8443. })).next((function() {
  8444. return Nt.waitFor(o);
  8445. })).next((function() {
  8446. return i;
  8447. }));
  8448. },
  8449. /**
  8450. * Call provided function with each `TargetData` that we have cached.
  8451. */
  8452. t.prototype.forEachTarget = function(t, e) {
  8453. return fu(t).X((function(t, n) {
  8454. var r = vo(n);
  8455. e(r);
  8456. }));
  8457. }, t.prototype.$n = function(t) {
  8458. return du(t).get("targetGlobalKey").next((function(t) {
  8459. return z(null !== t), t;
  8460. }));
  8461. }, t.prototype.On = function(t, e) {
  8462. return du(t).put("targetGlobalKey", e);
  8463. }, t.prototype.Fn = function(t, e) {
  8464. return fu(t).put(mo(this.serializer, e));
  8465. },
  8466. /**
  8467. * In-place updates the provided metadata to account for values in the given
  8468. * TargetData. Saving is done separately. Returns true if there were any
  8469. * changes to the metadata.
  8470. */
  8471. t.prototype.Bn = function(t, e) {
  8472. var n = !1;
  8473. return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0),
  8474. t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber,
  8475. n = !0), n;
  8476. }, t.prototype.getTargetCount = function(t) {
  8477. return this.$n(t).next((function(t) {
  8478. return t.targetCount;
  8479. }));
  8480. }, t.prototype.getTargetData = function(t, e) {
  8481. // Iterating by the canonicalId may yield more than one result because
  8482. // canonicalId values are not required to be unique per target. This query
  8483. // depends on the queryTargets index to be efficient.
  8484. var n = Bn(e), r = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]), i = null;
  8485. return fu(t).X({
  8486. range: r,
  8487. index: "queryTargetsIndex"
  8488. }, (function(t, n, r) {
  8489. var o = vo(n);
  8490. // After finding a potential match, check that the target is
  8491. // actually equal to the requested target.
  8492. Un(e, o.target) && (i = o, r.done());
  8493. })).next((function() {
  8494. return i;
  8495. }));
  8496. }, t.prototype.addMatchingKeys = function(t, e, n) {
  8497. var r = this, i = [], o = pu(t);
  8498. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8499. // IndexedDb.
  8500. return e.forEach((function(e) {
  8501. var u = Kt(e.path);
  8502. i.push(o.put({
  8503. targetId: n,
  8504. path: u
  8505. })), i.push(r.referenceDelegate.addReference(t, n, e));
  8506. })), Nt.waitFor(i);
  8507. }, t.prototype.removeMatchingKeys = function(t, e, n) {
  8508. var r = this, i = pu(t);
  8509. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8510. // IndexedDb.
  8511. return Nt.forEach(e, (function(e) {
  8512. var o = Kt(e.path);
  8513. return Nt.waitFor([ i.delete([ n, o ]), r.referenceDelegate.removeReference(t, n, e) ]);
  8514. }));
  8515. }, t.prototype.removeMatchingKeysForTargetId = function(t, e) {
  8516. var n = pu(t), r = IDBKeyRange.bound([ e ], [ e + 1 ],
  8517. /*lowerOpen=*/ !1,
  8518. /*upperOpen=*/ !0);
  8519. return n.delete(r);
  8520. }, t.prototype.getMatchingKeysForTargetId = function(t, e) {
  8521. var n = IDBKeyRange.bound([ e ], [ e + 1 ],
  8522. /*lowerOpen=*/ !1,
  8523. /*upperOpen=*/ !0), r = pu(t), i = Ir();
  8524. return r.X({
  8525. range: n,
  8526. Y: !0
  8527. }, (function(t, e, n) {
  8528. var r = Ht(t[1]), o = new pt(r);
  8529. i = i.add(o);
  8530. })).next((function() {
  8531. return i;
  8532. }));
  8533. }, t.prototype.containsKey = function(t, e) {
  8534. var n = Kt(e.path), r = IDBKeyRange.bound([ n ], [ at(n) ],
  8535. /*lowerOpen=*/ !1,
  8536. /*upperOpen=*/ !0), i = 0;
  8537. return pu(t).X({
  8538. index: "documentTargetsIndex",
  8539. Y: !0,
  8540. range: r
  8541. }, (function(t, e, n) {
  8542. var r = t[0];
  8543. t[1],
  8544. // Having a sentinel row for a document does not count as containing that document;
  8545. // For the target cache, containing the document means the document is part of some
  8546. // target.
  8547. 0 !== r && (i++, n.done());
  8548. })).next((function() {
  8549. return i > 0;
  8550. }));
  8551. },
  8552. /**
  8553. * Looks up a TargetData entry by target ID.
  8554. *
  8555. * @param targetId - The target ID of the TargetData entry to look up.
  8556. * @returns The cached TargetData entry, or null if the cache has no entry for
  8557. * the target.
  8558. */
  8559. // PORTING NOTE: Multi-tab only.
  8560. t.prototype.le = function(t, e) {
  8561. return fu(t).get(e).next((function(t) {
  8562. return t ? vo(t) : null;
  8563. }));
  8564. }, t;
  8565. }();
  8566. /**
  8567. * @license
  8568. * Copyright 2017 Google LLC
  8569. *
  8570. * Licensed under the Apache License, Version 2.0 (the "License");
  8571. * you may not use this file except in compliance with the License.
  8572. * You may obtain a copy of the License at
  8573. *
  8574. * http://www.apache.org/licenses/LICENSE-2.0
  8575. *
  8576. * Unless required by applicable law or agreed to in writing, software
  8577. * distributed under the License is distributed on an "AS IS" BASIS,
  8578. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8579. * See the License for the specific language governing permissions and
  8580. * limitations under the License.
  8581. */
  8582. /**
  8583. * Helper to get a typed SimpleDbStore for the queries object store.
  8584. */
  8585. function fu(t) {
  8586. return we(t, "targets");
  8587. }
  8588. /**
  8589. * Helper to get a typed SimpleDbStore for the target globals object store.
  8590. */ function du(t) {
  8591. return we(t, "targetGlobal");
  8592. }
  8593. /**
  8594. * Helper to get a typed SimpleDbStore for the document target object store.
  8595. */ function pu(t) {
  8596. return we(t, "targetDocuments");
  8597. }
  8598. /**
  8599. * @license
  8600. * Copyright 2020 Google LLC
  8601. *
  8602. * Licensed under the Apache License, Version 2.0 (the "License");
  8603. * you may not use this file except in compliance with the License.
  8604. * You may obtain a copy of the License at
  8605. *
  8606. * http://www.apache.org/licenses/LICENSE-2.0
  8607. *
  8608. * Unless required by applicable law or agreed to in writing, software
  8609. * distributed under the License is distributed on an "AS IS" BASIS,
  8610. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8611. * See the License for the specific language governing permissions and
  8612. * limitations under the License.
  8613. */ function vu(t, e) {
  8614. var n = t[0], r = t[1], i = e[0], o = e[1], u = ot(n, i);
  8615. return 0 === u ? ot(r, o) : u;
  8616. }
  8617. /**
  8618. * Used to calculate the nth sequence number. Keeps a rolling buffer of the
  8619. * lowest n values passed to `addElement`, and finally reports the largest of
  8620. * them in `maxValue`.
  8621. */ var mu = /** @class */ function() {
  8622. function t(t) {
  8623. this.Ln = t, this.buffer = new De(vu), this.qn = 0;
  8624. }
  8625. return t.prototype.Un = function() {
  8626. return ++this.qn;
  8627. }, t.prototype.Kn = function(t) {
  8628. var e = [ t, this.Un() ];
  8629. if (this.buffer.size < this.Ln) this.buffer = this.buffer.add(e); else {
  8630. var n = this.buffer.last();
  8631. vu(e, n) < 0 && (this.buffer = this.buffer.delete(n).add(e));
  8632. }
  8633. }, Object.defineProperty(t.prototype, "maxValue", {
  8634. get: function() {
  8635. // Guaranteed to be non-empty. If we decide we are not collecting any
  8636. // sequence numbers, nthSequenceNumber below short-circuits. If we have
  8637. // decided that we are collecting n sequence numbers, it's because n is some
  8638. // percentage of the existing sequence numbers. That means we should never
  8639. // be in a situation where we are collecting sequence numbers but don't
  8640. // actually have any.
  8641. return this.buffer.last()[0];
  8642. },
  8643. enumerable: !1,
  8644. configurable: !0
  8645. }), t;
  8646. }(), yu = /** @class */ function() {
  8647. function t(t, e, n) {
  8648. this.garbageCollector = t, this.asyncQueue = e, this.localStore = n, this.Gn = null;
  8649. }
  8650. return t.prototype.start = function() {
  8651. -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Qn(6e4);
  8652. }, t.prototype.stop = function() {
  8653. this.Gn && (this.Gn.cancel(), this.Gn = null);
  8654. }, Object.defineProperty(t.prototype, "started", {
  8655. get: function() {
  8656. return null !== this.Gn;
  8657. },
  8658. enumerable: !1,
  8659. configurable: !0
  8660. }), t.prototype.Qn = function(t) {
  8661. var r = this;
  8662. M("LruGarbageCollector", "Garbage collection scheduled in ".concat(t, "ms")), this.Gn = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */ , t, (function() {
  8663. return e(r, void 0, void 0, (function() {
  8664. var t;
  8665. return n(this, (function(e) {
  8666. switch (e.label) {
  8667. case 0:
  8668. this.Gn = null, e.label = 1;
  8669. case 1:
  8670. return e.trys.push([ 1, 3, , 7 ]), [ 4 /*yield*/ , this.localStore.collectGarbage(this.garbageCollector) ];
  8671. case 2:
  8672. return e.sent(), [ 3 /*break*/ , 7 ];
  8673. case 3:
  8674. return Pt(t = e.sent()) ? (M("LruGarbageCollector", "Ignoring IndexedDB error during garbage collection: ", t),
  8675. [ 3 /*break*/ , 6 ]) : [ 3 /*break*/ , 4 ];
  8676. case 4:
  8677. return [ 4 /*yield*/ , xt(t) ];
  8678. case 5:
  8679. e.sent(), e.label = 6;
  8680. case 6:
  8681. return [ 3 /*break*/ , 7 ];
  8682. case 7:
  8683. return [ 4 /*yield*/ , this.Qn(3e5) ];
  8684. case 8:
  8685. return e.sent(), [ 2 /*return*/ ];
  8686. }
  8687. }));
  8688. }));
  8689. }));
  8690. }, t;
  8691. }(), gu = /** @class */ function() {
  8692. function t(t, e) {
  8693. this.jn = t, this.params = e;
  8694. }
  8695. return t.prototype.calculateTargetCount = function(t, e) {
  8696. return this.jn.zn(t).next((function(t) {
  8697. return Math.floor(e / 100 * t);
  8698. }));
  8699. }, t.prototype.nthSequenceNumber = function(t, e) {
  8700. var n = this;
  8701. if (0 === e) return Nt.resolve(Ut.ct);
  8702. var r = new mu(e);
  8703. return this.jn.forEachTarget(t, (function(t) {
  8704. return r.Kn(t.sequenceNumber);
  8705. })).next((function() {
  8706. return n.jn.Wn(t, (function(t) {
  8707. return r.Kn(t);
  8708. }));
  8709. })).next((function() {
  8710. return r.maxValue;
  8711. }));
  8712. }, t.prototype.removeTargets = function(t, e, n) {
  8713. return this.jn.removeTargets(t, e, n);
  8714. }, t.prototype.removeOrphanedDocuments = function(t, e) {
  8715. return this.jn.removeOrphanedDocuments(t, e);
  8716. }, t.prototype.collect = function(t, e) {
  8717. var n = this;
  8718. return -1 === this.params.cacheSizeCollectionThreshold ? (M("LruGarbageCollector", "Garbage collection skipped; disabled"),
  8719. Nt.resolve(eu)) : this.getCacheSize(t).next((function(r) {
  8720. return r < n.params.cacheSizeCollectionThreshold ? (M("LruGarbageCollector", "Garbage collection skipped; Cache size ".concat(r, " is lower than threshold ").concat(n.params.cacheSizeCollectionThreshold)),
  8721. eu) : n.Hn(t, e);
  8722. }));
  8723. }, t.prototype.getCacheSize = function(t) {
  8724. return this.jn.getCacheSize(t);
  8725. }, t.prototype.Hn = function(t, e) {
  8726. var n, r, i, o, u, a, s, c = this, l = Date.now();
  8727. return this.calculateTargetCount(t, this.params.percentileToCollect).next((function(e) {
  8728. // Cap at the configured max
  8729. return e > c.params.maximumSequenceNumbersToCollect ? (M("LruGarbageCollector", "Capping sequence numbers to collect down to the maximum of ".concat(c.params.maximumSequenceNumbersToCollect, " from ").concat(e)),
  8730. r = c.params.maximumSequenceNumbersToCollect) : r = e, o = Date.now(), c.nthSequenceNumber(t, r);
  8731. })).next((function(r) {
  8732. return n = r, u = Date.now(), c.removeTargets(t, n, e);
  8733. })).next((function(e) {
  8734. return i = e, a = Date.now(), c.removeOrphanedDocuments(t, n);
  8735. })).next((function(t) {
  8736. return s = Date.now(), R() <= h.DEBUG && M("LruGarbageCollector", "LRU Garbage Collection\n\tCounted targets in ".concat(o - l, "ms\n\tDetermined least recently used ").concat(r, " in ") + (u - o) + "ms\n" + "\tRemoved ".concat(i, " targets in ") + (a - u) + "ms\n" + "\tRemoved ".concat(t, " documents in ") + (s - a) + "ms\n" + "Total Duration: ".concat(s - l, "ms")),
  8737. Nt.resolve({
  8738. didRun: !0,
  8739. sequenceNumbersCollected: r,
  8740. targetsRemoved: i,
  8741. documentsRemoved: t
  8742. });
  8743. }));
  8744. }, t;
  8745. }();
  8746. /**
  8747. * This class is responsible for the scheduling of LRU garbage collection. It handles checking
  8748. * whether or not GC is enabled, as well as which delay to use before the next run.
  8749. */ function wu(t, e) {
  8750. return new gu(t, e);
  8751. }
  8752. /**
  8753. * @license
  8754. * Copyright 2020 Google LLC
  8755. *
  8756. * Licensed under the Apache License, Version 2.0 (the "License");
  8757. * you may not use this file except in compliance with the License.
  8758. * You may obtain a copy of the License at
  8759. *
  8760. * http://www.apache.org/licenses/LICENSE-2.0
  8761. *
  8762. * Unless required by applicable law or agreed to in writing, software
  8763. * distributed under the License is distributed on an "AS IS" BASIS,
  8764. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8765. * See the License for the specific language governing permissions and
  8766. * limitations under the License.
  8767. */
  8768. /** Provides LRU functionality for IndexedDB persistence. */ var bu = /** @class */ function() {
  8769. function t(t, e) {
  8770. this.db = t, this.garbageCollector = wu(this, e);
  8771. }
  8772. return t.prototype.zn = function(t) {
  8773. var e = this.Jn(t);
  8774. return this.db.getTargetCache().getTargetCount(t).next((function(t) {
  8775. return e.next((function(e) {
  8776. return t + e;
  8777. }));
  8778. }));
  8779. }, t.prototype.Jn = function(t) {
  8780. var e = 0;
  8781. return this.Wn(t, (function(t) {
  8782. e++;
  8783. })).next((function() {
  8784. return e;
  8785. }));
  8786. }, t.prototype.forEachTarget = function(t, e) {
  8787. return this.db.getTargetCache().forEachTarget(t, e);
  8788. }, t.prototype.Wn = function(t, e) {
  8789. return this.Yn(t, (function(t, n) {
  8790. return e(n);
  8791. }));
  8792. }, t.prototype.addReference = function(t, e, n) {
  8793. return Iu(t, n);
  8794. }, t.prototype.removeReference = function(t, e, n) {
  8795. return Iu(t, n);
  8796. }, t.prototype.removeTargets = function(t, e, n) {
  8797. return this.db.getTargetCache().removeTargets(t, e, n);
  8798. }, t.prototype.markPotentiallyOrphaned = function(t, e) {
  8799. return Iu(t, e);
  8800. },
  8801. /**
  8802. * Returns true if anything would prevent this document from being garbage
  8803. * collected, given that the document in question is not present in any
  8804. * targets and has a sequence number less than or equal to the upper bound for
  8805. * the collection run.
  8806. */
  8807. t.prototype.Xn = function(t, e) {
  8808. return function(t, e) {
  8809. var n = !1;
  8810. return cu(t).Z((function(r) {
  8811. return uu(t, r, e).next((function(t) {
  8812. return t && (n = !0), Nt.resolve(!t);
  8813. }));
  8814. })).next((function() {
  8815. return n;
  8816. }));
  8817. }(t, e);
  8818. }, t.prototype.removeOrphanedDocuments = function(t, e) {
  8819. var n = this, r = this.db.getRemoteDocumentCache().newChangeBuffer(), i = [], o = 0;
  8820. return this.Yn(t, (function(u, a) {
  8821. if (a <= e) {
  8822. var s = n.Xn(t, u).next((function(e) {
  8823. if (!e)
  8824. // Our size accounting requires us to read all documents before
  8825. // removing them.
  8826. return o++, r.getEntry(t, u).next((function() {
  8827. return r.removeEntry(u, ct.min()), pu(t).delete([ 0, Kt(u.path) ]);
  8828. }));
  8829. }));
  8830. i.push(s);
  8831. }
  8832. })).next((function() {
  8833. return Nt.waitFor(i);
  8834. })).next((function() {
  8835. return r.apply(t);
  8836. })).next((function() {
  8837. return o;
  8838. }));
  8839. }, t.prototype.removeTarget = function(t, e) {
  8840. var n = e.withSequenceNumber(t.currentSequenceNumber);
  8841. return this.db.getTargetCache().updateTargetData(t, n);
  8842. }, t.prototype.updateLimboDocument = function(t, e) {
  8843. return Iu(t, e);
  8844. },
  8845. /**
  8846. * Call provided function for each document in the cache that is 'orphaned'. Orphaned
  8847. * means not a part of any target, so the only entry in the target-document index for
  8848. * that document will be the sentinel row (targetId 0), which will also have the sequence
  8849. * number for the last time the document was accessed.
  8850. */
  8851. t.prototype.Yn = function(t, e) {
  8852. var n, r = pu(t), i = Ut.ct;
  8853. return r.X({
  8854. index: "documentTargetsIndex"
  8855. }, (function(t, r) {
  8856. var o = t[0];
  8857. t[1];
  8858. var u = r.path, a = r.sequenceNumber;
  8859. 0 === o ? (
  8860. // if nextToReport is valid, report it, this is a new key so the
  8861. // last one must not be a member of any targets.
  8862. i !== Ut.ct && e(new pt(Ht(n)), i),
  8863. // set nextToReport to be this sequence number. It's the next one we
  8864. // might report, if we don't find any targets for this document.
  8865. // Note that the sequence number must be defined when the targetId
  8866. // is 0.
  8867. i = a, n = u) :
  8868. // set nextToReport to be invalid, we know we don't need to report
  8869. // this one since we found a target for it.
  8870. i = Ut.ct;
  8871. })).next((function() {
  8872. // Since we report sequence numbers after getting to the next key, we
  8873. // need to check if the last key we iterated over was an orphaned
  8874. // document and report it.
  8875. i !== Ut.ct && e(new pt(Ht(n)), i);
  8876. }));
  8877. }, t.prototype.getCacheSize = function(t) {
  8878. return this.db.getRemoteDocumentCache().getSize(t);
  8879. }, t;
  8880. }();
  8881. function Iu(t, e) {
  8882. return pu(t).put(
  8883. /**
  8884. * @returns A value suitable for writing a sentinel row in the target-document
  8885. * store.
  8886. */
  8887. function(t, e) {
  8888. return {
  8889. targetId: 0,
  8890. path: Kt(t.path),
  8891. sequenceNumber: e
  8892. };
  8893. }(e, t.currentSequenceNumber));
  8894. }
  8895. /**
  8896. * @license
  8897. * Copyright 2017 Google LLC
  8898. *
  8899. * Licensed under the Apache License, Version 2.0 (the "License");
  8900. * you may not use this file except in compliance with the License.
  8901. * You may obtain a copy of the License at
  8902. *
  8903. * http://www.apache.org/licenses/LICENSE-2.0
  8904. *
  8905. * Unless required by applicable law or agreed to in writing, software
  8906. * distributed under the License is distributed on an "AS IS" BASIS,
  8907. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8908. * See the License for the specific language governing permissions and
  8909. * limitations under the License.
  8910. */
  8911. /**
  8912. * An in-memory buffer of entries to be written to a RemoteDocumentCache.
  8913. * It can be used to batch up a set of changes to be written to the cache, but
  8914. * additionally supports reading entries back with the `getEntry()` method,
  8915. * falling back to the underlying RemoteDocumentCache if no entry is
  8916. * buffered.
  8917. *
  8918. * Entries added to the cache *must* be read first. This is to facilitate
  8919. * calculating the size delta of the pending changes.
  8920. *
  8921. * PORTING NOTE: This class was implemented then removed from other platforms.
  8922. * If byte-counting ends up being needed on the other platforms, consider
  8923. * porting this class as part of that implementation work.
  8924. */ var Eu = /** @class */ function() {
  8925. function t() {
  8926. // A mapping of document key to the new cache entry that should be written.
  8927. this.changes = new lr((function(t) {
  8928. return t.toString();
  8929. }), (function(t, e) {
  8930. return t.isEqual(e);
  8931. })), this.changesApplied = !1
  8932. /**
  8933. * Buffers a `RemoteDocumentCache.addEntry()` call.
  8934. *
  8935. * You can only modify documents that have already been retrieved via
  8936. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  8937. */;
  8938. }
  8939. return t.prototype.addEntry = function(t) {
  8940. this.assertNotApplied(), this.changes.set(t.key, t);
  8941. },
  8942. /**
  8943. * Buffers a `RemoteDocumentCache.removeEntry()` call.
  8944. *
  8945. * You can only remove documents that have already been retrieved via
  8946. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  8947. */
  8948. t.prototype.removeEntry = function(t, e) {
  8949. this.assertNotApplied(), this.changes.set(t, dn.newInvalidDocument(t).setReadTime(e));
  8950. },
  8951. /**
  8952. * Looks up an entry in the cache. The buffered changes will first be checked,
  8953. * and if no buffered change applies, this will forward to
  8954. * `RemoteDocumentCache.getEntry()`.
  8955. *
  8956. * @param transaction - The transaction in which to perform any persistence
  8957. * operations.
  8958. * @param documentKey - The key of the entry to look up.
  8959. * @returns The cached document or an invalid document if we have nothing
  8960. * cached.
  8961. */
  8962. t.prototype.getEntry = function(t, e) {
  8963. this.assertNotApplied();
  8964. var n = this.changes.get(e);
  8965. return void 0 !== n ? Nt.resolve(n) : this.getFromCache(t, e);
  8966. },
  8967. /**
  8968. * Looks up several entries in the cache, forwarding to
  8969. * `RemoteDocumentCache.getEntry()`.
  8970. *
  8971. * @param transaction - The transaction in which to perform any persistence
  8972. * operations.
  8973. * @param documentKeys - The keys of the entries to look up.
  8974. * @returns A map of cached documents, indexed by key. If an entry cannot be
  8975. * found, the corresponding key will be mapped to an invalid document.
  8976. */
  8977. t.prototype.getEntries = function(t, e) {
  8978. return this.getAllFromCache(t, e);
  8979. },
  8980. /**
  8981. * Applies buffered changes to the underlying RemoteDocumentCache, using
  8982. * the provided transaction.
  8983. */
  8984. t.prototype.apply = function(t) {
  8985. return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);
  8986. },
  8987. /** Helper to assert this.changes is not null */ t.prototype.assertNotApplied = function() {},
  8988. t;
  8989. }(), Tu = /** @class */ function() {
  8990. function t(t) {
  8991. this.serializer = t;
  8992. }
  8993. return t.prototype.setIndexManager = function(t) {
  8994. this.indexManager = t;
  8995. },
  8996. /**
  8997. * Adds the supplied entries to the cache.
  8998. *
  8999. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  9000. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9001. */
  9002. t.prototype.addEntry = function(t, e, n) {
  9003. return Cu(t).put(n);
  9004. },
  9005. /**
  9006. * Removes a document from the cache.
  9007. *
  9008. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  9009. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9010. */
  9011. t.prototype.removeEntry = function(t, e, n) {
  9012. return Cu(t).delete(
  9013. /**
  9014. * Returns a key that can be used for document lookups via the primary key of
  9015. * the DbRemoteDocument object store.
  9016. */
  9017. function(t, e) {
  9018. var n = t.path.toArray();
  9019. return [
  9020. /* prefix path */ n.slice(0, n.length - 2),
  9021. /* collection id */ n[n.length - 2], lo(e),
  9022. /* document id */ n[n.length - 1] ];
  9023. }(e, n));
  9024. },
  9025. /**
  9026. * Updates the current cache size.
  9027. *
  9028. * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
  9029. * cache's metadata.
  9030. */
  9031. t.prototype.updateMetadata = function(t, e) {
  9032. var n = this;
  9033. return this.getMetadata(t).next((function(r) {
  9034. return r.byteSize += e, n.Zn(t, r);
  9035. }));
  9036. }, t.prototype.getEntry = function(t, e) {
  9037. var n = this, r = dn.newInvalidDocument(e);
  9038. return Cu(t).X({
  9039. index: "documentKeyIndex",
  9040. range: IDBKeyRange.only(xu(e))
  9041. }, (function(t, i) {
  9042. r = n.ts(e, i);
  9043. })).next((function() {
  9044. return r;
  9045. }));
  9046. },
  9047. /**
  9048. * Looks up an entry in the cache.
  9049. *
  9050. * @param documentKey - The key of the entry to look up.
  9051. * @returns The cached document entry and its size.
  9052. */
  9053. t.prototype.es = function(t, e) {
  9054. var n = this, r = {
  9055. size: 0,
  9056. document: dn.newInvalidDocument(e)
  9057. };
  9058. return Cu(t).X({
  9059. index: "documentKeyIndex",
  9060. range: IDBKeyRange.only(xu(e))
  9061. }, (function(t, i) {
  9062. r = {
  9063. document: n.ts(e, i),
  9064. size: iu(i)
  9065. };
  9066. })).next((function() {
  9067. return r;
  9068. }));
  9069. }, t.prototype.getEntries = function(t, e) {
  9070. var n = this, r = fr();
  9071. return this.ns(t, e, (function(t, e) {
  9072. var i = n.ts(t, e);
  9073. r = r.insert(t, i);
  9074. })).next((function() {
  9075. return r;
  9076. }));
  9077. },
  9078. /**
  9079. * Looks up several entries in the cache.
  9080. *
  9081. * @param documentKeys - The set of keys entries to look up.
  9082. * @returns A map of documents indexed by key and a map of sizes indexed by
  9083. * key (zero if the document does not exist).
  9084. */
  9085. t.prototype.ss = function(t, e) {
  9086. var n = this, r = fr(), i = new Te(pt.comparator);
  9087. return this.ns(t, e, (function(t, e) {
  9088. var o = n.ts(t, e);
  9089. r = r.insert(t, o), i = i.insert(t, iu(e));
  9090. })).next((function() {
  9091. return {
  9092. documents: r,
  9093. rs: i
  9094. };
  9095. }));
  9096. }, t.prototype.ns = function(t, e, n) {
  9097. if (e.isEmpty()) return Nt.resolve();
  9098. var i = new De(Au);
  9099. e.forEach((function(t) {
  9100. return i = i.add(t);
  9101. }));
  9102. var o = IDBKeyRange.bound(xu(i.first()), xu(i.last())), u = i.getIterator(), a = u.getNext();
  9103. return Cu(t).X({
  9104. index: "documentKeyIndex",
  9105. range: o
  9106. }, (function(t, e, i) {
  9107. // Go through keys not found in cache.
  9108. for (var o = pt.fromSegments(r(r([], e.prefixPath, !0), [ e.collectionGroup, e.documentId ], !1)); a && Au(a, o) < 0; ) n(a, null),
  9109. a = u.getNext();
  9110. a && a.isEqual(o) && (
  9111. // Key found in cache.
  9112. n(a, e), a = u.hasNext() ? u.getNext() : null),
  9113. // Skip to the next key (if there is one).
  9114. a ? i.G(xu(a)) : i.done();
  9115. })).next((function() {
  9116. // The rest of the keys are not in the cache. One case where `iterate`
  9117. // above won't go through them is when the cache is empty.
  9118. for (;a; ) n(a, null), a = u.hasNext() ? u.getNext() : null;
  9119. }));
  9120. }, t.prototype.getDocumentsMatchingQuery = function(t, e, n, r) {
  9121. var i = this, o = e.path, u = [ o.popLast().toArray(), o.lastSegment(), lo(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment() ], a = [ o.popLast().toArray(), o.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], "" ];
  9122. return Cu(t).j(IDBKeyRange.bound(u, a, !0)).next((function(t) {
  9123. for (var n = fr(), o = 0, u = t; o < u.length; o++) {
  9124. var a = u[o], s = i.ts(pt.fromSegments(a.prefixPath.concat(a.collectionGroup, a.documentId)), a);
  9125. s.isFoundDocument() && (ur(e, s) || r.has(s.key)) && (
  9126. // Either the document matches the given query, or it is mutated.
  9127. n = n.insert(s.key, s));
  9128. }
  9129. return n;
  9130. }));
  9131. }, t.prototype.getAllFromCollectionGroup = function(t, e, n, r) {
  9132. var i = this, o = fr(), u = Nu(e, n), a = Nu(e, St.max());
  9133. return Cu(t).X({
  9134. index: "collectionGroupIndex",
  9135. range: IDBKeyRange.bound(u, a, !0)
  9136. }, (function(t, e, n) {
  9137. var u = i.ts(pt.fromSegments(e.prefixPath.concat(e.collectionGroup, e.documentId)), e);
  9138. (o = o.insert(u.key, u)).size === r && n.done();
  9139. })).next((function() {
  9140. return o;
  9141. }));
  9142. }, t.prototype.newChangeBuffer = function(t) {
  9143. return new _u(this, !!t && t.trackRemovals);
  9144. }, t.prototype.getSize = function(t) {
  9145. return this.getMetadata(t).next((function(t) {
  9146. return t.byteSize;
  9147. }));
  9148. }, t.prototype.getMetadata = function(t) {
  9149. return Du(t).get("remoteDocumentGlobalKey").next((function(t) {
  9150. return z(!!t), t;
  9151. }));
  9152. }, t.prototype.Zn = function(t, e) {
  9153. return Du(t).put("remoteDocumentGlobalKey", e);
  9154. },
  9155. /**
  9156. * Decodes `dbRemoteDoc` and returns the document (or an invalid document if
  9157. * the document corresponds to the format used for sentinel deletes).
  9158. */
  9159. t.prototype.ts = function(t, e) {
  9160. if (e) {
  9161. var n =
  9162. /** Decodes a remote document from storage locally to a Document. */ function(t, e) {
  9163. var n;
  9164. if (e.document) n = Qi(t.fe, e.document, !!e.hasCommittedMutations); else if (e.noDocument) {
  9165. var r = pt.fromSegments(e.noDocument.path), i = fo(e.noDocument.readTime);
  9166. n = dn.newNoDocument(r, i), e.hasCommittedMutations && n.setHasCommittedMutations();
  9167. } else {
  9168. if (!e.unknownDocument) return U();
  9169. var o = pt.fromSegments(e.unknownDocument.path), u = fo(e.unknownDocument.version);
  9170. n = dn.newUnknownDocument(o, u);
  9171. }
  9172. return e.readTime && n.setReadTime(function(t) {
  9173. var e = new st(t[0], t[1]);
  9174. return ct.fromTimestamp(e);
  9175. }(e.readTime)), n;
  9176. }(this.serializer, e);
  9177. // Whether the document is a sentinel removal and should only be used in the
  9178. // `getNewDocumentChanges()`
  9179. if (!n.isNoDocument() || !n.version.isEqual(ct.min())) return n;
  9180. }
  9181. return dn.newInvalidDocument(t);
  9182. }, t;
  9183. }();
  9184. /**
  9185. * @license
  9186. * Copyright 2017 Google LLC
  9187. *
  9188. * Licensed under the Apache License, Version 2.0 (the "License");
  9189. * you may not use this file except in compliance with the License.
  9190. * You may obtain a copy of the License at
  9191. *
  9192. * http://www.apache.org/licenses/LICENSE-2.0
  9193. *
  9194. * Unless required by applicable law or agreed to in writing, software
  9195. * distributed under the License is distributed on an "AS IS" BASIS,
  9196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9197. * See the License for the specific language governing permissions and
  9198. * limitations under the License.
  9199. */
  9200. /**
  9201. * The RemoteDocumentCache for IndexedDb. To construct, invoke
  9202. * `newIndexedDbRemoteDocumentCache()`.
  9203. */
  9204. /** Creates a new IndexedDbRemoteDocumentCache. */ function Su(t) {
  9205. return new Tu(t);
  9206. }
  9207. /**
  9208. * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.
  9209. *
  9210. * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size
  9211. * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb
  9212. * when we apply the changes.
  9213. */ var _u = /** @class */ function(e) {
  9214. /**
  9215. * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.
  9216. * @param trackRemovals - Whether to create sentinel deletes that can be tracked by
  9217. * `getNewDocumentChanges()`.
  9218. */
  9219. function n(t, n) {
  9220. var r = this;
  9221. return (r = e.call(this) || this).os = t, r.trackRemovals = n,
  9222. // A map of document sizes and read times prior to applying the changes in
  9223. // this buffer.
  9224. r.us = new lr((function(t) {
  9225. return t.toString();
  9226. }), (function(t, e) {
  9227. return t.isEqual(e);
  9228. })), r;
  9229. }
  9230. return t(n, e), n.prototype.applyChanges = function(t) {
  9231. var e = this, n = [], r = 0, i = new De((function(t, e) {
  9232. return ot(t.canonicalString(), e.canonicalString());
  9233. }));
  9234. return this.changes.forEach((function(o, u) {
  9235. var a = e.us.get(o);
  9236. if (n.push(e.os.removeEntry(t, o, a.readTime)), u.isValidDocument()) {
  9237. var s = co(e.os.serializer, u);
  9238. i = i.add(o.path.popLast());
  9239. var c = iu(s);
  9240. r += c - a.size, n.push(e.os.addEntry(t, o, s));
  9241. } else if (r -= a.size, e.trackRemovals) {
  9242. // In order to track removals, we store a "sentinel delete" in the
  9243. // RemoteDocumentCache. This entry is represented by a NoDocument
  9244. // with a version of 0 and ignored by `maybeDecodeDocument()` but
  9245. // preserved in `getNewDocumentChanges()`.
  9246. var l = co(e.os.serializer, u.convertToNoDocument(ct.min()));
  9247. n.push(e.os.addEntry(t, o, l));
  9248. }
  9249. })), i.forEach((function(r) {
  9250. n.push(e.os.indexManager.addToCollectionParentIndex(t, r));
  9251. })), n.push(this.os.updateMetadata(t, r)), Nt.waitFor(n);
  9252. }, n.prototype.getFromCache = function(t, e) {
  9253. var n = this;
  9254. // Record the size of everything we load from the cache so we can compute a delta later.
  9255. return this.os.es(t, e).next((function(t) {
  9256. return n.us.set(e, {
  9257. size: t.size,
  9258. readTime: t.document.readTime
  9259. }), t.document;
  9260. }));
  9261. }, n.prototype.getAllFromCache = function(t, e) {
  9262. var n = this;
  9263. // Record the size of everything we load from the cache so we can compute
  9264. // a delta later.
  9265. return this.os.ss(t, e).next((function(t) {
  9266. var e = t.documents;
  9267. // Note: `getAllFromCache` returns two maps instead of a single map from
  9268. // keys to `DocumentSizeEntry`s. This is to allow returning the
  9269. // `MutableDocumentMap` directly, without a conversion.
  9270. return t.rs.forEach((function(t, r) {
  9271. n.us.set(t, {
  9272. size: r,
  9273. readTime: e.get(t).readTime
  9274. });
  9275. })), e;
  9276. }));
  9277. }, n;
  9278. }(Eu);
  9279. function Du(t) {
  9280. return we(t, "remoteDocumentGlobal");
  9281. }
  9282. /**
  9283. * Helper to get a typed SimpleDbStore for the remoteDocuments object store.
  9284. */ function Cu(t) {
  9285. return we(t, "remoteDocumentsV14");
  9286. }
  9287. /**
  9288. * Returns a key that can be used for document lookups on the
  9289. * `DbRemoteDocumentDocumentKeyIndex` index.
  9290. */ function xu(t) {
  9291. var e = t.path.toArray();
  9292. return [
  9293. /* prefix path */ e.slice(0, e.length - 2),
  9294. /* collection id */ e[e.length - 2],
  9295. /* document id */ e[e.length - 1] ];
  9296. }
  9297. function Nu(t, e) {
  9298. var n = e.documentKey.path.toArray();
  9299. return [
  9300. /* collection id */ t, lo(e.readTime),
  9301. /* prefix path */ n.slice(0, n.length - 2),
  9302. /* document id */ n.length > 0 ? n[n.length - 1] : "" ];
  9303. }
  9304. /**
  9305. * Comparator that compares document keys according to the primary key sorting
  9306. * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
  9307. * and then document ID).
  9308. *
  9309. * Visible for testing.
  9310. */ function Au(t, e) {
  9311. for (var n = t.path.toArray(), r = e.path.toArray(), i = 0, o = 0
  9312. // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
  9313. ; o < n.length - 2 && o < r.length - 2; ++o) if (i = ot(n[o], r[o])) return i;
  9314. return (i = ot(n.length, r.length)) || ((i = ot(n[n.length - 2], r[r.length - 2])) || ot(n[n.length - 1], r[r.length - 1]));
  9315. }
  9316. /**
  9317. * @license
  9318. * Copyright 2017 Google LLC
  9319. *
  9320. * Licensed under the Apache License, Version 2.0 (the "License");
  9321. * you may not use this file except in compliance with the License.
  9322. * You may obtain a copy of the License at
  9323. *
  9324. * http://www.apache.org/licenses/LICENSE-2.0
  9325. *
  9326. * Unless required by applicable law or agreed to in writing, software
  9327. * distributed under the License is distributed on an "AS IS" BASIS,
  9328. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9329. * See the License for the specific language governing permissions and
  9330. * limitations under the License.
  9331. */
  9332. /**
  9333. * Schema Version for the Web client:
  9334. * 1. Initial version including Mutation Queue, Query Cache, and Remote
  9335. * Document Cache
  9336. * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No
  9337. * longer required because migration 3 unconditionally clears it.
  9338. * 3. Dropped and re-created Query Cache to deal with cache corruption related
  9339. * to limbo resolution. Addresses
  9340. * https://github.com/firebase/firebase-ios-sdk/issues/1548
  9341. * 4. Multi-Tab Support.
  9342. * 5. Removal of held write acks.
  9343. * 6. Create document global for tracking document cache size.
  9344. * 7. Ensure every cached document has a sentinel row with a sequence number.
  9345. * 8. Add collection-parent index for Collection Group queries.
  9346. * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than
  9347. * an auto-incrementing ID. This is required for Index-Free queries.
  9348. * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
  9349. * 11. Add bundles and named_queries for bundle support.
  9350. * 12. Add document overlays.
  9351. * 13. Rewrite the keys of the remote document cache to allow for efficient
  9352. * document lookup via `getAll()`.
  9353. * 14. Add overlays.
  9354. * 15. Add indexing support.
  9355. */
  9356. /**
  9357. * @license
  9358. * Copyright 2022 Google LLC
  9359. *
  9360. * Licensed under the Apache License, Version 2.0 (the "License");
  9361. * you may not use this file except in compliance with the License.
  9362. * You may obtain a copy of the License at
  9363. *
  9364. * http://www.apache.org/licenses/LICENSE-2.0
  9365. *
  9366. * Unless required by applicable law or agreed to in writing, software
  9367. * distributed under the License is distributed on an "AS IS" BASIS,
  9368. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9369. * See the License for the specific language governing permissions and
  9370. * limitations under the License.
  9371. */
  9372. /**
  9373. * Represents a local view (overlay) of a document, and the fields that are
  9374. * locally mutated.
  9375. */ var ku = function(t,
  9376. /**
  9377. * The fields that are locally mutated by patch mutations.
  9378. *
  9379. * If the overlayed document is from set or delete mutations, this is `null`.
  9380. * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
  9381. */
  9382. e) {
  9383. this.overlayedDocument = t, this.mutatedFields = e;
  9384. }, Ou = /** @class */ function() {
  9385. function t(t, e, n, r) {
  9386. this.remoteDocumentCache = t, this.mutationQueue = e, this.documentOverlayCache = n,
  9387. this.indexManager = r
  9388. /**
  9389. * Get the local view of the document identified by `key`.
  9390. *
  9391. * @returns Local view of the document or null if we don't have any cached
  9392. * state for it.
  9393. */;
  9394. }
  9395. return t.prototype.getDocument = function(t, e) {
  9396. var n = this, r = null;
  9397. return this.documentOverlayCache.getOverlay(t, e).next((function(i) {
  9398. return r = i, n.remoteDocumentCache.getEntry(t, e);
  9399. })).next((function(t) {
  9400. return null !== r && Qr(r.mutation, t, Ne.empty(), st.now()), t;
  9401. }));
  9402. },
  9403. /**
  9404. * Gets the local view of the documents identified by `keys`.
  9405. *
  9406. * If we don't have cached state for a document in `keys`, a NoDocument will
  9407. * be stored for that key in the resulting set.
  9408. */
  9409. t.prototype.getDocuments = function(t, e) {
  9410. var n = this;
  9411. return this.remoteDocumentCache.getEntries(t, e).next((function(e) {
  9412. return n.getLocalViewOfDocuments(t, e, Ir()).next((function() {
  9413. return e;
  9414. }));
  9415. }));
  9416. },
  9417. /**
  9418. * Similar to `getDocuments`, but creates the local view from the given
  9419. * `baseDocs` without retrieving documents from the local store.
  9420. *
  9421. * @param transaction - The transaction this operation is scoped to.
  9422. * @param docs - The documents to apply local mutations to get the local views.
  9423. * @param existenceStateChanged - The set of document keys whose existence state
  9424. * is changed. This is useful to determine if some documents overlay needs
  9425. * to be recalculated.
  9426. */
  9427. t.prototype.getLocalViewOfDocuments = function(t, e, n) {
  9428. var r = this;
  9429. void 0 === n && (n = Ir());
  9430. var i = mr();
  9431. return this.populateOverlays(t, i, e).next((function() {
  9432. return r.computeViews(t, e, i, n).next((function(t) {
  9433. var e = pr();
  9434. return t.forEach((function(t, n) {
  9435. e = e.insert(t, n.overlayedDocument);
  9436. })), e;
  9437. }));
  9438. }));
  9439. },
  9440. /**
  9441. * Gets the overlayed documents for the given document map, which will include
  9442. * the local view of those documents and a `FieldMask` indicating which fields
  9443. * are mutated locally, `null` if overlay is a Set or Delete mutation.
  9444. */
  9445. t.prototype.getOverlayedDocuments = function(t, e) {
  9446. var n = this, r = mr();
  9447. return this.populateOverlays(t, r, e).next((function() {
  9448. return n.computeViews(t, e, r, Ir());
  9449. }));
  9450. },
  9451. /**
  9452. * Fetches the overlays for {@code docs} and adds them to provided overlay map
  9453. * if the map does not already contain an entry for the given document key.
  9454. */
  9455. t.prototype.populateOverlays = function(t, e, n) {
  9456. var r = [];
  9457. return n.forEach((function(t) {
  9458. e.has(t) || r.push(t);
  9459. })), this.documentOverlayCache.getOverlays(t, r).next((function(t) {
  9460. t.forEach((function(t, n) {
  9461. e.set(t, n);
  9462. }));
  9463. }));
  9464. },
  9465. /**
  9466. * Computes the local view for the given documents.
  9467. *
  9468. * @param docs - The documents to compute views for. It also has the base
  9469. * version of the documents.
  9470. * @param overlays - The overlays that need to be applied to the given base
  9471. * version of the documents.
  9472. * @param existenceStateChanged - A set of documents whose existence states
  9473. * might have changed. This is used to determine if we need to re-calculate
  9474. * overlays from mutation queues.
  9475. * @return A map represents the local documents view.
  9476. */
  9477. t.prototype.computeViews = function(t, e, n, r) {
  9478. var i = fr(), o = gr(), u = gr();
  9479. return e.forEach((function(t, e) {
  9480. var u = n.get(e.key);
  9481. // Recalculate an overlay if the document's existence state changed due to
  9482. // a remote event *and* the overlay is a PatchMutation. This is because
  9483. // document existence state can change if some patch mutation's
  9484. // preconditions are met.
  9485. // NOTE: we recalculate when `overlay` is undefined as well, because there
  9486. // might be a patch mutation whose precondition does not match before the
  9487. // change (hence overlay is undefined), but would now match.
  9488. r.has(e.key) && (void 0 === u || u.mutation instanceof Xr) ? i = i.insert(e.key, e) : void 0 !== u ? (o.set(e.key, u.mutation.getFieldMask()),
  9489. Qr(u.mutation, e, u.mutation.getFieldMask(), st.now())) :
  9490. // no overlay exists
  9491. // Using EMPTY to indicate there is no overlay for the document.
  9492. o.set(e.key, Ne.empty());
  9493. })), this.recalculateAndSaveOverlays(t, i).next((function(t) {
  9494. return t.forEach((function(t, e) {
  9495. return o.set(t, e);
  9496. })), e.forEach((function(t, e) {
  9497. var n;
  9498. return u.set(t, new ku(e, null !== (n = o.get(t)) && void 0 !== n ? n : null));
  9499. })), u;
  9500. }));
  9501. }, t.prototype.recalculateAndSaveOverlays = function(t, e) {
  9502. var n = this, r = gr(), i = new Te((function(t, e) {
  9503. return t - e;
  9504. })), o = Ir();
  9505. return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t, e).next((function(t) {
  9506. for (var n = function(t) {
  9507. t.keys().forEach((function(n) {
  9508. var o = e.get(n);
  9509. if (null !== o) {
  9510. var u = r.get(n) || Ne.empty();
  9511. u = t.applyToLocalView(o, u), r.set(n, u);
  9512. var a = (i.get(t.batchId) || Ir()).add(n);
  9513. i = i.insert(t.batchId, a);
  9514. }
  9515. }));
  9516. }, o = 0, u = t; o < u.length; o++) {
  9517. n(u[o]);
  9518. }
  9519. })).next((function() {
  9520. // Iterate in descending order of batch IDs, and skip documents that are
  9521. // already saved.
  9522. for (var u = [], a = i.getReverseIterator(), s = function() {
  9523. var i = a.getNext(), s = i.key, c = i.value, l = yr();
  9524. c.forEach((function(t) {
  9525. if (!o.has(t)) {
  9526. var n = jr(e.get(t), r.get(t));
  9527. null !== n && l.set(t, n), o = o.add(t);
  9528. }
  9529. })), u.push(n.documentOverlayCache.saveOverlays(t, s, l));
  9530. }; a.hasNext(); ) s();
  9531. return Nt.waitFor(u);
  9532. })).next((function() {
  9533. return r;
  9534. }));
  9535. },
  9536. /**
  9537. * Recalculates overlays by reading the documents from remote document cache
  9538. * first, and saves them after they are calculated.
  9539. */
  9540. t.prototype.recalculateAndSaveOverlaysForDocumentKeys = function(t, e) {
  9541. var n = this;
  9542. return this.remoteDocumentCache.getEntries(t, e).next((function(e) {
  9543. return n.recalculateAndSaveOverlays(t, e);
  9544. }));
  9545. },
  9546. /**
  9547. * Performs a query against the local view of all documents.
  9548. *
  9549. * @param transaction - The persistence transaction.
  9550. * @param query - The query to match documents against.
  9551. * @param offset - Read time and key to start scanning by (exclusive).
  9552. */
  9553. t.prototype.getDocumentsMatchingQuery = function(t, e, n) {
  9554. /**
  9555. * Returns whether the query matches a single document by path (rather than a
  9556. * collection).
  9557. */
  9558. return function(t) {
  9559. return pt.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  9560. }(e) ? this.getDocumentsMatchingDocumentQuery(t, e.path) : Zn(e) ? this.getDocumentsMatchingCollectionGroupQuery(t, e, n) : this.getDocumentsMatchingCollectionQuery(t, e, n);
  9561. },
  9562. /**
  9563. * Given a collection group, returns the next documents that follow the provided offset, along
  9564. * with an updated batch ID.
  9565. *
  9566. * <p>The documents returned by this method are ordered by remote version from the provided
  9567. * offset. If there are no more remote documents after the provided offset, documents with
  9568. * mutations in order of batch id from the offset are returned. Since all documents in a batch are
  9569. * returned together, the total number of documents returned can exceed {@code count}.
  9570. *
  9571. * @param transaction
  9572. * @param collectionGroup The collection group for the documents.
  9573. * @param offset The offset to index into.
  9574. * @param count The number of documents to return
  9575. * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
  9576. */
  9577. t.prototype.getNextDocuments = function(t, e, n, r) {
  9578. var i = this;
  9579. return this.remoteDocumentCache.getAllFromCollectionGroup(t, e, n, r).next((function(o) {
  9580. var u = r - o.size > 0 ? i.documentOverlayCache.getOverlaysForCollectionGroup(t, e, n.largestBatchId, r - o.size) : Nt.resolve(mr()), a = -1, s = o;
  9581. // The callsite will use the largest batch ID together with the latest read time to create
  9582. // a new index offset. Since we only process batch IDs if all remote documents have been read,
  9583. // no overlay will increase the overall read time. This is why we only need to special case
  9584. // the batch id.
  9585. return u.next((function(e) {
  9586. return Nt.forEach(e, (function(e, n) {
  9587. return a < n.largestBatchId && (a = n.largestBatchId), o.get(e) ? Nt.resolve() : i.remoteDocumentCache.getEntry(t, e).next((function(t) {
  9588. s = s.insert(e, t);
  9589. }));
  9590. })).next((function() {
  9591. return i.populateOverlays(t, e, o);
  9592. })).next((function() {
  9593. return i.computeViews(t, s, e, Ir());
  9594. })).next((function(t) {
  9595. return {
  9596. batchId: a,
  9597. changes: vr(t)
  9598. };
  9599. }));
  9600. }));
  9601. }));
  9602. }, t.prototype.getDocumentsMatchingDocumentQuery = function(t, e) {
  9603. // Just do a simple document lookup.
  9604. return this.getDocument(t, new pt(e)).next((function(t) {
  9605. var e = pr();
  9606. return t.isFoundDocument() && (e = e.insert(t.key, t)), e;
  9607. }));
  9608. }, t.prototype.getDocumentsMatchingCollectionGroupQuery = function(t, e, n) {
  9609. var r = this, i = e.collectionGroup, o = pr();
  9610. return this.indexManager.getCollectionParents(t, i).next((function(u) {
  9611. return Nt.forEach(u, (function(u) {
  9612. var a = function(t, e) {
  9613. return new Qn(e,
  9614. /*collectionGroup=*/ null, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  9615. }(e, u.child(i));
  9616. return r.getDocumentsMatchingCollectionQuery(t, a, n).next((function(t) {
  9617. t.forEach((function(t, e) {
  9618. o = o.insert(t, e);
  9619. }));
  9620. }));
  9621. })).next((function() {
  9622. return o;
  9623. }));
  9624. }));
  9625. }, t.prototype.getDocumentsMatchingCollectionQuery = function(t, e, n) {
  9626. var r, i = this;
  9627. // Query the remote documents and overlay mutations.
  9628. return this.documentOverlayCache.getOverlaysForCollection(t, e.path, n.largestBatchId).next((function(o) {
  9629. return r = o, i.remoteDocumentCache.getDocumentsMatchingQuery(t, e, n, r);
  9630. })).next((function(t) {
  9631. // As documents might match the query because of their overlay we need to
  9632. // include documents for all overlays in the initial document set.
  9633. r.forEach((function(e, n) {
  9634. var r = n.getKey();
  9635. null === t.get(r) && (t = t.insert(r, dn.newInvalidDocument(r)));
  9636. }));
  9637. // Apply the overlays and match against the query.
  9638. var n = pr();
  9639. return t.forEach((function(t, i) {
  9640. var o = r.get(t);
  9641. void 0 !== o && Qr(o.mutation, i, Ne.empty(), st.now()),
  9642. // Finally, insert the documents that still match the query
  9643. ur(e, i) && (n = n.insert(t, i));
  9644. })), n;
  9645. }));
  9646. }, t;
  9647. }(), Fu = /** @class */ function() {
  9648. function t(t) {
  9649. this.serializer = t, this.cs = new Map, this.hs = new Map;
  9650. }
  9651. return t.prototype.getBundleMetadata = function(t, e) {
  9652. return Nt.resolve(this.cs.get(e));
  9653. }, t.prototype.saveBundleMetadata = function(t, e) {
  9654. /** Decodes a BundleMetadata proto into a BundleMetadata object. */
  9655. var n;
  9656. return this.cs.set(e.id, {
  9657. id: (n = e).id,
  9658. version: n.version,
  9659. createTime: Vi(n.createTime)
  9660. }), Nt.resolve();
  9661. }, t.prototype.getNamedQuery = function(t, e) {
  9662. return Nt.resolve(this.hs.get(e));
  9663. }, t.prototype.saveNamedQuery = function(t, e) {
  9664. return this.hs.set(e.name, function(t) {
  9665. return {
  9666. name: t.name,
  9667. query: yo(t.bundledQuery),
  9668. readTime: Vi(t.readTime)
  9669. };
  9670. }(e)), Nt.resolve();
  9671. }, t;
  9672. }(), Pu = /** @class */ function() {
  9673. function t() {
  9674. // A map sorted by DocumentKey, whose value is a pair of the largest batch id
  9675. // for the overlay and the overlay itself.
  9676. this.overlays = new Te(pt.comparator), this.ls = new Map;
  9677. }
  9678. return t.prototype.getOverlay = function(t, e) {
  9679. return Nt.resolve(this.overlays.get(e));
  9680. }, t.prototype.getOverlays = function(t, e) {
  9681. var n = this, r = mr();
  9682. return Nt.forEach(e, (function(e) {
  9683. return n.getOverlay(t, e).next((function(t) {
  9684. null !== t && r.set(e, t);
  9685. }));
  9686. })).next((function() {
  9687. return r;
  9688. }));
  9689. }, t.prototype.saveOverlays = function(t, e, n) {
  9690. var r = this;
  9691. return n.forEach((function(n, i) {
  9692. r.we(t, e, i);
  9693. })), Nt.resolve();
  9694. }, t.prototype.removeOverlaysForBatchId = function(t, e, n) {
  9695. var r = this, i = this.ls.get(n);
  9696. return void 0 !== i && (i.forEach((function(t) {
  9697. return r.overlays = r.overlays.remove(t);
  9698. })), this.ls.delete(n)), Nt.resolve();
  9699. }, t.prototype.getOverlaysForCollection = function(t, e, n) {
  9700. for (var r = mr(), i = e.length + 1, o = new pt(e.child("")), u = this.overlays.getIteratorFrom(o); u.hasNext(); ) {
  9701. var a = u.getNext().value, s = a.getKey();
  9702. if (!e.isPrefixOf(s.path)) break;
  9703. // Documents from sub-collections
  9704. s.path.length === i && a.largestBatchId > n && r.set(a.getKey(), a);
  9705. }
  9706. return Nt.resolve(r);
  9707. }, t.prototype.getOverlaysForCollectionGroup = function(t, e, n, r) {
  9708. for (var i = new Te((function(t, e) {
  9709. return t - e;
  9710. })), o = this.overlays.getIterator(); o.hasNext(); ) {
  9711. var u = o.getNext().value;
  9712. if (u.getKey().getCollectionGroup() === e && u.largestBatchId > n) {
  9713. var a = i.get(u.largestBatchId);
  9714. null === a && (a = mr(), i = i.insert(u.largestBatchId, a)), a.set(u.getKey(), u);
  9715. }
  9716. }
  9717. for (var s = mr(), c = i.getIterator(); c.hasNext() && (c.getNext().value.forEach((function(t, e) {
  9718. return s.set(t, e);
  9719. })), !(s.size() >= r)); ) ;
  9720. return Nt.resolve(s);
  9721. }, t.prototype.we = function(t, e, n) {
  9722. // Remove the association of the overlay to its batch id.
  9723. var r = this.overlays.get(n.key);
  9724. if (null !== r) {
  9725. var i = this.ls.get(r.largestBatchId).delete(n.key);
  9726. this.ls.set(r.largestBatchId, i);
  9727. }
  9728. this.overlays = this.overlays.insert(n.key, new ui(e, n));
  9729. // Create the association of this overlay to the given largestBatchId.
  9730. var o = this.ls.get(e);
  9731. void 0 === o && (o = Ir(), this.ls.set(e, o)), this.ls.set(e, o.add(n.key));
  9732. }, t;
  9733. }(), Ru = /** @class */ function() {
  9734. function t() {
  9735. // A set of outstanding references to a document sorted by key.
  9736. this.fs = new De(Vu.ds),
  9737. // A set of outstanding references to a document sorted by target id.
  9738. this.ws = new De(Vu._s)
  9739. /** Returns true if the reference set contains no references. */;
  9740. }
  9741. return t.prototype.isEmpty = function() {
  9742. return this.fs.isEmpty();
  9743. },
  9744. /** Adds a reference to the given document key for the given ID. */ t.prototype.addReference = function(t, e) {
  9745. var n = new Vu(t, e);
  9746. this.fs = this.fs.add(n), this.ws = this.ws.add(n);
  9747. },
  9748. /** Add references to the given document keys for the given ID. */ t.prototype.gs = function(t, e) {
  9749. var n = this;
  9750. t.forEach((function(t) {
  9751. return n.addReference(t, e);
  9752. }));
  9753. },
  9754. /**
  9755. * Removes a reference to the given document key for the given
  9756. * ID.
  9757. */
  9758. t.prototype.removeReference = function(t, e) {
  9759. this.ys(new Vu(t, e));
  9760. }, t.prototype.ps = function(t, e) {
  9761. var n = this;
  9762. t.forEach((function(t) {
  9763. return n.removeReference(t, e);
  9764. }));
  9765. },
  9766. /**
  9767. * Clears all references with a given ID. Calls removeRef() for each key
  9768. * removed.
  9769. */
  9770. t.prototype.Is = function(t) {
  9771. var e = this, n = new pt(new ht([])), r = new Vu(n, t), i = new Vu(n, t + 1), o = [];
  9772. return this.ws.forEachInRange([ r, i ], (function(t) {
  9773. e.ys(t), o.push(t.key);
  9774. })), o;
  9775. }, t.prototype.Ts = function() {
  9776. var t = this;
  9777. this.fs.forEach((function(e) {
  9778. return t.ys(e);
  9779. }));
  9780. }, t.prototype.ys = function(t) {
  9781. this.fs = this.fs.delete(t), this.ws = this.ws.delete(t);
  9782. }, t.prototype.Es = function(t) {
  9783. var e = new pt(new ht([])), n = new Vu(e, t), r = new Vu(e, t + 1), i = Ir();
  9784. return this.ws.forEachInRange([ n, r ], (function(t) {
  9785. i = i.add(t.key);
  9786. })), i;
  9787. }, t.prototype.containsKey = function(t) {
  9788. var e = new Vu(t, 0), n = this.fs.firstAfterOrEqual(e);
  9789. return null !== n && t.isEqual(n.key);
  9790. }, t;
  9791. }(), Vu = /** @class */ function() {
  9792. function t(t, e) {
  9793. this.key = t, this.As = e
  9794. /** Compare by key then by ID */;
  9795. }
  9796. return t.ds = function(t, e) {
  9797. return pt.comparator(t.key, e.key) || ot(t.As, e.As);
  9798. },
  9799. /** Compare by ID then by key */ t._s = function(t, e) {
  9800. return ot(t.As, e.As) || pt.comparator(t.key, e.key);
  9801. }, t;
  9802. }(), Mu = /** @class */ function() {
  9803. function t(t, e) {
  9804. this.indexManager = t, this.referenceDelegate = e,
  9805. /**
  9806. * The set of all mutations that have been sent but not yet been applied to
  9807. * the backend.
  9808. */
  9809. this.mutationQueue = [],
  9810. /** Next value to use when assigning sequential IDs to each mutation batch. */
  9811. this.vs = 1,
  9812. /** An ordered mapping between documents and the mutations batch IDs. */
  9813. this.Rs = new De(Vu.ds);
  9814. }
  9815. return t.prototype.checkEmpty = function(t) {
  9816. return Nt.resolve(0 === this.mutationQueue.length);
  9817. }, t.prototype.addMutationBatch = function(t, e, n, r) {
  9818. var i = this.vs;
  9819. this.vs++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];
  9820. var o = new ii(i, e, n, r);
  9821. this.mutationQueue.push(o);
  9822. // Track references by document key and index collection parents.
  9823. for (var u = 0, a = r; u < a.length; u++) {
  9824. var s = a[u];
  9825. this.Rs = this.Rs.add(new Vu(s.key, i)), this.indexManager.addToCollectionParentIndex(t, s.key.path.popLast());
  9826. }
  9827. return Nt.resolve(o);
  9828. }, t.prototype.lookupMutationBatch = function(t, e) {
  9829. return Nt.resolve(this.Ps(e));
  9830. }, t.prototype.getNextMutationBatchAfterBatchId = function(t, e) {
  9831. var n = e + 1, r = this.bs(n), i = r < 0 ? 0 : r;
  9832. // The requested batchId may still be out of range so normalize it to the
  9833. // start of the queue.
  9834. return Nt.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);
  9835. }, t.prototype.getHighestUnacknowledgedBatchId = function() {
  9836. return Nt.resolve(0 === this.mutationQueue.length ? -1 : this.vs - 1);
  9837. }, t.prototype.getAllMutationBatches = function(t) {
  9838. return Nt.resolve(this.mutationQueue.slice());
  9839. }, t.prototype.getAllMutationBatchesAffectingDocumentKey = function(t, e) {
  9840. var n = this, r = new Vu(e, 0), i = new Vu(e, Number.POSITIVE_INFINITY), o = [];
  9841. return this.Rs.forEachInRange([ r, i ], (function(t) {
  9842. var e = n.Ps(t.As);
  9843. o.push(e);
  9844. })), Nt.resolve(o);
  9845. }, t.prototype.getAllMutationBatchesAffectingDocumentKeys = function(t, e) {
  9846. var n = this, r = new De(ot);
  9847. return e.forEach((function(t) {
  9848. var e = new Vu(t, 0), i = new Vu(t, Number.POSITIVE_INFINITY);
  9849. n.Rs.forEachInRange([ e, i ], (function(t) {
  9850. r = r.add(t.As);
  9851. }));
  9852. })), Nt.resolve(this.Vs(r));
  9853. }, t.prototype.getAllMutationBatchesAffectingQuery = function(t, e) {
  9854. // Use the query path as a prefix for testing if a document matches the
  9855. // query.
  9856. var n = e.path, r = n.length + 1, i = n;
  9857. // Construct a document reference for actually scanning the index. Unlike
  9858. // the prefix the document key in this reference must have an even number of
  9859. // segments. The empty segment can be used a suffix of the query path
  9860. // because it precedes all other segments in an ordered traversal.
  9861. pt.isDocumentKey(i) || (i = i.child(""));
  9862. var o = new Vu(new pt(i), 0), u = new De(ot);
  9863. // Find unique batchIDs referenced by all documents potentially matching the
  9864. // query.
  9865. return this.Rs.forEachWhile((function(t) {
  9866. var e = t.key.path;
  9867. return !!n.isPrefixOf(e) && (
  9868. // Rows with document keys more than one segment longer than the query
  9869. // path can't be matches. For example, a query on 'rooms' can't match
  9870. // the document /rooms/abc/messages/xyx.
  9871. // TODO(mcg): we'll need a different scanner when we implement
  9872. // ancestor queries.
  9873. e.length === r && (u = u.add(t.As)), !0);
  9874. }), o), Nt.resolve(this.Vs(u));
  9875. }, t.prototype.Vs = function(t) {
  9876. var e = this, n = [];
  9877. // Construct an array of matching batches, sorted by batchID to ensure that
  9878. // multiple mutations affecting the same document key are applied in order.
  9879. return t.forEach((function(t) {
  9880. var r = e.Ps(t);
  9881. null !== r && n.push(r);
  9882. })), n;
  9883. }, t.prototype.removeMutationBatch = function(t, e) {
  9884. var n = this;
  9885. z(0 === this.Ss(e.batchId, "removed")), this.mutationQueue.shift();
  9886. var r = this.Rs;
  9887. return Nt.forEach(e.mutations, (function(i) {
  9888. var o = new Vu(i.key, e.batchId);
  9889. return r = r.delete(o), n.referenceDelegate.markPotentiallyOrphaned(t, i.key);
  9890. })).next((function() {
  9891. n.Rs = r;
  9892. }));
  9893. }, t.prototype.Cn = function(t) {
  9894. // No-op since the memory mutation queue does not maintain a separate cache.
  9895. }, t.prototype.containsKey = function(t, e) {
  9896. var n = new Vu(e, 0), r = this.Rs.firstAfterOrEqual(n);
  9897. return Nt.resolve(e.isEqual(r && r.key));
  9898. }, t.prototype.performConsistencyCheck = function(t) {
  9899. return this.mutationQueue.length, Nt.resolve();
  9900. },
  9901. /**
  9902. * Finds the index of the given batchId in the mutation queue and asserts that
  9903. * the resulting index is within the bounds of the queue.
  9904. *
  9905. * @param batchId - The batchId to search for
  9906. * @param action - A description of what the caller is doing, phrased in passive
  9907. * form (e.g. "acknowledged" in a routine that acknowledges batches).
  9908. */
  9909. t.prototype.Ss = function(t, e) {
  9910. return this.bs(t);
  9911. },
  9912. /**
  9913. * Finds the index of the given batchId in the mutation queue. This operation
  9914. * is O(1).
  9915. *
  9916. * @returns The computed index of the batch with the given batchId, based on
  9917. * the state of the queue. Note this index can be negative if the requested
  9918. * batchId has already been remvoed from the queue or past the end of the
  9919. * queue if the batchId is larger than the last added batch.
  9920. */
  9921. t.prototype.bs = function(t) {
  9922. return 0 === this.mutationQueue.length ? 0 : t - this.mutationQueue[0].batchId;
  9923. // Examine the front of the queue to figure out the difference between the
  9924. // batchId and indexes in the array. Note that since the queue is ordered
  9925. // by batchId, if the first batch has a larger batchId then the requested
  9926. // batchId doesn't exist in the queue.
  9927. },
  9928. /**
  9929. * A version of lookupMutationBatch that doesn't return a promise, this makes
  9930. * other functions that uses this code easier to read and more efficent.
  9931. */
  9932. t.prototype.Ps = function(t) {
  9933. var e = this.bs(t);
  9934. return e < 0 || e >= this.mutationQueue.length ? null : this.mutationQueue[e];
  9935. }, t;
  9936. }(), Lu = /** @class */ function() {
  9937. /**
  9938. * @param sizer - Used to assess the size of a document. For eager GC, this is
  9939. * expected to just return 0 to avoid unnecessarily doing the work of
  9940. * calculating the size.
  9941. */
  9942. function t(t) {
  9943. this.Ds = t,
  9944. /** Underlying cache of documents and their read times. */
  9945. this.docs = new Te(pt.comparator),
  9946. /** Size of all cached documents. */
  9947. this.size = 0;
  9948. }
  9949. return t.prototype.setIndexManager = function(t) {
  9950. this.indexManager = t;
  9951. },
  9952. /**
  9953. * Adds the supplied entry to the cache and updates the cache size as appropriate.
  9954. *
  9955. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  9956. * returned by `newChangeBuffer()`.
  9957. */
  9958. t.prototype.addEntry = function(t, e) {
  9959. var n = e.key, r = this.docs.get(n), i = r ? r.size : 0, o = this.Ds(e);
  9960. return this.docs = this.docs.insert(n, {
  9961. document: e.mutableCopy(),
  9962. size: o
  9963. }), this.size += o - i, this.indexManager.addToCollectionParentIndex(t, n.path.popLast());
  9964. },
  9965. /**
  9966. * Removes the specified entry from the cache and updates the cache size as appropriate.
  9967. *
  9968. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  9969. * returned by `newChangeBuffer()`.
  9970. */
  9971. t.prototype.removeEntry = function(t) {
  9972. var e = this.docs.get(t);
  9973. e && (this.docs = this.docs.remove(t), this.size -= e.size);
  9974. }, t.prototype.getEntry = function(t, e) {
  9975. var n = this.docs.get(e);
  9976. return Nt.resolve(n ? n.document.mutableCopy() : dn.newInvalidDocument(e));
  9977. }, t.prototype.getEntries = function(t, e) {
  9978. var n = this, r = fr();
  9979. return e.forEach((function(t) {
  9980. var e = n.docs.get(t);
  9981. r = r.insert(t, e ? e.document.mutableCopy() : dn.newInvalidDocument(t));
  9982. })), Nt.resolve(r);
  9983. }, t.prototype.getDocumentsMatchingQuery = function(t, e, n, r) {
  9984. for (var i = fr(), o = e.path, u = new pt(o.child("")), a = this.docs.getIteratorFrom(u)
  9985. // Documents are ordered by key, so we can use a prefix scan to narrow down
  9986. // the documents we need to match the query against.
  9987. ; a.hasNext(); ) {
  9988. var s = a.getNext(), c = s.key, l = s.value.document;
  9989. if (!o.isPrefixOf(c.path)) break;
  9990. c.path.length > o.length + 1 || _t(Tt(l), n) <= 0 || (r.has(l.key) || ur(e, l)) && (i = i.insert(l.key, l.mutableCopy()));
  9991. }
  9992. return Nt.resolve(i);
  9993. }, t.prototype.getAllFromCollectionGroup = function(t, e, n, r) {
  9994. // This method should only be called from the IndexBackfiller if persistence
  9995. // is enabled.
  9996. U();
  9997. }, t.prototype.Cs = function(t, e) {
  9998. return Nt.forEach(this.docs, (function(t) {
  9999. return e(t);
  10000. }));
  10001. }, t.prototype.newChangeBuffer = function(t) {
  10002. // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
  10003. // a separate changelog and does not need special handling for removals.
  10004. return new qu(this);
  10005. }, t.prototype.getSize = function(t) {
  10006. return Nt.resolve(this.size);
  10007. }, t;
  10008. }(), qu = /** @class */ function(e) {
  10009. function n(t) {
  10010. var n = this;
  10011. return (n = e.call(this) || this).os = t, n;
  10012. }
  10013. return t(n, e), n.prototype.applyChanges = function(t) {
  10014. var e = this, n = [];
  10015. return this.changes.forEach((function(r, i) {
  10016. i.isValidDocument() ? n.push(e.os.addEntry(t, i)) : e.os.removeEntry(r);
  10017. })), Nt.waitFor(n);
  10018. }, n.prototype.getFromCache = function(t, e) {
  10019. return this.os.getEntry(t, e);
  10020. }, n.prototype.getAllFromCache = function(t, e) {
  10021. return this.os.getEntries(t, e);
  10022. }, n;
  10023. }(Eu), Bu = /** @class */ function() {
  10024. function t(t) {
  10025. this.persistence = t,
  10026. /**
  10027. * Maps a target to the data about that target
  10028. */
  10029. this.xs = new lr((function(t) {
  10030. return Bn(t);
  10031. }), Un),
  10032. /** The last received snapshot version. */
  10033. this.lastRemoteSnapshotVersion = ct.min(),
  10034. /** The highest numbered target ID encountered. */
  10035. this.highestTargetId = 0,
  10036. /** The highest sequence number encountered. */
  10037. this.Ns = 0,
  10038. /**
  10039. * A ordered bidirectional mapping between documents and the remote target
  10040. * IDs.
  10041. */
  10042. this.ks = new Ru, this.targetCount = 0, this.Ms = lu.kn();
  10043. }
  10044. return t.prototype.forEachTarget = function(t, e) {
  10045. return this.xs.forEach((function(t, n) {
  10046. return e(n);
  10047. })), Nt.resolve();
  10048. }, t.prototype.getLastRemoteSnapshotVersion = function(t) {
  10049. return Nt.resolve(this.lastRemoteSnapshotVersion);
  10050. }, t.prototype.getHighestSequenceNumber = function(t) {
  10051. return Nt.resolve(this.Ns);
  10052. }, t.prototype.allocateTargetId = function(t) {
  10053. return this.highestTargetId = this.Ms.next(), Nt.resolve(this.highestTargetId);
  10054. }, t.prototype.setTargetsMetadata = function(t, e, n) {
  10055. return n && (this.lastRemoteSnapshotVersion = n), e > this.Ns && (this.Ns = e),
  10056. Nt.resolve();
  10057. }, t.prototype.Fn = function(t) {
  10058. this.xs.set(t.target, t);
  10059. var e = t.targetId;
  10060. e > this.highestTargetId && (this.Ms = new lu(e), this.highestTargetId = e), t.sequenceNumber > this.Ns && (this.Ns = t.sequenceNumber);
  10061. }, t.prototype.addTargetData = function(t, e) {
  10062. return this.Fn(e), this.targetCount += 1, Nt.resolve();
  10063. }, t.prototype.updateTargetData = function(t, e) {
  10064. return this.Fn(e), Nt.resolve();
  10065. }, t.prototype.removeTargetData = function(t, e) {
  10066. return this.xs.delete(e.target), this.ks.Is(e.targetId), this.targetCount -= 1,
  10067. Nt.resolve();
  10068. }, t.prototype.removeTargets = function(t, e, n) {
  10069. var r = this, i = 0, o = [];
  10070. return this.xs.forEach((function(u, a) {
  10071. a.sequenceNumber <= e && null === n.get(a.targetId) && (r.xs.delete(u), o.push(r.removeMatchingKeysForTargetId(t, a.targetId)),
  10072. i++);
  10073. })), Nt.waitFor(o).next((function() {
  10074. return i;
  10075. }));
  10076. }, t.prototype.getTargetCount = function(t) {
  10077. return Nt.resolve(this.targetCount);
  10078. }, t.prototype.getTargetData = function(t, e) {
  10079. var n = this.xs.get(e) || null;
  10080. return Nt.resolve(n);
  10081. }, t.prototype.addMatchingKeys = function(t, e, n) {
  10082. return this.ks.gs(e, n), Nt.resolve();
  10083. }, t.prototype.removeMatchingKeys = function(t, e, n) {
  10084. this.ks.ps(e, n);
  10085. var r = this.persistence.referenceDelegate, i = [];
  10086. return r && e.forEach((function(e) {
  10087. i.push(r.markPotentiallyOrphaned(t, e));
  10088. })), Nt.waitFor(i);
  10089. }, t.prototype.removeMatchingKeysForTargetId = function(t, e) {
  10090. return this.ks.Is(e), Nt.resolve();
  10091. }, t.prototype.getMatchingKeysForTargetId = function(t, e) {
  10092. var n = this.ks.Es(e);
  10093. return Nt.resolve(n);
  10094. }, t.prototype.containsKey = function(t, e) {
  10095. return Nt.resolve(this.ks.containsKey(e));
  10096. }, t;
  10097. }(), Uu = /** @class */ function() {
  10098. /**
  10099. * The constructor accepts a factory for creating a reference delegate. This
  10100. * allows both the delegate and this instance to have strong references to
  10101. * each other without having nullable fields that would then need to be
  10102. * checked or asserted on every access.
  10103. */
  10104. function t(t, e) {
  10105. var n = this;
  10106. this.$s = {}, this.overlays = {}, this.Os = new Ut(0), this.Fs = !1, this.Fs = !0,
  10107. this.referenceDelegate = t(this), this.Bs = new Bu(this), this.indexManager = new Qo,
  10108. this.remoteDocumentCache = new Lu((function(t) {
  10109. return n.referenceDelegate.Ls(t);
  10110. })), this.serializer = new so(e), this.qs = new Fu(this.serializer);
  10111. }
  10112. return t.prototype.start = function() {
  10113. return Promise.resolve();
  10114. }, t.prototype.shutdown = function() {
  10115. // No durable state to ensure is closed on shutdown.
  10116. return this.Fs = !1, Promise.resolve();
  10117. }, Object.defineProperty(t.prototype, "started", {
  10118. get: function() {
  10119. return this.Fs;
  10120. },
  10121. enumerable: !1,
  10122. configurable: !0
  10123. }), t.prototype.setDatabaseDeletedListener = function() {
  10124. // No op.
  10125. }, t.prototype.setNetworkEnabled = function() {
  10126. // No op.
  10127. }, t.prototype.getIndexManager = function(t) {
  10128. // We do not currently support indices for memory persistence, so we can
  10129. // return the same shared instance of the memory index manager.
  10130. return this.indexManager;
  10131. }, t.prototype.getDocumentOverlayCache = function(t) {
  10132. var e = this.overlays[t.toKey()];
  10133. return e || (e = new Pu, this.overlays[t.toKey()] = e), e;
  10134. }, t.prototype.getMutationQueue = function(t, e) {
  10135. var n = this.$s[t.toKey()];
  10136. return n || (n = new Mu(e, this.referenceDelegate), this.$s[t.toKey()] = n), n;
  10137. }, t.prototype.getTargetCache = function() {
  10138. return this.Bs;
  10139. }, t.prototype.getRemoteDocumentCache = function() {
  10140. return this.remoteDocumentCache;
  10141. }, t.prototype.getBundleCache = function() {
  10142. return this.qs;
  10143. }, t.prototype.runTransaction = function(t, e, n) {
  10144. var r = this;
  10145. M("MemoryPersistence", "Starting transaction:", t);
  10146. var i = new zu(this.Os.next());
  10147. return this.referenceDelegate.Us(), n(i).next((function(t) {
  10148. return r.referenceDelegate.Ks(i).next((function() {
  10149. return t;
  10150. }));
  10151. })).toPromise().then((function(t) {
  10152. return i.raiseOnCommittedEvent(), t;
  10153. }));
  10154. }, t.prototype.Gs = function(t, e) {
  10155. return Nt.or(Object.values(this.$s).map((function(n) {
  10156. return function() {
  10157. return n.containsKey(t, e);
  10158. };
  10159. })));
  10160. }, t;
  10161. }(), zu = /** @class */ function(e) {
  10162. function n(t) {
  10163. var n = this;
  10164. return (n = e.call(this) || this).currentSequenceNumber = t, n;
  10165. }
  10166. return t(n, e), n;
  10167. }(Ct), Gu = /** @class */ function() {
  10168. function t(t) {
  10169. this.persistence = t,
  10170. /** Tracks all documents that are active in Query views. */
  10171. this.Qs = new Ru,
  10172. /** The list of documents that are potentially GCed after each transaction. */
  10173. this.js = null;
  10174. }
  10175. return t.zs = function(e) {
  10176. return new t(e);
  10177. }, Object.defineProperty(t.prototype, "Ws", {
  10178. get: function() {
  10179. if (this.js) return this.js;
  10180. throw U();
  10181. },
  10182. enumerable: !1,
  10183. configurable: !0
  10184. }), t.prototype.addReference = function(t, e, n) {
  10185. return this.Qs.addReference(n, e), this.Ws.delete(n.toString()), Nt.resolve();
  10186. }, t.prototype.removeReference = function(t, e, n) {
  10187. return this.Qs.removeReference(n, e), this.Ws.add(n.toString()), Nt.resolve();
  10188. }, t.prototype.markPotentiallyOrphaned = function(t, e) {
  10189. return this.Ws.add(e.toString()), Nt.resolve();
  10190. }, t.prototype.removeTarget = function(t, e) {
  10191. var n = this;
  10192. this.Qs.Is(e.targetId).forEach((function(t) {
  10193. return n.Ws.add(t.toString());
  10194. }));
  10195. var r = this.persistence.getTargetCache();
  10196. return r.getMatchingKeysForTargetId(t, e.targetId).next((function(t) {
  10197. t.forEach((function(t) {
  10198. return n.Ws.add(t.toString());
  10199. }));
  10200. })).next((function() {
  10201. return r.removeTargetData(t, e);
  10202. }));
  10203. }, t.prototype.Us = function() {
  10204. this.js = new Set;
  10205. }, t.prototype.Ks = function(t) {
  10206. var e = this, n = this.persistence.getRemoteDocumentCache().newChangeBuffer();
  10207. // Remove newly orphaned documents.
  10208. return Nt.forEach(this.Ws, (function(r) {
  10209. var i = pt.fromPath(r);
  10210. return e.Hs(t, i).next((function(t) {
  10211. t || n.removeEntry(i, ct.min());
  10212. }));
  10213. })).next((function() {
  10214. return e.js = null, n.apply(t);
  10215. }));
  10216. }, t.prototype.updateLimboDocument = function(t, e) {
  10217. var n = this;
  10218. return this.Hs(t, e).next((function(t) {
  10219. t ? n.Ws.delete(e.toString()) : n.Ws.add(e.toString());
  10220. }));
  10221. }, t.prototype.Ls = function(t) {
  10222. // For eager GC, we don't care about the document size, there are no size thresholds.
  10223. return 0;
  10224. }, t.prototype.Hs = function(t, e) {
  10225. var n = this;
  10226. return Nt.or([ function() {
  10227. return Nt.resolve(n.Qs.containsKey(e));
  10228. }, function() {
  10229. return n.persistence.getTargetCache().containsKey(t, e);
  10230. }, function() {
  10231. return n.persistence.Gs(t, e);
  10232. } ]);
  10233. }, t;
  10234. }(), ju = /** @class */ function() {
  10235. function t(t, e) {
  10236. this.persistence = t, this.Js = new lr((function(t) {
  10237. return Kt(t.path);
  10238. }), (function(t, e) {
  10239. return t.isEqual(e);
  10240. })), this.garbageCollector = wu(this, e);
  10241. }
  10242. return t.zs = function(e, n) {
  10243. return new t(e, n);
  10244. },
  10245. // No-ops, present so memory persistence doesn't have to care which delegate
  10246. // it has.
  10247. t.prototype.Us = function() {}, t.prototype.Ks = function(t) {
  10248. return Nt.resolve();
  10249. }, t.prototype.forEachTarget = function(t, e) {
  10250. return this.persistence.getTargetCache().forEachTarget(t, e);
  10251. }, t.prototype.zn = function(t) {
  10252. var e = this.Jn(t);
  10253. return this.persistence.getTargetCache().getTargetCount(t).next((function(t) {
  10254. return e.next((function(e) {
  10255. return t + e;
  10256. }));
  10257. }));
  10258. }, t.prototype.Jn = function(t) {
  10259. var e = 0;
  10260. return this.Wn(t, (function(t) {
  10261. e++;
  10262. })).next((function() {
  10263. return e;
  10264. }));
  10265. }, t.prototype.Wn = function(t, e) {
  10266. var n = this;
  10267. return Nt.forEach(this.Js, (function(r, i) {
  10268. return n.Xn(t, r, i).next((function(t) {
  10269. return t ? Nt.resolve() : e(i);
  10270. }));
  10271. }));
  10272. }, t.prototype.removeTargets = function(t, e, n) {
  10273. return this.persistence.getTargetCache().removeTargets(t, e, n);
  10274. }, t.prototype.removeOrphanedDocuments = function(t, e) {
  10275. var n = this, r = 0, i = this.persistence.getRemoteDocumentCache(), o = i.newChangeBuffer();
  10276. return i.Cs(t, (function(i) {
  10277. return n.Xn(t, i, e).next((function(t) {
  10278. t || (r++, o.removeEntry(i, ct.min()));
  10279. }));
  10280. })).next((function() {
  10281. return o.apply(t);
  10282. })).next((function() {
  10283. return r;
  10284. }));
  10285. }, t.prototype.markPotentiallyOrphaned = function(t, e) {
  10286. return this.Js.set(e, t.currentSequenceNumber), Nt.resolve();
  10287. }, t.prototype.removeTarget = function(t, e) {
  10288. var n = e.withSequenceNumber(t.currentSequenceNumber);
  10289. return this.persistence.getTargetCache().updateTargetData(t, n);
  10290. }, t.prototype.addReference = function(t, e, n) {
  10291. return this.Js.set(n, t.currentSequenceNumber), Nt.resolve();
  10292. }, t.prototype.removeReference = function(t, e, n) {
  10293. return this.Js.set(n, t.currentSequenceNumber), Nt.resolve();
  10294. }, t.prototype.updateLimboDocument = function(t, e) {
  10295. return this.Js.set(e, t.currentSequenceNumber), Nt.resolve();
  10296. }, t.prototype.Ls = function(t) {
  10297. var e = t.key.toString().length;
  10298. return t.isFoundDocument() && (e += Je(t.data.value)), e;
  10299. }, t.prototype.Xn = function(t, e, n) {
  10300. var r = this;
  10301. return Nt.or([ function() {
  10302. return r.persistence.Gs(t, e);
  10303. }, function() {
  10304. return r.persistence.getTargetCache().containsKey(t, e);
  10305. }, function() {
  10306. var t = r.Js.get(e);
  10307. return Nt.resolve(void 0 !== t && t > n);
  10308. } ]);
  10309. }, t.prototype.getCacheSize = function(t) {
  10310. return this.persistence.getRemoteDocumentCache().getSize(t);
  10311. }, t;
  10312. }(), Ku = /** @class */ function() {
  10313. function t(t) {
  10314. this.serializer = t;
  10315. }
  10316. /**
  10317. * Performs database creation and schema upgrades.
  10318. *
  10319. * Note that in production, this method is only ever used to upgrade the schema
  10320. * to SCHEMA_VERSION. Different values of toVersion are only used for testing
  10321. * and local feature development.
  10322. */ return t.prototype.O = function(t, e, n, r) {
  10323. var i = this, o = new At("createOrUpgrade", e);
  10324. n < 1 && r >= 1 && (function(t) {
  10325. t.createObjectStore("owner");
  10326. }(t), function(t) {
  10327. t.createObjectStore("mutationQueues", {
  10328. keyPath: "userId"
  10329. }), t.createObjectStore("mutations", {
  10330. keyPath: "batchId",
  10331. autoIncrement: !0
  10332. }).createIndex("userMutationsIndex", Yt, {
  10333. unique: !0
  10334. }), t.createObjectStore("documentMutations");
  10335. }(t), Qu(t), function(t) {
  10336. t.createObjectStore("remoteDocuments");
  10337. }(t));
  10338. // Migration 2 to populate the targetGlobal object no longer needed since
  10339. // migration 3 unconditionally clears it.
  10340. var u = Nt.resolve();
  10341. return n < 3 && r >= 3 && (
  10342. // Brand new clients don't need to drop and recreate--only clients that
  10343. // potentially have corrupt data.
  10344. 0 !== n && (function(t) {
  10345. t.deleteObjectStore("targetDocuments"), t.deleteObjectStore("targets"), t.deleteObjectStore("targetGlobal");
  10346. }(t), Qu(t)), u = u.next((function() {
  10347. /**
  10348. * Creates the target global singleton row.
  10349. *
  10350. * @param txn - The version upgrade transaction for indexeddb
  10351. */
  10352. return function(t) {
  10353. var e = t.store("targetGlobal"), n = {
  10354. highestTargetId: 0,
  10355. highestListenSequenceNumber: 0,
  10356. lastRemoteSnapshotVersion: ct.min().toTimestamp(),
  10357. targetCount: 0
  10358. };
  10359. return e.put("targetGlobalKey", n);
  10360. }(o);
  10361. }))), n < 4 && r >= 4 && (0 !== n && (
  10362. // Schema version 3 uses auto-generated keys to generate globally unique
  10363. // mutation batch IDs (this was previously ensured internally by the
  10364. // client). To migrate to the new schema, we have to read all mutations
  10365. // and write them back out. We preserve the existing batch IDs to guarantee
  10366. // consistency with other object stores. Any further mutation batch IDs will
  10367. // be auto-generated.
  10368. u = u.next((function() {
  10369. return function(t, e) {
  10370. return e.store("mutations").j().next((function(n) {
  10371. t.deleteObjectStore("mutations"), t.createObjectStore("mutations", {
  10372. keyPath: "batchId",
  10373. autoIncrement: !0
  10374. }).createIndex("userMutationsIndex", Yt, {
  10375. unique: !0
  10376. });
  10377. var r = e.store("mutations"), i = n.map((function(t) {
  10378. return r.put(t);
  10379. }));
  10380. return Nt.waitFor(i);
  10381. }));
  10382. }(t, o);
  10383. }))), u = u.next((function() {
  10384. !function(t) {
  10385. t.createObjectStore("clientMetadata", {
  10386. keyPath: "clientId"
  10387. });
  10388. }(t);
  10389. }))), n < 5 && r >= 5 && (u = u.next((function() {
  10390. return i.Ys(o);
  10391. }))), n < 6 && r >= 6 && (u = u.next((function() {
  10392. return function(t) {
  10393. t.createObjectStore("remoteDocumentGlobal");
  10394. }(t), i.Xs(o);
  10395. }))), n < 7 && r >= 7 && (u = u.next((function() {
  10396. return i.Zs(o);
  10397. }))), n < 8 && r >= 8 && (u = u.next((function() {
  10398. return i.ti(t, o);
  10399. }))), n < 9 && r >= 9 && (u = u.next((function() {
  10400. // Multi-Tab used to manage its own changelog, but this has been moved
  10401. // to the DbRemoteDocument object store itself. Since the previous change
  10402. // log only contained transient data, we can drop its object store.
  10403. !function(t) {
  10404. t.objectStoreNames.contains("remoteDocumentChanges") && t.deleteObjectStore("remoteDocumentChanges");
  10405. }(t);
  10406. // Note: Schema version 9 used to create a read time index for the
  10407. // RemoteDocumentCache. This is now done with schema version 13.
  10408. }))), n < 10 && r >= 10 && (u = u.next((function() {
  10409. return i.ei(o);
  10410. }))), n < 11 && r >= 11 && (u = u.next((function() {
  10411. !function(t) {
  10412. t.createObjectStore("bundles", {
  10413. keyPath: "bundleId"
  10414. });
  10415. }(t), function(t) {
  10416. t.createObjectStore("namedQueries", {
  10417. keyPath: "name"
  10418. });
  10419. }(t);
  10420. }))), n < 12 && r >= 12 && (u = u.next((function() {
  10421. !function(t) {
  10422. var e = t.createObjectStore("documentOverlays", {
  10423. keyPath: le
  10424. });
  10425. e.createIndex("collectionPathOverlayIndex", he, {
  10426. unique: !1
  10427. }), e.createIndex("collectionGroupOverlayIndex", fe, {
  10428. unique: !1
  10429. });
  10430. }(t);
  10431. }))), n < 13 && r >= 13 && (u = u.next((function() {
  10432. return function(t) {
  10433. var e = t.createObjectStore("remoteDocumentsV14", {
  10434. keyPath: $t
  10435. });
  10436. e.createIndex("documentKeyIndex", te), e.createIndex("collectionGroupIndex", ee);
  10437. }(t);
  10438. })).next((function() {
  10439. return i.ni(t, o);
  10440. })).next((function() {
  10441. return t.deleteObjectStore("remoteDocuments");
  10442. }))), n < 14 && r >= 14 && (u = u.next((function() {
  10443. return i.si(t, o);
  10444. }))), n < 15 && r >= 15 && (u = u.next((function() {
  10445. return function(t) {
  10446. t.createObjectStore("indexConfiguration", {
  10447. keyPath: "indexId",
  10448. autoIncrement: !0
  10449. }).createIndex("collectionGroupIndex", "collectionGroup", {
  10450. unique: !1
  10451. }), t.createObjectStore("indexState", {
  10452. keyPath: ue
  10453. }).createIndex("sequenceNumberIndex", ae, {
  10454. unique: !1
  10455. }), t.createObjectStore("indexEntries", {
  10456. keyPath: se
  10457. }).createIndex("documentKeyIndex", ce, {
  10458. unique: !1
  10459. });
  10460. }(t);
  10461. }))), u;
  10462. }, t.prototype.Xs = function(t) {
  10463. var e = 0;
  10464. return t.store("remoteDocuments").X((function(t, n) {
  10465. e += iu(n);
  10466. })).next((function() {
  10467. var n = {
  10468. byteSize: e
  10469. };
  10470. return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey", n);
  10471. }));
  10472. }, t.prototype.Ys = function(t) {
  10473. var e = this, n = t.store("mutationQueues"), r = t.store("mutations");
  10474. return n.j().next((function(n) {
  10475. return Nt.forEach(n, (function(n) {
  10476. var i = IDBKeyRange.bound([ n.userId, -1 ], [ n.userId, n.lastAcknowledgedBatchId ]);
  10477. return r.j("userMutationsIndex", i).next((function(r) {
  10478. return Nt.forEach(r, (function(r) {
  10479. z(r.userId === n.userId);
  10480. var i = po(e.serializer, r);
  10481. return ru(t, n.userId, i).next((function() {}));
  10482. }));
  10483. }));
  10484. }));
  10485. }));
  10486. },
  10487. /**
  10488. * Ensures that every document in the remote document cache has a corresponding sentinel row
  10489. * with a sequence number. Missing rows are given the most recently used sequence number.
  10490. */
  10491. t.prototype.Zs = function(t) {
  10492. var e = t.store("targetDocuments"), n = t.store("remoteDocuments");
  10493. return t.store("targetGlobal").get("targetGlobalKey").next((function(t) {
  10494. var r = [];
  10495. return n.X((function(n, i) {
  10496. var o = new ht(n), u = function(t) {
  10497. return [ 0, Kt(t) ];
  10498. }(o);
  10499. r.push(e.get(u).next((function(n) {
  10500. return n ? Nt.resolve() : function(n) {
  10501. return e.put({
  10502. targetId: 0,
  10503. path: Kt(n),
  10504. sequenceNumber: t.highestListenSequenceNumber
  10505. });
  10506. }(o);
  10507. })));
  10508. })).next((function() {
  10509. return Nt.waitFor(r);
  10510. }));
  10511. }));
  10512. }, t.prototype.ti = function(t, e) {
  10513. // Create the index.
  10514. t.createObjectStore("collectionParents", {
  10515. keyPath: oe
  10516. });
  10517. var n = e.store("collectionParents"), r = new Wo, i = function(t) {
  10518. if (r.add(t)) {
  10519. var e = t.lastSegment(), i = t.popLast();
  10520. return n.put({
  10521. collectionId: e,
  10522. parent: Kt(i)
  10523. });
  10524. }
  10525. };
  10526. // Helper to add an index entry iff we haven't already written it.
  10527. // Index existing remote documents.
  10528. return e.store("remoteDocuments").X({
  10529. Y: !0
  10530. }, (function(t, e) {
  10531. var n = new ht(t);
  10532. return i(n.popLast());
  10533. })).next((function() {
  10534. return e.store("documentMutations").X({
  10535. Y: !0
  10536. }, (function(t, e) {
  10537. t[0];
  10538. var n = t[1];
  10539. t[2];
  10540. var r = Ht(n);
  10541. return i(r.popLast());
  10542. }));
  10543. }));
  10544. }, t.prototype.ei = function(t) {
  10545. var e = this, n = t.store("targets");
  10546. return n.X((function(t, r) {
  10547. var i = vo(r), o = mo(e.serializer, i);
  10548. return n.put(o);
  10549. }));
  10550. }, t.prototype.ni = function(t, e) {
  10551. var n = e.store("remoteDocuments"), r = [];
  10552. return n.X((function(t, n) {
  10553. var i, o = e.store("remoteDocumentsV14"), u = (i = n, i.document ? new pt(ht.fromString(i.document.name).popFirst(5)) : i.noDocument ? pt.fromSegments(i.noDocument.path) : i.unknownDocument ? pt.fromSegments(i.unknownDocument.path) : U()).path.toArray(), a = {
  10554. prefixPath: u.slice(0, u.length - 2),
  10555. collectionGroup: u[u.length - 2],
  10556. documentId: u[u.length - 1],
  10557. readTime: n.readTime || [ 0, 0 ],
  10558. unknownDocument: n.unknownDocument,
  10559. noDocument: n.noDocument,
  10560. document: n.document,
  10561. hasCommittedMutations: !!n.hasCommittedMutations
  10562. };
  10563. r.push(o.put(a));
  10564. })).next((function() {
  10565. return Nt.waitFor(r);
  10566. }));
  10567. }, t.prototype.si = function(t, e) {
  10568. var n = this, r = e.store("mutations"), i = Su(this.serializer), o = new Uu(Gu.zs, this.serializer.fe);
  10569. return r.j().next((function(t) {
  10570. var r = new Map;
  10571. return t.forEach((function(t) {
  10572. var e, i = null !== (e = r.get(t.userId)) && void 0 !== e ? e : Ir();
  10573. po(n.serializer, t).keys().forEach((function(t) {
  10574. return i = i.add(t);
  10575. })), r.set(t.userId, i);
  10576. })), Nt.forEach(r, (function(t, r) {
  10577. var u = new O(r), a = So.de(n.serializer, u), s = o.getIndexManager(u), c = ou.de(u, n.serializer, s, o.referenceDelegate);
  10578. return new Ou(i, c, a, s).recalculateAndSaveOverlaysForDocumentKeys(new ge(e, Ut.ct), t).next();
  10579. }));
  10580. }));
  10581. }, t;
  10582. }();
  10583. /**
  10584. * @license
  10585. * Copyright 2017 Google LLC
  10586. *
  10587. * Licensed under the Apache License, Version 2.0 (the "License");
  10588. * you may not use this file except in compliance with the License.
  10589. * You may obtain a copy of the License at
  10590. *
  10591. * http://www.apache.org/licenses/LICENSE-2.0
  10592. *
  10593. * Unless required by applicable law or agreed to in writing, software
  10594. * distributed under the License is distributed on an "AS IS" BASIS,
  10595. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10596. * See the License for the specific language governing permissions and
  10597. * limitations under the License.
  10598. */
  10599. /**
  10600. * A readonly view of the local state of all documents we're tracking (i.e. we
  10601. * have a cached version in remoteDocumentCache or local mutations for the
  10602. * document). The view is computed by applying the mutations in the
  10603. * MutationQueue to the RemoteDocumentCache.
  10604. */ function Qu(t) {
  10605. t.createObjectStore("targetDocuments", {
  10606. keyPath: re
  10607. }).createIndex("documentTargetsIndex", ie, {
  10608. unique: !0
  10609. }),
  10610. // NOTE: This is unique only because the TargetId is the suffix.
  10611. t.createObjectStore("targets", {
  10612. keyPath: "targetId"
  10613. }).createIndex("queryTargetsIndex", ne, {
  10614. unique: !0
  10615. }), t.createObjectStore("targetGlobal");
  10616. }
  10617. var Wu = "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.", Hu = /** @class */ function() {
  10618. function t(
  10619. /**
  10620. * Whether to synchronize the in-memory state of multiple tabs and share
  10621. * access to local persistence.
  10622. */
  10623. e, n, r, i, o, u, a, s, c,
  10624. /**
  10625. * If set to true, forcefully obtains database access. Existing tabs will
  10626. * no longer be able to access IndexedDB.
  10627. */
  10628. l, h) {
  10629. if (void 0 === h && (h = 15), this.allowTabSynchronization = e, this.persistenceKey = n,
  10630. this.clientId = r, this.ii = o, this.window = u, this.document = a, this.ri = c,
  10631. this.oi = l, this.ui = h, this.Os = null, this.Fs = !1, this.isPrimary = !1, this.networkEnabled = !0,
  10632. /** Our window.unload handler, if registered. */
  10633. this.ci = null, this.inForeground = !1,
  10634. /** Our 'visibilitychange' listener if registered. */
  10635. this.ai = null,
  10636. /** The client metadata refresh task. */
  10637. this.hi = null,
  10638. /** The last time we garbage collected the client metadata object store. */
  10639. this.li = Number.NEGATIVE_INFINITY,
  10640. /** A listener to notify on primary state changes. */
  10641. this.fi = function(t) {
  10642. return Promise.resolve();
  10643. }, !t.D()) throw new Q(K.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
  10644. this.referenceDelegate = new bu(this, i), this.di = n + "main", this.serializer = new so(s),
  10645. this.wi = new kt(this.di, this.ui, new Ku(this.serializer)), this.Bs = new hu(this.referenceDelegate, this.serializer),
  10646. this.remoteDocumentCache = Su(this.serializer), this.qs = new Io, this.window && this.window.localStorage ? this._i = this.window.localStorage : (this._i = null,
  10647. !1 === l && L("IndexedDbPersistence", "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."));
  10648. }
  10649. /**
  10650. * Attempt to start IndexedDb persistence.
  10651. *
  10652. * @returns Whether persistence was enabled.
  10653. */ return t.prototype.start = function() {
  10654. var t = this;
  10655. // NOTE: This is expected to fail sometimes (in the case of another tab
  10656. // already having the persistence lock), so it's the first thing we should
  10657. // do.
  10658. return this.mi().then((function() {
  10659. if (!t.isPrimary && !t.allowTabSynchronization)
  10660. // Fail `start()` if `synchronizeTabs` is disabled and we cannot
  10661. // obtain the primary lease.
  10662. throw new Q(K.FAILED_PRECONDITION, Wu);
  10663. return t.gi(), t.yi(), t.pi(), t.runTransaction("getHighestListenSequenceNumber", "readonly", (function(e) {
  10664. return t.Bs.getHighestSequenceNumber(e);
  10665. }));
  10666. })).then((function(e) {
  10667. t.Os = new Ut(e, t.ri);
  10668. })).then((function() {
  10669. t.Fs = !0;
  10670. })).catch((function(e) {
  10671. return t.wi && t.wi.close(), Promise.reject(e);
  10672. }));
  10673. },
  10674. /**
  10675. * Registers a listener that gets called when the primary state of the
  10676. * instance changes. Upon registering, this listener is invoked immediately
  10677. * with the current primary state.
  10678. *
  10679. * PORTING NOTE: This is only used for Web multi-tab.
  10680. */
  10681. t.prototype.Ii = function(t) {
  10682. var r = this;
  10683. return this.fi = function(i) {
  10684. return e(r, void 0, void 0, (function() {
  10685. return n(this, (function(e) {
  10686. return this.started ? [ 2 /*return*/ , t(i) ] : [ 2 /*return*/ ];
  10687. }));
  10688. }));
  10689. }, t(this.isPrimary);
  10690. },
  10691. /**
  10692. * Registers a listener that gets called when the database receives a
  10693. * version change event indicating that it has deleted.
  10694. *
  10695. * PORTING NOTE: This is only used for Web multi-tab.
  10696. */
  10697. t.prototype.setDatabaseDeletedListener = function(t) {
  10698. var r = this;
  10699. this.wi.B((function(i) {
  10700. return e(r, void 0, void 0, (function() {
  10701. return n(this, (function(e) {
  10702. switch (e.label) {
  10703. case 0:
  10704. return null === i.newVersion ? [ 4 /*yield*/ , t() ] : [ 3 /*break*/ , 2 ];
  10705. case 1:
  10706. e.sent(), e.label = 2;
  10707. case 2:
  10708. return [ 2 /*return*/ ];
  10709. }
  10710. }));
  10711. }));
  10712. }));
  10713. },
  10714. /**
  10715. * Adjusts the current network state in the client's metadata, potentially
  10716. * affecting the primary lease.
  10717. *
  10718. * PORTING NOTE: This is only used for Web multi-tab.
  10719. */
  10720. t.prototype.setNetworkEnabled = function(t) {
  10721. var r = this;
  10722. this.networkEnabled !== t && (this.networkEnabled = t,
  10723. // Schedule a primary lease refresh for immediate execution. The eventual
  10724. // lease update will be propagated via `primaryStateListener`.
  10725. this.ii.enqueueAndForget((function() {
  10726. return e(r, void 0, void 0, (function() {
  10727. return n(this, (function(t) {
  10728. switch (t.label) {
  10729. case 0:
  10730. return this.started ? [ 4 /*yield*/ , this.mi() ] : [ 3 /*break*/ , 2 ];
  10731. case 1:
  10732. t.sent(), t.label = 2;
  10733. case 2:
  10734. return [ 2 /*return*/ ];
  10735. }
  10736. }));
  10737. }));
  10738. })));
  10739. },
  10740. /**
  10741. * Updates the client metadata in IndexedDb and attempts to either obtain or
  10742. * extend the primary lease for the local client. Asynchronously notifies the
  10743. * primary state listener if the client either newly obtained or released its
  10744. * primary lease.
  10745. */
  10746. t.prototype.mi = function() {
  10747. var t = this;
  10748. return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (function(e) {
  10749. return Xu(e).put({
  10750. clientId: t.clientId,
  10751. updateTimeMs: Date.now(),
  10752. networkEnabled: t.networkEnabled,
  10753. inForeground: t.inForeground
  10754. }).next((function() {
  10755. if (t.isPrimary) return t.Ti(e).next((function(e) {
  10756. e || (t.isPrimary = !1, t.ii.enqueueRetryable((function() {
  10757. return t.fi(!1);
  10758. })));
  10759. }));
  10760. })).next((function() {
  10761. return t.Ei(e);
  10762. })).next((function(n) {
  10763. return t.isPrimary && !n ? t.Ai(e).next((function() {
  10764. return !1;
  10765. })) : !!n && t.vi(e).next((function() {
  10766. return !0;
  10767. }));
  10768. }));
  10769. })).catch((function(e) {
  10770. if (Pt(e))
  10771. // Proceed with the existing state. Any subsequent access to
  10772. // IndexedDB will verify the lease.
  10773. return M("IndexedDbPersistence", "Failed to extend owner lease: ", e), t.isPrimary;
  10774. if (!t.allowTabSynchronization) throw e;
  10775. return M("IndexedDbPersistence", "Releasing owner lease after error during lease refresh", e),
  10776. /* isPrimary= */ !1;
  10777. })).then((function(e) {
  10778. t.isPrimary !== e && t.ii.enqueueRetryable((function() {
  10779. return t.fi(e);
  10780. })), t.isPrimary = e;
  10781. }));
  10782. }, t.prototype.Ti = function(t) {
  10783. var e = this;
  10784. return Yu(t).get("owner").next((function(t) {
  10785. return Nt.resolve(e.Ri(t));
  10786. }));
  10787. }, t.prototype.Pi = function(t) {
  10788. return Xu(t).delete(this.clientId);
  10789. },
  10790. /**
  10791. * If the garbage collection threshold has passed, prunes the
  10792. * RemoteDocumentChanges and the ClientMetadata store based on the last update
  10793. * time of all clients.
  10794. */
  10795. t.prototype.bi = function() {
  10796. return e(this, void 0, void 0, (function() {
  10797. var t, e, r, i, o = this;
  10798. return n(this, (function(n) {
  10799. switch (n.label) {
  10800. case 0:
  10801. return !this.isPrimary || this.Vi(this.li, 18e5) ? [ 3 /*break*/ , 2 ] : (this.li = Date.now(),
  10802. [ 4 /*yield*/ , this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (function(t) {
  10803. var e = we(t, "clientMetadata");
  10804. return e.j().next((function(t) {
  10805. var n = o.Si(t, 18e5), r = t.filter((function(t) {
  10806. return -1 === n.indexOf(t);
  10807. }));
  10808. // Delete metadata for clients that are no longer considered active.
  10809. return Nt.forEach(r, (function(t) {
  10810. return e.delete(t.clientId);
  10811. })).next((function() {
  10812. return r;
  10813. }));
  10814. }));
  10815. })).catch((function() {
  10816. return [];
  10817. })) ]);
  10818. case 1:
  10819. // Delete potential leftover entries that may continue to mark the
  10820. // inactive clients as zombied in LocalStorage.
  10821. // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for
  10822. // the client atomically, but we can't. So we opt to delete the IndexedDb
  10823. // entries first to avoid potentially reviving a zombied client.
  10824. if (t = n.sent(), this._i) for (e = 0, r = t; e < r.length; e++) i = r[e], this._i.removeItem(this.Di(i.clientId));
  10825. n.label = 2;
  10826. case 2:
  10827. return [ 2 /*return*/ ];
  10828. }
  10829. }));
  10830. }));
  10831. },
  10832. /**
  10833. * Schedules a recurring timer to update the client metadata and to either
  10834. * extend or acquire the primary lease if the client is eligible.
  10835. */
  10836. t.prototype.pi = function() {
  10837. var t = this;
  10838. this.hi = this.ii.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */ , 4e3, (function() {
  10839. return t.mi().then((function() {
  10840. return t.bi();
  10841. })).then((function() {
  10842. return t.pi();
  10843. }));
  10844. }));
  10845. },
  10846. /** Checks whether `client` is the local client. */ t.prototype.Ri = function(t) {
  10847. return !!t && t.ownerId === this.clientId;
  10848. },
  10849. /**
  10850. * Evaluate the state of all active clients and determine whether the local
  10851. * client is or can act as the holder of the primary lease. Returns whether
  10852. * the client is eligible for the lease, but does not actually acquire it.
  10853. * May return 'false' even if there is no active leaseholder and another
  10854. * (foreground) client should become leaseholder instead.
  10855. */
  10856. t.prototype.Ei = function(t) {
  10857. var e = this;
  10858. return this.oi ? Nt.resolve(!0) : Yu(t).get("owner").next((function(n) {
  10859. // A client is eligible for the primary lease if:
  10860. // - its network is enabled and the client's tab is in the foreground.
  10861. // - its network is enabled and no other client's tab is in the
  10862. // foreground.
  10863. // - every clients network is disabled and the client's tab is in the
  10864. // foreground.
  10865. // - every clients network is disabled and no other client's tab is in
  10866. // the foreground.
  10867. // - the `forceOwningTab` setting was passed in.
  10868. if (null !== n && e.Vi(n.leaseTimestampMs, 5e3) && !e.Ci(n.ownerId)) {
  10869. if (e.Ri(n) && e.networkEnabled) return !0;
  10870. if (!e.Ri(n)) {
  10871. if (!n.allowTabSynchronization)
  10872. // Fail the `canActAsPrimary` check if the current leaseholder has
  10873. // not opted into multi-tab synchronization. If this happens at
  10874. // client startup, we reject the Promise returned by
  10875. // `enablePersistence()` and the user can continue to use Firestore
  10876. // with in-memory persistence.
  10877. // If this fails during a lease refresh, we will instead block the
  10878. // AsyncQueue from executing further operations. Note that this is
  10879. // acceptable since mixing & matching different `synchronizeTabs`
  10880. // settings is not supported.
  10881. // TODO(b/114226234): Remove this check when `synchronizeTabs` can
  10882. // no longer be turned off.
  10883. throw new Q(K.FAILED_PRECONDITION, Wu);
  10884. return !1;
  10885. }
  10886. }
  10887. return !(!e.networkEnabled || !e.inForeground) || Xu(t).j().next((function(t) {
  10888. return void 0 === e.Si(t, 5e3).find((function(t) {
  10889. if (e.clientId !== t.clientId) {
  10890. var n = !e.networkEnabled && t.networkEnabled, r = !e.inForeground && t.inForeground, i = e.networkEnabled === t.networkEnabled;
  10891. if (n || r && i) return !0;
  10892. }
  10893. return !1;
  10894. }));
  10895. }));
  10896. })).next((function(t) {
  10897. return e.isPrimary !== t && M("IndexedDbPersistence", "Client ".concat(t ? "is" : "is not", " eligible for a primary lease.")),
  10898. t;
  10899. }));
  10900. }, t.prototype.shutdown = function() {
  10901. return e(this, void 0, void 0, (function() {
  10902. var t = this;
  10903. return n(this, (function(e) {
  10904. switch (e.label) {
  10905. case 0:
  10906. // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
  10907. // has obtained the primary lease.
  10908. // The shutdown() operations are idempotent and can be called even when
  10909. // start() aborted (e.g. because it couldn't acquire the persistence lease).
  10910. return this.Fs = !1, this.xi(), this.hi && (this.hi.cancel(), this.hi = null), this.Ni(),
  10911. this.ki(), [ 4 /*yield*/ , this.wi.runTransaction("shutdown", "readwrite", [ "owner", "clientMetadata" ], (function(e) {
  10912. var n = new ge(e, Ut.ct);
  10913. return t.Ai(n).next((function() {
  10914. return t.Pi(n);
  10915. }));
  10916. })) ];
  10917. case 1:
  10918. // The shutdown() operations are idempotent and can be called even when
  10919. // start() aborted (e.g. because it couldn't acquire the persistence lease).
  10920. // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
  10921. // has obtained the primary lease.
  10922. return e.sent(), this.wi.close(),
  10923. // Remove the entry marking the client as zombied from LocalStorage since
  10924. // we successfully deleted its metadata from IndexedDb.
  10925. this.Mi(), [ 2 /*return*/ ];
  10926. }
  10927. }));
  10928. }));
  10929. },
  10930. /**
  10931. * Returns clients that are not zombied and have an updateTime within the
  10932. * provided threshold.
  10933. */
  10934. t.prototype.Si = function(t, e) {
  10935. var n = this;
  10936. return t.filter((function(t) {
  10937. return n.Vi(t.updateTimeMs, e) && !n.Ci(t.clientId);
  10938. }));
  10939. },
  10940. /**
  10941. * Returns the IDs of the clients that are currently active. If multi-tab
  10942. * is not supported, returns an array that only contains the local client's
  10943. * ID.
  10944. *
  10945. * PORTING NOTE: This is only used for Web multi-tab.
  10946. */
  10947. t.prototype.$i = function() {
  10948. var t = this;
  10949. return this.runTransaction("getActiveClients", "readonly", (function(e) {
  10950. return Xu(e).j().next((function(e) {
  10951. return t.Si(e, 18e5).map((function(t) {
  10952. return t.clientId;
  10953. }));
  10954. }));
  10955. }));
  10956. }, Object.defineProperty(t.prototype, "started", {
  10957. get: function() {
  10958. return this.Fs;
  10959. },
  10960. enumerable: !1,
  10961. configurable: !0
  10962. }), t.prototype.getMutationQueue = function(t, e) {
  10963. return ou.de(t, this.serializer, e, this.referenceDelegate);
  10964. }, t.prototype.getTargetCache = function() {
  10965. return this.Bs;
  10966. }, t.prototype.getRemoteDocumentCache = function() {
  10967. return this.remoteDocumentCache;
  10968. }, t.prototype.getIndexManager = function(t) {
  10969. return new Yo(t, this.serializer.fe.databaseId);
  10970. }, t.prototype.getDocumentOverlayCache = function(t) {
  10971. return So.de(this.serializer, t);
  10972. }, t.prototype.getBundleCache = function() {
  10973. return this.qs;
  10974. }, t.prototype.runTransaction = function(t, e, n) {
  10975. var r = this;
  10976. M("IndexedDbPersistence", "Starting transaction:", t);
  10977. var i, o, u = "readonly" === e ? "readonly" : "readwrite", a = 15 === (i = this.ui) ? ye : 14 === i ? me : 13 === i ? ve : 12 === i ? pe : 11 === i ? de : void U();
  10978. /** Returns the object stores for the provided schema. */
  10979. // Do all transactions as readwrite against all object stores, since we
  10980. // are the only reader/writer.
  10981. return this.wi.runTransaction(t, u, a, (function(i) {
  10982. return o = new ge(i, r.Os ? r.Os.next() : Ut.ct), "readwrite-primary" === e ? r.Ti(o).next((function(t) {
  10983. return !!t || r.Ei(o);
  10984. })).next((function(e) {
  10985. if (!e) throw L("Failed to obtain primary lease for action '".concat(t, "'.")),
  10986. r.isPrimary = !1, r.ii.enqueueRetryable((function() {
  10987. return r.fi(!1);
  10988. })), new Q(K.FAILED_PRECONDITION, Dt);
  10989. return n(o);
  10990. })).next((function(t) {
  10991. return r.vi(o).next((function() {
  10992. return t;
  10993. }));
  10994. })) : r.Oi(o).next((function() {
  10995. return n(o);
  10996. }));
  10997. })).then((function(t) {
  10998. return o.raiseOnCommittedEvent(), t;
  10999. }));
  11000. },
  11001. /**
  11002. * Verifies that the current tab is the primary leaseholder or alternatively
  11003. * that the leaseholder has opted into multi-tab synchronization.
  11004. */
  11005. // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
  11006. // be turned off.
  11007. t.prototype.Oi = function(t) {
  11008. var e = this;
  11009. return Yu(t).get("owner").next((function(t) {
  11010. if (null !== t && e.Vi(t.leaseTimestampMs, 5e3) && !e.Ci(t.ownerId) && !e.Ri(t) && !(e.oi || e.allowTabSynchronization && t.allowTabSynchronization)) throw new Q(K.FAILED_PRECONDITION, Wu);
  11011. }));
  11012. },
  11013. /**
  11014. * Obtains or extends the new primary lease for the local client. This
  11015. * method does not verify that the client is eligible for this lease.
  11016. */
  11017. t.prototype.vi = function(t) {
  11018. var e = {
  11019. ownerId: this.clientId,
  11020. allowTabSynchronization: this.allowTabSynchronization,
  11021. leaseTimestampMs: Date.now()
  11022. };
  11023. return Yu(t).put("owner", e);
  11024. }, t.D = function() {
  11025. return kt.D();
  11026. },
  11027. /** Checks the primary lease and removes it if we are the current primary. */ t.prototype.Ai = function(t) {
  11028. var e = this, n = Yu(t);
  11029. return n.get("owner").next((function(t) {
  11030. return e.Ri(t) ? (M("IndexedDbPersistence", "Releasing primary lease."), n.delete("owner")) : Nt.resolve();
  11031. }));
  11032. },
  11033. /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ t.prototype.Vi = function(t, e) {
  11034. var n = Date.now();
  11035. return !(t < n - e || t > n && (L("Detected an update time that is in the future: ".concat(t, " > ").concat(n)),
  11036. 1));
  11037. }, t.prototype.gi = function() {
  11038. var t = this;
  11039. null !== this.document && "function" == typeof this.document.addEventListener && (this.ai = function() {
  11040. t.ii.enqueueAndForget((function() {
  11041. return t.inForeground = "visible" === t.document.visibilityState, t.mi();
  11042. }));
  11043. }, this.document.addEventListener("visibilitychange", this.ai), this.inForeground = "visible" === this.document.visibilityState);
  11044. }, t.prototype.Ni = function() {
  11045. this.ai && (this.document.removeEventListener("visibilitychange", this.ai), this.ai = null);
  11046. },
  11047. /**
  11048. * Attaches a window.unload handler that will synchronously write our
  11049. * clientId to a "zombie client id" location in LocalStorage. This can be used
  11050. * by tabs trying to acquire the primary lease to determine that the lease
  11051. * is no longer valid even if the timestamp is recent. This is particularly
  11052. * important for the refresh case (so the tab correctly re-acquires the
  11053. * primary lease). LocalStorage is used for this rather than IndexedDb because
  11054. * it is a synchronous API and so can be used reliably from an unload
  11055. * handler.
  11056. */
  11057. t.prototype.yi = function() {
  11058. var t, e = this;
  11059. "function" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.ci = function() {
  11060. // Note: In theory, this should be scheduled on the AsyncQueue since it
  11061. // accesses internal state. We execute this code directly during shutdown
  11062. // to make sure it gets a chance to run.
  11063. e.xi();
  11064. var t = /(?:Version|Mobile)\/1[456]/;
  11065. p() && (navigator.appVersion.match(t) || navigator.userAgent.match(t)) &&
  11066. // On Safari 14, 15, and 16, we do not run any cleanup actions as it might
  11067. // trigger a bug that prevents Safari from re-opening IndexedDB during
  11068. // the next page load.
  11069. // See https://bugs.webkit.org/show_bug.cgi?id=226547
  11070. e.ii.enterRestrictedMode(/* purgeExistingTasks= */ !0), e.ii.enqueueAndForget((function() {
  11071. return e.shutdown();
  11072. }));
  11073. }, this.window.addEventListener("pagehide", this.ci));
  11074. }, t.prototype.ki = function() {
  11075. this.ci && (this.window.removeEventListener("pagehide", this.ci), this.ci = null);
  11076. },
  11077. /**
  11078. * Returns whether a client is "zombied" based on its LocalStorage entry.
  11079. * Clients become zombied when their tab closes without running all of the
  11080. * cleanup logic in `shutdown()`.
  11081. */
  11082. t.prototype.Ci = function(t) {
  11083. var e;
  11084. try {
  11085. var n = null !== (null === (e = this._i) || void 0 === e ? void 0 : e.getItem(this.Di(t)));
  11086. return M("IndexedDbPersistence", "Client '".concat(t, "' ").concat(n ? "is" : "is not", " zombied in LocalStorage")),
  11087. n;
  11088. } catch (t) {
  11089. // Gracefully handle if LocalStorage isn't working.
  11090. return L("IndexedDbPersistence", "Failed to get zombied client id.", t), !1;
  11091. }
  11092. },
  11093. /**
  11094. * Record client as zombied (a client that had its tab closed). Zombied
  11095. * clients are ignored during primary tab selection.
  11096. */
  11097. t.prototype.xi = function() {
  11098. if (this._i) try {
  11099. this._i.setItem(this.Di(this.clientId), String(Date.now()));
  11100. } catch (t) {
  11101. // Gracefully handle if LocalStorage isn't available / working.
  11102. L("Failed to set zombie client id.", t);
  11103. }
  11104. },
  11105. /** Removes the zombied client entry if it exists. */ t.prototype.Mi = function() {
  11106. if (this._i) try {
  11107. this._i.removeItem(this.Di(this.clientId));
  11108. } catch (t) {
  11109. // Ignore
  11110. }
  11111. }, t.prototype.Di = function(t) {
  11112. return "firestore_zombie_".concat(this.persistenceKey, "_").concat(t);
  11113. }, t;
  11114. }();
  11115. /**
  11116. * Oldest acceptable age in milliseconds for client metadata before the client
  11117. * is considered inactive and its associated data is garbage collected.
  11118. */
  11119. /**
  11120. * An IndexedDB-backed instance of Persistence. Data is stored persistently
  11121. * across sessions.
  11122. *
  11123. * On Web only, the Firestore SDKs support shared access to its persistence
  11124. * layer. This allows multiple browser tabs to read and write to IndexedDb and
  11125. * to synchronize state even without network connectivity. Shared access is
  11126. * currently optional and not enabled unless all clients invoke
  11127. * `enablePersistence()` with `{synchronizeTabs:true}`.
  11128. *
  11129. * In multi-tab mode, if multiple clients are active at the same time, the SDK
  11130. * will designate one client as the “primary client”. An effort is made to pick
  11131. * a visible, network-connected and active client, and this client is
  11132. * responsible for letting other clients know about its presence. The primary
  11133. * client writes a unique client-generated identifier (the client ID) to
  11134. * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to
  11135. * update this entry, another client can acquire the lease and take over as
  11136. * primary.
  11137. *
  11138. * Some persistence operations in the SDK are designated as primary-client only
  11139. * operations. This includes the acknowledgment of mutations and all updates of
  11140. * remote documents. The effects of these operations are written to persistence
  11141. * and then broadcast to other tabs via LocalStorage (see
  11142. * `WebStorageSharedClientState`), which then refresh their state from
  11143. * persistence.
  11144. *
  11145. * Similarly, the primary client listens to notifications sent by secondary
  11146. * clients to discover persistence changes written by secondary clients, such as
  11147. * the addition of new mutations and query targets.
  11148. *
  11149. * If multi-tab is not enabled and another tab already obtained the primary
  11150. * lease, IndexedDbPersistence enters a failed state and all subsequent
  11151. * operations will automatically fail.
  11152. *
  11153. * Additionally, there is an optimization so that when a tab is closed, the
  11154. * primary lease is released immediately (this is especially important to make
  11155. * sure that a refreshed tab is able to immediately re-acquire the primary
  11156. * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload
  11157. * since it is an asynchronous API. So in addition to attempting to give up the
  11158. * lease, the leaseholder writes its client ID to a "zombiedClient" entry in
  11159. * LocalStorage which acts as an indicator that another tab should go ahead and
  11160. * take the primary lease immediately regardless of the current lease timestamp.
  11161. *
  11162. * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no
  11163. * longer optional.
  11164. */
  11165. /**
  11166. * Helper to get a typed SimpleDbStore for the primary client object store.
  11167. */
  11168. function Yu(t) {
  11169. return we(t, "owner");
  11170. }
  11171. /**
  11172. * Helper to get a typed SimpleDbStore for the client metadata object store.
  11173. */ function Xu(t) {
  11174. return we(t, "clientMetadata");
  11175. }
  11176. /**
  11177. * Generates a string used as a prefix when storing data in IndexedDB and
  11178. * LocalStorage.
  11179. */ function Ju(t, e) {
  11180. // Use two different prefix formats:
  11181. // * firestore / persistenceKey / projectID . databaseID / ...
  11182. // * firestore / persistenceKey / projectID / ...
  11183. // projectIDs are DNS-compatible names and cannot contain dots
  11184. // so there's no danger of collisions.
  11185. var n = t.projectId;
  11186. return t.isDefaultDatabase || (n += "." + t.database), "firestore/" + e + "/" + n + "/"
  11187. /**
  11188. * @license
  11189. * Copyright 2017 Google LLC
  11190. *
  11191. * Licensed under the Apache License, Version 2.0 (the "License");
  11192. * you may not use this file except in compliance with the License.
  11193. * You may obtain a copy of the License at
  11194. *
  11195. * http://www.apache.org/licenses/LICENSE-2.0
  11196. *
  11197. * Unless required by applicable law or agreed to in writing, software
  11198. * distributed under the License is distributed on an "AS IS" BASIS,
  11199. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11200. * See the License for the specific language governing permissions and
  11201. * limitations under the License.
  11202. */
  11203. /**
  11204. * A set of changes to what documents are currently in view and out of view for
  11205. * a given query. These changes are sent to the LocalStore by the View (via
  11206. * the SyncEngine) and are used to pin / unpin documents as appropriate.
  11207. */;
  11208. }
  11209. var Zu = /** @class */ function() {
  11210. function t(t, e, n, r) {
  11211. this.targetId = t, this.fromCache = e, this.Fi = n, this.Bi = r;
  11212. }
  11213. return t.Li = function(e, n) {
  11214. for (var r = Ir(), i = Ir(), o = 0, u = n.docChanges; o < u.length; o++) {
  11215. var a = u[o];
  11216. switch (a.type) {
  11217. case 0 /* ChangeType.Added */ :
  11218. r = r.add(a.doc.key);
  11219. break;
  11220. case 1 /* ChangeType.Removed */ :
  11221. i = i.add(a.doc.key);
  11222. // do nothing
  11223. }
  11224. }
  11225. return new t(e, n.fromCache, r, i);
  11226. }, t;
  11227. }(), $u = /** @class */ function() {
  11228. function t() {
  11229. this.qi = !1;
  11230. }
  11231. /** Sets the document view to query against. */ return t.prototype.initialize = function(t, e) {
  11232. this.Ui = t, this.indexManager = e, this.qi = !0;
  11233. },
  11234. /** Returns all local documents matching the specified query. */ t.prototype.getDocumentsMatchingQuery = function(t, e, n, r) {
  11235. var i = this;
  11236. return this.Ki(t, e).next((function(o) {
  11237. return o || i.Gi(t, e, r, n);
  11238. })).next((function(n) {
  11239. return n || i.Qi(t, e);
  11240. }));
  11241. },
  11242. /**
  11243. * Performs an indexed query that evaluates the query based on a collection's
  11244. * persisted index values. Returns `null` if an index is not available.
  11245. */
  11246. t.prototype.Ki = function(t, e) {
  11247. var n = this;
  11248. if (Yn(e))
  11249. // Queries that match all documents don't benefit from using
  11250. // key-based lookups. It is more efficient to scan all documents in a
  11251. // collection, rather than to perform individual lookups.
  11252. return Nt.resolve(null);
  11253. var r = tr(e);
  11254. return this.indexManager.getIndexType(t, r).next((function(i) {
  11255. return 0 /* IndexType.NONE */ === i ? null : (null !== e.limit && 1 /* IndexType.PARTIAL */ === i && (
  11256. // We cannot apply a limit for targets that are served using a partial
  11257. // index. If a partial index will be used to serve the target, the
  11258. // query may return a superset of documents that match the target
  11259. // (e.g. if the index doesn't include all the target's filters), or
  11260. // may return the correct set of documents in the wrong order (e.g. if
  11261. // the index doesn't include a segment for one of the orderBys).
  11262. // Therefore, a limit should not be applied in such cases.
  11263. e = nr(e, null, "F" /* LimitType.First */), r = tr(e)), n.indexManager.getDocumentsMatchingTarget(t, r).next((function(i) {
  11264. var o = Ir.apply(void 0, i);
  11265. return n.Ui.getDocuments(t, o).next((function(i) {
  11266. return n.indexManager.getMinOffset(t, r).next((function(r) {
  11267. var u = n.ji(e, i);
  11268. return n.zi(e, u, o, r.readTime) ? n.Ki(t, nr(e, null, "F" /* LimitType.First */)) : n.Wi(t, u, e, r);
  11269. }));
  11270. }));
  11271. })));
  11272. }));
  11273. },
  11274. /**
  11275. * Performs a query based on the target's persisted query mapping. Returns
  11276. * `null` if the mapping is not available or cannot be used.
  11277. */
  11278. t.prototype.Gi = function(t, e, n, r) {
  11279. var i = this;
  11280. return Yn(e) || r.isEqual(ct.min()) ? this.Qi(t, e) : this.Ui.getDocuments(t, n).next((function(o) {
  11281. var u = i.ji(e, o);
  11282. return i.zi(e, u, n, r) ? i.Qi(t, e) : (R() <= h.DEBUG && M("QueryEngine", "Re-using previous result from %s to execute query: %s", r.toString(), or(e)),
  11283. i.Wi(t, u, e, Et(r, -1)));
  11284. }));
  11285. // Queries that have never seen a snapshot without limbo free documents
  11286. // should also be run as a full collection scan.
  11287. },
  11288. /** Applies the query filter and sorting to the provided documents. */ t.prototype.ji = function(t, e) {
  11289. // Sort the documents and re-apply the query filter since previously
  11290. // matching documents do not necessarily still match the query.
  11291. var n = new De(sr(t));
  11292. return e.forEach((function(e, r) {
  11293. ur(t, r) && (n = n.add(r));
  11294. })), n;
  11295. },
  11296. /**
  11297. * Determines if a limit query needs to be refilled from cache, making it
  11298. * ineligible for index-free execution.
  11299. *
  11300. * @param query - The query.
  11301. * @param sortedPreviousResults - The documents that matched the query when it
  11302. * was last synchronized, sorted by the query's comparator.
  11303. * @param remoteKeys - The document keys that matched the query at the last
  11304. * snapshot.
  11305. * @param limboFreeSnapshotVersion - The version of the snapshot when the
  11306. * query was last synchronized.
  11307. */
  11308. t.prototype.zi = function(t, e, n, r) {
  11309. if (null === t.limit)
  11310. // Queries without limits do not need to be refilled.
  11311. return !1;
  11312. if (n.size !== e.size)
  11313. // The query needs to be refilled if a previously matching document no
  11314. // longer matches.
  11315. return !0;
  11316. // Limit queries are not eligible for index-free query execution if there is
  11317. // a potential that an older document from cache now sorts before a document
  11318. // that was previously part of the limit. This, however, can only happen if
  11319. // the document at the edge of the limit goes out of limit.
  11320. // If a document that is not the limit boundary sorts differently,
  11321. // the boundary of the limit itself did not change and documents from cache
  11322. // will continue to be "rejected" by this boundary. Therefore, we can ignore
  11323. // any modifications that don't affect the last document.
  11324. var i = "F" /* LimitType.First */ === t.limitType ? e.last() : e.first();
  11325. return !!i && (i.hasPendingWrites || i.version.compareTo(r) > 0);
  11326. }, t.prototype.Qi = function(t, e) {
  11327. return R() <= h.DEBUG && M("QueryEngine", "Using full collection scan to execute query:", or(e)),
  11328. this.Ui.getDocumentsMatchingQuery(t, e, St.min());
  11329. },
  11330. /**
  11331. * Combines the results from an indexed execution with the remaining documents
  11332. * that have not yet been indexed.
  11333. */
  11334. t.prototype.Wi = function(t, e, n, r) {
  11335. // Retrieve all results for documents that were updated since the offset.
  11336. return this.Ui.getDocumentsMatchingQuery(t, n, r).next((function(t) {
  11337. // Merge with existing results
  11338. return e.forEach((function(e) {
  11339. t = t.insert(e.key, e);
  11340. })), t;
  11341. }));
  11342. }, t;
  11343. }(), ta = /** @class */ function() {
  11344. function t(
  11345. /** Manages our in-memory or durable persistence. */
  11346. t, e, n, r) {
  11347. this.persistence = t, this.Hi = e, this.serializer = r,
  11348. /**
  11349. * Maps a targetID to data about its target.
  11350. *
  11351. * PORTING NOTE: We are using an immutable data structure on Web to make re-runs
  11352. * of `applyRemoteEvent()` idempotent.
  11353. */
  11354. this.Ji = new Te(ot),
  11355. /** Maps a target to its targetID. */
  11356. // TODO(wuandy): Evaluate if TargetId can be part of Target.
  11357. this.Yi = new lr((function(t) {
  11358. return Bn(t);
  11359. }), Un),
  11360. /**
  11361. * A per collection group index of the last read time processed by
  11362. * `getNewDocumentChanges()`.
  11363. *
  11364. * PORTING NOTE: This is only used for multi-tab synchronization.
  11365. */
  11366. this.Xi = new Map, this.Zi = t.getRemoteDocumentCache(), this.Bs = t.getTargetCache(),
  11367. this.qs = t.getBundleCache(), this.tr(n);
  11368. }
  11369. return t.prototype.tr = function(t) {
  11370. // TODO(indexing): Add spec tests that test these components change after a
  11371. // user change
  11372. this.documentOverlayCache = this.persistence.getDocumentOverlayCache(t), this.indexManager = this.persistence.getIndexManager(t),
  11373. this.mutationQueue = this.persistence.getMutationQueue(t, this.indexManager), this.localDocuments = new Ou(this.Zi, this.mutationQueue, this.documentOverlayCache, this.indexManager),
  11374. this.Zi.setIndexManager(this.indexManager), this.Hi.initialize(this.localDocuments, this.indexManager);
  11375. }, t.prototype.collectGarbage = function(t) {
  11376. var e = this;
  11377. return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (function(n) {
  11378. return t.collect(n, e.Ji);
  11379. }));
  11380. }, t;
  11381. }();
  11382. /**
  11383. * @license
  11384. * Copyright 2019 Google LLC
  11385. *
  11386. * Licensed under the Apache License, Version 2.0 (the "License");
  11387. * you may not use this file except in compliance with the License.
  11388. * You may obtain a copy of the License at
  11389. *
  11390. * http://www.apache.org/licenses/LICENSE-2.0
  11391. *
  11392. * Unless required by applicable law or agreed to in writing, software
  11393. * distributed under the License is distributed on an "AS IS" BASIS,
  11394. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11395. * See the License for the specific language governing permissions and
  11396. * limitations under the License.
  11397. */
  11398. /**
  11399. * The Firestore query engine.
  11400. *
  11401. * Firestore queries can be executed in three modes. The Query Engine determines
  11402. * what mode to use based on what data is persisted. The mode only determines
  11403. * the runtime complexity of the query - the result set is equivalent across all
  11404. * implementations.
  11405. *
  11406. * The Query engine will use indexed-based execution if a user has configured
  11407. * any index that can be used to execute query (via `setIndexConfiguration()`).
  11408. * Otherwise, the engine will try to optimize the query by re-using a previously
  11409. * persisted query result. If that is not possible, the query will be executed
  11410. * via a full collection scan.
  11411. *
  11412. * Index-based execution is the default when available. The query engine
  11413. * supports partial indexed execution and merges the result from the index
  11414. * lookup with documents that have not yet been indexed. The index evaluation
  11415. * matches the backend's format and as such, the SDK can use indexing for all
  11416. * queries that the backend supports.
  11417. *
  11418. * If no index exists, the query engine tries to take advantage of the target
  11419. * document mapping in the TargetCache. These mappings exists for all queries
  11420. * that have been synced with the backend at least once and allow the query
  11421. * engine to only read documents that previously matched a query plus any
  11422. * documents that were edited after the query was last listened to.
  11423. *
  11424. * There are some cases when this optimization is not guaranteed to produce
  11425. * the same results as full collection scans. In these cases, query
  11426. * processing falls back to full scans. These cases are:
  11427. *
  11428. * - Limit queries where a document that matched the query previously no longer
  11429. * matches the query.
  11430. *
  11431. * - Limit queries where a document edit may cause the document to sort below
  11432. * another document that is in the local cache.
  11433. *
  11434. * - Queries that have never been CURRENT or free of limbo documents.
  11435. */ function ea(
  11436. /** Manages our in-memory or durable persistence. */
  11437. t, e, n, r) {
  11438. return new ta(t, e, n, r);
  11439. }
  11440. /**
  11441. * Tells the LocalStore that the currently authenticated user has changed.
  11442. *
  11443. * In response the local store switches the mutation queue to the new user and
  11444. * returns any resulting document changes.
  11445. */
  11446. // PORTING NOTE: Android and iOS only return the documents affected by the
  11447. // change.
  11448. function na(t, r) {
  11449. return e(this, void 0, void 0, (function() {
  11450. var e;
  11451. return n(this, (function(n) {
  11452. switch (n.label) {
  11453. case 0:
  11454. return [ 4 /*yield*/ , (e = j(t)).persistence.runTransaction("Handle user change", "readonly", (function(t) {
  11455. // Swap out the mutation queue, grabbing the pending mutation batches
  11456. // before and after.
  11457. var n;
  11458. return e.mutationQueue.getAllMutationBatches(t).next((function(i) {
  11459. return n = i, e.tr(r), e.mutationQueue.getAllMutationBatches(t);
  11460. })).next((function(r) {
  11461. for (var i = [], o = [], u = Ir(), a = 0, s = n
  11462. // Union the old/new changed keys.
  11463. ; a < s.length; a++) {
  11464. var c = s[a];
  11465. i.push(c.batchId);
  11466. for (var l = 0, h = c.mutations; l < h.length; l++) {
  11467. var f = h[l];
  11468. u = u.add(f.key);
  11469. }
  11470. }
  11471. for (var d = 0, p = r; d < p.length; d++) {
  11472. var v = p[d];
  11473. o.push(v.batchId);
  11474. for (var m = 0, y = v.mutations; m < y.length; m++) {
  11475. var g = y[m];
  11476. u = u.add(g.key);
  11477. }
  11478. }
  11479. // Return the set of all (potentially) changed documents and the list
  11480. // of mutation batch IDs that were affected by change.
  11481. return e.localDocuments.getDocuments(t, u).next((function(t) {
  11482. return {
  11483. er: t,
  11484. removedBatchIds: i,
  11485. addedBatchIds: o
  11486. };
  11487. }));
  11488. }));
  11489. })) ];
  11490. case 1:
  11491. return [ 2 /*return*/ , n.sent() ];
  11492. }
  11493. }));
  11494. }));
  11495. }
  11496. /* Accepts locally generated Mutations and commit them to storage. */
  11497. /**
  11498. * Acknowledges the given batch.
  11499. *
  11500. * On the happy path when a batch is acknowledged, the local store will
  11501. *
  11502. * + remove the batch from the mutation queue;
  11503. * + apply the changes to the remote document cache;
  11504. * + recalculate the latency compensated view implied by those changes (there
  11505. * may be mutations in the queue that affect the documents but haven't been
  11506. * acknowledged yet); and
  11507. * + give the changed documents back the sync engine
  11508. *
  11509. * @returns The resulting (modified) documents.
  11510. */ function ra(t, e) {
  11511. var n = j(t);
  11512. return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (function(t) {
  11513. var r = e.batch.keys(), i = n.Zi.newChangeBuffer({
  11514. trackRemovals: !0
  11515. });
  11516. return function(t, e, n, r) {
  11517. var i = n.batch, o = i.keys(), u = Nt.resolve();
  11518. return o.forEach((function(t) {
  11519. u = u.next((function() {
  11520. return r.getEntry(e, t);
  11521. })).next((function(e) {
  11522. var o = n.docVersions.get(t);
  11523. z(null !== o), e.version.compareTo(o) < 0 && (i.applyToRemoteDocument(e, n), e.isValidDocument() && (
  11524. // We use the commitVersion as the readTime rather than the
  11525. // document's updateTime since the updateTime is not advanced
  11526. // for updates that do not modify the underlying document.
  11527. e.setReadTime(n.commitVersion), r.addEntry(e)));
  11528. }));
  11529. })), u.next((function() {
  11530. return t.mutationQueue.removeMutationBatch(e, i);
  11531. }));
  11532. }(n, t, e, i).next((function() {
  11533. return i.apply(t);
  11534. })).next((function() {
  11535. return n.mutationQueue.performConsistencyCheck(t);
  11536. })).next((function() {
  11537. return n.documentOverlayCache.removeOverlaysForBatchId(t, r, e.batch.batchId);
  11538. })).next((function() {
  11539. return n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, function(t) {
  11540. for (var e = Ir(), n = 0; n < t.mutationResults.length; ++n) t.mutationResults[n].transformResults.length > 0 && (e = e.add(t.batch.mutations[n].key));
  11541. return e;
  11542. }(e));
  11543. })).next((function() {
  11544. return n.localDocuments.getDocuments(t, r);
  11545. }));
  11546. }));
  11547. }
  11548. /**
  11549. * Returns the last consistent snapshot processed (used by the RemoteStore to
  11550. * determine whether to buffer incoming snapshots from the backend).
  11551. */ function ia(t) {
  11552. var e = j(t);
  11553. return e.persistence.runTransaction("Get last remote snapshot version", "readonly", (function(t) {
  11554. return e.Bs.getLastRemoteSnapshotVersion(t);
  11555. }));
  11556. }
  11557. /**
  11558. * Updates the "ground-state" (remote) documents. We assume that the remote
  11559. * event reflects any write batches that have been acknowledged or rejected
  11560. * (i.e. we do not re-apply local mutations to updates from this event).
  11561. *
  11562. * LocalDocuments are re-calculated if there are remaining mutations in the
  11563. * queue.
  11564. */ function oa(t, e) {
  11565. var n = j(t), r = e.snapshotVersion, i = n.Ji;
  11566. return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (function(t) {
  11567. var o = n.Zi.newChangeBuffer({
  11568. trackRemovals: !0
  11569. });
  11570. // Reset newTargetDataByTargetMap in case this transaction gets re-run.
  11571. i = n.Ji;
  11572. var u = [];
  11573. e.targetChanges.forEach((function(o, a) {
  11574. var s = i.get(a);
  11575. if (s) {
  11576. // Only update the remote keys if the target is still active. This
  11577. // ensures that we can persist the updated target data along with
  11578. // the updated assignment.
  11579. u.push(n.Bs.removeMatchingKeys(t, o.removedDocuments, a).next((function() {
  11580. return n.Bs.addMatchingKeys(t, o.addedDocuments, a);
  11581. })));
  11582. var c = s.withSequenceNumber(t.currentSequenceNumber);
  11583. null !== e.targetMismatches.get(a) ? c = c.withResumeToken(Oe.EMPTY_BYTE_STRING, ct.min()).withLastLimboFreeSnapshotVersion(ct.min()) : o.resumeToken.approximateByteSize() > 0 && (c = c.withResumeToken(o.resumeToken, r)),
  11584. i = i.insert(a, c),
  11585. // Update the target data if there are target changes (or if
  11586. // sufficient time has passed since the last update).
  11587. /**
  11588. * Returns true if the newTargetData should be persisted during an update of
  11589. * an active target. TargetData should always be persisted when a target is
  11590. * being released and should not call this function.
  11591. *
  11592. * While the target is active, TargetData updates can be omitted when nothing
  11593. * about the target has changed except metadata like the resume token or
  11594. * snapshot version. Occasionally it's worth the extra write to prevent these
  11595. * values from getting too stale after a crash, but this doesn't have to be
  11596. * too frequent.
  11597. */
  11598. function(t, e, n) {
  11599. // Always persist target data if we don't already have a resume token.
  11600. return 0 === t.resumeToken.approximateByteSize() || (
  11601. // Don't allow resume token changes to be buffered indefinitely. This
  11602. // allows us to be reasonably up-to-date after a crash and avoids needing
  11603. // to loop over all active queries on shutdown. Especially in the browser
  11604. // we may not get time to do anything interesting while the current tab is
  11605. // closing.
  11606. e.snapshotVersion.toMicroseconds() - t.snapshotVersion.toMicroseconds() >= 3e8 || n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0);
  11607. }(s, c, o) && u.push(n.Bs.updateTargetData(t, c));
  11608. }
  11609. }));
  11610. var a = fr(), s = Ir();
  11611. // HACK: The only reason we allow a null snapshot version is so that we
  11612. // can synthesize remote events when we get permission denied errors while
  11613. // trying to resolve the state of a locally cached document that is in
  11614. // limbo.
  11615. if (e.documentUpdates.forEach((function(r) {
  11616. e.resolvedLimboDocuments.has(r) && u.push(n.persistence.referenceDelegate.updateLimboDocument(t, r));
  11617. })),
  11618. // Each loop iteration only affects its "own" doc, so it's safe to get all
  11619. // the remote documents in advance in a single call.
  11620. u.push(ua(t, o, e.documentUpdates).next((function(t) {
  11621. a = t.nr, s = t.sr;
  11622. }))), !r.isEqual(ct.min())) {
  11623. var c = n.Bs.getLastRemoteSnapshotVersion(t).next((function(e) {
  11624. return n.Bs.setTargetsMetadata(t, t.currentSequenceNumber, r);
  11625. }));
  11626. u.push(c);
  11627. }
  11628. return Nt.waitFor(u).next((function() {
  11629. return o.apply(t);
  11630. })).next((function() {
  11631. return n.localDocuments.getLocalViewOfDocuments(t, a, s);
  11632. })).next((function() {
  11633. return a;
  11634. }));
  11635. })).then((function(t) {
  11636. return n.Ji = i, t;
  11637. }));
  11638. }
  11639. /**
  11640. * Populates document change buffer with documents from backend or a bundle.
  11641. * Returns the document changes resulting from applying those documents, and
  11642. * also a set of documents whose existence state are changed as a result.
  11643. *
  11644. * @param txn - Transaction to use to read existing documents from storage.
  11645. * @param documentBuffer - Document buffer to collect the resulted changes to be
  11646. * applied to storage.
  11647. * @param documents - Documents to be applied.
  11648. */ function ua(t, e, n) {
  11649. var r = Ir(), i = Ir();
  11650. return n.forEach((function(t) {
  11651. return r = r.add(t);
  11652. })), e.getEntries(t, r).next((function(t) {
  11653. var r = fr();
  11654. return n.forEach((function(n, o) {
  11655. var u = t.get(n);
  11656. // Check if see if there is a existence state change for this document.
  11657. o.isFoundDocument() !== u.isFoundDocument() && (i = i.add(n)),
  11658. // Note: The order of the steps below is important, since we want
  11659. // to ensure that rejected limbo resolutions (which fabricate
  11660. // NoDocuments with SnapshotVersion.min()) never add documents to
  11661. // cache.
  11662. o.isNoDocument() && o.version.isEqual(ct.min()) ? (
  11663. // NoDocuments with SnapshotVersion.min() are used in manufactured
  11664. // events. We remove these documents from cache since we lost
  11665. // access.
  11666. e.removeEntry(n, o.readTime), r = r.insert(n, o)) : !u.isValidDocument() || o.version.compareTo(u.version) > 0 || 0 === o.version.compareTo(u.version) && u.hasPendingWrites ? (e.addEntry(o),
  11667. r = r.insert(n, o)) : M("LocalStore", "Ignoring outdated watch update for ", n, ". Current version:", u.version, " Watch version:", o.version);
  11668. })), {
  11669. nr: r,
  11670. sr: i
  11671. };
  11672. }))
  11673. /**
  11674. * Gets the mutation batch after the passed in batchId in the mutation queue
  11675. * or null if empty.
  11676. * @param afterBatchId - If provided, the batch to search after.
  11677. * @returns The next mutation or null if there wasn't one.
  11678. */;
  11679. }
  11680. function aa(t, e) {
  11681. var n = j(t);
  11682. return n.persistence.runTransaction("Get next mutation batch", "readonly", (function(t) {
  11683. return void 0 === e && (e = -1), n.mutationQueue.getNextMutationBatchAfterBatchId(t, e);
  11684. }));
  11685. }
  11686. /**
  11687. * Reads the current value of a Document with a given key or null if not
  11688. * found - used for testing.
  11689. */
  11690. /**
  11691. * Assigns the given target an internal ID so that its results can be pinned so
  11692. * they don't get GC'd. A target must be allocated in the local store before
  11693. * the store can be used to manage its view.
  11694. *
  11695. * Allocating an already allocated `Target` will return the existing `TargetData`
  11696. * for that `Target`.
  11697. */ function sa(t, e) {
  11698. var n = j(t);
  11699. return n.persistence.runTransaction("Allocate target", "readwrite", (function(t) {
  11700. var r;
  11701. return n.Bs.getTargetData(t, e).next((function(i) {
  11702. return i ? (
  11703. // This target has been listened to previously, so reuse the
  11704. // previous targetID.
  11705. // TODO(mcg): freshen last accessed date?
  11706. r = i, Nt.resolve(r)) : n.Bs.allocateTargetId(t).next((function(i) {
  11707. return r = new ao(e, i, "TargetPurposeListen" /* TargetPurpose.Listen */ , t.currentSequenceNumber),
  11708. n.Bs.addTargetData(t, r).next((function() {
  11709. return r;
  11710. }));
  11711. }));
  11712. }));
  11713. })).then((function(t) {
  11714. // If Multi-Tab is enabled, the existing target data may be newer than
  11715. // the in-memory data
  11716. var r = n.Ji.get(t.targetId);
  11717. return (null === r || t.snapshotVersion.compareTo(r.snapshotVersion) > 0) && (n.Ji = n.Ji.insert(t.targetId, t),
  11718. n.Yi.set(e, t.targetId)), t;
  11719. }));
  11720. }
  11721. /**
  11722. * Returns the TargetData as seen by the LocalStore, including updates that may
  11723. * have not yet been persisted to the TargetCache.
  11724. */
  11725. // Visible for testing.
  11726. /**
  11727. * Unpins all the documents associated with the given target. If
  11728. * `keepPersistedTargetData` is set to false and Eager GC enabled, the method
  11729. * directly removes the associated target data from the target cache.
  11730. *
  11731. * Releasing a non-existing `Target` is a no-op.
  11732. */
  11733. // PORTING NOTE: `keepPersistedTargetData` is multi-tab only.
  11734. function ca(t, r, i) {
  11735. return e(this, void 0, void 0, (function() {
  11736. var e, o, u, a;
  11737. return n(this, (function(n) {
  11738. switch (n.label) {
  11739. case 0:
  11740. e = j(t), o = e.Ji.get(r), u = i ? "readwrite" : "readwrite-primary", n.label = 1;
  11741. case 1:
  11742. return n.trys.push([ 1, 4, , 5 ]), i ? [ 3 /*break*/ , 3 ] : [ 4 /*yield*/ , e.persistence.runTransaction("Release target", u, (function(t) {
  11743. return e.persistence.referenceDelegate.removeTarget(t, o);
  11744. })) ];
  11745. case 2:
  11746. n.sent(), n.label = 3;
  11747. case 3:
  11748. return [ 3 /*break*/ , 5 ];
  11749. case 4:
  11750. if (!Pt(a = n.sent())) throw a;
  11751. // All `releaseTarget` does is record the final metadata state for the
  11752. // target, but we've been recording this periodically during target
  11753. // activity. If we lose this write this could cause a very slight
  11754. // difference in the order of target deletion during GC, but we
  11755. // don't define exact LRU semantics so this is acceptable.
  11756. return M("LocalStore", "Failed to update sequence numbers for target ".concat(r, ": ").concat(a)),
  11757. [ 3 /*break*/ , 5 ];
  11758. case 5:
  11759. return e.Ji = e.Ji.remove(r), e.Yi.delete(o.target), [ 2 /*return*/ ];
  11760. }
  11761. }));
  11762. }));
  11763. }
  11764. /**
  11765. * Runs the specified query against the local store and returns the results,
  11766. * potentially taking advantage of query data from previous executions (such
  11767. * as the set of remote keys).
  11768. *
  11769. * @param usePreviousResults - Whether results from previous executions can
  11770. * be used to optimize this query execution.
  11771. */ function la(t, e, n) {
  11772. var r = j(t), i = ct.min(), o = Ir();
  11773. return r.persistence.runTransaction("Execute query", "readonly", (function(t) {
  11774. return function(t, e, n) {
  11775. var r = j(t), i = r.Yi.get(n);
  11776. return void 0 !== i ? Nt.resolve(r.Ji.get(i)) : r.Bs.getTargetData(e, n);
  11777. }(r, t, tr(e)).next((function(e) {
  11778. if (e) return i = e.lastLimboFreeSnapshotVersion, r.Bs.getMatchingKeysForTargetId(t, e.targetId).next((function(t) {
  11779. o = t;
  11780. }));
  11781. })).next((function() {
  11782. return r.Hi.getDocumentsMatchingQuery(t, e, n ? i : ct.min(), n ? o : Ir());
  11783. })).next((function(t) {
  11784. return da(r, ar(e), t), {
  11785. documents: t,
  11786. ir: o
  11787. };
  11788. }));
  11789. }));
  11790. }
  11791. // PORTING NOTE: Multi-Tab only.
  11792. function ha(t, e) {
  11793. var n = j(t), r = j(n.Bs), i = n.Ji.get(e);
  11794. return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (function(t) {
  11795. return r.le(t, e).next((function(t) {
  11796. return t ? t.target : null;
  11797. }));
  11798. }));
  11799. }
  11800. /**
  11801. * Returns the set of documents that have been updated since the last call.
  11802. * If this is the first call, returns the set of changes since client
  11803. * initialization. Further invocations will return document that have changed
  11804. * since the prior call.
  11805. */
  11806. // PORTING NOTE: Multi-Tab only.
  11807. function fa(t, e) {
  11808. var n = j(t), r = n.Xi.get(e) || ct.min();
  11809. // Get the current maximum read time for the collection. This should always
  11810. // exist, but to reduce the chance for regressions we default to
  11811. // SnapshotVersion.Min()
  11812. // TODO(indexing): Consider removing the default value.
  11813. return n.persistence.runTransaction("Get new document changes", "readonly", (function(t) {
  11814. return n.Zi.getAllFromCollectionGroup(t, e, Et(r, -1),
  11815. /* limit= */ Number.MAX_SAFE_INTEGER);
  11816. })).then((function(t) {
  11817. return da(n, e, t), t;
  11818. }));
  11819. }
  11820. /** Sets the collection group's maximum read time from the given documents. */
  11821. // PORTING NOTE: Multi-Tab only.
  11822. function da(t, e, n) {
  11823. var r = t.Xi.get(e) || ct.min();
  11824. n.forEach((function(t, e) {
  11825. e.readTime.compareTo(r) > 0 && (r = e.readTime);
  11826. })), t.Xi.set(e, r);
  11827. }
  11828. /**
  11829. * Creates a new target using the given bundle name, which will be used to
  11830. * hold the keys of all documents from the bundle in query-document mappings.
  11831. * This ensures that the loaded documents do not get garbage collected
  11832. * right away.
  11833. */
  11834. /**
  11835. * Applies the documents from a bundle to the "ground-state" (remote)
  11836. * documents.
  11837. *
  11838. * LocalDocuments are re-calculated if there are remaining mutations in the
  11839. * queue.
  11840. */ function pa(t, r, i, o) {
  11841. return e(this, void 0, void 0, (function() {
  11842. var e, u, a, s, c, l, h, f, d, p;
  11843. return n(this, (function(n) {
  11844. switch (n.label) {
  11845. case 0:
  11846. for (e = j(t), u = Ir(), a = fr(), s = 0, c = i; s < c.length; s++) l = c[s], h = r.rr(l.metadata.name),
  11847. l.document && (u = u.add(h)), (f = r.ur(l)).setReadTime(r.cr(l.metadata.readTime)),
  11848. a = a.insert(h, f);
  11849. return d = e.Zi.newChangeBuffer({
  11850. trackRemovals: !0
  11851. }), [ 4 /*yield*/ , sa(e, function(t) {
  11852. // It is OK that the path used for the query is not valid, because this will
  11853. // not be read and queried.
  11854. return tr(Hn(ht.fromString("__bundle__/docs/".concat(t))));
  11855. }(o)) ];
  11856. case 1:
  11857. // Allocates a target to hold all document keys from the bundle, such that
  11858. // they will not get garbage collected right away.
  11859. return p = n.sent(), [ 2 /*return*/ , e.persistence.runTransaction("Apply bundle documents", "readwrite", (function(t) {
  11860. return ua(t, d, a).next((function(e) {
  11861. return d.apply(t), e;
  11862. })).next((function(n) {
  11863. return e.Bs.removeMatchingKeysForTargetId(t, p.targetId).next((function() {
  11864. return e.Bs.addMatchingKeys(t, u, p.targetId);
  11865. })).next((function() {
  11866. return e.localDocuments.getLocalViewOfDocuments(t, n.nr, n.sr);
  11867. })).next((function() {
  11868. return n.nr;
  11869. }));
  11870. }));
  11871. })) ];
  11872. }
  11873. }));
  11874. }));
  11875. }
  11876. /**
  11877. * Returns a promise of a boolean to indicate if the given bundle has already
  11878. * been loaded and the create time is newer than the current loading bundle.
  11879. */
  11880. /**
  11881. * Saves the given `NamedQuery` to local persistence.
  11882. */ function va(t, r, i) {
  11883. return void 0 === i && (i = Ir()), e(this, void 0, void 0, (function() {
  11884. var e, o;
  11885. return n(this, (function(n) {
  11886. switch (n.label) {
  11887. case 0:
  11888. return [ 4 /*yield*/ , sa(t, tr(yo(r.bundledQuery))) ];
  11889. case 1:
  11890. return e = n.sent(), [ 2 /*return*/ , (o = j(t)).persistence.runTransaction("Save named query", "readwrite", (function(t) {
  11891. var n = Vi(r.readTime);
  11892. // Simply save the query itself if it is older than what the SDK already
  11893. // has.
  11894. if (e.snapshotVersion.compareTo(n) >= 0) return o.qs.saveNamedQuery(t, r);
  11895. // Update existing target data because the query from the bundle is newer.
  11896. var u = e.withResumeToken(Oe.EMPTY_BYTE_STRING, n);
  11897. return o.Ji = o.Ji.insert(u.targetId, u), o.Bs.updateTargetData(t, u).next((function() {
  11898. return o.Bs.removeMatchingKeysForTargetId(t, e.targetId);
  11899. })).next((function() {
  11900. return o.Bs.addMatchingKeys(t, i, e.targetId);
  11901. })).next((function() {
  11902. return o.qs.saveNamedQuery(t, r);
  11903. }));
  11904. })) ];
  11905. }
  11906. }));
  11907. }));
  11908. }
  11909. /** Assembles the key for a client state in WebStorage */ function ma(t, e) {
  11910. return "firestore_clients_".concat(t, "_").concat(e);
  11911. }
  11912. // The format of the WebStorage key that stores the mutation state is:
  11913. // firestore_mutations_<persistence_prefix>_<batch_id>
  11914. // (for unauthenticated users)
  11915. // or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>
  11916. // 'user_uid' is last to avoid needing to escape '_' characters that it might
  11917. // contain.
  11918. /** Assembles the key for a mutation batch in WebStorage */ function ya(t, e, n) {
  11919. var r = "firestore_mutations_".concat(t, "_").concat(n);
  11920. return e.isAuthenticated() && (r += "_".concat(e.uid)), r;
  11921. }
  11922. // The format of the WebStorage key that stores a query target's metadata is:
  11923. // firestore_targets_<persistence_prefix>_<target_id>
  11924. /** Assembles the key for a query state in WebStorage */ function ga(t, e) {
  11925. return "firestore_targets_".concat(t, "_").concat(e);
  11926. }
  11927. // The WebStorage prefix that stores the primary tab's online state. The
  11928. // format of the key is:
  11929. // firestore_online_state_<persistence_prefix>
  11930. /**
  11931. * Holds the state of a mutation batch, including its user ID, batch ID and
  11932. * whether the batch is 'pending', 'acknowledged' or 'rejected'.
  11933. */
  11934. // Visible for testing
  11935. var wa = /** @class */ function() {
  11936. function t(t, e, n, r) {
  11937. this.user = t, this.batchId = e, this.state = n, this.error = r
  11938. /**
  11939. * Parses a MutationMetadata from its JSON representation in WebStorage.
  11940. * Logs a warning and returns null if the format of the data is not valid.
  11941. */;
  11942. }
  11943. return t.ar = function(e, n, r) {
  11944. var i, o = JSON.parse(r), u = "object" == typeof o && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(o.state) && (void 0 === o.error || "object" == typeof o.error);
  11945. return u && o.error && ((u = "string" == typeof o.error.message && "string" == typeof o.error.code) && (i = new Q(o.error.code, o.error.message))),
  11946. u ? new t(e, n, o.state, i) : (L("SharedClientState", "Failed to parse mutation state for ID '".concat(n, "': ").concat(r)),
  11947. null);
  11948. }, t.prototype.hr = function() {
  11949. var t = {
  11950. state: this.state,
  11951. updateTimeMs: Date.now()
  11952. };
  11953. return this.error && (t.error = {
  11954. code: this.error.code,
  11955. message: this.error.message
  11956. }), JSON.stringify(t);
  11957. }, t;
  11958. }(), ba = /** @class */ function() {
  11959. function t(t, e, n) {
  11960. this.targetId = t, this.state = e, this.error = n
  11961. /**
  11962. * Parses a QueryTargetMetadata from its JSON representation in WebStorage.
  11963. * Logs a warning and returns null if the format of the data is not valid.
  11964. */;
  11965. }
  11966. return t.ar = function(e, n) {
  11967. var r, i = JSON.parse(n), o = "object" == typeof i && -1 !== [ "not-current", "current", "rejected" ].indexOf(i.state) && (void 0 === i.error || "object" == typeof i.error);
  11968. return o && i.error && ((o = "string" == typeof i.error.message && "string" == typeof i.error.code) && (r = new Q(i.error.code, i.error.message))),
  11969. o ? new t(e, i.state, r) : (L("SharedClientState", "Failed to parse target state for ID '".concat(e, "': ").concat(n)),
  11970. null);
  11971. }, t.prototype.hr = function() {
  11972. var t = {
  11973. state: this.state,
  11974. updateTimeMs: Date.now()
  11975. };
  11976. return this.error && (t.error = {
  11977. code: this.error.code,
  11978. message: this.error.message
  11979. }), JSON.stringify(t);
  11980. }, t;
  11981. }(), Ia = /** @class */ function() {
  11982. function t(t, e) {
  11983. this.clientId = t, this.activeTargetIds = e
  11984. /**
  11985. * Parses a RemoteClientState from the JSON representation in WebStorage.
  11986. * Logs a warning and returns null if the format of the data is not valid.
  11987. */;
  11988. }
  11989. return t.ar = function(e, n) {
  11990. for (var r = JSON.parse(n), i = "object" == typeof r && r.activeTargetIds instanceof Array, o = Tr(), u = 0; i && u < r.activeTargetIds.length; ++u) i = jt(r.activeTargetIds[u]),
  11991. o = o.add(r.activeTargetIds[u]);
  11992. return i ? new t(e, o) : (L("SharedClientState", "Failed to parse client data for instance '".concat(e, "': ").concat(n)),
  11993. null);
  11994. }, t;
  11995. }(), Ea = /** @class */ function() {
  11996. function t(t, e) {
  11997. this.clientId = t, this.onlineState = e
  11998. /**
  11999. * Parses a SharedOnlineState from its JSON representation in WebStorage.
  12000. * Logs a warning and returns null if the format of the data is not valid.
  12001. */;
  12002. }
  12003. return t.ar = function(e) {
  12004. var n = JSON.parse(e);
  12005. return "object" == typeof n && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(n.onlineState) && "string" == typeof n.clientId ? new t(n.clientId, n.onlineState) : (L("SharedClientState", "Failed to parse online state: ".concat(e)),
  12006. null);
  12007. }, t;
  12008. }(), Ta = /** @class */ function() {
  12009. function t() {
  12010. this.activeTargetIds = Tr();
  12011. }
  12012. return t.prototype.lr = function(t) {
  12013. this.activeTargetIds = this.activeTargetIds.add(t);
  12014. }, t.prototype.dr = function(t) {
  12015. this.activeTargetIds = this.activeTargetIds.delete(t);
  12016. },
  12017. /**
  12018. * Converts this entry into a JSON-encoded format we can use for WebStorage.
  12019. * Does not encode `clientId` as it is part of the key in WebStorage.
  12020. */
  12021. t.prototype.hr = function() {
  12022. var t = {
  12023. activeTargetIds: this.activeTargetIds.toArray(),
  12024. updateTimeMs: Date.now()
  12025. };
  12026. return JSON.stringify(t);
  12027. }, t;
  12028. }(), Sa = /** @class */ function() {
  12029. function t(t, e, n, r, i) {
  12030. this.window = t, this.ii = e, this.persistenceKey = n, this.wr = r, this.syncEngine = null,
  12031. this.onlineStateHandler = null, this.sequenceNumberHandler = null, this._r = this.mr.bind(this),
  12032. this.gr = new Te(ot), this.started = !1,
  12033. /**
  12034. * Captures WebStorage events that occur before `start()` is called. These
  12035. * events are replayed once `WebStorageSharedClientState` is started.
  12036. */
  12037. this.yr = [];
  12038. // Escape the special characters mentioned here:
  12039. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
  12040. var o = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  12041. this.storage = this.window.localStorage, this.currentUser = i, this.pr = ma(this.persistenceKey, this.wr),
  12042. this.Ir =
  12043. /** Assembles the key for the current sequence number. */
  12044. function(t) {
  12045. return "firestore_sequence_number_".concat(t);
  12046. }(this.persistenceKey), this.gr = this.gr.insert(this.wr, new Ta), this.Tr = new RegExp("^firestore_clients_".concat(o, "_([^_]*)$")),
  12047. this.Er = new RegExp("^firestore_mutations_".concat(o, "_(\\d+)(?:_(.*))?$")), this.Ar = new RegExp("^firestore_targets_".concat(o, "_(\\d+)$")),
  12048. this.vr =
  12049. /** Assembles the key for the online state of the primary tab. */
  12050. function(t) {
  12051. return "firestore_online_state_".concat(t);
  12052. }(this.persistenceKey), this.Rr = function(t) {
  12053. return "firestore_bundle_loaded_v2_".concat(t);
  12054. }(this.persistenceKey),
  12055. // Rather than adding the storage observer during start(), we add the
  12056. // storage observer during initialization. This ensures that we collect
  12057. // events before other components populate their initial state (during their
  12058. // respective start() calls). Otherwise, we might for example miss a
  12059. // mutation that is added after LocalStore's start() processed the existing
  12060. // mutations but before we observe WebStorage events.
  12061. this.window.addEventListener("storage", this._r);
  12062. }
  12063. /** Returns 'true' if WebStorage is available in the current environment. */ return t.D = function(t) {
  12064. return !(!t || !t.localStorage);
  12065. }, t.prototype.start = function() {
  12066. return e(this, void 0, void 0, (function() {
  12067. var t, e, r, i, o, u, a, s, c, l, h, f = this;
  12068. return n(this, (function(n) {
  12069. switch (n.label) {
  12070. case 0:
  12071. return [ 4 /*yield*/ , this.syncEngine.$i() ];
  12072. case 1:
  12073. for (t = n.sent(), e = 0, r = t; e < r.length; e++) (i = r[e]) !== this.wr && (o = this.getItem(ma(this.persistenceKey, i))) && (u = Ia.ar(i, o)) && (this.gr = this.gr.insert(u.clientId, u));
  12074. for (this.Pr(), (a = this.storage.getItem(this.vr)) && (s = this.br(a)) && this.Vr(s),
  12075. c = 0, l = this.yr; c < l.length; c++) h = l[c], this.mr(h);
  12076. return this.yr = [],
  12077. // Register a window unload hook to remove the client metadata entry from
  12078. // WebStorage even if `shutdown()` was not called.
  12079. this.window.addEventListener("pagehide", (function() {
  12080. return f.shutdown();
  12081. })), this.started = !0, [ 2 /*return*/ ];
  12082. }
  12083. }));
  12084. }));
  12085. }, t.prototype.writeSequenceNumber = function(t) {
  12086. this.setItem(this.Ir, JSON.stringify(t));
  12087. }, t.prototype.getAllActiveQueryTargets = function() {
  12088. return this.Sr(this.gr);
  12089. }, t.prototype.isActiveQueryTarget = function(t) {
  12090. var e = !1;
  12091. return this.gr.forEach((function(n, r) {
  12092. r.activeTargetIds.has(t) && (e = !0);
  12093. })), e;
  12094. }, t.prototype.addPendingMutation = function(t) {
  12095. this.Dr(t, "pending");
  12096. }, t.prototype.updateMutationState = function(t, e, n) {
  12097. this.Dr(t, e, n),
  12098. // Once a final mutation result is observed by other clients, they no longer
  12099. // access the mutation's metadata entry. Since WebStorage replays events
  12100. // in order, it is safe to delete the entry right after updating it.
  12101. this.Cr(t);
  12102. }, t.prototype.addLocalQueryTarget = function(t) {
  12103. var e = "not-current";
  12104. // Lookup an existing query state if the target ID was already registered
  12105. // by another tab
  12106. if (this.isActiveQueryTarget(t)) {
  12107. var n = this.storage.getItem(ga(this.persistenceKey, t));
  12108. if (n) {
  12109. var r = ba.ar(t, n);
  12110. r && (e = r.state);
  12111. }
  12112. }
  12113. return this.Nr.lr(t), this.Pr(), e;
  12114. }, t.prototype.removeLocalQueryTarget = function(t) {
  12115. this.Nr.dr(t), this.Pr();
  12116. }, t.prototype.isLocalQueryTarget = function(t) {
  12117. return this.Nr.activeTargetIds.has(t);
  12118. }, t.prototype.clearQueryState = function(t) {
  12119. this.removeItem(ga(this.persistenceKey, t));
  12120. }, t.prototype.updateQueryState = function(t, e, n) {
  12121. this.kr(t, e, n);
  12122. }, t.prototype.handleUserChange = function(t, e, n) {
  12123. var r = this;
  12124. e.forEach((function(t) {
  12125. r.Cr(t);
  12126. })), this.currentUser = t, n.forEach((function(t) {
  12127. r.addPendingMutation(t);
  12128. }));
  12129. }, t.prototype.setOnlineState = function(t) {
  12130. this.Mr(t);
  12131. }, t.prototype.notifyBundleLoaded = function(t) {
  12132. this.$r(t);
  12133. }, t.prototype.shutdown = function() {
  12134. this.started && (this.window.removeEventListener("storage", this._r), this.removeItem(this.pr),
  12135. this.started = !1);
  12136. }, t.prototype.getItem = function(t) {
  12137. var e = this.storage.getItem(t);
  12138. return M("SharedClientState", "READ", t, e), e;
  12139. }, t.prototype.setItem = function(t, e) {
  12140. M("SharedClientState", "SET", t, e), this.storage.setItem(t, e);
  12141. }, t.prototype.removeItem = function(t) {
  12142. M("SharedClientState", "REMOVE", t), this.storage.removeItem(t);
  12143. }, t.prototype.mr = function(t) {
  12144. var r = this, i = t;
  12145. // Note: The function is typed to take Event to be interface-compatible with
  12146. // `Window.addEventListener`.
  12147. if (i.storageArea === this.storage) {
  12148. if (M("SharedClientState", "EVENT", i.key, i.newValue), i.key === this.pr) return void L("Received WebStorage notification for local change. Another client might have garbage-collected our state");
  12149. this.ii.enqueueRetryable((function() {
  12150. return e(r, void 0, void 0, (function() {
  12151. var t, e, r, o, u, a, s, c = this;
  12152. return n(this, (function(n) {
  12153. switch (n.label) {
  12154. case 0:
  12155. return this.started ? null === i.key ? [ 3 /*break*/ , 7 ] : this.Tr.test(i.key) ? null == i.newValue ? (t = this.Or(i.key),
  12156. [ 2 /*return*/ , this.Fr(t, null) ]) : (e = this.Br(i.key, i.newValue)) ? [ 2 /*return*/ , this.Fr(e.clientId, e) ] : [ 3 /*break*/ , 7 ] : [ 3 /*break*/ , 1 ] : [ 3 /*break*/ , 8 ];
  12157. case 1:
  12158. return this.Er.test(i.key) ? null !== i.newValue && (r = this.Lr(i.key, i.newValue)) ? [ 2 /*return*/ , this.qr(r) ] : [ 3 /*break*/ , 7 ] : [ 3 /*break*/ , 2 ];
  12159. case 2:
  12160. return this.Ar.test(i.key) ? null !== i.newValue && (o = this.Ur(i.key, i.newValue)) ? [ 2 /*return*/ , this.Kr(o) ] : [ 3 /*break*/ , 7 ] : [ 3 /*break*/ , 3 ];
  12161. case 3:
  12162. return i.key !== this.vr ? [ 3 /*break*/ , 4 ] : null !== i.newValue && (u = this.br(i.newValue)) ? [ 2 /*return*/ , this.Vr(u) ] : [ 3 /*break*/ , 7 ];
  12163. case 4:
  12164. return i.key !== this.Ir ? [ 3 /*break*/ , 5 ] : (a = function(t) {
  12165. var e = Ut.ct;
  12166. if (null != t) try {
  12167. var n = JSON.parse(t);
  12168. z("number" == typeof n), e = n;
  12169. } catch (t) {
  12170. L("SharedClientState", "Failed to read sequence number from WebStorage", t);
  12171. }
  12172. return e;
  12173. }(i.newValue), a !== Ut.ct && this.sequenceNumberHandler(a), [ 3 /*break*/ , 7 ]);
  12174. case 5:
  12175. return i.key !== this.Rr ? [ 3 /*break*/ , 7 ] : (s = this.Gr(i.newValue), [ 4 /*yield*/ , Promise.all(s.map((function(t) {
  12176. return c.syncEngine.Qr(t);
  12177. }))) ]);
  12178. case 6:
  12179. n.sent(), n.label = 7;
  12180. case 7:
  12181. return [ 3 /*break*/ , 9 ];
  12182. case 8:
  12183. this.yr.push(i), n.label = 9;
  12184. case 9:
  12185. return [ 2 /*return*/ ];
  12186. }
  12187. }));
  12188. }));
  12189. }));
  12190. }
  12191. }, Object.defineProperty(t.prototype, "Nr", {
  12192. get: function() {
  12193. return this.gr.get(this.wr);
  12194. },
  12195. enumerable: !1,
  12196. configurable: !0
  12197. }), t.prototype.Pr = function() {
  12198. this.setItem(this.pr, this.Nr.hr());
  12199. }, t.prototype.Dr = function(t, e, n) {
  12200. var r = new wa(this.currentUser, t, e, n), i = ya(this.persistenceKey, this.currentUser, t);
  12201. this.setItem(i, r.hr());
  12202. }, t.prototype.Cr = function(t) {
  12203. var e = ya(this.persistenceKey, this.currentUser, t);
  12204. this.removeItem(e);
  12205. }, t.prototype.Mr = function(t) {
  12206. var e = {
  12207. clientId: this.wr,
  12208. onlineState: t
  12209. };
  12210. this.storage.setItem(this.vr, JSON.stringify(e));
  12211. }, t.prototype.kr = function(t, e, n) {
  12212. var r = ga(this.persistenceKey, t), i = new ba(t, e, n);
  12213. this.setItem(r, i.hr());
  12214. }, t.prototype.$r = function(t) {
  12215. var e = JSON.stringify(Array.from(t));
  12216. this.setItem(this.Rr, e);
  12217. },
  12218. /**
  12219. * Parses a client state key in WebStorage. Returns null if the key does not
  12220. * match the expected key format.
  12221. */
  12222. t.prototype.Or = function(t) {
  12223. var e = this.Tr.exec(t);
  12224. return e ? e[1] : null;
  12225. },
  12226. /**
  12227. * Parses a client state in WebStorage. Returns 'null' if the value could not
  12228. * be parsed.
  12229. */
  12230. t.prototype.Br = function(t, e) {
  12231. var n = this.Or(t);
  12232. return Ia.ar(n, e);
  12233. },
  12234. /**
  12235. * Parses a mutation batch state in WebStorage. Returns 'null' if the value
  12236. * could not be parsed.
  12237. */
  12238. t.prototype.Lr = function(t, e) {
  12239. var n = this.Er.exec(t), r = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;
  12240. return wa.ar(new O(i), r, e);
  12241. },
  12242. /**
  12243. * Parses a query target state from WebStorage. Returns 'null' if the value
  12244. * could not be parsed.
  12245. */
  12246. t.prototype.Ur = function(t, e) {
  12247. var n = this.Ar.exec(t), r = Number(n[1]);
  12248. return ba.ar(r, e);
  12249. },
  12250. /**
  12251. * Parses an online state from WebStorage. Returns 'null' if the value
  12252. * could not be parsed.
  12253. */
  12254. t.prototype.br = function(t) {
  12255. return Ea.ar(t);
  12256. }, t.prototype.Gr = function(t) {
  12257. return JSON.parse(t);
  12258. }, t.prototype.qr = function(t) {
  12259. return e(this, void 0, void 0, (function() {
  12260. return n(this, (function(e) {
  12261. return t.user.uid === this.currentUser.uid ? [ 2 /*return*/ , this.syncEngine.jr(t.batchId, t.state, t.error) ] : (M("SharedClientState", "Ignoring mutation for non-active user ".concat(t.user.uid)),
  12262. [ 2 /*return*/ ]);
  12263. }));
  12264. }));
  12265. }, t.prototype.Kr = function(t) {
  12266. return this.syncEngine.zr(t.targetId, t.state, t.error);
  12267. }, t.prototype.Fr = function(t, e) {
  12268. var n = this, r = e ? this.gr.insert(t, e) : this.gr.remove(t), i = this.Sr(this.gr), o = this.Sr(r), u = [], a = [];
  12269. return o.forEach((function(t) {
  12270. i.has(t) || u.push(t);
  12271. })), i.forEach((function(t) {
  12272. o.has(t) || a.push(t);
  12273. })), this.syncEngine.Wr(u, a).then((function() {
  12274. n.gr = r;
  12275. }));
  12276. }, t.prototype.Vr = function(t) {
  12277. // We check whether the client that wrote this online state is still active
  12278. // by comparing its client ID to the list of clients kept active in
  12279. // IndexedDb. If a client does not update their IndexedDb client state
  12280. // within 5 seconds, it is considered inactive and we don't emit an online
  12281. // state event.
  12282. this.gr.get(t.clientId) && this.onlineStateHandler(t.onlineState);
  12283. }, t.prototype.Sr = function(t) {
  12284. var e = Tr();
  12285. return t.forEach((function(t, n) {
  12286. e = e.unionWith(n.activeTargetIds);
  12287. })), e;
  12288. }, t;
  12289. }(), _a = /** @class */ function() {
  12290. function t() {
  12291. this.Hr = new Ta, this.Jr = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;
  12292. }
  12293. return t.prototype.addPendingMutation = function(t) {
  12294. // No op.
  12295. }, t.prototype.updateMutationState = function(t, e, n) {
  12296. // No op.
  12297. }, t.prototype.addLocalQueryTarget = function(t) {
  12298. return this.Hr.lr(t), this.Jr[t] || "not-current";
  12299. }, t.prototype.updateQueryState = function(t, e, n) {
  12300. this.Jr[t] = e;
  12301. }, t.prototype.removeLocalQueryTarget = function(t) {
  12302. this.Hr.dr(t);
  12303. }, t.prototype.isLocalQueryTarget = function(t) {
  12304. return this.Hr.activeTargetIds.has(t);
  12305. }, t.prototype.clearQueryState = function(t) {
  12306. delete this.Jr[t];
  12307. }, t.prototype.getAllActiveQueryTargets = function() {
  12308. return this.Hr.activeTargetIds;
  12309. }, t.prototype.isActiveQueryTarget = function(t) {
  12310. return this.Hr.activeTargetIds.has(t);
  12311. }, t.prototype.start = function() {
  12312. return this.Hr = new Ta, Promise.resolve();
  12313. }, t.prototype.handleUserChange = function(t, e, n) {
  12314. // No op.
  12315. }, t.prototype.setOnlineState = function(t) {
  12316. // No op.
  12317. }, t.prototype.shutdown = function() {}, t.prototype.writeSequenceNumber = function(t) {},
  12318. t.prototype.notifyBundleLoaded = function(t) {
  12319. // No op.
  12320. }, t;
  12321. }(), Da = /** @class */ function() {
  12322. function t() {}
  12323. return t.prototype.Yr = function(t) {
  12324. // No-op.
  12325. }, t.prototype.shutdown = function() {
  12326. // No-op.
  12327. }, t;
  12328. }(), Ca = /** @class */ function() {
  12329. function t() {
  12330. var t = this;
  12331. this.Xr = function() {
  12332. return t.Zr();
  12333. }, this.eo = function() {
  12334. return t.no();
  12335. }, this.so = [], this.io();
  12336. }
  12337. return t.prototype.Yr = function(t) {
  12338. this.so.push(t);
  12339. }, t.prototype.shutdown = function() {
  12340. window.removeEventListener("online", this.Xr), window.removeEventListener("offline", this.eo);
  12341. }, t.prototype.io = function() {
  12342. window.addEventListener("online", this.Xr), window.addEventListener("offline", this.eo);
  12343. }, t.prototype.Zr = function() {
  12344. M("ConnectivityMonitor", "Network connectivity changed: AVAILABLE");
  12345. for (var t = 0, e = this.so; t < e.length; t++) {
  12346. (0, e[t])(0 /* NetworkStatus.AVAILABLE */);
  12347. }
  12348. }, t.prototype.no = function() {
  12349. M("ConnectivityMonitor", "Network connectivity changed: UNAVAILABLE");
  12350. for (var t = 0, e = this.so; t < e.length; t++) {
  12351. (0, e[t])(1 /* NetworkStatus.UNAVAILABLE */);
  12352. }
  12353. },
  12354. // TODO(chenbrian): Consider passing in window either into this component or
  12355. // here for testing via FakeWindow.
  12356. /** Checks that all used attributes of window are available. */
  12357. t.D = function() {
  12358. return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
  12359. }, t;
  12360. }(), xa = null;
  12361. /**
  12362. * Holds the state of a query target, including its target ID and whether the
  12363. * target is 'not-current', 'current' or 'rejected'.
  12364. */
  12365. // Visible for testing
  12366. /**
  12367. * Generates and returns an initial value for `lastUniqueDebugId`.
  12368. *
  12369. * The returned value is randomly selected from a range of integers that are
  12370. * represented as 8 hexadecimal digits. This means that (within reason) any
  12371. * numbers generated by incrementing the returned number by 1 will also be
  12372. * represented by 8 hexadecimal digits. This leads to all "IDs" having the same
  12373. * length when converted to a hexadecimal string, making reading logs containing
  12374. * these IDs easier to follow. And since the return value is randomly selected
  12375. * it will help to differentiate between logs from different executions.
  12376. */
  12377. /**
  12378. * Generates and returns a unique ID as a hexadecimal string.
  12379. *
  12380. * The returned ID is intended to be used in debug logging messages to help
  12381. * correlate log messages that may be spatially separated in the logs, but
  12382. * logically related. For example, a network connection could include the same
  12383. * "debug ID" string in all of its log messages to help trace a specific
  12384. * connection over time.
  12385. *
  12386. * @return the 10-character generated ID (e.g. "0xa1b2c3d4").
  12387. */
  12388. function Na() {
  12389. return null === xa ? xa = 268435456 + Math.round(2147483648 * Math.random()) : xa++,
  12390. "0x" + xa.toString(16)
  12391. /**
  12392. * @license
  12393. * Copyright 2020 Google LLC
  12394. *
  12395. * Licensed under the Apache License, Version 2.0 (the "License");
  12396. * you may not use this file except in compliance with the License.
  12397. * You may obtain a copy of the License at
  12398. *
  12399. * http://www.apache.org/licenses/LICENSE-2.0
  12400. *
  12401. * Unless required by applicable law or agreed to in writing, software
  12402. * distributed under the License is distributed on an "AS IS" BASIS,
  12403. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12404. * See the License for the specific language governing permissions and
  12405. * limitations under the License.
  12406. */;
  12407. }
  12408. var Aa = {
  12409. BatchGetDocuments: "batchGet",
  12410. Commit: "commit",
  12411. RunQuery: "runQuery",
  12412. RunAggregationQuery: "runAggregationQuery"
  12413. }, ka = /** @class */ function() {
  12414. function t(t) {
  12415. this.ro = t.ro, this.oo = t.oo;
  12416. }
  12417. return t.prototype.uo = function(t) {
  12418. this.co = t;
  12419. }, t.prototype.ao = function(t) {
  12420. this.ho = t;
  12421. }, t.prototype.onMessage = function(t) {
  12422. this.lo = t;
  12423. }, t.prototype.close = function() {
  12424. this.oo();
  12425. }, t.prototype.send = function(t) {
  12426. this.ro(t);
  12427. }, t.prototype.fo = function() {
  12428. this.co();
  12429. }, t.prototype.wo = function(t) {
  12430. this.ho(t);
  12431. }, t.prototype._o = function(t) {
  12432. this.lo(t);
  12433. }, t;
  12434. }(), Oa = "WebChannelConnection", Fa = /** @class */ function(e) {
  12435. function n(t) {
  12436. var n = this;
  12437. return (n = e.call(this, t) || this).forceLongPolling = t.forceLongPolling, n.autoDetectLongPolling = t.autoDetectLongPolling,
  12438. n.useFetchStreams = t.useFetchStreams, n.longPollingOptions = t.longPollingOptions,
  12439. n;
  12440. }
  12441. /**
  12442. * Base class for all Rest-based connections to the backend (WebChannel and
  12443. * HTTP).
  12444. */
  12445. return t(n, e), n.prototype.Ao = function(t, e, n, r) {
  12446. var i = Na();
  12447. return new Promise((function(o, u) {
  12448. var a = new I;
  12449. a.setWithCredentials(!0), a.listenOnce(E.COMPLETE, (function() {
  12450. try {
  12451. switch (a.getLastErrorCode()) {
  12452. case T.NO_ERROR:
  12453. var e = a.getResponseJson();
  12454. M(Oa, "XHR for RPC '".concat(t, "' ").concat(i, " received:"), JSON.stringify(e)),
  12455. o(e);
  12456. break;
  12457. case T.TIMEOUT:
  12458. M(Oa, "RPC '".concat(t, "' ").concat(i, " timed out")), u(new Q(K.DEADLINE_EXCEEDED, "Request time out"));
  12459. break;
  12460. case T.HTTP_ERROR:
  12461. var n = a.getStatus();
  12462. if (M(Oa, "RPC '".concat(t, "' ").concat(i, " failed with status:"), n, "response text:", a.getResponseText()),
  12463. n > 0) {
  12464. var r = a.getResponseJson();
  12465. Array.isArray(r) && (r = r[0]);
  12466. var s = null == r ? void 0 : r.error;
  12467. if (s && s.status && s.message) {
  12468. var c = function(t) {
  12469. var e = t.toLowerCase().replace(/_/g, "-");
  12470. return Object.values(K).indexOf(e) >= 0 ? e : K.UNKNOWN;
  12471. }(s.status);
  12472. u(new Q(c, s.message));
  12473. } else u(new Q(K.UNKNOWN, "Server responded with status " + a.getStatus()));
  12474. } else
  12475. // If we received an HTTP_ERROR but there's no status code,
  12476. // it's most probably a connection issue
  12477. u(new Q(K.UNAVAILABLE, "Connection failed."));
  12478. break;
  12479. default:
  12480. U();
  12481. }
  12482. } finally {
  12483. M(Oa, "RPC '".concat(t, "' ").concat(i, " completed."));
  12484. }
  12485. }));
  12486. var s = JSON.stringify(r);
  12487. M(Oa, "RPC '".concat(t, "' ").concat(i, " sending request:"), r), a.send(e, "POST", s, n, 15);
  12488. }));
  12489. }, n.prototype.Ro = function(t, e, n) {
  12490. var r = Na(), i = [ this.mo, "/", "google.firestore.v1.Firestore", "/", t, "/channel" ], o = S(), u = _(), a = {
  12491. // Required for backend stickiness, routing behavior is based on this
  12492. // parameter.
  12493. httpSessionIdParam: "gsessionid",
  12494. initMessageHeaders: {},
  12495. messageUrlParams: {
  12496. // This param is used to improve routing and project isolation by the
  12497. // backend and must be included in every request.
  12498. database: "projects/".concat(this.databaseId.projectId, "/databases/").concat(this.databaseId.database)
  12499. },
  12500. sendRawJson: !0,
  12501. supportsCrossDomainXhr: !0,
  12502. internalChannelParams: {
  12503. // Override the default timeout (randomized between 10-20 seconds) since
  12504. // a large write batch on a slow internet connection may take a long
  12505. // time to send to the backend. Rather than have WebChannel impose a
  12506. // tight timeout which could lead to infinite timeouts and retries, we
  12507. // set it very large (5-10 minutes) and rely on the browser's builtin
  12508. // timeouts to kick in if the request isn't working.
  12509. forwardChannelRequestTimeoutMs: 6e5
  12510. },
  12511. forceLongPolling: this.forceLongPolling,
  12512. detectBufferingProxy: this.autoDetectLongPolling
  12513. }, s = this.longPollingOptions.timeoutSeconds;
  12514. void 0 !== s && (a.longPollingTimeout = Math.round(1e3 * s)), this.useFetchStreams && (a.xmlHttpFactory = new D({})),
  12515. this.Eo(a.initMessageHeaders, e, n),
  12516. // Sending the custom headers we just added to request.initMessageHeaders
  12517. // (Authorization, etc.) will trigger the browser to make a CORS preflight
  12518. // request because the XHR will no longer meet the criteria for a "simple"
  12519. // CORS request:
  12520. // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
  12521. // Therefore to avoid the CORS preflight request (an extra network
  12522. // roundtrip), we use the encodeInitMessageHeaders option to specify that
  12523. // the headers should instead be encoded in the request's POST payload,
  12524. // which is recognized by the webchannel backend.
  12525. a.encodeInitMessageHeaders = !0;
  12526. var c = i.join("");
  12527. M(Oa, "Creating RPC '".concat(t, "' stream ").concat(r, ": ").concat(c), a);
  12528. var l = o.createWebChannel(c, a), h = !1, f = !1, d = new ka({
  12529. ro: function(e) {
  12530. f ? M(Oa, "Not sending because RPC '".concat(t, "' stream ").concat(r, " is closed:"), e) : (h || (M(Oa, "Opening RPC '".concat(t, "' stream ").concat(r, " transport.")),
  12531. l.open(), h = !0), M(Oa, "RPC '".concat(t, "' stream ").concat(r, " sending:"), e),
  12532. l.send(e));
  12533. },
  12534. oo: function() {
  12535. return l.close();
  12536. }
  12537. }), p = function(t, e, n) {
  12538. // TODO(dimond): closure typing seems broken because WebChannel does
  12539. // not implement goog.events.Listenable
  12540. t.listen(e, (function(t) {
  12541. try {
  12542. n(t);
  12543. } catch (t) {
  12544. setTimeout((function() {
  12545. throw t;
  12546. }), 0);
  12547. }
  12548. }));
  12549. };
  12550. // WebChannel supports sending the first message with the handshake - saving
  12551. // a network round trip. However, it will have to call send in the same
  12552. // JS event loop as open. In order to enforce this, we delay actually
  12553. // opening the WebChannel until send is called. Whether we have called
  12554. // open is tracked with this variable.
  12555. // Closure events are guarded and exceptions are swallowed, so catch any
  12556. // exception and rethrow using a setTimeout so they become visible again.
  12557. // Note that eventually this function could go away if we are confident
  12558. // enough the code is exception free.
  12559. return p(l, C.EventType.OPEN, (function() {
  12560. f || M(Oa, "RPC '".concat(t, "' stream ").concat(r, " transport opened."));
  12561. })), p(l, C.EventType.CLOSE, (function() {
  12562. f || (f = !0, M(Oa, "RPC '".concat(t, "' stream ").concat(r, " transport closed")),
  12563. d.wo());
  12564. })), p(l, C.EventType.ERROR, (function(e) {
  12565. f || (f = !0, q(Oa, "RPC '".concat(t, "' stream ").concat(r, " transport errored:"), e),
  12566. d.wo(new Q(K.UNAVAILABLE, "The operation could not be completed")));
  12567. })), p(l, C.EventType.MESSAGE, (function(e) {
  12568. var n;
  12569. if (!f) {
  12570. var i = e.data[0];
  12571. z(!!i);
  12572. // TODO(b/35143891): There is a bug in One Platform that caused errors
  12573. // (and only errors) to be wrapped in an extra array. To be forward
  12574. // compatible with the bug we need to check either condition. The latter
  12575. // can be removed once the fix has been rolled out.
  12576. // Use any because msgData.error is not typed.
  12577. var o = i, u = o.error || (null === (n = o[0]) || void 0 === n ? void 0 : n.error);
  12578. if (u) {
  12579. M(Oa, "RPC '".concat(t, "' stream ").concat(r, " received error:"), u);
  12580. // error.status will be a string like 'OK' or 'NOT_FOUND'.
  12581. var a = u.status, s =
  12582. /**
  12583. * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
  12584. *
  12585. * @returns The Code equivalent to the given status string or undefined if
  12586. * there is no match.
  12587. */
  12588. function(t) {
  12589. // lookup by string
  12590. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12591. var e = ti[t];
  12592. if (void 0 !== e) return li(e);
  12593. }(a), c = u.message;
  12594. void 0 === s && (s = K.INTERNAL, c = "Unknown error status: " + a + " with message " + u.message),
  12595. // Mark closed so no further events are propagated
  12596. f = !0, d.wo(new Q(s, c)), l.close();
  12597. } else M(Oa, "RPC '".concat(t, "' stream ").concat(r, " received:"), i), d._o(i);
  12598. }
  12599. })), p(u, x.STAT_EVENT, (function(e) {
  12600. e.stat === N.PROXY ? M(Oa, "RPC '".concat(t, "' stream ").concat(r, " detected buffering proxy")) : e.stat === N.NOPROXY && M(Oa, "RPC '".concat(t, "' stream ").concat(r, " detected no buffering proxy"));
  12601. })), setTimeout((function() {
  12602. // Technically we could/should wait for the WebChannel opened event,
  12603. // but because we want to send the first message with the WebChannel
  12604. // handshake we pretend the channel opened here (asynchronously), and
  12605. // then delay the actual open until the first message is sent.
  12606. d.fo();
  12607. }), 0), d;
  12608. }, n;
  12609. }(/** @class */ function() {
  12610. function t(t) {
  12611. this.databaseInfo = t, this.databaseId = t.databaseId;
  12612. var e = t.ssl ? "https" : "http";
  12613. this.mo = e + "://" + t.host, this.yo = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents";
  12614. }
  12615. return Object.defineProperty(t.prototype, "po", {
  12616. get: function() {
  12617. // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
  12618. // where to run the query, and expect the `request` to NOT specify the "path".
  12619. return !1;
  12620. },
  12621. enumerable: !1,
  12622. configurable: !0
  12623. }), t.prototype.Io = function(t, e, n, r, i) {
  12624. var o = Na(), u = this.To(t, e);
  12625. M("RestConnection", "Sending RPC '".concat(t, "' ").concat(o, ":"), u, n);
  12626. var a = {};
  12627. return this.Eo(a, r, i), this.Ao(t, u, a, n).then((function(e) {
  12628. return M("RestConnection", "Received RPC '".concat(t, "' ").concat(o, ": "), e),
  12629. e;
  12630. }), (function(e) {
  12631. throw q("RestConnection", "RPC '".concat(t, "' ").concat(o, " failed with error: "), e, "url: ", u, "request:", n),
  12632. e;
  12633. }));
  12634. }, t.prototype.vo = function(t, e, n, r, i, o) {
  12635. // The REST API automatically aggregates all of the streamed results, so we
  12636. // can just use the normal invoke() method.
  12637. return this.Io(t, e, n, r, i);
  12638. },
  12639. /**
  12640. * Modifies the headers for a request, adding any authorization token if
  12641. * present and any additional headers for the request.
  12642. */
  12643. t.prototype.Eo = function(t, e, n) {
  12644. t["X-Goog-Api-Client"] = "gl-js/ fire/" + F,
  12645. // Content-Type: text/plain will avoid preflight requests which might
  12646. // mess with CORS and redirects by proxies. If we add custom headers
  12647. // we will need to change this code to potentially use the $httpOverwrite
  12648. // parameter supported by ESF to avoid triggering preflight requests.
  12649. t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId),
  12650. e && e.headers.forEach((function(e, n) {
  12651. return t[n] = e;
  12652. })), n && n.headers.forEach((function(e, n) {
  12653. return t[n] = e;
  12654. }));
  12655. }, t.prototype.To = function(t, e) {
  12656. var n = Aa[t];
  12657. return "".concat(this.mo, "/v1/").concat(e, ":").concat(n);
  12658. }, t;
  12659. }());
  12660. /**
  12661. * Maps RPC names to the corresponding REST endpoint name.
  12662. *
  12663. * We use array notation to avoid mangling.
  12664. */
  12665. /**
  12666. * @license
  12667. * Copyright 2017 Google LLC
  12668. *
  12669. * Licensed under the Apache License, Version 2.0 (the "License");
  12670. * you may not use this file except in compliance with the License.
  12671. * You may obtain a copy of the License at
  12672. *
  12673. * http://www.apache.org/licenses/LICENSE-2.0
  12674. *
  12675. * Unless required by applicable law or agreed to in writing, software
  12676. * distributed under the License is distributed on an "AS IS" BASIS,
  12677. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12678. * See the License for the specific language governing permissions and
  12679. * limitations under the License.
  12680. */
  12681. /**
  12682. * Provides a simple helper class that implements the Stream interface to
  12683. * bridge to other implementations that are streams but do not implement the
  12684. * interface. The stream callbacks are invoked with the callOn... methods.
  12685. */
  12686. /**
  12687. * @license
  12688. * Copyright 2020 Google LLC
  12689. *
  12690. * Licensed under the Apache License, Version 2.0 (the "License");
  12691. * you may not use this file except in compliance with the License.
  12692. * You may obtain a copy of the License at
  12693. *
  12694. * http://www.apache.org/licenses/LICENSE-2.0
  12695. *
  12696. * Unless required by applicable law or agreed to in writing, software
  12697. * distributed under the License is distributed on an "AS IS" BASIS,
  12698. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12699. * See the License for the specific language governing permissions and
  12700. * limitations under the License.
  12701. */
  12702. /** Initializes the WebChannelConnection for the browser. */
  12703. /**
  12704. * @license
  12705. * Copyright 2020 Google LLC
  12706. *
  12707. * Licensed under the Apache License, Version 2.0 (the "License");
  12708. * you may not use this file except in compliance with the License.
  12709. * You may obtain a copy of the License at
  12710. *
  12711. * http://www.apache.org/licenses/LICENSE-2.0
  12712. *
  12713. * Unless required by applicable law or agreed to in writing, software
  12714. * distributed under the License is distributed on an "AS IS" BASIS,
  12715. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12716. * See the License for the specific language governing permissions and
  12717. * limitations under the License.
  12718. */
  12719. /** The Platform's 'window' implementation or null if not available. */
  12720. function Pa() {
  12721. // `window` is not always available, e.g. in ReactNative and WebWorkers.
  12722. // eslint-disable-next-line no-restricted-globals
  12723. return "undefined" != typeof window ? window : null;
  12724. }
  12725. /** The Platform's 'document' implementation or null if not available. */ function Ra() {
  12726. // `document` is not always available, e.g. in ReactNative and WebWorkers.
  12727. // eslint-disable-next-line no-restricted-globals
  12728. return "undefined" != typeof document ? document : null;
  12729. }
  12730. /**
  12731. * @license
  12732. * Copyright 2020 Google LLC
  12733. *
  12734. * Licensed under the Apache License, Version 2.0 (the "License");
  12735. * you may not use this file except in compliance with the License.
  12736. * You may obtain a copy of the License at
  12737. *
  12738. * http://www.apache.org/licenses/LICENSE-2.0
  12739. *
  12740. * Unless required by applicable law or agreed to in writing, software
  12741. * distributed under the License is distributed on an "AS IS" BASIS,
  12742. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12743. * See the License for the specific language governing permissions and
  12744. * limitations under the License.
  12745. */ function Va(t) {
  12746. return new ki(t, /* useProto3Json= */ !0);
  12747. }
  12748. /**
  12749. * @license
  12750. * Copyright 2017 Google LLC
  12751. *
  12752. * Licensed under the Apache License, Version 2.0 (the "License");
  12753. * you may not use this file except in compliance with the License.
  12754. * You may obtain a copy of the License at
  12755. *
  12756. * http://www.apache.org/licenses/LICENSE-2.0
  12757. *
  12758. * Unless required by applicable law or agreed to in writing, software
  12759. * distributed under the License is distributed on an "AS IS" BASIS,
  12760. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12761. * See the License for the specific language governing permissions and
  12762. * limitations under the License.
  12763. */
  12764. /**
  12765. * A helper for running delayed tasks following an exponential backoff curve
  12766. * between attempts.
  12767. *
  12768. * Each delay is made up of a "base" delay which follows the exponential
  12769. * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
  12770. * base delay. This prevents clients from accidentally synchronizing their
  12771. * delays causing spikes of load to the backend.
  12772. */ var Ma = /** @class */ function() {
  12773. function t(
  12774. /**
  12775. * The AsyncQueue to run backoff operations on.
  12776. */
  12777. t,
  12778. /**
  12779. * The ID to use when scheduling backoff operations on the AsyncQueue.
  12780. */
  12781. e,
  12782. /**
  12783. * The initial delay (used as the base delay on the first retry attempt).
  12784. * Note that jitter will still be applied, so the actual delay could be as
  12785. * little as 0.5*initialDelayMs.
  12786. */
  12787. n
  12788. /**
  12789. * The multiplier to use to determine the extended base delay after each
  12790. * attempt.
  12791. */ , r
  12792. /**
  12793. * The maximum base delay after which no further backoff is performed.
  12794. * Note that jitter will still be applied, so the actual delay could be as
  12795. * much as 1.5*maxDelayMs.
  12796. */ , i) {
  12797. void 0 === n && (n = 1e3), void 0 === r && (r = 1.5), void 0 === i && (i = 6e4),
  12798. this.ii = t, this.timerId = e, this.Po = n, this.bo = r, this.Vo = i, this.So = 0,
  12799. this.Do = null,
  12800. /** The last backoff attempt, as epoch milliseconds. */
  12801. this.Co = Date.now(), this.reset();
  12802. }
  12803. /**
  12804. * Resets the backoff delay.
  12805. *
  12806. * The very next backoffAndWait() will have no delay. If it is called again
  12807. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  12808. * subsequent ones will increase according to the backoffFactor.
  12809. */ return t.prototype.reset = function() {
  12810. this.So = 0;
  12811. },
  12812. /**
  12813. * Resets the backoff delay to the maximum delay (e.g. for use after a
  12814. * RESOURCE_EXHAUSTED error).
  12815. */
  12816. t.prototype.xo = function() {
  12817. this.So = this.Vo;
  12818. },
  12819. /**
  12820. * Returns a promise that resolves after currentDelayMs, and increases the
  12821. * delay for any subsequent attempts. If there was a pending backoff operation
  12822. * already, it will be canceled.
  12823. */
  12824. t.prototype.No = function(t) {
  12825. var e = this;
  12826. // Cancel any pending backoff operation.
  12827. this.cancel();
  12828. // First schedule using the current base (which may be 0 and should be
  12829. // honored as such).
  12830. var n = Math.floor(this.So + this.ko()), r = Math.max(0, Date.now() - this.Co), i = Math.max(0, n - r);
  12831. // Guard against lastAttemptTime being in the future due to a clock change.
  12832. i > 0 && M("ExponentialBackoff", "Backing off for ".concat(i, " ms (base delay: ").concat(this.So, " ms, delay with jitter: ").concat(n, " ms, last attempt: ").concat(r, " ms ago)")),
  12833. this.Do = this.ii.enqueueAfterDelay(this.timerId, i, (function() {
  12834. return e.Co = Date.now(), t();
  12835. })),
  12836. // Apply backoff factor to determine next delay and ensure it is within
  12837. // bounds.
  12838. this.So *= this.bo, this.So < this.Po && (this.So = this.Po), this.So > this.Vo && (this.So = this.Vo);
  12839. }, t.prototype.Mo = function() {
  12840. null !== this.Do && (this.Do.skipDelay(), this.Do = null);
  12841. }, t.prototype.cancel = function() {
  12842. null !== this.Do && (this.Do.cancel(), this.Do = null);
  12843. },
  12844. /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ t.prototype.ko = function() {
  12845. return (Math.random() - .5) * this.So;
  12846. }, t;
  12847. }(), La = /** @class */ function() {
  12848. function t(t, e, n, r, i, o, u, a) {
  12849. this.ii = t, this.$o = n, this.Oo = r, this.connection = i, this.authCredentialsProvider = o,
  12850. this.appCheckCredentialsProvider = u, this.listener = a, this.state = 0 /* PersistentStreamState.Initial */ ,
  12851. /**
  12852. * A close count that's incremented every time the stream is closed; used by
  12853. * getCloseGuardedDispatcher() to invalidate callbacks that happen after
  12854. * close.
  12855. */
  12856. this.Fo = 0, this.Bo = null, this.Lo = null, this.stream = null, this.qo = new Ma(t, e)
  12857. /**
  12858. * Returns true if start() has been called and no error has occurred. True
  12859. * indicates the stream is open or in the process of opening (which
  12860. * encompasses respecting backoff, getting auth tokens, and starting the
  12861. * actual RPC). Use isOpen() to determine if the stream is open and ready for
  12862. * outbound requests.
  12863. */;
  12864. }
  12865. return t.prototype.Uo = function() {
  12866. return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.Ko();
  12867. },
  12868. /**
  12869. * Returns true if the underlying RPC is open (the onOpen() listener has been
  12870. * called) and the stream is ready for outbound requests.
  12871. */
  12872. t.prototype.Ko = function() {
  12873. return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;
  12874. },
  12875. /**
  12876. * Starts the RPC. Only allowed if isStarted() returns false. The stream is
  12877. * not immediately ready for use: onOpen() will be invoked when the RPC is
  12878. * ready for outbound requests, at which point isOpen() will return true.
  12879. *
  12880. * When start returns, isStarted() will return true.
  12881. */
  12882. t.prototype.start = function() {
  12883. 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Go();
  12884. },
  12885. /**
  12886. * Stops the RPC. This call is idempotent and allowed regardless of the
  12887. * current isStarted() state.
  12888. *
  12889. * When stop returns, isStarted() and isOpen() will both return false.
  12890. */
  12891. t.prototype.stop = function() {
  12892. return e(this, void 0, void 0, (function() {
  12893. return n(this, (function(t) {
  12894. switch (t.label) {
  12895. case 0:
  12896. return this.Uo() ? [ 4 /*yield*/ , this.close(0 /* PersistentStreamState.Initial */) ] : [ 3 /*break*/ , 2 ];
  12897. case 1:
  12898. t.sent(), t.label = 2;
  12899. case 2:
  12900. return [ 2 /*return*/ ];
  12901. }
  12902. }));
  12903. }));
  12904. },
  12905. /**
  12906. * After an error the stream will usually back off on the next attempt to
  12907. * start it. If the error warrants an immediate restart of the stream, the
  12908. * sender can use this to indicate that the receiver should not back off.
  12909. *
  12910. * Each error will call the onClose() listener. That function can decide to
  12911. * inhibit backoff if required.
  12912. */
  12913. t.prototype.Qo = function() {
  12914. this.state = 0 /* PersistentStreamState.Initial */ , this.qo.reset();
  12915. },
  12916. /**
  12917. * Marks this stream as idle. If no further actions are performed on the
  12918. * stream for one minute, the stream will automatically close itself and
  12919. * notify the stream's onClose() handler with Status.OK. The stream will then
  12920. * be in a !isStarted() state, requiring the caller to start the stream again
  12921. * before further use.
  12922. *
  12923. * Only streams that are in state 'Open' can be marked idle, as all other
  12924. * states imply pending network operations.
  12925. */
  12926. t.prototype.jo = function() {
  12927. var t = this;
  12928. // Starts the idle time if we are in state 'Open' and are not yet already
  12929. // running a timer (in which case the previous idle timeout still applies).
  12930. this.Ko() && null === this.Bo && (this.Bo = this.ii.enqueueAfterDelay(this.$o, 6e4, (function() {
  12931. return t.zo();
  12932. })));
  12933. },
  12934. /** Sends a message to the underlying stream. */ t.prototype.Wo = function(t) {
  12935. this.Ho(), this.stream.send(t);
  12936. },
  12937. /** Called by the idle timer when the stream should close due to inactivity. */ t.prototype.zo = function() {
  12938. return e(this, void 0, void 0, (function() {
  12939. return n(this, (function(t) {
  12940. return this.Ko() ? [ 2 /*return*/ , this.close(0 /* PersistentStreamState.Initial */) ] : [ 2 /*return*/ ];
  12941. }));
  12942. }));
  12943. },
  12944. /** Marks the stream as active again. */ t.prototype.Ho = function() {
  12945. this.Bo && (this.Bo.cancel(), this.Bo = null);
  12946. },
  12947. /** Cancels the health check delayed operation. */ t.prototype.Jo = function() {
  12948. this.Lo && (this.Lo.cancel(), this.Lo = null);
  12949. },
  12950. /**
  12951. * Closes the stream and cleans up as necessary:
  12952. *
  12953. * * closes the underlying GRPC stream;
  12954. * * calls the onClose handler with the given 'error';
  12955. * * sets internal stream state to 'finalState';
  12956. * * adjusts the backoff timer based on the error
  12957. *
  12958. * A new stream can be opened by calling start().
  12959. *
  12960. * @param finalState - the intended state of the stream after closing.
  12961. * @param error - the error the connection was closed with.
  12962. */
  12963. t.prototype.close = function(t, r) {
  12964. return e(this, void 0, void 0, (function() {
  12965. return n(this, (function(e) {
  12966. switch (e.label) {
  12967. case 0:
  12968. // Notify the listener that the stream closed.
  12969. // Cancel any outstanding timers (they're guaranteed not to execute).
  12970. return this.Ho(), this.Jo(), this.qo.cancel(),
  12971. // Invalidates any stream-related callbacks (e.g. from auth or the
  12972. // underlying stream), guaranteeing they won't execute.
  12973. this.Fo++, 4 /* PersistentStreamState.Error */ !== t ?
  12974. // If this is an intentional close ensure we don't delay our next connection attempt.
  12975. this.qo.reset() : r && r.code === K.RESOURCE_EXHAUSTED ? (
  12976. // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
  12977. L(r.toString()), L("Using maximum backoff delay to prevent overloading the backend."),
  12978. this.qo.xo()) : r && r.code === K.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (
  12979. // "unauthenticated" error means the token was rejected. This should rarely
  12980. // happen since both Auth and AppCheck ensure a sufficient TTL when we
  12981. // request a token. If a user manually resets their system clock this can
  12982. // fail, however. In this case, we should get a Code.UNAUTHENTICATED error
  12983. // before we received the first message and we need to invalidate the token
  12984. // to ensure that we fetch a new token.
  12985. this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()),
  12986. // Clean up the underlying stream because we are no longer interested in events.
  12987. null !== this.stream && (this.Yo(), this.stream.close(), this.stream = null),
  12988. // This state must be assigned before calling onClose() to allow the callback to
  12989. // inhibit backoff or otherwise manipulate the state in its non-started state.
  12990. this.state = t, [ 4 /*yield*/ , this.listener.ao(r) ];
  12991. case 1:
  12992. // Cancel any outstanding timers (they're guaranteed not to execute).
  12993. // Notify the listener that the stream closed.
  12994. return e.sent(), [ 2 /*return*/ ];
  12995. }
  12996. }));
  12997. }));
  12998. },
  12999. /**
  13000. * Can be overridden to perform additional cleanup before the stream is closed.
  13001. * Calling super.tearDown() is not required.
  13002. */
  13003. t.prototype.Yo = function() {}, t.prototype.auth = function() {
  13004. var t = this;
  13005. this.state = 1 /* PersistentStreamState.Starting */;
  13006. var e = this.Xo(this.Fo), n = this.Fo;
  13007. // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
  13008. Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((function(e) {
  13009. var r = e[0], i = e[1];
  13010. // Stream can be stopped while waiting for authentication.
  13011. // TODO(mikelehen): We really should just use dispatchIfNotClosed
  13012. // and let this dispatch onto the queue, but that opened a spec test can
  13013. // of worms that I don't want to deal with in this PR.
  13014. t.Fo === n &&
  13015. // Normally we'd have to schedule the callback on the AsyncQueue.
  13016. // However, the following calls are safe to be called outside the
  13017. // AsyncQueue since they don't chain asynchronous calls
  13018. t.Zo(r, i);
  13019. }), (function(n) {
  13020. e((function() {
  13021. var e = new Q(K.UNKNOWN, "Fetching auth token failed: " + n.message);
  13022. return t.tu(e);
  13023. }));
  13024. }));
  13025. }, t.prototype.Zo = function(t, e) {
  13026. var n = this, r = this.Xo(this.Fo);
  13027. this.stream = this.eu(t, e), this.stream.uo((function() {
  13028. r((function() {
  13029. return n.state = 2 /* PersistentStreamState.Open */ , n.Lo = n.ii.enqueueAfterDelay(n.Oo, 1e4, (function() {
  13030. return n.Ko() && (n.state = 3 /* PersistentStreamState.Healthy */), Promise.resolve();
  13031. })), n.listener.uo();
  13032. }));
  13033. })), this.stream.ao((function(t) {
  13034. r((function() {
  13035. return n.tu(t);
  13036. }));
  13037. })), this.stream.onMessage((function(t) {
  13038. r((function() {
  13039. return n.onMessage(t);
  13040. }));
  13041. }));
  13042. }, t.prototype.Go = function() {
  13043. var t = this;
  13044. this.state = 5 /* PersistentStreamState.Backoff */ , this.qo.No((function() {
  13045. return e(t, void 0, void 0, (function() {
  13046. return n(this, (function(t) {
  13047. return this.state = 0 /* PersistentStreamState.Initial */ , this.start(), [ 2 /*return*/ ];
  13048. }));
  13049. }));
  13050. }));
  13051. },
  13052. // Visible for tests
  13053. t.prototype.tu = function(t) {
  13054. // In theory the stream could close cleanly, however, in our current model
  13055. // we never expect this to happen because if we stop a stream ourselves,
  13056. // this callback will never be called. To prevent cases where we retry
  13057. // without a backoff accidentally, we set the stream to error in all cases.
  13058. return M("PersistentStream", "close with error: ".concat(t)), this.stream = null,
  13059. this.close(4 /* PersistentStreamState.Error */ , t);
  13060. },
  13061. /**
  13062. * Returns a "dispatcher" function that dispatches operations onto the
  13063. * AsyncQueue but only runs them if closeCount remains unchanged. This allows
  13064. * us to turn auth / stream callbacks into no-ops if the stream is closed /
  13065. * re-opened, etc.
  13066. */
  13067. t.prototype.Xo = function(t) {
  13068. var e = this;
  13069. return function(n) {
  13070. e.ii.enqueueAndForget((function() {
  13071. return e.Fo === t ? n() : (M("PersistentStream", "stream callback skipped by getCloseGuardedDispatcher."),
  13072. Promise.resolve());
  13073. }));
  13074. };
  13075. }, t;
  13076. }(), qa = /** @class */ function(e) {
  13077. function n(t, n, r, i, o, u) {
  13078. var a = this;
  13079. return (a = e.call(this, t, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */ , "listen_stream_idle" /* TimerId.ListenStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , n, r, i, u) || this).serializer = o,
  13080. a;
  13081. }
  13082. return t(n, e), n.prototype.eu = function(t, e) {
  13083. return this.connection.Ro("Listen", t, e);
  13084. }, n.prototype.onMessage = function(t) {
  13085. // A successful response means the stream is healthy
  13086. this.qo.reset();
  13087. var e = function(t, e) {
  13088. var n;
  13089. if ("targetChange" in e) {
  13090. e.targetChange;
  13091. // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
  13092. // if unset
  13093. var r = function(t) {
  13094. 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 */ : U();
  13095. }(e.targetChange.targetChangeType || "NO_CHANGE"), i = e.targetChange.targetIds || [], o = function(t, e) {
  13096. return t.useProto3Json ? (z(void 0 === e || "string" == typeof e), Oe.fromBase64String(e || "")) : (z(void 0 === e || e instanceof Uint8Array),
  13097. Oe.fromUint8Array(e || new Uint8Array));
  13098. }(t, e.targetChange.resumeToken), u = e.targetChange.cause, a = u && function(t) {
  13099. var e = void 0 === t.code ? K.UNKNOWN : li(t.code);
  13100. return new Q(e, t.message || "");
  13101. }(u);
  13102. n = new Ti(r, i, o, a || null);
  13103. } else if ("documentChange" in e) {
  13104. e.documentChange;
  13105. var s = e.documentChange;
  13106. s.document, s.document.name, s.document.updateTime;
  13107. var c = Bi(t, s.document.name), l = Vi(s.document.updateTime), h = s.document.createTime ? Vi(s.document.createTime) : ct.min(), f = new hn({
  13108. mapValue: {
  13109. fields: s.document.fields
  13110. }
  13111. }), d = dn.newFoundDocument(c, l, h, f), p = s.targetIds || [], v = s.removedTargetIds || [];
  13112. n = new Ii(p, v, d.key, d);
  13113. } else if ("documentDelete" in e) {
  13114. e.documentDelete;
  13115. var m = e.documentDelete;
  13116. m.document;
  13117. var y = Bi(t, m.document), g = m.readTime ? Vi(m.readTime) : ct.min(), w = dn.newNoDocument(y, g), b = m.removedTargetIds || [];
  13118. n = new Ii([], b, w.key, w);
  13119. } else if ("documentRemove" in e) {
  13120. e.documentRemove;
  13121. var I = e.documentRemove;
  13122. I.document;
  13123. var E = Bi(t, I.document), T = I.removedTargetIds || [];
  13124. n = new Ii([], T, E, null);
  13125. } else {
  13126. if (!("filter" in e)) return U();
  13127. e.filter;
  13128. var S = e.filter;
  13129. S.targetId;
  13130. var _ = S.count, D = void 0 === _ ? 0 : _, C = S.unchangedNames, x = new si(D, C), N = S.targetId;
  13131. n = new Ei(N, x);
  13132. }
  13133. return n;
  13134. }(this.serializer, t), n = function(t) {
  13135. // We have only reached a consistent snapshot for the entire stream if there
  13136. // is a read_time set and it applies to all targets (i.e. the list of
  13137. // targets is empty). The backend is guaranteed to send such responses.
  13138. if (!("targetChange" in t)) return ct.min();
  13139. var e = t.targetChange;
  13140. return e.targetIds && e.targetIds.length ? ct.min() : e.readTime ? Vi(e.readTime) : ct.min();
  13141. }(t);
  13142. return this.listener.nu(e, n);
  13143. },
  13144. /**
  13145. * Registers interest in the results of the given target. If the target
  13146. * includes a resumeToken it will be included in the request. Results that
  13147. * affect the target will be streamed back as WatchChange messages that
  13148. * reference the targetId.
  13149. */
  13150. n.prototype.su = function(t) {
  13151. var e = {};
  13152. e.database = Gi(this.serializer), e.addTarget = function(t, e) {
  13153. var n, r = e.target;
  13154. if ((n = zn(r) ? {
  13155. documents: Yi(t, r)
  13156. } : {
  13157. query: Xi(t, r)
  13158. }).targetId = e.targetId, e.resumeToken.approximateByteSize() > 0) {
  13159. n.resumeToken = Pi(t, e.resumeToken);
  13160. var i = Oi(t, e.expectedCount);
  13161. null !== i && (n.expectedCount = i);
  13162. } else if (e.snapshotVersion.compareTo(ct.min()) > 0) {
  13163. // TODO(wuandy): Consider removing above check because it is most likely true.
  13164. // Right now, many tests depend on this behaviour though (leaving min() out
  13165. // of serialization).
  13166. n.readTime = Fi(t, e.snapshotVersion.toTimestamp());
  13167. var o = Oi(t, e.expectedCount);
  13168. null !== o && (n.expectedCount = o);
  13169. }
  13170. return n;
  13171. }(this.serializer, t);
  13172. var n = function(t, e) {
  13173. var n = function(t) {
  13174. switch (t) {
  13175. case "TargetPurposeListen" /* TargetPurpose.Listen */ :
  13176. return null;
  13177. case "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */ :
  13178. return "existence-filter-mismatch";
  13179. case "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ :
  13180. return "existence-filter-mismatch-bloom";
  13181. case "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ :
  13182. return "limbo-document";
  13183. default:
  13184. return U();
  13185. }
  13186. }(e.purpose);
  13187. return null == n ? null : {
  13188. "goog-listen-tags": n
  13189. };
  13190. }(this.serializer, t);
  13191. n && (e.labels = n), this.Wo(e);
  13192. },
  13193. /**
  13194. * Unregisters interest in the results of the target associated with the
  13195. * given targetId.
  13196. */
  13197. n.prototype.iu = function(t) {
  13198. var e = {};
  13199. e.database = Gi(this.serializer), e.removeTarget = t, this.Wo(e);
  13200. }, n;
  13201. }(La), Ba = /** @class */ function(e) {
  13202. function n(t, n, r, i, o, u) {
  13203. var a = this;
  13204. return (a = e.call(this, t, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */ , "write_stream_idle" /* TimerId.WriteStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , n, r, i, u) || this).serializer = o,
  13205. a.ru = !1, a;
  13206. }
  13207. return t(n, e), Object.defineProperty(n.prototype, "ou", {
  13208. /**
  13209. * Tracks whether or not a handshake has been successfully exchanged and
  13210. * the stream is ready to accept mutations.
  13211. */
  13212. get: function() {
  13213. return this.ru;
  13214. },
  13215. enumerable: !1,
  13216. configurable: !0
  13217. }),
  13218. // Override of PersistentStream.start
  13219. n.prototype.start = function() {
  13220. this.ru = !1, this.lastStreamToken = void 0, e.prototype.start.call(this);
  13221. }, n.prototype.Yo = function() {
  13222. this.ru && this.uu([]);
  13223. }, n.prototype.eu = function(t, e) {
  13224. return this.connection.Ro("Write", t, e);
  13225. }, n.prototype.onMessage = function(t) {
  13226. if (
  13227. // Always capture the last stream token.
  13228. z(!!t.streamToken), this.lastStreamToken = t.streamToken, this.ru) {
  13229. // A successful first write response means the stream is healthy,
  13230. // Note, that we could consider a successful handshake healthy, however,
  13231. // the write itself might be causing an error we want to back off from.
  13232. this.qo.reset();
  13233. var e = function(t, e) {
  13234. return t && t.length > 0 ? (z(void 0 !== e), t.map((function(t) {
  13235. return function(t, e) {
  13236. // NOTE: Deletes don't have an updateTime.
  13237. var n = t.updateTime ? Vi(t.updateTime) : Vi(e);
  13238. return n.isEqual(ct.min()) && (
  13239. // The Firestore Emulator currently returns an update time of 0 for
  13240. // deletes of non-existing documents (rather than null). This breaks the
  13241. // test "get deleted doc while offline with source=cache" as NoDocuments
  13242. // with version 0 are filtered by IndexedDb's RemoteDocumentCache.
  13243. // TODO(#2149): Remove this when Emulator is fixed
  13244. n = Vi(e)), new Br(n, t.transformResults || []);
  13245. }(t, e);
  13246. }))) : [];
  13247. }(t.writeResults, t.commitTime), n = Vi(t.commitTime);
  13248. return this.listener.cu(n, e);
  13249. }
  13250. // The first response is always the handshake response
  13251. return z(!t.writeResults || 0 === t.writeResults.length), this.ru = !0,
  13252. this.listener.au();
  13253. },
  13254. /**
  13255. * Sends an initial streamToken to the server, performing the handshake
  13256. * required to make the StreamingWrite RPC work. Subsequent
  13257. * calls should wait until onHandshakeComplete was called.
  13258. */
  13259. n.prototype.hu = function() {
  13260. // TODO(dimond): Support stream resumption. We intentionally do not set the
  13261. // stream token on the handshake, ignoring any stream token we might have.
  13262. var t = {};
  13263. t.database = Gi(this.serializer), this.Wo(t);
  13264. },
  13265. /** Sends a group of mutations to the Firestore backend to apply. */ n.prototype.uu = function(t) {
  13266. var e = this, n = {
  13267. streamToken: this.lastStreamToken,
  13268. writes: t.map((function(t) {
  13269. return Wi(e.serializer, t);
  13270. }))
  13271. };
  13272. this.Wo(n);
  13273. }, n;
  13274. }(La), Ua = /** @class */ function(e) {
  13275. function n(t, n, r, i) {
  13276. var o = this;
  13277. return (o = e.call(this) || this).authCredentials = t, o.appCheckCredentials = n,
  13278. o.connection = r, o.serializer = i, o.lu = !1, o;
  13279. }
  13280. return t(n, e), n.prototype.fu = function() {
  13281. if (this.lu) throw new Q(K.FAILED_PRECONDITION, "The client has already been terminated.");
  13282. },
  13283. /** Invokes the provided RPC with auth and AppCheck tokens. */ n.prototype.Io = function(t, e, n) {
  13284. var r = this;
  13285. return this.fu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((function(i) {
  13286. var o = i[0], u = i[1];
  13287. return r.connection.Io(t, e, n, o, u);
  13288. })).catch((function(t) {
  13289. throw "FirebaseError" === t.name ? (t.code === K.UNAUTHENTICATED && (r.authCredentials.invalidateToken(),
  13290. r.appCheckCredentials.invalidateToken()), t) : new Q(K.UNKNOWN, t.toString());
  13291. }));
  13292. },
  13293. /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ n.prototype.vo = function(t, e, n, r) {
  13294. var i = this;
  13295. return this.fu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((function(o) {
  13296. var u = o[0], a = o[1];
  13297. return i.connection.vo(t, e, n, u, a, r);
  13298. })).catch((function(t) {
  13299. throw "FirebaseError" === t.name ? (t.code === K.UNAUTHENTICATED && (i.authCredentials.invalidateToken(),
  13300. i.appCheckCredentials.invalidateToken()), t) : new Q(K.UNKNOWN, t.toString());
  13301. }));
  13302. }, n.prototype.terminate = function() {
  13303. this.lu = !0;
  13304. }, n;
  13305. }((function() {}));
  13306. /**
  13307. * @license
  13308. * Copyright 2017 Google LLC
  13309. *
  13310. * Licensed under the Apache License, Version 2.0 (the "License");
  13311. * you may not use this file except in compliance with the License.
  13312. * You may obtain a copy of the License at
  13313. *
  13314. * http://www.apache.org/licenses/LICENSE-2.0
  13315. *
  13316. * Unless required by applicable law or agreed to in writing, software
  13317. * distributed under the License is distributed on an "AS IS" BASIS,
  13318. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13319. * See the License for the specific language governing permissions and
  13320. * limitations under the License.
  13321. */
  13322. /**
  13323. * A PersistentStream is an abstract base class that represents a streaming RPC
  13324. * to the Firestore backend. It's built on top of the connections own support
  13325. * for streaming RPCs, and adds several critical features for our clients:
  13326. *
  13327. * - Exponential backoff on failure
  13328. * - Authentication via CredentialsProvider
  13329. * - Dispatching all callbacks into the shared worker queue
  13330. * - Closing idle streams after 60 seconds of inactivity
  13331. *
  13332. * Subclasses of PersistentStream implement serialization of models to and
  13333. * from the JSON representation of the protocol buffers for a specific
  13334. * streaming RPC.
  13335. *
  13336. * ## Starting and Stopping
  13337. *
  13338. * Streaming RPCs are stateful and need to be start()ed before messages can
  13339. * be sent and received. The PersistentStream will call the onOpen() function
  13340. * of the listener once the stream is ready to accept requests.
  13341. *
  13342. * Should a start() fail, PersistentStream will call the registered onClose()
  13343. * listener with a FirestoreError indicating what went wrong.
  13344. *
  13345. * A PersistentStream can be started and stopped repeatedly.
  13346. *
  13347. * Generic types:
  13348. * SendType: The type of the outgoing message of the underlying
  13349. * connection stream
  13350. * ReceiveType: The type of the incoming message of the underlying
  13351. * connection stream
  13352. * ListenerType: The type of the listener that will be used for callbacks
  13353. */
  13354. /**
  13355. * A component used by the RemoteStore to track the OnlineState (that is,
  13356. * whether or not the client as a whole should be considered to be online or
  13357. * offline), implementing the appropriate heuristics.
  13358. *
  13359. * In particular, when the client is trying to connect to the backend, we
  13360. * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for
  13361. * a connection to succeed. If we have too many failures or the timeout elapses,
  13362. * then we set the OnlineState to Offline, and the client will behave as if
  13363. * it is offline (get()s will return cached data, etc.).
  13364. */
  13365. var za = /** @class */ function() {
  13366. function t(t, e) {
  13367. this.asyncQueue = t, this.onlineStateHandler = e,
  13368. /** The current OnlineState. */
  13369. this.state = "Unknown" /* OnlineState.Unknown */ ,
  13370. /**
  13371. * A count of consecutive failures to open the stream. If it reaches the
  13372. * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
  13373. * Offline.
  13374. */
  13375. this.wu = 0,
  13376. /**
  13377. * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
  13378. * transition from OnlineState.Unknown to OnlineState.Offline without waiting
  13379. * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
  13380. */
  13381. this._u = null,
  13382. /**
  13383. * Whether the client should log a warning message if it fails to connect to
  13384. * the backend (initially true, cleared after a successful stream, or if we've
  13385. * logged the message already).
  13386. */
  13387. this.mu = !0
  13388. /**
  13389. * Called by RemoteStore when a watch stream is started (including on each
  13390. * backoff attempt).
  13391. *
  13392. * If this is the first attempt, it sets the OnlineState to Unknown and starts
  13393. * the onlineStateTimer.
  13394. */;
  13395. }
  13396. return t.prototype.gu = function() {
  13397. var t = this;
  13398. 0 === this.wu && (this.yu("Unknown" /* OnlineState.Unknown */), this._u = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */ , 1e4, (function() {
  13399. return t._u = null, t.pu("Backend didn't respond within 10 seconds."), t.yu("Offline" /* OnlineState.Offline */),
  13400. Promise.resolve();
  13401. })));
  13402. },
  13403. /**
  13404. * Updates our OnlineState as appropriate after the watch stream reports a
  13405. * failure. The first failure moves us to the 'Unknown' state. We then may
  13406. * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
  13407. * actually transition to the 'Offline' state.
  13408. */
  13409. t.prototype.Iu = function(t) {
  13410. "Online" /* OnlineState.Online */ === this.state ? this.yu("Unknown" /* OnlineState.Unknown */) : (this.wu++,
  13411. this.wu >= 1 && (this.Tu(), this.pu("Connection failed 1 times. Most recent error: ".concat(t.toString())),
  13412. this.yu("Offline" /* OnlineState.Offline */)));
  13413. },
  13414. /**
  13415. * Explicitly sets the OnlineState to the specified state.
  13416. *
  13417. * Note that this resets our timers / failure counters, etc. used by our
  13418. * Offline heuristics, so must not be used in place of
  13419. * handleWatchStreamStart() and handleWatchStreamFailure().
  13420. */
  13421. t.prototype.set = function(t) {
  13422. this.Tu(), this.wu = 0, "Online" /* OnlineState.Online */ === t && (
  13423. // We've connected to watch at least once. Don't warn the developer
  13424. // about being offline going forward.
  13425. this.mu = !1), this.yu(t);
  13426. }, t.prototype.yu = function(t) {
  13427. t !== this.state && (this.state = t, this.onlineStateHandler(t));
  13428. }, t.prototype.pu = function(t) {
  13429. var e = "Could not reach Cloud Firestore backend. ".concat(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.");
  13430. this.mu ? (L(e), this.mu = !1) : M("OnlineStateTracker", e);
  13431. }, t.prototype.Tu = function() {
  13432. null !== this._u && (this._u.cancel(), this._u = null);
  13433. }, t;
  13434. }(), Ga = function(
  13435. /**
  13436. * The local store, used to fill the write pipeline with outbound mutations.
  13437. */
  13438. t,
  13439. /** The client-side proxy for interacting with the backend. */
  13440. r, i, o, u) {
  13441. var a = this;
  13442. this.localStore = t, this.datastore = r, this.asyncQueue = i, this.remoteSyncer = {},
  13443. /**
  13444. * A list of up to MAX_PENDING_WRITES writes that we have fetched from the
  13445. * LocalStore via fillWritePipeline() and have or will send to the write
  13446. * stream.
  13447. *
  13448. * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
  13449. * restart the write stream. When the stream is established the writes in the
  13450. * pipeline will be sent in order.
  13451. *
  13452. * Writes remain in writePipeline until they are acknowledged by the backend
  13453. * and thus will automatically be re-sent if the stream is interrupted /
  13454. * restarted before they're acknowledged.
  13455. *
  13456. * Write responses from the backend are linked to their originating request
  13457. * purely based on order, and so we can just shift() writes from the front of
  13458. * the writePipeline as we receive responses.
  13459. */
  13460. this.Eu = [],
  13461. /**
  13462. * A mapping of watched targets that the client cares about tracking and the
  13463. * user has explicitly called a 'listen' for this target.
  13464. *
  13465. * These targets may or may not have been sent to or acknowledged by the
  13466. * server. On re-establishing the listen stream, these targets should be sent
  13467. * to the server. The targets removed with unlistens are removed eagerly
  13468. * without waiting for confirmation from the listen stream.
  13469. */
  13470. this.Au = new Map,
  13471. /**
  13472. * A set of reasons for why the RemoteStore may be offline. If empty, the
  13473. * RemoteStore may start its network connections.
  13474. */
  13475. this.vu = new Set,
  13476. /**
  13477. * Event handlers that get called when the network is disabled or enabled.
  13478. *
  13479. * PORTING NOTE: These functions are used on the Web client to create the
  13480. * underlying streams (to support tree-shakeable streams). On Android and iOS,
  13481. * the streams are created during construction of RemoteStore.
  13482. */
  13483. this.Ru = [], this.Pu = u, this.Pu.Yr((function(t) {
  13484. i.enqueueAndForget((function() {
  13485. return e(a, void 0, void 0, (function() {
  13486. return n(this, (function(t) {
  13487. switch (t.label) {
  13488. case 0:
  13489. return Za(this) ? (M("RemoteStore", "Restarting streams for network reachability change."),
  13490. [ 4 /*yield*/ , function(t) {
  13491. return e(this, void 0, void 0, (function() {
  13492. var e;
  13493. return n(this, (function(n) {
  13494. switch (n.label) {
  13495. case 0:
  13496. return (e = j(t)).vu.add(4 /* OfflineCause.ConnectivityChange */), [ 4 /*yield*/ , Ka(e) ];
  13497. case 1:
  13498. return n.sent(), e.bu.set("Unknown" /* OnlineState.Unknown */), e.vu.delete(4 /* OfflineCause.ConnectivityChange */),
  13499. [ 4 /*yield*/ , ja(e) ];
  13500. case 2:
  13501. return n.sent(), [ 2 /*return*/ ];
  13502. }
  13503. }));
  13504. }));
  13505. }(this) ]) : [ 3 /*break*/ , 2 ];
  13506. case 1:
  13507. t.sent(), t.label = 2;
  13508. case 2:
  13509. return [ 2 /*return*/ ];
  13510. }
  13511. }));
  13512. }));
  13513. }));
  13514. })), this.bu = new za(i, o);
  13515. };
  13516. /**
  13517. * @license
  13518. * Copyright 2017 Google LLC
  13519. *
  13520. * Licensed under the Apache License, Version 2.0 (the "License");
  13521. * you may not use this file except in compliance with the License.
  13522. * You may obtain a copy of the License at
  13523. *
  13524. * http://www.apache.org/licenses/LICENSE-2.0
  13525. *
  13526. * Unless required by applicable law or agreed to in writing, software
  13527. * distributed under the License is distributed on an "AS IS" BASIS,
  13528. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13529. * See the License for the specific language governing permissions and
  13530. * limitations under the License.
  13531. */ function ja(t) {
  13532. return e(this, void 0, void 0, (function() {
  13533. var e, r;
  13534. return n(this, (function(n) {
  13535. switch (n.label) {
  13536. case 0:
  13537. if (!Za(t)) return [ 3 /*break*/ , 4 ];
  13538. e = 0, r = t.Ru, n.label = 1;
  13539. case 1:
  13540. return e < r.length ? [ 4 /*yield*/ , (0, r[e])(/* enabled= */ !0) ] : [ 3 /*break*/ , 4 ];
  13541. case 2:
  13542. n.sent(), n.label = 3;
  13543. case 3:
  13544. return e++, [ 3 /*break*/ , 1 ];
  13545. case 4:
  13546. return [ 2 /*return*/ ];
  13547. }
  13548. }));
  13549. }));
  13550. }
  13551. /**
  13552. * Temporarily disables the network. The network can be re-enabled using
  13553. * enableNetwork().
  13554. */ function Ka(t) {
  13555. return e(this, void 0, void 0, (function() {
  13556. var e, r;
  13557. return n(this, (function(n) {
  13558. switch (n.label) {
  13559. case 0:
  13560. e = 0, r = t.Ru, n.label = 1;
  13561. case 1:
  13562. return e < r.length ? [ 4 /*yield*/ , (0, r[e])(/* enabled= */ !1) ] : [ 3 /*break*/ , 4 ];
  13563. case 2:
  13564. n.sent(), n.label = 3;
  13565. case 3:
  13566. return e++, [ 3 /*break*/ , 1 ];
  13567. case 4:
  13568. return [ 2 /*return*/ ];
  13569. }
  13570. }));
  13571. }));
  13572. }
  13573. /**
  13574. * Starts new listen for the given target. Uses resume token if provided. It
  13575. * is a no-op if the target of given `TargetData` is already being listened to.
  13576. */ function Qa(t, e) {
  13577. var n = j(t);
  13578. n.Au.has(e.targetId) || (
  13579. // Mark this as something the client is currently listening for.
  13580. n.Au.set(e.targetId, e), Ja(n) ?
  13581. // The listen will be sent in onWatchStreamOpen
  13582. Xa(n) : ps(n).Ko() && Ha(n, e));
  13583. }
  13584. /**
  13585. * Removes the listen from server. It is a no-op if the given target id is
  13586. * not being listened to.
  13587. */ function Wa(t, e) {
  13588. var n = j(t), r = ps(n);
  13589. n.Au.delete(e), r.Ko() && Ya(n, e), 0 === n.Au.size && (r.Ko() ? r.jo() : Za(n) &&
  13590. // Revert to OnlineState.Unknown if the watch stream is not open and we
  13591. // have no listeners, since without any listens to send we cannot
  13592. // confirm if the stream is healthy and upgrade to OnlineState.Online.
  13593. n.bu.set("Unknown" /* OnlineState.Unknown */));
  13594. }
  13595. /**
  13596. * We need to increment the the expected number of pending responses we're due
  13597. * from watch so we wait for the ack to process any messages from this target.
  13598. */ function Ha(t, e) {
  13599. if (t.Vu.qt(e.targetId), e.resumeToken.approximateByteSize() > 0 || e.snapshotVersion.compareTo(ct.min()) > 0) {
  13600. var n = t.remoteSyncer.getRemoteKeysForTarget(e.targetId).size;
  13601. e = e.withExpectedCount(n);
  13602. }
  13603. ps(t).su(e);
  13604. }
  13605. /**
  13606. * We need to increment the expected number of pending responses we're due
  13607. * from watch so we wait for the removal on the server before we process any
  13608. * messages from this target.
  13609. */ function Ya(t, e) {
  13610. t.Vu.qt(e), ps(t).iu(e);
  13611. }
  13612. function Xa(t) {
  13613. t.Vu = new _i({
  13614. getRemoteKeysForTarget: function(e) {
  13615. return t.remoteSyncer.getRemoteKeysForTarget(e);
  13616. },
  13617. le: function(e) {
  13618. return t.Au.get(e) || null;
  13619. },
  13620. ue: function() {
  13621. return t.datastore.serializer.databaseId;
  13622. }
  13623. }), ps(t).start(), t.bu.gu()
  13624. /**
  13625. * Returns whether the watch stream should be started because it's necessary
  13626. * and has not yet been started.
  13627. */;
  13628. }
  13629. function Ja(t) {
  13630. return Za(t) && !ps(t).Uo() && t.Au.size > 0;
  13631. }
  13632. function Za(t) {
  13633. return 0 === j(t).vu.size;
  13634. }
  13635. function $a(t) {
  13636. t.Vu = void 0;
  13637. }
  13638. function ts(t) {
  13639. return e(this, void 0, void 0, (function() {
  13640. return n(this, (function(e) {
  13641. return t.Au.forEach((function(e, n) {
  13642. Ha(t, e);
  13643. })), [ 2 /*return*/ ];
  13644. }));
  13645. }));
  13646. }
  13647. function es(t, r) {
  13648. return e(this, void 0, void 0, (function() {
  13649. return n(this, (function(e) {
  13650. return $a(t),
  13651. // If we still need the watch stream, retry the connection.
  13652. Ja(t) ? (t.bu.Iu(r), Xa(t)) :
  13653. // No need to restart watch stream because there are no active targets.
  13654. // The online state is set to unknown because there is no active attempt
  13655. // at establishing a connection
  13656. t.bu.set("Unknown" /* OnlineState.Unknown */), [ 2 /*return*/ ];
  13657. }));
  13658. }));
  13659. }
  13660. function ns(t, r, i) {
  13661. return e(this, void 0, void 0, (function() {
  13662. var o, u, a;
  13663. return n(this, (function(s) {
  13664. switch (s.label) {
  13665. case 0:
  13666. if (t.bu.set("Online" /* OnlineState.Online */), !(r instanceof Ti && 2 /* WatchTargetChangeState.Removed */ === r.state && r.cause))
  13667. // Mark the client as online since we got a message from the server
  13668. return [ 3 /*break*/ , 6 ];
  13669. s.label = 1;
  13670. case 1:
  13671. return s.trys.push([ 1, 3, , 5 ]), [ 4 /*yield*/ ,
  13672. /** Handles an error on a target */
  13673. function(t, r) {
  13674. return e(this, void 0, void 0, (function() {
  13675. var e, i, o, u;
  13676. return n(this, (function(n) {
  13677. switch (n.label) {
  13678. case 0:
  13679. e = r.cause, i = 0, o = r.targetIds, n.label = 1;
  13680. case 1:
  13681. return i < o.length ? (u = o[i], t.Au.has(u) ? [ 4 /*yield*/ , t.remoteSyncer.rejectListen(u, e) ] : [ 3 /*break*/ , 3 ]) : [ 3 /*break*/ , 5 ];
  13682. case 2:
  13683. n.sent(), t.Au.delete(u), t.Vu.removeTarget(u), n.label = 3;
  13684. case 3:
  13685. n.label = 4;
  13686. case 4:
  13687. return i++, [ 3 /*break*/ , 1 ];
  13688. case 5:
  13689. return [ 2 /*return*/ ];
  13690. }
  13691. }));
  13692. }));
  13693. }(t, r) ];
  13694. case 2:
  13695. return s.sent(), [ 3 /*break*/ , 5 ];
  13696. case 3:
  13697. return o = s.sent(), M("RemoteStore", "Failed to remove targets %s: %s ", r.targetIds.join(","), o),
  13698. [ 4 /*yield*/ , rs(t, o) ];
  13699. case 4:
  13700. return s.sent(), [ 3 /*break*/ , 5 ];
  13701. case 5:
  13702. return [ 3 /*break*/ , 13 ];
  13703. case 6:
  13704. if (r instanceof Ii ? t.Vu.Ht(r) : r instanceof Ei ? t.Vu.ne(r) : t.Vu.Xt(r), i.isEqual(ct.min())) return [ 3 /*break*/ , 13 ];
  13705. s.label = 7;
  13706. case 7:
  13707. return s.trys.push([ 7, 11, , 13 ]), [ 4 /*yield*/ , ia(t.localStore) ];
  13708. case 8:
  13709. return u = s.sent(), i.compareTo(u) >= 0 ? [ 4 /*yield*/ ,
  13710. /**
  13711. * Takes a batch of changes from the Datastore, repackages them as a
  13712. * RemoteEvent, and passes that on to the listener, which is typically the
  13713. * SyncEngine.
  13714. */
  13715. function(t, e) {
  13716. var n = t.Vu.ce(e);
  13717. // Update in-memory resume tokens. LocalStore will update the
  13718. // persistent view of these when applying the completed RemoteEvent.
  13719. return n.targetChanges.forEach((function(n, r) {
  13720. if (n.resumeToken.approximateByteSize() > 0) {
  13721. var i = t.Au.get(r);
  13722. // A watched target might have been removed already.
  13723. i && t.Au.set(r, i.withResumeToken(n.resumeToken, e));
  13724. }
  13725. })),
  13726. // Re-establish listens for the targets that have been invalidated by
  13727. // existence filter mismatches.
  13728. n.targetMismatches.forEach((function(e, n) {
  13729. var r = t.Au.get(e);
  13730. if (r) {
  13731. // Clear the resume token for the target, since we're in a known mismatch
  13732. // state.
  13733. t.Au.set(e, r.withResumeToken(Oe.EMPTY_BYTE_STRING, r.snapshotVersion)),
  13734. // Cause a hard reset by unwatching and rewatching immediately, but
  13735. // deliberately don't send a resume token so that we get a full update.
  13736. Ya(t, e);
  13737. // Mark the target we send as being on behalf of an existence filter
  13738. // mismatch, but don't actually retain that in listenTargets. This ensures
  13739. // that we flag the first re-listen this way without impacting future
  13740. // listens of this target (that might happen e.g. on reconnect).
  13741. var i = new ao(r.target, e, n, r.sequenceNumber);
  13742. Ha(t, i);
  13743. }
  13744. })), t.remoteSyncer.applyRemoteEvent(n);
  13745. }(t, i) ] : [ 3 /*break*/ , 10 ];
  13746. // We have received a target change with a global snapshot if the snapshot
  13747. // version is not equal to SnapshotVersion.min().
  13748. case 9:
  13749. // We have received a target change with a global snapshot if the snapshot
  13750. // version is not equal to SnapshotVersion.min().
  13751. s.sent(), s.label = 10;
  13752. case 10:
  13753. return [ 3 /*break*/ , 13 ];
  13754. case 11:
  13755. return M("RemoteStore", "Failed to raise snapshot:", a = s.sent()), [ 4 /*yield*/ , rs(t, a) ];
  13756. case 12:
  13757. return s.sent(), [ 3 /*break*/ , 13 ];
  13758. case 13:
  13759. return [ 2 /*return*/ ];
  13760. }
  13761. }));
  13762. }));
  13763. }
  13764. /**
  13765. * Recovery logic for IndexedDB errors that takes the network offline until
  13766. * `op` succeeds. Retries are scheduled with backoff using
  13767. * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is
  13768. * validated via a generic operation.
  13769. *
  13770. * The returned Promise is resolved once the network is disabled and before
  13771. * any retry attempt.
  13772. */ function rs(t, r, i) {
  13773. return e(this, void 0, void 0, (function() {
  13774. var o = this;
  13775. return n(this, (function(u) {
  13776. switch (u.label) {
  13777. case 0:
  13778. if (!Pt(r)) throw r;
  13779. // Disable network and raise offline snapshots
  13780. return t.vu.add(1 /* OfflineCause.IndexedDbFailed */), [ 4 /*yield*/ , Ka(t) ];
  13781. case 1:
  13782. // Disable network and raise offline snapshots
  13783. return u.sent(), t.bu.set("Offline" /* OnlineState.Offline */), i || (
  13784. // Use a simple read operation to determine if IndexedDB recovered.
  13785. // Ideally, we would expose a health check directly on SimpleDb, but
  13786. // RemoteStore only has access to persistence through LocalStore.
  13787. i = function() {
  13788. return ia(t.localStore);
  13789. }),
  13790. // Probe IndexedDB periodically and re-enable network
  13791. t.asyncQueue.enqueueRetryable((function() {
  13792. return e(o, void 0, void 0, (function() {
  13793. return n(this, (function(e) {
  13794. switch (e.label) {
  13795. case 0:
  13796. return M("RemoteStore", "Retrying IndexedDB access"), [ 4 /*yield*/ , i() ];
  13797. case 1:
  13798. return e.sent(), t.vu.delete(1 /* OfflineCause.IndexedDbFailed */), [ 4 /*yield*/ , ja(t) ];
  13799. case 2:
  13800. return e.sent(), [ 2 /*return*/ ];
  13801. }
  13802. }));
  13803. }));
  13804. })), [ 2 /*return*/ ];
  13805. }
  13806. }));
  13807. }));
  13808. }
  13809. /**
  13810. * Executes `op`. If `op` fails, takes the network offline until `op`
  13811. * succeeds. Returns after the first attempt.
  13812. */ function is(t, e) {
  13813. return e().catch((function(n) {
  13814. return rs(t, n, e);
  13815. }));
  13816. }
  13817. function os(t) {
  13818. return e(this, void 0, void 0, (function() {
  13819. var e, r, i, o, u;
  13820. return n(this, (function(n) {
  13821. switch (n.label) {
  13822. case 0:
  13823. e = j(t), r = vs(e), i = e.Eu.length > 0 ? e.Eu[e.Eu.length - 1].batchId : -1, n.label = 1;
  13824. case 1:
  13825. if (!
  13826. /**
  13827. * Returns true if we can add to the write pipeline (i.e. the network is
  13828. * enabled and the write pipeline is not full).
  13829. */
  13830. function(t) {
  13831. return Za(t) && t.Eu.length < 10;
  13832. }
  13833. /**
  13834. * Queues additional writes to be sent to the write stream, sending them
  13835. * immediately if the write stream is established.
  13836. */ (e)) return [ 3 /*break*/ , 7 ];
  13837. n.label = 2;
  13838. case 2:
  13839. return n.trys.push([ 2, 4, , 6 ]), [ 4 /*yield*/ , aa(e.localStore, i) ];
  13840. case 3:
  13841. return null === (o = n.sent()) ? (0 === e.Eu.length && r.jo(), [ 3 /*break*/ , 7 ]) : (i = o.batchId,
  13842. function(t, e) {
  13843. t.Eu.push(e);
  13844. var n = vs(t);
  13845. n.Ko() && n.ou && n.uu(e.mutations);
  13846. }(e, o), [ 3 /*break*/ , 6 ]);
  13847. case 4:
  13848. return u = n.sent(), [ 4 /*yield*/ , rs(e, u) ];
  13849. case 5:
  13850. return n.sent(), [ 3 /*break*/ , 6 ];
  13851. case 6:
  13852. return [ 3 /*break*/ , 1 ];
  13853. case 7:
  13854. return us(e) && as(e), [ 2 /*return*/ ];
  13855. }
  13856. }));
  13857. }));
  13858. }
  13859. function us(t) {
  13860. return Za(t) && !vs(t).Uo() && t.Eu.length > 0;
  13861. }
  13862. function as(t) {
  13863. vs(t).start();
  13864. }
  13865. function ss(t) {
  13866. return e(this, void 0, void 0, (function() {
  13867. return n(this, (function(e) {
  13868. return vs(t).hu(), [ 2 /*return*/ ];
  13869. }));
  13870. }));
  13871. }
  13872. function cs(t) {
  13873. return e(this, void 0, void 0, (function() {
  13874. var e, r, i, o;
  13875. return n(this, (function(n) {
  13876. // Send the write pipeline now that the stream is established.
  13877. for (e = vs(t), r = 0, i = t.Eu; r < i.length; r++) o = i[r], e.uu(o.mutations);
  13878. return [ 2 /*return*/ ];
  13879. }));
  13880. }));
  13881. }
  13882. function ls(t, r, i) {
  13883. return e(this, void 0, void 0, (function() {
  13884. var e, o;
  13885. return n(this, (function(n) {
  13886. switch (n.label) {
  13887. case 0:
  13888. return e = t.Eu.shift(), o = oi.from(e, r, i), [ 4 /*yield*/ , is(t, (function() {
  13889. return t.remoteSyncer.applySuccessfulWrite(o);
  13890. })) ];
  13891. case 1:
  13892. // It's possible that with the completion of this mutation another
  13893. // slot has freed up.
  13894. return n.sent(), [ 4 /*yield*/ , os(t) ];
  13895. case 2:
  13896. // It's possible that with the completion of this mutation another
  13897. // slot has freed up.
  13898. return n.sent(), [ 2 /*return*/ ];
  13899. }
  13900. }));
  13901. }));
  13902. }
  13903. function hs(t, r) {
  13904. return e(this, void 0, void 0, (function() {
  13905. return n(this, (function(i) {
  13906. switch (i.label) {
  13907. case 0:
  13908. return r && vs(t).ou ? [ 4 /*yield*/ , function(t, r) {
  13909. return e(this, void 0, void 0, (function() {
  13910. var e, i;
  13911. return n(this, (function(n) {
  13912. switch (n.label) {
  13913. case 0:
  13914. return ci(i = r.code) && i !== K.ABORTED ? (e = t.Eu.shift(),
  13915. // In this case it's also unlikely that the server itself is melting
  13916. // down -- this was just a bad request so inhibit backoff on the next
  13917. // restart.
  13918. vs(t).Qo(), [ 4 /*yield*/ , is(t, (function() {
  13919. return t.remoteSyncer.rejectFailedWrite(e.batchId, r);
  13920. })) ]) : [ 3 /*break*/ , 3 ];
  13921. case 1:
  13922. // It's possible that with the completion of this mutation
  13923. // another slot has freed up.
  13924. return n.sent(), [ 4 /*yield*/ , os(t) ];
  13925. case 2:
  13926. // In this case it's also unlikely that the server itself is melting
  13927. // down -- this was just a bad request so inhibit backoff on the next
  13928. // restart.
  13929. // It's possible that with the completion of this mutation
  13930. // another slot has freed up.
  13931. n.sent(), n.label = 3;
  13932. case 3:
  13933. return [ 2 /*return*/ ];
  13934. }
  13935. }));
  13936. }));
  13937. }(t, r) ] : [ 3 /*break*/ , 2 ];
  13938. // This error affects the actual write.
  13939. case 1:
  13940. // This error affects the actual write.
  13941. i.sent(), i.label = 2;
  13942. case 2:
  13943. // If the write stream closed after the write handshake completes, a write
  13944. // operation failed and we fail the pending operation.
  13945. // The write stream might have been started by refilling the write
  13946. // pipeline for failed writes
  13947. return us(t) && as(t), [ 2 /*return*/ ];
  13948. }
  13949. }));
  13950. }));
  13951. }
  13952. function fs(t, r) {
  13953. return e(this, void 0, void 0, (function() {
  13954. var e, i;
  13955. return n(this, (function(n) {
  13956. switch (n.label) {
  13957. case 0:
  13958. return (e = j(t)).asyncQueue.verifyOperationInProgress(), M("RemoteStore", "RemoteStore received new credentials"),
  13959. i = Za(e),
  13960. // Tear down and re-create our network streams. This will ensure we get a
  13961. // fresh auth token for the new user and re-fill the write pipeline with
  13962. // new mutations from the LocalStore (since mutations are per-user).
  13963. e.vu.add(3 /* OfflineCause.CredentialChange */), [ 4 /*yield*/ , Ka(e) ];
  13964. case 1:
  13965. return n.sent(), i &&
  13966. // Don't set the network status to Unknown if we are offline.
  13967. e.bu.set("Unknown" /* OnlineState.Unknown */), [ 4 /*yield*/ , e.remoteSyncer.handleCredentialChange(r) ];
  13968. case 2:
  13969. return n.sent(), e.vu.delete(3 /* OfflineCause.CredentialChange */), [ 4 /*yield*/ , ja(e) ];
  13970. case 3:
  13971. // Tear down and re-create our network streams. This will ensure we get a
  13972. // fresh auth token for the new user and re-fill the write pipeline with
  13973. // new mutations from the LocalStore (since mutations are per-user).
  13974. return n.sent(), [ 2 /*return*/ ];
  13975. }
  13976. }));
  13977. }));
  13978. }
  13979. /**
  13980. * Toggles the network state when the client gains or loses its primary lease.
  13981. */ function ds(t, r) {
  13982. return e(this, void 0, void 0, (function() {
  13983. var e;
  13984. return n(this, (function(n) {
  13985. switch (n.label) {
  13986. case 0:
  13987. return e = j(t), r ? (e.vu.delete(2 /* OfflineCause.IsSecondary */), [ 4 /*yield*/ , ja(e) ]) : [ 3 /*break*/ , 2 ];
  13988. case 1:
  13989. return n.sent(), [ 3 /*break*/ , 5 ];
  13990. case 2:
  13991. return r ? [ 3 /*break*/ , 4 ] : (e.vu.add(2 /* OfflineCause.IsSecondary */), [ 4 /*yield*/ , Ka(e) ]);
  13992. case 3:
  13993. n.sent(), e.bu.set("Unknown" /* OnlineState.Unknown */), n.label = 4;
  13994. case 4:
  13995. n.label = 5;
  13996. case 5:
  13997. return [ 2 /*return*/ ];
  13998. }
  13999. }));
  14000. }));
  14001. }
  14002. /**
  14003. * If not yet initialized, registers the WatchStream and its network state
  14004. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  14005. * already available.
  14006. *
  14007. * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.
  14008. * This is not done on Web to allow it to be tree-shaken.
  14009. */ function ps(t) {
  14010. var r = this;
  14011. return t.Su || (
  14012. // Create stream (but note that it is not started yet).
  14013. t.Su = function(t, e, n) {
  14014. var r = j(t);
  14015. return r.fu(), new qa(e, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);
  14016. }(t.datastore, t.asyncQueue, {
  14017. uo: ts.bind(null, t),
  14018. ao: es.bind(null, t),
  14019. nu: ns.bind(null, t)
  14020. }), t.Ru.push((function(i) {
  14021. return e(r, void 0, void 0, (function() {
  14022. return n(this, (function(e) {
  14023. switch (e.label) {
  14024. case 0:
  14025. return i ? (t.Su.Qo(), Ja(t) ? Xa(t) : t.bu.set("Unknown" /* OnlineState.Unknown */),
  14026. [ 3 /*break*/ , 3 ]) : [ 3 /*break*/ , 1 ];
  14027. case 1:
  14028. return [ 4 /*yield*/ , t.Su.stop() ];
  14029. case 2:
  14030. e.sent(), $a(t), e.label = 3;
  14031. case 3:
  14032. return [ 2 /*return*/ ];
  14033. }
  14034. }));
  14035. }));
  14036. }))), t.Su
  14037. /**
  14038. * If not yet initialized, registers the WriteStream and its network state
  14039. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  14040. * already available.
  14041. *
  14042. * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.
  14043. * This is not done on Web to allow it to be tree-shaken.
  14044. */;
  14045. }
  14046. function vs(t) {
  14047. var r = this;
  14048. return t.Du || (
  14049. // Create stream (but note that it is not started yet).
  14050. t.Du = function(t, e, n) {
  14051. var r = j(t);
  14052. return r.fu(), new Ba(e, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);
  14053. }(t.datastore, t.asyncQueue, {
  14054. uo: ss.bind(null, t),
  14055. ao: hs.bind(null, t),
  14056. au: cs.bind(null, t),
  14057. cu: ls.bind(null, t)
  14058. }), t.Ru.push((function(i) {
  14059. return e(r, void 0, void 0, (function() {
  14060. return n(this, (function(e) {
  14061. switch (e.label) {
  14062. case 0:
  14063. return i ? (t.Du.Qo(), [ 4 /*yield*/ , os(t) ]) : [ 3 /*break*/ , 2 ];
  14064. case 1:
  14065. // This will start the write stream if necessary.
  14066. return e.sent(), [ 3 /*break*/ , 4 ];
  14067. case 2:
  14068. return [ 4 /*yield*/ , t.Du.stop() ];
  14069. case 3:
  14070. e.sent(), t.Eu.length > 0 && (M("RemoteStore", "Stopping write stream with ".concat(t.Eu.length, " pending writes")),
  14071. t.Eu = []), e.label = 4;
  14072. case 4:
  14073. return [ 2 /*return*/ ];
  14074. }
  14075. }));
  14076. }));
  14077. }))), t.Du
  14078. /**
  14079. * @license
  14080. * Copyright 2017 Google LLC
  14081. *
  14082. * Licensed under the Apache License, Version 2.0 (the "License");
  14083. * you may not use this file except in compliance with the License.
  14084. * You may obtain a copy of the License at
  14085. *
  14086. * http://www.apache.org/licenses/LICENSE-2.0
  14087. *
  14088. * Unless required by applicable law or agreed to in writing, software
  14089. * distributed under the License is distributed on an "AS IS" BASIS,
  14090. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14091. * See the License for the specific language governing permissions and
  14092. * limitations under the License.
  14093. */
  14094. /**
  14095. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  14096. *
  14097. * It is created via DelayedOperation.createAndSchedule().
  14098. *
  14099. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  14100. *
  14101. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  14102. * in newer versions of TypeScript defines `finally`, which is not available in
  14103. * IE.
  14104. */;
  14105. }
  14106. var ms = /** @class */ function() {
  14107. function t(t, e, n, r, i) {
  14108. this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = r, this.removalCallback = i,
  14109. this.deferred = new W, this.then = this.deferred.promise.then.bind(this.deferred.promise),
  14110. // It's normal for the deferred promise to be canceled (due to cancellation)
  14111. // and so we attach a dummy catch callback to avoid
  14112. // 'UnhandledPromiseRejectionWarning' log spam.
  14113. this.deferred.promise.catch((function(t) {}))
  14114. /**
  14115. * Creates and returns a DelayedOperation that has been scheduled to be
  14116. * executed on the provided asyncQueue after the provided delayMs.
  14117. *
  14118. * @param asyncQueue - The queue to schedule the operation on.
  14119. * @param id - A Timer ID identifying the type of operation this is.
  14120. * @param delayMs - The delay (ms) before the operation should be scheduled.
  14121. * @param op - The operation to run.
  14122. * @param removalCallback - A callback to be called synchronously once the
  14123. * operation is executed or canceled, notifying the AsyncQueue to remove it
  14124. * from its delayedOperations list.
  14125. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  14126. * the DelayedOperation class public.
  14127. */;
  14128. }
  14129. return t.createAndSchedule = function(e, n, r, i, o) {
  14130. var u = new t(e, n, Date.now() + r, i, o);
  14131. return u.start(r), u;
  14132. },
  14133. /**
  14134. * Starts the timer. This is called immediately after construction by
  14135. * createAndSchedule().
  14136. */
  14137. t.prototype.start = function(t) {
  14138. var e = this;
  14139. this.timerHandle = setTimeout((function() {
  14140. return e.handleDelayElapsed();
  14141. }), t);
  14142. },
  14143. /**
  14144. * Queues the operation to run immediately (if it hasn't already been run or
  14145. * canceled).
  14146. */
  14147. t.prototype.skipDelay = function() {
  14148. return this.handleDelayElapsed();
  14149. },
  14150. /**
  14151. * Cancels the operation if it hasn't already been executed or canceled. The
  14152. * promise will be rejected.
  14153. *
  14154. * As long as the operation has not yet been run, calling cancel() provides a
  14155. * guarantee that the operation will not be run.
  14156. */
  14157. t.prototype.cancel = function(t) {
  14158. null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new Q(K.CANCELLED, "Operation cancelled" + (t ? ": " + t : ""))));
  14159. }, t.prototype.handleDelayElapsed = function() {
  14160. var t = this;
  14161. this.asyncQueue.enqueueAndForget((function() {
  14162. return null !== t.timerHandle ? (t.clearTimeout(), t.op().then((function(e) {
  14163. return t.deferred.resolve(e);
  14164. }))) : Promise.resolve();
  14165. }));
  14166. }, t.prototype.clearTimeout = function() {
  14167. null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle),
  14168. this.timerHandle = null);
  14169. }, t;
  14170. }();
  14171. /**
  14172. * Returns a FirestoreError that can be surfaced to the user if the provided
  14173. * error is an IndexedDbTransactionError. Re-throws the error otherwise.
  14174. */ function ys(t, e) {
  14175. if (L("AsyncQueue", "".concat(e, ": ").concat(t)), Pt(t)) return new Q(K.UNAVAILABLE, "".concat(e, ": ").concat(t));
  14176. throw t;
  14177. }
  14178. /**
  14179. * @license
  14180. * Copyright 2017 Google LLC
  14181. *
  14182. * Licensed under the Apache License, Version 2.0 (the "License");
  14183. * you may not use this file except in compliance with the License.
  14184. * You may obtain a copy of the License at
  14185. *
  14186. * http://www.apache.org/licenses/LICENSE-2.0
  14187. *
  14188. * Unless required by applicable law or agreed to in writing, software
  14189. * distributed under the License is distributed on an "AS IS" BASIS,
  14190. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14191. * See the License for the specific language governing permissions and
  14192. * limitations under the License.
  14193. */
  14194. /**
  14195. * DocumentSet is an immutable (copy-on-write) collection that holds documents
  14196. * in order specified by the provided comparator. We always add a document key
  14197. * comparator on top of what is provided to guarantee document equality based on
  14198. * the key.
  14199. */ var gs = /** @class */ function() {
  14200. /** The default ordering is by key if the comparator is omitted */
  14201. function t(t) {
  14202. // We are adding document key comparator to the end as it's the only
  14203. // guaranteed unique property of a document.
  14204. this.comparator = t ? function(e, n) {
  14205. return t(e, n) || pt.comparator(e.key, n.key);
  14206. } : function(t, e) {
  14207. return pt.comparator(t.key, e.key);
  14208. }, this.keyedMap = pr(), this.sortedSet = new Te(this.comparator)
  14209. /**
  14210. * Returns an empty copy of the existing DocumentSet, using the same
  14211. * comparator.
  14212. */;
  14213. }
  14214. return t.emptySet = function(e) {
  14215. return new t(e.comparator);
  14216. }, t.prototype.has = function(t) {
  14217. return null != this.keyedMap.get(t);
  14218. }, t.prototype.get = function(t) {
  14219. return this.keyedMap.get(t);
  14220. }, t.prototype.first = function() {
  14221. return this.sortedSet.minKey();
  14222. }, t.prototype.last = function() {
  14223. return this.sortedSet.maxKey();
  14224. }, t.prototype.isEmpty = function() {
  14225. return this.sortedSet.isEmpty();
  14226. },
  14227. /**
  14228. * Returns the index of the provided key in the document set, or -1 if the
  14229. * document key is not present in the set;
  14230. */
  14231. t.prototype.indexOf = function(t) {
  14232. var e = this.keyedMap.get(t);
  14233. return e ? this.sortedSet.indexOf(e) : -1;
  14234. }, Object.defineProperty(t.prototype, "size", {
  14235. get: function() {
  14236. return this.sortedSet.size;
  14237. },
  14238. enumerable: !1,
  14239. configurable: !0
  14240. }),
  14241. /** Iterates documents in order defined by "comparator" */ t.prototype.forEach = function(t) {
  14242. this.sortedSet.inorderTraversal((function(e, n) {
  14243. return t(e), !1;
  14244. }));
  14245. },
  14246. /** Inserts or updates a document with the same key */ t.prototype.add = function(t) {
  14247. // First remove the element if we have it.
  14248. var e = this.delete(t.key);
  14249. return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));
  14250. },
  14251. /** Deletes a document with a given key */ t.prototype.delete = function(t) {
  14252. var e = this.get(t);
  14253. return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;
  14254. }, t.prototype.isEqual = function(e) {
  14255. if (!(e instanceof t)) return !1;
  14256. if (this.size !== e.size) return !1;
  14257. for (var n = this.sortedSet.getIterator(), r = e.sortedSet.getIterator(); n.hasNext(); ) {
  14258. var i = n.getNext().key, o = r.getNext().key;
  14259. if (!i.isEqual(o)) return !1;
  14260. }
  14261. return !0;
  14262. }, t.prototype.toString = function() {
  14263. var t = [];
  14264. return this.forEach((function(e) {
  14265. t.push(e.toString());
  14266. })), 0 === t.length ? "DocumentSet ()" : "DocumentSet (\n " + t.join(" \n") + "\n)";
  14267. }, t.prototype.copy = function(e, n) {
  14268. var r = new t;
  14269. return r.comparator = this.comparator, r.keyedMap = e, r.sortedSet = n, r;
  14270. }, t;
  14271. }(), ws = /** @class */ function() {
  14272. function t() {
  14273. this.Cu = new Te(pt.comparator);
  14274. }
  14275. return t.prototype.track = function(t) {
  14276. var e = t.doc.key, n = this.Cu.get(e);
  14277. n ?
  14278. // Merge the new change with the existing change.
  14279. 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, {
  14280. type: n.type,
  14281. doc: t.doc
  14282. }) : 2 /* ChangeType.Modified */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Cu = this.Cu.insert(e, {
  14283. type: 2 /* ChangeType.Modified */ ,
  14284. doc: t.doc
  14285. }) : 2 /* ChangeType.Modified */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Cu = this.Cu.insert(e, {
  14286. type: 0 /* ChangeType.Added */ ,
  14287. doc: t.doc
  14288. }) : 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, {
  14289. type: 1 /* ChangeType.Removed */ ,
  14290. doc: n.doc
  14291. }) : 0 /* ChangeType.Added */ === t.type && 1 /* ChangeType.Removed */ === n.type ? this.Cu = this.Cu.insert(e, {
  14292. type: 2 /* ChangeType.Modified */ ,
  14293. doc: t.doc
  14294. }) :
  14295. // This includes these cases, which don't make sense:
  14296. // Added->Added
  14297. // Removed->Removed
  14298. // Modified->Added
  14299. // Removed->Modified
  14300. // Metadata->Added
  14301. // Removed->Metadata
  14302. U() : this.Cu = this.Cu.insert(e, t);
  14303. }, t.prototype.xu = function() {
  14304. var t = [];
  14305. return this.Cu.inorderTraversal((function(e, n) {
  14306. t.push(n);
  14307. })), t;
  14308. }, t;
  14309. }(), bs = /** @class */ function() {
  14310. function t(t, e, n, r, i, o, u, a, s) {
  14311. this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = r, this.mutatedKeys = i,
  14312. this.fromCache = o, this.syncStateChanged = u, this.excludesMetadataChanges = a,
  14313. this.hasCachedResults = s
  14314. /** Returns a view snapshot as if all documents in the snapshot were added. */;
  14315. }
  14316. return t.fromInitialDocuments = function(e, n, r, i, o) {
  14317. var u = [];
  14318. return n.forEach((function(t) {
  14319. u.push({
  14320. type: 0 /* ChangeType.Added */ ,
  14321. doc: t
  14322. });
  14323. })), new t(e, n, gs.emptySet(n), u, r, i,
  14324. /* syncStateChanged= */ !0,
  14325. /* excludesMetadataChanges= */ !1, o);
  14326. }, Object.defineProperty(t.prototype, "hasPendingWrites", {
  14327. get: function() {
  14328. return !this.mutatedKeys.isEmpty();
  14329. },
  14330. enumerable: !1,
  14331. configurable: !0
  14332. }), t.prototype.isEqual = function(t) {
  14333. if (!(this.fromCache === t.fromCache && this.hasCachedResults === t.hasCachedResults && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && rr(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;
  14334. var e = this.docChanges, n = t.docChanges;
  14335. if (e.length !== n.length) return !1;
  14336. for (var r = 0; r < e.length; r++) if (e[r].type !== n[r].type || !e[r].doc.isEqual(n[r].doc)) return !1;
  14337. return !0;
  14338. }, t;
  14339. }(), Is = function() {
  14340. this.Nu = void 0, this.listeners = [];
  14341. }, Es = function() {
  14342. this.queries = new lr((function(t) {
  14343. return ir(t);
  14344. }), rr), this.onlineState = "Unknown" /* OnlineState.Unknown */ , this.ku = new Set;
  14345. };
  14346. /**
  14347. * @license
  14348. * Copyright 2017 Google LLC
  14349. *
  14350. * Licensed under the Apache License, Version 2.0 (the "License");
  14351. * you may not use this file except in compliance with the License.
  14352. * You may obtain a copy of the License at
  14353. *
  14354. * http://www.apache.org/licenses/LICENSE-2.0
  14355. *
  14356. * Unless required by applicable law or agreed to in writing, software
  14357. * distributed under the License is distributed on an "AS IS" BASIS,
  14358. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14359. * See the License for the specific language governing permissions and
  14360. * limitations under the License.
  14361. */
  14362. /**
  14363. * DocumentChangeSet keeps track of a set of changes to docs in a query, merging
  14364. * duplicate events for the same doc.
  14365. */ function Ts(t, r) {
  14366. return e(this, void 0, void 0, (function() {
  14367. var e, i, o, u, a, s, c;
  14368. return n(this, (function(n) {
  14369. switch (n.label) {
  14370. case 0:
  14371. if (e = j(t), i = r.query, o = !1, (u = e.queries.get(i)) || (o = !0, u = new Is),
  14372. !o) return [ 3 /*break*/ , 4 ];
  14373. n.label = 1;
  14374. case 1:
  14375. return n.trys.push([ 1, 3, , 4 ]), a = u, [ 4 /*yield*/ , e.onListen(i) ];
  14376. case 2:
  14377. return a.Nu = n.sent(), [ 3 /*break*/ , 4 ];
  14378. case 3:
  14379. return s = n.sent(), c = ys(s, "Initialization of query '".concat(or(r.query), "' failed")),
  14380. [ 2 /*return*/ , void r.onError(c) ];
  14381. case 4:
  14382. return e.queries.set(i, u), u.listeners.push(r),
  14383. // Run global snapshot listeners if a consistent snapshot has been emitted.
  14384. r.Mu(e.onlineState), u.Nu && r.$u(u.Nu) && Cs(e), [ 2 /*return*/ ];
  14385. }
  14386. }));
  14387. }));
  14388. }
  14389. function Ss(t, r) {
  14390. return e(this, void 0, void 0, (function() {
  14391. var e, i, o, u, a;
  14392. return n(this, (function(n) {
  14393. return e = j(t), i = r.query, o = !1, (u = e.queries.get(i)) && (a = u.listeners.indexOf(r)) >= 0 && (u.listeners.splice(a, 1),
  14394. o = 0 === u.listeners.length), o ? [ 2 /*return*/ , (e.queries.delete(i), e.onUnlisten(i)) ] : [ 2 /*return*/ ];
  14395. }));
  14396. }));
  14397. }
  14398. function _s(t, e) {
  14399. for (var n = j(t), r = !1, i = 0, o = e; i < o.length; i++) {
  14400. var u = o[i], a = u.query, s = n.queries.get(a);
  14401. if (s) {
  14402. for (var c = 0, l = s.listeners; c < l.length; c++) {
  14403. l[c].$u(u) && (r = !0);
  14404. }
  14405. s.Nu = u;
  14406. }
  14407. }
  14408. r && Cs(n);
  14409. }
  14410. function Ds(t, e, n) {
  14411. var r = j(t), i = r.queries.get(e);
  14412. if (i) for (var o = 0, u = i.listeners; o < u.length; o++) {
  14413. u[o].onError(n);
  14414. }
  14415. // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
  14416. // after an error.
  14417. r.queries.delete(e);
  14418. }
  14419. // Call all global snapshot listeners that have been set.
  14420. function Cs(t) {
  14421. t.ku.forEach((function(t) {
  14422. t.next();
  14423. }));
  14424. }
  14425. /**
  14426. * QueryListener takes a series of internal view snapshots and determines
  14427. * when to raise the event.
  14428. *
  14429. * It uses an Observer to dispatch events.
  14430. */ var xs = /** @class */ function() {
  14431. function t(t, e, n) {
  14432. this.query = t, this.Ou = e,
  14433. /**
  14434. * Initial snapshots (e.g. from cache) may not be propagated to the wrapped
  14435. * observer. This flag is set to true once we've actually raised an event.
  14436. */
  14437. this.Fu = !1, this.Bu = null, this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14438. this.options = n || {}
  14439. /**
  14440. * Applies the new ViewSnapshot to this listener, raising a user-facing event
  14441. * if applicable (depending on what changed, whether the user has opted into
  14442. * metadata-only changes, etc.). Returns true if a user-facing event was
  14443. * indeed raised.
  14444. */;
  14445. }
  14446. return t.prototype.$u = function(t) {
  14447. if (!this.options.includeMetadataChanges) {
  14448. for (
  14449. // Remove the metadata only changes.
  14450. var e = [], n = 0, r = t.docChanges; n < r.length; n++) {
  14451. var i = r[n];
  14452. 3 /* ChangeType.Metadata */ !== i.type && e.push(i);
  14453. }
  14454. t = new bs(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged,
  14455. /* excludesMetadataChanges= */ !0, t.hasCachedResults);
  14456. }
  14457. var o = !1;
  14458. return this.Fu ? this.Lu(t) && (this.Ou.next(t), o = !0) : this.qu(t, this.onlineState) && (this.Uu(t),
  14459. o = !0), this.Bu = t, o;
  14460. }, t.prototype.onError = function(t) {
  14461. this.Ou.error(t);
  14462. },
  14463. /** Returns whether a snapshot was raised. */ t.prototype.Mu = function(t) {
  14464. this.onlineState = t;
  14465. var e = !1;
  14466. return this.Bu && !this.Fu && this.qu(this.Bu, t) && (this.Uu(this.Bu), e = !0),
  14467. e;
  14468. }, t.prototype.qu = function(t, e) {
  14469. // Always raise the first event when we're synced
  14470. if (!t.fromCache) return !0;
  14471. // NOTE: We consider OnlineState.Unknown as online (it should become Offline
  14472. // or Online if we wait long enough).
  14473. var n = "Offline" /* OnlineState.Offline */ !== e;
  14474. // Don't raise the event if we're online, aren't synced yet (checked
  14475. // above) and are waiting for a sync.
  14476. return (!this.options.Ku || !n) && (!t.docs.isEmpty() || t.hasCachedResults || "Offline" /* OnlineState.Offline */ === e);
  14477. // Raise data from cache if we have any documents, have cached results before,
  14478. // or we are offline.
  14479. }, t.prototype.Lu = function(t) {
  14480. // We don't need to handle includeDocumentMetadataChanges here because
  14481. // the Metadata only changes have already been stripped out if needed.
  14482. // At this point the only changes we will see are the ones we should
  14483. // propagate.
  14484. if (t.docChanges.length > 0) return !0;
  14485. var e = this.Bu && this.Bu.hasPendingWrites !== t.hasPendingWrites;
  14486. return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;
  14487. // Generally we should have hit one of the cases above, but it's possible
  14488. // to get here if there were only metadata docChanges and they got
  14489. // stripped out.
  14490. }, t.prototype.Uu = function(t) {
  14491. t = bs.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache, t.hasCachedResults),
  14492. this.Fu = !0, this.Ou.next(t);
  14493. }, t;
  14494. }(), Ns = /** @class */ function() {
  14495. function t(t,
  14496. // How many bytes this element takes to store in the bundle.
  14497. e) {
  14498. this.Gu = t, this.byteLength = e;
  14499. }
  14500. return t.prototype.Qu = function() {
  14501. return "metadata" in this.Gu;
  14502. }, t;
  14503. }(), As = /** @class */ function() {
  14504. function t(t) {
  14505. this.serializer = t;
  14506. }
  14507. return t.prototype.rr = function(t) {
  14508. return Bi(this.serializer, t);
  14509. },
  14510. /**
  14511. * Converts a BundleDocument to a MutableDocument.
  14512. */
  14513. t.prototype.ur = function(t) {
  14514. return t.metadata.exists ? Qi(this.serializer, t.document, !1) : dn.newNoDocument(this.rr(t.metadata.name), this.cr(t.metadata.readTime));
  14515. }, t.prototype.cr = function(t) {
  14516. return Vi(t);
  14517. }, t;
  14518. }(), ks = /** @class */ function() {
  14519. function t(t, e, n) {
  14520. this.ju = t, this.localStore = e, this.serializer = n,
  14521. /** Batched queries to be saved into storage */
  14522. this.queries = [],
  14523. /** Batched documents to be saved into storage */
  14524. this.documents = [],
  14525. /** The collection groups affected by this bundle. */
  14526. this.collectionGroups = new Set, this.progress = Os(t)
  14527. /**
  14528. * Adds an element from the bundle to the loader.
  14529. *
  14530. * Returns a new progress if adding the element leads to a new progress,
  14531. * otherwise returns null.
  14532. */;
  14533. }
  14534. return t.prototype.zu = function(t) {
  14535. this.progress.bytesLoaded += t.byteLength;
  14536. var e = this.progress.documentsLoaded;
  14537. if (t.Gu.namedQuery) this.queries.push(t.Gu.namedQuery); else if (t.Gu.documentMetadata) {
  14538. this.documents.push({
  14539. metadata: t.Gu.documentMetadata
  14540. }), t.Gu.documentMetadata.exists || ++e;
  14541. var n = ht.fromString(t.Gu.documentMetadata.name);
  14542. this.collectionGroups.add(n.get(n.length - 2));
  14543. } else t.Gu.document && (this.documents[this.documents.length - 1].document = t.Gu.document,
  14544. ++e);
  14545. return e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e,
  14546. Object.assign({}, this.progress)) : null;
  14547. }, t.prototype.Wu = function(t) {
  14548. for (var e = new Map, n = new As(this.serializer), r = 0, i = t; r < i.length; r++) {
  14549. var o = i[r];
  14550. if (o.metadata.queries) for (var u = n.rr(o.metadata.name), a = 0, s = o.metadata.queries; a < s.length; a++) {
  14551. var c = s[a], l = (e.get(c) || Ir()).add(u);
  14552. e.set(c, l);
  14553. }
  14554. }
  14555. return e;
  14556. },
  14557. /**
  14558. * Update the progress to 'Success' and return the updated progress.
  14559. */
  14560. t.prototype.complete = function() {
  14561. return e(this, void 0, void 0, (function() {
  14562. var t, e, r, i, o;
  14563. return n(this, (function(n) {
  14564. switch (n.label) {
  14565. case 0:
  14566. return [ 4 /*yield*/ , pa(this.localStore, new As(this.serializer), this.documents, this.ju.id) ];
  14567. case 1:
  14568. t = n.sent(), e = this.Wu(this.documents), r = 0, i = this.queries, n.label = 2;
  14569. case 2:
  14570. return r < i.length ? (o = i[r], [ 4 /*yield*/ , va(this.localStore, o, e.get(o.name)) ]) : [ 3 /*break*/ , 5 ];
  14571. case 3:
  14572. n.sent(), n.label = 4;
  14573. case 4:
  14574. return r++, [ 3 /*break*/ , 2 ];
  14575. case 5:
  14576. return [ 2 /*return*/ , (this.progress.taskState = "Success", {
  14577. progress: this.progress,
  14578. Hu: this.collectionGroups,
  14579. Ju: t
  14580. }) ];
  14581. }
  14582. }));
  14583. }));
  14584. }, t;
  14585. }();
  14586. /**
  14587. * @license
  14588. * Copyright 2020 Google LLC
  14589. *
  14590. * Licensed under the Apache License, Version 2.0 (the "License");
  14591. * you may not use this file except in compliance with the License.
  14592. * You may obtain a copy of the License at
  14593. *
  14594. * http://www.apache.org/licenses/LICENSE-2.0
  14595. *
  14596. * Unless required by applicable law or agreed to in writing, software
  14597. * distributed under the License is distributed on an "AS IS" BASIS,
  14598. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14599. * See the License for the specific language governing permissions and
  14600. * limitations under the License.
  14601. */
  14602. /**
  14603. * A complete element in the bundle stream, together with the byte length it
  14604. * occupies in the stream.
  14605. */
  14606. /**
  14607. * Returns a `LoadBundleTaskProgress` representing the initial progress of
  14608. * loading a bundle.
  14609. */
  14610. function Os(t) {
  14611. return {
  14612. taskState: "Running",
  14613. documentsLoaded: 0,
  14614. bytesLoaded: 0,
  14615. totalDocuments: t.totalDocuments,
  14616. totalBytes: t.totalBytes
  14617. };
  14618. }
  14619. /**
  14620. * Returns a `LoadBundleTaskProgress` representing the progress that the loading
  14621. * has succeeded.
  14622. */
  14623. /**
  14624. * @license
  14625. * Copyright 2017 Google LLC
  14626. *
  14627. * Licensed under the Apache License, Version 2.0 (the "License");
  14628. * you may not use this file except in compliance with the License.
  14629. * You may obtain a copy of the License at
  14630. *
  14631. * http://www.apache.org/licenses/LICENSE-2.0
  14632. *
  14633. * Unless required by applicable law or agreed to in writing, software
  14634. * distributed under the License is distributed on an "AS IS" BASIS,
  14635. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14636. * See the License for the specific language governing permissions and
  14637. * limitations under the License.
  14638. */ var Fs = function(t) {
  14639. this.key = t;
  14640. }, Ps = function(t) {
  14641. this.key = t;
  14642. }, Rs = /** @class */ function() {
  14643. function t(t,
  14644. /** Documents included in the remote target */
  14645. e) {
  14646. this.query = t, this.Yu = e, this.Xu = null, this.hasCachedResults = !1,
  14647. /**
  14648. * A flag whether the view is current with the backend. A view is considered
  14649. * current after it has seen the current flag from the backend and did not
  14650. * lose consistency within the watch stream (e.g. because of an existence
  14651. * filter mismatch).
  14652. */
  14653. this.current = !1,
  14654. /** Documents in the view but not in the remote target */
  14655. this.Zu = Ir(),
  14656. /** Document Keys that have local changes */
  14657. this.mutatedKeys = Ir(), this.tc = sr(t), this.ec = new gs(this.tc);
  14658. }
  14659. return Object.defineProperty(t.prototype, "nc", {
  14660. /**
  14661. * The set of remote documents that the server has told us belongs to the target associated with
  14662. * this view.
  14663. */
  14664. get: function() {
  14665. return this.Yu;
  14666. },
  14667. enumerable: !1,
  14668. configurable: !0
  14669. }),
  14670. /**
  14671. * Iterates over a set of doc changes, applies the query limit, and computes
  14672. * what the new results should be, what the changes were, and whether we may
  14673. * need to go back to the local cache for more results. Does not make any
  14674. * changes to the view.
  14675. * @param docChanges - The doc changes to apply to this view.
  14676. * @param previousChanges - If this is being called with a refill, then start
  14677. * with this set of docs and changes instead of the current view.
  14678. * @returns a new set of docs, changes, and refill flag.
  14679. */
  14680. t.prototype.sc = function(t, e) {
  14681. var n = this, r = e ? e.ic : new ws, i = e ? e.ec : this.ec, o = e ? e.mutatedKeys : this.mutatedKeys, u = i, a = !1, s = "F" /* LimitType.First */ === this.query.limitType && i.size === this.query.limit ? i.last() : null, c = "L" /* LimitType.Last */ === this.query.limitType && i.size === this.query.limit ? i.first() : null;
  14682. // Drop documents out to meet limit/limitToLast requirement.
  14683. if (t.inorderTraversal((function(t, e) {
  14684. var l = i.get(t), h = ur(n.query, e) ? e : null, f = !!l && n.mutatedKeys.has(l.key), d = !!h && (h.hasLocalMutations ||
  14685. // We only consider committed mutations for documents that were
  14686. // mutated during the lifetime of the view.
  14687. n.mutatedKeys.has(h.key) && h.hasCommittedMutations), p = !1;
  14688. // Calculate change
  14689. l && h ? l.data.isEqual(h.data) ? f !== d && (r.track({
  14690. type: 3 /* ChangeType.Metadata */ ,
  14691. doc: h
  14692. }), p = !0) : n.rc(l, h) || (r.track({
  14693. type: 2 /* ChangeType.Modified */ ,
  14694. doc: h
  14695. }), p = !0, (s && n.tc(h, s) > 0 || c && n.tc(h, c) < 0) && (
  14696. // This doc moved from inside the limit to outside the limit.
  14697. // That means there may be some other doc in the local cache
  14698. // that should be included instead.
  14699. a = !0)) : !l && h ? (r.track({
  14700. type: 0 /* ChangeType.Added */ ,
  14701. doc: h
  14702. }), p = !0) : l && !h && (r.track({
  14703. type: 1 /* ChangeType.Removed */ ,
  14704. doc: l
  14705. }), p = !0, (s || c) && (
  14706. // A doc was removed from a full limit query. We'll need to
  14707. // requery from the local cache to see if we know about some other
  14708. // doc that should be in the results.
  14709. a = !0)), p && (h ? (u = u.add(h), o = d ? o.add(t) : o.delete(t)) : (u = u.delete(t),
  14710. o = o.delete(t)));
  14711. })), null !== this.query.limit) for (;u.size > this.query.limit; ) {
  14712. var l = "F" /* LimitType.First */ === this.query.limitType ? u.last() : u.first();
  14713. u = u.delete(l.key), o = o.delete(l.key), r.track({
  14714. type: 1 /* ChangeType.Removed */ ,
  14715. doc: l
  14716. });
  14717. }
  14718. return {
  14719. ec: u,
  14720. ic: r,
  14721. zi: a,
  14722. mutatedKeys: o
  14723. };
  14724. }, t.prototype.rc = function(t, e) {
  14725. // We suppress the initial change event for documents that were modified as
  14726. // part of a write acknowledgment (e.g. when the value of a server transform
  14727. // is applied) as Watch will send us the same document again.
  14728. // By suppressing the event, we only raise two user visible events (one with
  14729. // `hasPendingWrites` and the final state of the document) instead of three
  14730. // (one with `hasPendingWrites`, the modified document with
  14731. // `hasPendingWrites` and the final state of the document).
  14732. return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;
  14733. },
  14734. /**
  14735. * Updates the view with the given ViewDocumentChanges and optionally updates
  14736. * limbo docs and sync state from the provided target change.
  14737. * @param docChanges - The set of changes to make to the view's docs.
  14738. * @param updateLimboDocuments - Whether to update limbo documents based on
  14739. * this change.
  14740. * @param targetChange - A target change to apply for computing limbo docs and
  14741. * sync state.
  14742. * @returns A new ViewChange with the given docs, changes, and sync state.
  14743. */
  14744. // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
  14745. t.prototype.applyChanges = function(t, e, n) {
  14746. var r = this, i = this.ec;
  14747. this.ec = t.ec, this.mutatedKeys = t.mutatedKeys;
  14748. // Sort changes based on type and query comparator
  14749. var o = t.ic.xu();
  14750. o.sort((function(t, e) {
  14751. return function(t, e) {
  14752. var n = function(t) {
  14753. switch (t) {
  14754. case 0 /* ChangeType.Added */ :
  14755. return 1;
  14756. case 2 /* ChangeType.Modified */ :
  14757. case 3 /* ChangeType.Metadata */ :
  14758. // A metadata change is converted to a modified change at the public
  14759. // api layer. Since we sort by document key and then change type,
  14760. // metadata and modified changes must be sorted equivalently.
  14761. return 2;
  14762. case 1 /* ChangeType.Removed */ :
  14763. return 0;
  14764. default:
  14765. return U();
  14766. }
  14767. };
  14768. return n(t) - n(e);
  14769. }(t.type, e.type) || r.tc(t.doc, e.doc);
  14770. })), this.oc(n);
  14771. var u = e ? this.uc() : [], a = 0 === this.Zu.size && this.current ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , s = a !== this.Xu;
  14772. return this.Xu = a, 0 !== o.length || s ? {
  14773. snapshot: new bs(this.query, t.ec, i, o, t.mutatedKeys, 0 /* SyncState.Local */ === a, s,
  14774. /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),
  14775. cc: u
  14776. } : {
  14777. cc: u
  14778. };
  14779. // no changes
  14780. },
  14781. /**
  14782. * Applies an OnlineState change to the view, potentially generating a
  14783. * ViewChange if the view's syncState changes as a result.
  14784. */
  14785. t.prototype.Mu = function(t) {
  14786. return this.current && "Offline" /* OnlineState.Offline */ === t ? (
  14787. // If we're offline, set `current` to false and then call applyChanges()
  14788. // to refresh our syncState and generate a ViewChange as appropriate. We
  14789. // are guaranteed to get a new TargetChange that sets `current` back to
  14790. // true once the client is back online.
  14791. this.current = !1, this.applyChanges({
  14792. ec: this.ec,
  14793. ic: new ws,
  14794. mutatedKeys: this.mutatedKeys,
  14795. zi: !1
  14796. },
  14797. /* updateLimboDocuments= */ !1)) : {
  14798. cc: []
  14799. };
  14800. },
  14801. /**
  14802. * Returns whether the doc for the given key should be in limbo.
  14803. */
  14804. t.prototype.ac = function(t) {
  14805. // If the remote end says it's part of this query, it's not in limbo.
  14806. return !this.Yu.has(t) &&
  14807. // The local store doesn't think it's a result, so it shouldn't be in limbo.
  14808. !!this.ec.has(t) && !this.ec.get(t).hasLocalMutations;
  14809. },
  14810. /**
  14811. * Updates syncedDocuments, current, and limbo docs based on the given change.
  14812. * Returns the list of changes to which docs are in limbo.
  14813. */
  14814. t.prototype.oc = function(t) {
  14815. var e = this;
  14816. t && (t.addedDocuments.forEach((function(t) {
  14817. return e.Yu = e.Yu.add(t);
  14818. })), t.modifiedDocuments.forEach((function(t) {})), t.removedDocuments.forEach((function(t) {
  14819. return e.Yu = e.Yu.delete(t);
  14820. })), this.current = t.current);
  14821. }, t.prototype.uc = function() {
  14822. var t = this;
  14823. // We can only determine limbo documents when we're in-sync with the server.
  14824. if (!this.current) return [];
  14825. // TODO(klimt): Do this incrementally so that it's not quadratic when
  14826. // updating many documents.
  14827. var e = this.Zu;
  14828. this.Zu = Ir(), this.ec.forEach((function(e) {
  14829. t.ac(e.key) && (t.Zu = t.Zu.add(e.key));
  14830. }));
  14831. // Diff the new limbo docs with the old limbo docs.
  14832. var n = [];
  14833. return e.forEach((function(e) {
  14834. t.Zu.has(e) || n.push(new Ps(e));
  14835. })), this.Zu.forEach((function(t) {
  14836. e.has(t) || n.push(new Fs(t));
  14837. })), n;
  14838. },
  14839. /**
  14840. * Update the in-memory state of the current view with the state read from
  14841. * persistence.
  14842. *
  14843. * We update the query view whenever a client's primary status changes:
  14844. * - When a client transitions from primary to secondary, it can miss
  14845. * LocalStorage updates and its query views may temporarily not be
  14846. * synchronized with the state on disk.
  14847. * - For secondary to primary transitions, the client needs to update the list
  14848. * of `syncedDocuments` since secondary clients update their query views
  14849. * based purely on synthesized RemoteEvents.
  14850. *
  14851. * @param queryResult.documents - The documents that match the query according
  14852. * to the LocalStore.
  14853. * @param queryResult.remoteKeys - The keys of the documents that match the
  14854. * query according to the backend.
  14855. *
  14856. * @returns The ViewChange that resulted from this synchronization.
  14857. */
  14858. // PORTING NOTE: Multi-tab only.
  14859. t.prototype.hc = function(t) {
  14860. this.Yu = t.ir, this.Zu = Ir();
  14861. var e = this.sc(t.documents);
  14862. return this.applyChanges(e, /*updateLimboDocuments=*/ !0);
  14863. },
  14864. /**
  14865. * Returns a view snapshot as if this query was just listened to. Contains
  14866. * a document add for every existing document and the `fromCache` and
  14867. * `hasPendingWrites` status of the already established view.
  14868. */
  14869. // PORTING NOTE: Multi-tab only.
  14870. t.prototype.lc = function() {
  14871. return bs.fromInitialDocuments(this.query, this.ec, this.mutatedKeys, 0 /* SyncState.Local */ === this.Xu, this.hasCachedResults);
  14872. }, t;
  14873. }(), Vs = function(
  14874. /**
  14875. * The query itself.
  14876. */
  14877. t,
  14878. /**
  14879. * The target number created by the client that is used in the watch
  14880. * stream to identify this query.
  14881. */
  14882. e,
  14883. /**
  14884. * The view is responsible for computing the final merged truth of what
  14885. * docs are in the query. It gets notified of local and remote changes,
  14886. * and applies the query filters and limits to determine the most correct
  14887. * possible results.
  14888. */
  14889. n) {
  14890. this.query = t, this.targetId = e, this.view = n;
  14891. }, Ms = function(t) {
  14892. this.key = t,
  14893. /**
  14894. * Set to true once we've received a document. This is used in
  14895. * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
  14896. * decide whether it needs to manufacture a delete event for the target once
  14897. * the target is CURRENT.
  14898. */
  14899. this.fc = !1;
  14900. }, Ls = /** @class */ function() {
  14901. function t(t, e, n,
  14902. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  14903. r, i, o) {
  14904. this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = r,
  14905. this.currentUser = i, this.maxConcurrentLimboResolutions = o, this.dc = {}, this.wc = new lr((function(t) {
  14906. return ir(t);
  14907. }), rr), this._c = new Map,
  14908. /**
  14909. * The keys of documents that are in limbo for which we haven't yet started a
  14910. * limbo resolution query. The strings in this set are the result of calling
  14911. * `key.path.canonicalString()` where `key` is a `DocumentKey` object.
  14912. *
  14913. * The `Set` type was chosen because it provides efficient lookup and removal
  14914. * of arbitrary elements and it also maintains insertion order, providing the
  14915. * desired queue-like FIFO semantics.
  14916. */
  14917. this.mc = new Set,
  14918. /**
  14919. * Keeps track of the target ID for each document that is in limbo with an
  14920. * active target.
  14921. */
  14922. this.gc = new Te(pt.comparator),
  14923. /**
  14924. * Keeps track of the information about an active limbo resolution for each
  14925. * active target ID that was started for the purpose of limbo resolution.
  14926. */
  14927. this.yc = new Map, this.Ic = new Ru,
  14928. /** Stores user completion handlers, indexed by User and BatchId. */
  14929. this.Tc = {},
  14930. /** Stores user callbacks waiting for all pending writes to be acknowledged. */
  14931. this.Ec = new Map, this.Ac = lu.Mn(), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14932. // The primary state is set to `true` or `false` immediately after Firestore
  14933. // startup. In the interim, a client should only be considered primary if
  14934. // `isPrimary` is true.
  14935. this.vc = void 0;
  14936. }
  14937. return Object.defineProperty(t.prototype, "isPrimaryClient", {
  14938. get: function() {
  14939. return !0 === this.vc;
  14940. },
  14941. enumerable: !1,
  14942. configurable: !0
  14943. }), t;
  14944. }();
  14945. /**
  14946. * Initiates the new listen, resolves promise when listen enqueued to the
  14947. * server. All the subsequent view snapshots or errors are sent to the
  14948. * subscribed handlers. Returns the initial snapshot.
  14949. */
  14950. function qs(t, r) {
  14951. return e(this, void 0, void 0, (function() {
  14952. var e, i, o, u, a, s;
  14953. return n(this, (function(n) {
  14954. switch (n.label) {
  14955. case 0:
  14956. return e = pc(t), (u = e.wc.get(r)) ? (
  14957. // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
  14958. // already exists when EventManager calls us for the first time. This
  14959. // happens when the primary tab is already listening to this query on
  14960. // behalf of another tab and the user of the primary also starts listening
  14961. // to the query. EventManager will not have an assigned target ID in this
  14962. // case and calls `listen` to obtain this ID.
  14963. i = u.targetId, e.sharedClientState.addLocalQueryTarget(i), o = u.view.lc(), [ 3 /*break*/ , 4 ]) : [ 3 /*break*/ , 1 ];
  14964. case 1:
  14965. return [ 4 /*yield*/ , sa(e.localStore, tr(r)) ];
  14966. case 2:
  14967. return a = n.sent(), s = e.sharedClientState.addLocalQueryTarget(a.targetId), i = a.targetId,
  14968. [ 4 /*yield*/ , Bs(e, r, i, "current" === s, a.resumeToken) ];
  14969. case 3:
  14970. o = n.sent(), e.isPrimaryClient && Qa(e.remoteStore, a), n.label = 4;
  14971. case 4:
  14972. return [ 2 /*return*/ , o ];
  14973. }
  14974. }));
  14975. }));
  14976. }
  14977. /**
  14978. * Registers a view for a previously unknown query and computes its initial
  14979. * snapshot.
  14980. */ function Bs(t, r, i, o, u) {
  14981. return e(this, void 0, void 0, (function() {
  14982. var a, s, c, l, h, f;
  14983. return n(this, (function(d) {
  14984. switch (d.label) {
  14985. case 0:
  14986. // PORTING NOTE: On Web only, we inject the code that registers new Limbo
  14987. // targets based on view changes. This allows us to only depend on Limbo
  14988. // changes when user code includes queries.
  14989. return t.Rc = function(r, i, o) {
  14990. return function(t, r, i, o) {
  14991. return e(this, void 0, void 0, (function() {
  14992. var e, u, a;
  14993. return n(this, (function(n) {
  14994. switch (n.label) {
  14995. case 0:
  14996. return e = r.view.sc(i), e.zi ? [ 4 /*yield*/ , la(t.localStore, r.query,
  14997. /* usePreviousResults= */ !1).then((function(t) {
  14998. var n = t.documents;
  14999. return r.view.sc(n, e);
  15000. })) ] : [ 3 /*break*/ , 2 ];
  15001. case 1:
  15002. // The query has a limit and some docs were removed, so we need
  15003. // to re-run the query against the local store to make sure we
  15004. // didn't lose any good docs that had been past the limit.
  15005. e = n.sent(), n.label = 2;
  15006. case 2:
  15007. return u = o && o.targetChanges.get(r.targetId), a = r.view.applyChanges(e,
  15008. /* updateLimboDocuments= */ t.isPrimaryClient, u), [ 2 /*return*/ , ($s(t, r.targetId, a.cc),
  15009. a.snapshot) ];
  15010. }
  15011. }));
  15012. }));
  15013. }(t, r, i, o);
  15014. }, [ 4 /*yield*/ , la(t.localStore, r,
  15015. /* usePreviousResults= */ !0) ];
  15016. case 1:
  15017. return a = d.sent(), s = new Rs(r, a.ir), c = s.sc(a.documents), l = bi.createSynthesizedTargetChangeForCurrentChange(i, o && "Offline" /* OnlineState.Offline */ !== t.onlineState, u),
  15018. h = s.applyChanges(c,
  15019. /* updateLimboDocuments= */ t.isPrimaryClient, l), $s(t, i, h.cc), f = new Vs(r, i, s),
  15020. [ 2 /*return*/ , (t.wc.set(r, f), t._c.has(i) ? t._c.get(i).push(r) : t._c.set(i, [ r ]),
  15021. h.snapshot) ];
  15022. }
  15023. }));
  15024. }));
  15025. }
  15026. /** Stops listening to the query. */ function Us(t, r) {
  15027. return e(this, void 0, void 0, (function() {
  15028. var e, i, o;
  15029. return n(this, (function(n) {
  15030. switch (n.label) {
  15031. case 0:
  15032. return e = j(t), i = e.wc.get(r), (o = e._c.get(i.targetId)).length > 1 ? [ 2 /*return*/ , (e._c.set(i.targetId, o.filter((function(t) {
  15033. return !rr(t, r);
  15034. }))), void e.wc.delete(r)) ] : e.isPrimaryClient ? (
  15035. // We need to remove the local query target first to allow us to verify
  15036. // whether any other client is still interested in this target.
  15037. e.sharedClientState.removeLocalQueryTarget(i.targetId), e.sharedClientState.isActiveQueryTarget(i.targetId) ? [ 3 /*break*/ , 2 ] : [ 4 /*yield*/ , ca(e.localStore, i.targetId,
  15038. /*keepPersistedTargetData=*/ !1).then((function() {
  15039. e.sharedClientState.clearQueryState(i.targetId), Wa(e.remoteStore, i.targetId),
  15040. Js(e, i.targetId);
  15041. })).catch(xt) ]) : [ 3 /*break*/ , 3 ];
  15042. case 1:
  15043. n.sent(), n.label = 2;
  15044. case 2:
  15045. return [ 3 /*break*/ , 5 ];
  15046. case 3:
  15047. return Js(e, i.targetId), [ 4 /*yield*/ , ca(e.localStore, i.targetId,
  15048. /*keepPersistedTargetData=*/ !0) ];
  15049. case 4:
  15050. n.sent(), n.label = 5;
  15051. case 5:
  15052. return [ 2 /*return*/ ];
  15053. }
  15054. }));
  15055. }));
  15056. }
  15057. /**
  15058. * Initiates the write of local mutation batch which involves adding the
  15059. * writes to the mutation queue, notifying the remote store about new
  15060. * mutations and raising events for any changes this write caused.
  15061. *
  15062. * The promise returned by this call is resolved when the above steps
  15063. * have completed, *not* when the write was acked by the backend. The
  15064. * userCallback is resolved once the write was acked/rejected by the
  15065. * backend (or failed locally for any other reason).
  15066. */ function zs(t, r, i) {
  15067. return e(this, void 0, void 0, (function() {
  15068. var e, o, u, a;
  15069. return n(this, (function(n) {
  15070. switch (n.label) {
  15071. case 0:
  15072. e = vc(t), n.label = 1;
  15073. case 1:
  15074. return n.trys.push([ 1, 5, , 6 ]), [ 4 /*yield*/ , function(t, e) {
  15075. var n, r, i = j(t), o = st.now(), u = e.reduce((function(t, e) {
  15076. return t.add(e.key);
  15077. }), Ir());
  15078. return i.persistence.runTransaction("Locally write mutations", "readwrite", (function(t) {
  15079. // Figure out which keys do not have a remote version in the cache, this
  15080. // is needed to create the right overlay mutation: if no remote version
  15081. // presents, we do not need to create overlays as patch mutations.
  15082. // TODO(Overlay): Is there a better way to determine this? Using the
  15083. // document version does not work because local mutations set them back
  15084. // to 0.
  15085. var a = fr(), s = Ir();
  15086. return i.Zi.getEntries(t, u).next((function(t) {
  15087. (a = t).forEach((function(t, e) {
  15088. e.isValidDocument() || (s = s.add(t));
  15089. }));
  15090. })).next((function() {
  15091. return i.localDocuments.getOverlayedDocuments(t, a);
  15092. })).next((function(r) {
  15093. n = r;
  15094. for (
  15095. // For non-idempotent mutations (such as `FieldValue.increment()`),
  15096. // we record the base state in a separate patch mutation. This is
  15097. // later used to guarantee consistent values and prevents flicker
  15098. // even if the backend sends us an update that already includes our
  15099. // transform.
  15100. var u = [], a = 0, s = e; a < s.length; a++) {
  15101. var c = s[a], l = Wr(c, n.get(c.key).overlayedDocument);
  15102. null != l &&
  15103. // NOTE: The base state should only be applied if there's some
  15104. // existing document to override, so use a Precondition of
  15105. // exists=true
  15106. u.push(new Xr(c.key, l, fn(l.value.mapValue), Ur.exists(!0)));
  15107. }
  15108. return i.mutationQueue.addMutationBatch(t, o, u, e);
  15109. })).next((function(e) {
  15110. r = e;
  15111. var o = e.applyToLocalDocumentSet(n, s);
  15112. return i.documentOverlayCache.saveOverlays(t, e.batchId, o);
  15113. }));
  15114. })).then((function() {
  15115. return {
  15116. batchId: r.batchId,
  15117. changes: vr(n)
  15118. };
  15119. }));
  15120. }(e.localStore, r) ];
  15121. case 2:
  15122. return o = n.sent(), e.sharedClientState.addPendingMutation(o.batchId), function(t, e, n) {
  15123. var r = t.Tc[t.currentUser.toKey()];
  15124. r || (r = new Te(ot)), r = r.insert(e, n), t.Tc[t.currentUser.toKey()] = r;
  15125. }(e, o.batchId, i), [ 4 /*yield*/ , nc(e, o.changes) ];
  15126. case 3:
  15127. return n.sent(), [ 4 /*yield*/ , os(e.remoteStore) ];
  15128. case 4:
  15129. return n.sent(), [ 3 /*break*/ , 6 ];
  15130. case 5:
  15131. return u = n.sent(), a = ys(u, "Failed to persist write"), i.reject(a), [ 3 /*break*/ , 6 ];
  15132. case 6:
  15133. return [ 2 /*return*/ ];
  15134. }
  15135. }));
  15136. }));
  15137. }
  15138. /**
  15139. * Applies one remote event to the sync engine, notifying any views of the
  15140. * changes, and releasing any pending mutation batches that would become
  15141. * visible because of the snapshot version the remote event contains.
  15142. */ function Gs(t, r) {
  15143. return e(this, void 0, void 0, (function() {
  15144. var e, i;
  15145. return n(this, (function(n) {
  15146. switch (n.label) {
  15147. case 0:
  15148. e = j(t), n.label = 1;
  15149. case 1:
  15150. return n.trys.push([ 1, 4, , 6 ]), [ 4 /*yield*/ , oa(e.localStore, r) ];
  15151. case 2:
  15152. return i = n.sent(),
  15153. // Update `receivedDocument` as appropriate for any limbo targets.
  15154. r.targetChanges.forEach((function(t, n) {
  15155. var r = e.yc.get(n);
  15156. r && (
  15157. // Since this is a limbo resolution lookup, it's for a single document
  15158. // and it could be added, modified, or removed, but not a combination.
  15159. z(t.addedDocuments.size + t.modifiedDocuments.size + t.removedDocuments.size <= 1),
  15160. t.addedDocuments.size > 0 ? r.fc = !0 : t.modifiedDocuments.size > 0 ? z(r.fc) : t.removedDocuments.size > 0 && (z(r.fc),
  15161. r.fc = !1));
  15162. })), [ 4 /*yield*/ , nc(e, i, r) ];
  15163. case 3:
  15164. // Update `receivedDocument` as appropriate for any limbo targets.
  15165. return n.sent(), [ 3 /*break*/ , 6 ];
  15166. case 4:
  15167. return [ 4 /*yield*/ , xt(n.sent()) ];
  15168. case 5:
  15169. return n.sent(), [ 3 /*break*/ , 6 ];
  15170. case 6:
  15171. return [ 2 /*return*/ ];
  15172. }
  15173. }));
  15174. }));
  15175. }
  15176. /**
  15177. * Applies an OnlineState change to the sync engine and notifies any views of
  15178. * the change.
  15179. */ function js(t, e, n) {
  15180. var r = j(t);
  15181. // If we are the secondary client, we explicitly ignore the remote store's
  15182. // online state (the local client may go offline, even though the primary
  15183. // tab remains online) and only apply the primary tab's online state from
  15184. // SharedClientState.
  15185. if (r.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !r.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {
  15186. var i = [];
  15187. r.wc.forEach((function(t, n) {
  15188. var r = n.view.Mu(e);
  15189. r.snapshot && i.push(r.snapshot);
  15190. })), function(t, e) {
  15191. var n = j(t);
  15192. n.onlineState = e;
  15193. var r = !1;
  15194. n.queries.forEach((function(t, n) {
  15195. for (var i = 0, o = n.listeners; i < o.length; i++) {
  15196. // Run global snapshot listeners if a consistent snapshot has been emitted.
  15197. o[i].Mu(e) && (r = !0);
  15198. }
  15199. })), r && Cs(n);
  15200. }(r.eventManager, e), i.length && r.dc.nu(i), r.onlineState = e, r.isPrimaryClient && r.sharedClientState.setOnlineState(e);
  15201. }
  15202. }
  15203. /**
  15204. * Rejects the listen for the given targetID. This can be triggered by the
  15205. * backend for any active target.
  15206. *
  15207. * @param syncEngine - The sync engine implementation.
  15208. * @param targetId - The targetID corresponds to one previously initiated by the
  15209. * user as part of TargetData passed to listen() on RemoteStore.
  15210. * @param err - A description of the condition that has forced the rejection.
  15211. * Nearly always this will be an indication that the user is no longer
  15212. * authorized to see the data matching the target.
  15213. */ function Ks(t, r, i) {
  15214. return e(this, void 0, void 0, (function() {
  15215. var e, o, u, a, s, c;
  15216. return n(this, (function(n) {
  15217. switch (n.label) {
  15218. case 0:
  15219. // PORTING NOTE: Multi-tab only.
  15220. return (e = j(t)).sharedClientState.updateQueryState(r, "rejected", i), o = e.yc.get(r),
  15221. (u = o && o.key) ? (
  15222. // TODO(b/217189216): This limbo document should ideally have a read time,
  15223. // so that it is picked up by any read-time based scans. The backend,
  15224. // however, does not send a read time for target removals.
  15225. a = (a = new Te(pt.comparator)).insert(u, dn.newNoDocument(u, ct.min())), s = Ir().add(u),
  15226. c = new wi(ct.min(),
  15227. /* targetChanges= */ new Map,
  15228. /* targetMismatches= */ new Te(ot), a, s), [ 4 /*yield*/ , Gs(e, c) ]) : [ 3 /*break*/ , 2 ];
  15229. case 1:
  15230. return n.sent(),
  15231. // Since this query failed, we won't want to manually unlisten to it.
  15232. // We only remove it from bookkeeping after we successfully applied the
  15233. // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
  15234. // this query when the RemoteStore restarts the Watch stream, which should
  15235. // re-trigger the target failure.
  15236. e.gc = e.gc.remove(u), e.yc.delete(r), ec(e), [ 3 /*break*/ , 4 ];
  15237. case 2:
  15238. return [ 4 /*yield*/ , ca(e.localStore, r,
  15239. /* keepPersistedTargetData */ !1).then((function() {
  15240. return Js(e, r, i);
  15241. })).catch(xt) ];
  15242. case 3:
  15243. n.sent(), n.label = 4;
  15244. case 4:
  15245. return [ 2 /*return*/ ];
  15246. }
  15247. }));
  15248. }));
  15249. }
  15250. function Qs(t, r) {
  15251. return e(this, void 0, void 0, (function() {
  15252. var e, i, o;
  15253. return n(this, (function(n) {
  15254. switch (n.label) {
  15255. case 0:
  15256. e = j(t), i = r.batch.batchId, n.label = 1;
  15257. case 1:
  15258. return n.trys.push([ 1, 4, , 6 ]), [ 4 /*yield*/ , ra(e.localStore, r) ];
  15259. case 2:
  15260. return o = n.sent(),
  15261. // The local store may or may not be able to apply the write result and
  15262. // raise events immediately (depending on whether the watcher is caught
  15263. // up), so we raise user callbacks first so that they consistently happen
  15264. // before listen events.
  15265. Xs(e, i, /*error=*/ null), Ys(e, i), e.sharedClientState.updateMutationState(i, "acknowledged"),
  15266. [ 4 /*yield*/ , nc(e, o) ];
  15267. case 3:
  15268. // The local store may or may not be able to apply the write result and
  15269. // raise events immediately (depending on whether the watcher is caught
  15270. // up), so we raise user callbacks first so that they consistently happen
  15271. // before listen events.
  15272. return n.sent(), [ 3 /*break*/ , 6 ];
  15273. case 4:
  15274. return [ 4 /*yield*/ , xt(n.sent()) ];
  15275. case 5:
  15276. return n.sent(), [ 3 /*break*/ , 6 ];
  15277. case 6:
  15278. return [ 2 /*return*/ ];
  15279. }
  15280. }));
  15281. }));
  15282. }
  15283. function Ws(t, r, i) {
  15284. return e(this, void 0, void 0, (function() {
  15285. var e, o;
  15286. return n(this, (function(n) {
  15287. switch (n.label) {
  15288. case 0:
  15289. e = j(t), n.label = 1;
  15290. case 1:
  15291. return n.trys.push([ 1, 4, , 6 ]), [ 4 /*yield*/ , function(t, e) {
  15292. var n = j(t);
  15293. return n.persistence.runTransaction("Reject batch", "readwrite-primary", (function(t) {
  15294. var r;
  15295. return n.mutationQueue.lookupMutationBatch(t, e).next((function(e) {
  15296. return z(null !== e), r = e.keys(), n.mutationQueue.removeMutationBatch(t, e);
  15297. })).next((function() {
  15298. return n.mutationQueue.performConsistencyCheck(t);
  15299. })).next((function() {
  15300. return n.documentOverlayCache.removeOverlaysForBatchId(t, r, e);
  15301. })).next((function() {
  15302. return n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, r);
  15303. })).next((function() {
  15304. return n.localDocuments.getDocuments(t, r);
  15305. }));
  15306. }));
  15307. }(e.localStore, r) ];
  15308. case 2:
  15309. return o = n.sent(),
  15310. // The local store may or may not be able to apply the write result and
  15311. // raise events immediately (depending on whether the watcher is caught up),
  15312. // so we raise user callbacks first so that they consistently happen before
  15313. // listen events.
  15314. Xs(e, r, i), Ys(e, r), e.sharedClientState.updateMutationState(r, "rejected", i),
  15315. [ 4 /*yield*/ , nc(e, o) ];
  15316. case 3:
  15317. // The local store may or may not be able to apply the write result and
  15318. // raise events immediately (depending on whether the watcher is caught up),
  15319. // so we raise user callbacks first so that they consistently happen before
  15320. // listen events.
  15321. return n.sent(), [ 3 /*break*/ , 6 ];
  15322. case 4:
  15323. return [ 4 /*yield*/ , xt(n.sent()) ];
  15324. case 5:
  15325. return n.sent(), [ 3 /*break*/ , 6 ];
  15326. case 6:
  15327. return [ 2 /*return*/ ];
  15328. }
  15329. }));
  15330. }));
  15331. }
  15332. /**
  15333. * Registers a user callback that resolves when all pending mutations at the moment of calling
  15334. * are acknowledged .
  15335. */ function Hs(t, r) {
  15336. return e(this, void 0, void 0, (function() {
  15337. var e, i, o, u, a;
  15338. return n(this, (function(n) {
  15339. switch (n.label) {
  15340. case 0:
  15341. Za((e = j(t)).remoteStore) || M("SyncEngine", "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled."),
  15342. n.label = 1;
  15343. case 1:
  15344. return n.trys.push([ 1, 3, , 4 ]), [ 4 /*yield*/ , function(t) {
  15345. var e = j(t);
  15346. return e.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (function(t) {
  15347. return e.mutationQueue.getHighestUnacknowledgedBatchId(t);
  15348. }));
  15349. }(e.localStore) ];
  15350. case 2:
  15351. return -1 === (i = n.sent()) ? [ 2 /*return*/ , void r.resolve() ] : ((o = e.Ec.get(i) || []).push(r),
  15352. e.Ec.set(i, o), [ 3 /*break*/ , 4 ]);
  15353. case 3:
  15354. return u = n.sent(), a = ys(u, "Initialization of waitForPendingWrites() operation failed"),
  15355. r.reject(a), [ 3 /*break*/ , 4 ];
  15356. case 4:
  15357. return [ 2 /*return*/ ];
  15358. }
  15359. }));
  15360. }));
  15361. }
  15362. /**
  15363. * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,
  15364. * if there are any.
  15365. */ function Ys(t, e) {
  15366. (t.Ec.get(e) || []).forEach((function(t) {
  15367. t.resolve();
  15368. })), t.Ec.delete(e)
  15369. /** Reject all outstanding callbacks waiting for pending writes to complete. */;
  15370. }
  15371. function Xs(t, e, n) {
  15372. var r = j(t), i = r.Tc[r.currentUser.toKey()];
  15373. // NOTE: Mutations restored from persistence won't have callbacks, so it's
  15374. // okay for there to be no callback for this ID.
  15375. if (i) {
  15376. var o = i.get(e);
  15377. o && (n ? o.reject(n) : o.resolve(), i = i.remove(e)), r.Tc[r.currentUser.toKey()] = i;
  15378. }
  15379. }
  15380. function Js(t, e, n) {
  15381. void 0 === n && (n = null), t.sharedClientState.removeLocalQueryTarget(e);
  15382. for (var r = 0, i = t._c.get(e); r < i.length; r++) {
  15383. var o = i[r];
  15384. t.wc.delete(o), n && t.dc.Pc(o, n);
  15385. }
  15386. t._c.delete(e), t.isPrimaryClient && t.Ic.Is(e).forEach((function(e) {
  15387. t.Ic.containsKey(e) ||
  15388. // We removed the last reference for this key
  15389. Zs(t, e);
  15390. }));
  15391. }
  15392. function Zs(t, e) {
  15393. t.mc.delete(e.path.canonicalString());
  15394. // It's possible that the target already got removed because the query failed. In that case,
  15395. // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.
  15396. var n = t.gc.get(e);
  15397. null !== n && (Wa(t.remoteStore, n), t.gc = t.gc.remove(e), t.yc.delete(n), ec(t));
  15398. }
  15399. function $s(t, e, n) {
  15400. for (var r = 0, i = n; r < i.length; r++) {
  15401. var o = i[r];
  15402. o instanceof Fs ? (t.Ic.addReference(o.key, e), tc(t, o)) : o instanceof Ps ? (M("SyncEngine", "Document no longer in limbo: " + o.key),
  15403. t.Ic.removeReference(o.key, e), t.Ic.containsKey(o.key) ||
  15404. // We removed the last reference for this key
  15405. Zs(t, o.key)) : U();
  15406. }
  15407. }
  15408. function tc(t, e) {
  15409. var n = e.key, r = n.path.canonicalString();
  15410. t.gc.get(n) || t.mc.has(r) || (M("SyncEngine", "New document in limbo: " + n), t.mc.add(r),
  15411. ec(t));
  15412. }
  15413. /**
  15414. * Starts listens for documents in limbo that are enqueued for resolution,
  15415. * subject to a maximum number of concurrent resolutions.
  15416. *
  15417. * Without bounding the number of concurrent resolutions, the server can fail
  15418. * with "resource exhausted" errors which can lead to pathological client
  15419. * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.
  15420. */ function ec(t) {
  15421. for (;t.mc.size > 0 && t.gc.size < t.maxConcurrentLimboResolutions; ) {
  15422. var e = t.mc.values().next().value;
  15423. t.mc.delete(e);
  15424. var n = new pt(ht.fromString(e)), r = t.Ac.next();
  15425. t.yc.set(r, new Ms(n)), t.gc = t.gc.insert(n, r), Qa(t.remoteStore, new ao(tr(Hn(n.path)), r, "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ , Ut.ct));
  15426. }
  15427. }
  15428. function nc(t, r, i) {
  15429. return e(this, void 0, void 0, (function() {
  15430. var o, u, a, s;
  15431. return n(this, (function(c) {
  15432. switch (c.label) {
  15433. case 0:
  15434. return o = j(t), u = [], a = [], s = [], o.wc.isEmpty() ? [ 3 /*break*/ , 3 ] : (o.wc.forEach((function(t, e) {
  15435. s.push(o.Rc(e, r, i).then((function(t) {
  15436. // Update views if there are actual changes.
  15437. if (
  15438. // If there are changes, or we are handling a global snapshot, notify
  15439. // secondary clients to update query state.
  15440. (t || i) && o.isPrimaryClient && o.sharedClientState.updateQueryState(e.targetId, (null == t ? void 0 : t.fromCache) ? "not-current" : "current"),
  15441. t) {
  15442. u.push(t);
  15443. var n = Zu.Li(e.targetId, t);
  15444. a.push(n);
  15445. }
  15446. })));
  15447. })), [ 4 /*yield*/ , Promise.all(s) ]);
  15448. case 1:
  15449. return c.sent(), o.dc.nu(u), [ 4 /*yield*/ , function(t, r) {
  15450. return e(this, void 0, void 0, (function() {
  15451. var e, i, o, u, a, s, c, l, h;
  15452. return n(this, (function(n) {
  15453. switch (n.label) {
  15454. case 0:
  15455. e = j(t), n.label = 1;
  15456. case 1:
  15457. return n.trys.push([ 1, 3, , 4 ]), [ 4 /*yield*/ , e.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (function(t) {
  15458. return Nt.forEach(r, (function(n) {
  15459. return Nt.forEach(n.Fi, (function(r) {
  15460. return e.persistence.referenceDelegate.addReference(t, n.targetId, r);
  15461. })).next((function() {
  15462. return Nt.forEach(n.Bi, (function(r) {
  15463. return e.persistence.referenceDelegate.removeReference(t, n.targetId, r);
  15464. }));
  15465. }));
  15466. }));
  15467. })) ];
  15468. case 2:
  15469. return n.sent(), [ 3 /*break*/ , 4 ];
  15470. case 3:
  15471. if (!Pt(i = n.sent())) throw i;
  15472. // If `notifyLocalViewChanges` fails, we did not advance the sequence
  15473. // number for the documents that were included in this transaction.
  15474. // This might trigger them to be deleted earlier than they otherwise
  15475. // would have, but it should not invalidate the integrity of the data.
  15476. return M("LocalStore", "Failed to update sequence numbers: " + i),
  15477. [ 3 /*break*/ , 4 ];
  15478. case 4:
  15479. for (o = 0, u = r; o < u.length; o++) a = u[o], s = a.targetId, a.fromCache || (c = e.Ji.get(s),
  15480. l = c.snapshotVersion, h = c.withLastLimboFreeSnapshotVersion(l),
  15481. // Advance the last limbo free snapshot version
  15482. e.Ji = e.Ji.insert(s, h));
  15483. return [ 2 /*return*/ ];
  15484. }
  15485. }));
  15486. }));
  15487. }(o.localStore, a) ];
  15488. case 2:
  15489. c.sent(), c.label = 3;
  15490. case 3:
  15491. return [ 2 /*return*/ ];
  15492. }
  15493. }));
  15494. }));
  15495. }
  15496. function rc(t, r) {
  15497. return e(this, void 0, void 0, (function() {
  15498. var e, i;
  15499. return n(this, (function(n) {
  15500. switch (n.label) {
  15501. case 0:
  15502. return (e = j(t)).currentUser.isEqual(r) ? [ 3 /*break*/ , 3 ] : (M("SyncEngine", "User change. New user:", r.toKey()),
  15503. [ 4 /*yield*/ , na(e.localStore, r) ]);
  15504. case 1:
  15505. return i = n.sent(), e.currentUser = r,
  15506. // Fails tasks waiting for pending writes requested by previous user.
  15507. function(t, e) {
  15508. t.Ec.forEach((function(t) {
  15509. t.forEach((function(t) {
  15510. t.reject(new Q(K.CANCELLED, "'waitForPendingWrites' promise is rejected due to a user change."));
  15511. }));
  15512. })), t.Ec.clear();
  15513. }(e),
  15514. // TODO(b/114226417): Consider calling this only in the primary tab.
  15515. e.sharedClientState.handleUserChange(r, i.removedBatchIds, i.addedBatchIds), [ 4 /*yield*/ , nc(e, i.er) ];
  15516. case 2:
  15517. n.sent(), n.label = 3;
  15518. case 3:
  15519. return [ 2 /*return*/ ];
  15520. }
  15521. }));
  15522. }));
  15523. }
  15524. function ic(t, e) {
  15525. var n = j(t), r = n.yc.get(e);
  15526. if (r && r.fc) return Ir().add(r.key);
  15527. var i = Ir(), o = n._c.get(e);
  15528. if (!o) return i;
  15529. for (var u = 0, a = o; u < a.length; u++) {
  15530. var s = a[u], c = n.wc.get(s);
  15531. i = i.unionWith(c.view.nc);
  15532. }
  15533. return i;
  15534. }
  15535. /**
  15536. * Reconcile the list of synced documents in an existing view with those
  15537. * from persistence.
  15538. */ function oc(t, r) {
  15539. return e(this, void 0, void 0, (function() {
  15540. var e, i, o;
  15541. return n(this, (function(n) {
  15542. switch (n.label) {
  15543. case 0:
  15544. return [ 4 /*yield*/ , la((e = j(t)).localStore, r.query,
  15545. /* usePreviousResults= */ !0) ];
  15546. case 1:
  15547. return i = n.sent(), o = r.view.hc(i), [ 2 /*return*/ , (e.isPrimaryClient && $s(e, r.targetId, o.cc),
  15548. o) ];
  15549. }
  15550. }));
  15551. }));
  15552. }
  15553. /**
  15554. * Retrieves newly changed documents from remote document cache and raises
  15555. * snapshots if needed.
  15556. */
  15557. // PORTING NOTE: Multi-Tab only.
  15558. function uc(t, r) {
  15559. return e(this, void 0, void 0, (function() {
  15560. var e;
  15561. return n(this, (function(n) {
  15562. return [ 2 /*return*/ , fa((e = j(t)).localStore, r).then((function(t) {
  15563. return nc(e, t);
  15564. })) ];
  15565. }));
  15566. }));
  15567. }
  15568. /** Applies a mutation state to an existing batch. */
  15569. // PORTING NOTE: Multi-Tab only.
  15570. function ac(t, r, i, o) {
  15571. return e(this, void 0, void 0, (function() {
  15572. var e, u;
  15573. return n(this, (function(n) {
  15574. switch (n.label) {
  15575. case 0:
  15576. return [ 4 /*yield*/ , function(t, e) {
  15577. var n = j(t), r = j(n.mutationQueue);
  15578. return n.persistence.runTransaction("Lookup mutation documents", "readonly", (function(t) {
  15579. return r.Sn(t, e).next((function(e) {
  15580. return e ? n.localDocuments.getDocuments(t, e) : Nt.resolve(null);
  15581. }));
  15582. }));
  15583. }((e = j(t)).localStore, r) ];
  15584. case 1:
  15585. return null === (u = n.sent()) ? [ 3 /*break*/ , 6 ] : "pending" !== i ? [ 3 /*break*/ , 3 ] : [ 4 /*yield*/ , os(e.remoteStore) ];
  15586. case 2:
  15587. // If we are the primary client, we need to send this write to the
  15588. // backend. Secondary clients will ignore these writes since their remote
  15589. // connection is disabled.
  15590. return n.sent(), [ 3 /*break*/ , 4 ];
  15591. case 3:
  15592. "acknowledged" === i || "rejected" === i ? (
  15593. // NOTE: Both these methods are no-ops for batches that originated from
  15594. // other clients.
  15595. Xs(e, r, o || null), Ys(e, r), function(t, e) {
  15596. j(j(t).mutationQueue).Cn(e);
  15597. }(e.localStore, r)) : U(), n.label = 4;
  15598. case 4:
  15599. return [ 4 /*yield*/ , nc(e, u) ];
  15600. case 5:
  15601. return n.sent(), [ 3 /*break*/ , 7 ];
  15602. case 6:
  15603. // A throttled tab may not have seen the mutation before it was completed
  15604. // and removed from the mutation queue, in which case we won't have cached
  15605. // the affected documents. In this case we can safely ignore the update
  15606. // since that means we didn't apply the mutation locally at all (if we
  15607. // had, we would have cached the affected documents), and so we will just
  15608. // see any resulting document changes via normal remote document updates
  15609. // as applicable.
  15610. M("SyncEngine", "Cannot apply mutation batch with id: " + r), n.label = 7;
  15611. case 7:
  15612. return [ 2 /*return*/ ];
  15613. }
  15614. }));
  15615. }));
  15616. }
  15617. /** Applies a query target change from a different tab. */
  15618. // PORTING NOTE: Multi-Tab only.
  15619. function sc(t, r) {
  15620. return e(this, void 0, void 0, (function() {
  15621. var e, i, o, u, a, s, c, l;
  15622. return n(this, (function(n) {
  15623. switch (n.label) {
  15624. case 0:
  15625. return pc(e = j(t)), vc(e), !0 !== r || !0 === e.vc ? [ 3 /*break*/ , 3 ] : (i = e.sharedClientState.getAllActiveQueryTargets(),
  15626. [ 4 /*yield*/ , cc(e, i.toArray()) ]);
  15627. case 1:
  15628. return o = n.sent(), e.vc = !0, [ 4 /*yield*/ , ds(e.remoteStore, !0) ];
  15629. case 2:
  15630. for (n.sent(), u = 0, a = o; u < a.length; u++) s = a[u], Qa(e.remoteStore, s);
  15631. return [ 3 /*break*/ , 7 ];
  15632. case 3:
  15633. return !1 !== r || !1 === e.vc ? [ 3 /*break*/ , 7 ] : (c = [], l = Promise.resolve(),
  15634. e._c.forEach((function(t, n) {
  15635. e.sharedClientState.isLocalQueryTarget(n) ? c.push(n) : l = l.then((function() {
  15636. return Js(e, n), ca(e.localStore, n,
  15637. /*keepPersistedTargetData=*/ !0);
  15638. })), Wa(e.remoteStore, n);
  15639. })), [ 4 /*yield*/ , l ]);
  15640. case 4:
  15641. return n.sent(), [ 4 /*yield*/ , cc(e, c) ];
  15642. case 5:
  15643. return n.sent(),
  15644. // PORTING NOTE: Multi-Tab only.
  15645. function(t) {
  15646. var e = j(t);
  15647. e.yc.forEach((function(t, n) {
  15648. Wa(e.remoteStore, n);
  15649. })), e.Ic.Ts(), e.yc = new Map, e.gc = new Te(pt.comparator);
  15650. }(e), e.vc = !1, [ 4 /*yield*/ , ds(e.remoteStore, !1) ];
  15651. case 6:
  15652. n.sent(), n.label = 7;
  15653. case 7:
  15654. return [ 2 /*return*/ ];
  15655. }
  15656. }));
  15657. }));
  15658. }
  15659. function cc(t, r, i) {
  15660. return e(this, void 0, void 0, (function() {
  15661. var e, i, o, u, a, s, c, l, h, f, d, p, v, m;
  15662. return n(this, (function(n) {
  15663. switch (n.label) {
  15664. case 0:
  15665. e = j(t), i = [], o = [], u = 0, a = r, n.label = 1;
  15666. case 1:
  15667. return u < a.length ? (s = a[u], c = void 0, (l = e._c.get(s)) && 0 !== l.length ? [ 4 /*yield*/ , sa(e.localStore, tr(l[0])) ] : [ 3 /*break*/ , 7 ]) : [ 3 /*break*/ , 13 ];
  15668. case 2:
  15669. // For queries that have a local View, we fetch their current state
  15670. // from LocalStore (as the resume token and the snapshot version
  15671. // might have changed) and reconcile their views with the persisted
  15672. // state (the list of syncedDocuments may have gotten out of sync).
  15673. c = n.sent(), h = 0, f = l, n.label = 3;
  15674. case 3:
  15675. return h < f.length ? (d = f[h], p = e.wc.get(d), [ 4 /*yield*/ , oc(e, p) ]) : [ 3 /*break*/ , 6 ];
  15676. case 4:
  15677. (v = n.sent()).snapshot && o.push(v.snapshot), n.label = 5;
  15678. case 5:
  15679. return h++, [ 3 /*break*/ , 3 ];
  15680. case 6:
  15681. return [ 3 /*break*/ , 11 ];
  15682. case 7:
  15683. return [ 4 /*yield*/ , ha(e.localStore, s) ];
  15684. case 8:
  15685. return m = n.sent(), [ 4 /*yield*/ , sa(e.localStore, m) ];
  15686. case 9:
  15687. return c = n.sent(), [ 4 /*yield*/ , Bs(e, lc(m), s,
  15688. /*current=*/ !1, c.resumeToken) ];
  15689. case 10:
  15690. n.sent(), n.label = 11;
  15691. case 11:
  15692. i.push(c), n.label = 12;
  15693. case 12:
  15694. return u++, [ 3 /*break*/ , 1 ];
  15695. case 13:
  15696. return [ 2 /*return*/ , (e.dc.nu(o), i) ];
  15697. }
  15698. }));
  15699. }));
  15700. }
  15701. /**
  15702. * Creates a `Query` object from the specified `Target`. There is no way to
  15703. * obtain the original `Query`, so we synthesize a `Query` from the `Target`
  15704. * object.
  15705. *
  15706. * The synthesized result might be different from the original `Query`, but
  15707. * since the synthesized `Query` should return the same results as the
  15708. * original one (only the presentation of results might differ), the potential
  15709. * difference will not cause issues.
  15710. */
  15711. // PORTING NOTE: Multi-Tab only.
  15712. function lc(t) {
  15713. return Wn(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, "F" /* LimitType.First */ , t.startAt, t.endAt);
  15714. }
  15715. /** Returns the IDs of the clients that are currently active. */
  15716. // PORTING NOTE: Multi-Tab only.
  15717. function hc(t) {
  15718. var e = j(t);
  15719. return j(j(e.localStore).persistence).$i();
  15720. }
  15721. /** Applies a query target change from a different tab. */
  15722. // PORTING NOTE: Multi-Tab only.
  15723. function fc(t, r, i, o) {
  15724. return e(this, void 0, void 0, (function() {
  15725. var e, u, a, s;
  15726. return n(this, (function(n) {
  15727. switch (n.label) {
  15728. case 0:
  15729. if ((e = j(t)).vc)
  15730. // If we receive a target state notification via WebStorage, we are
  15731. // either already secondary or another tab has taken the primary lease.
  15732. return [ 2 /*return*/ , void M("SyncEngine", "Ignoring unexpected query state notification.") ];
  15733. if (!((u = e._c.get(r)) && u.length > 0)) return [ 3 /*break*/ , 7 ];
  15734. switch (i) {
  15735. case "current":
  15736. case "not-current":
  15737. return [ 3 /*break*/ , 1 ];
  15738. case "rejected":
  15739. return [ 3 /*break*/ , 4 ];
  15740. }
  15741. return [ 3 /*break*/ , 6 ];
  15742. case 1:
  15743. return [ 4 /*yield*/ , fa(e.localStore, ar(u[0])) ];
  15744. case 2:
  15745. return a = n.sent(), s = wi.createSynthesizedRemoteEventForCurrentChange(r, "current" === i, Oe.EMPTY_BYTE_STRING),
  15746. [ 4 /*yield*/ , nc(e, a, s) ];
  15747. case 3:
  15748. return n.sent(), [ 3 /*break*/ , 7 ];
  15749. case 4:
  15750. return [ 4 /*yield*/ , ca(e.localStore, r,
  15751. /* keepPersistedTargetData */ !0) ];
  15752. case 5:
  15753. return n.sent(), Js(e, r, o), [ 3 /*break*/ , 7 ];
  15754. case 6:
  15755. U(), n.label = 7;
  15756. case 7:
  15757. return [ 2 /*return*/ ];
  15758. }
  15759. }));
  15760. }));
  15761. }
  15762. /** Adds or removes Watch targets for queries from different tabs. */ function dc(t, r, i) {
  15763. return e(this, void 0, void 0, (function() {
  15764. var e, o, u, a, s, c, l, h, f, d;
  15765. return n(this, (function(p) {
  15766. switch (p.label) {
  15767. case 0:
  15768. if (!(e = pc(t)).vc) return [ 3 /*break*/ , 10 ];
  15769. o = 0, u = r, p.label = 1;
  15770. case 1:
  15771. return o < u.length ? (a = u[o], e._c.has(a) ? (
  15772. // A target might have been added in a previous attempt
  15773. M("SyncEngine", "Adding an already active target " + a), [ 3 /*break*/ , 5 ]) : [ 4 /*yield*/ , ha(e.localStore, a) ]) : [ 3 /*break*/ , 6 ];
  15774. case 2:
  15775. return s = p.sent(), [ 4 /*yield*/ , sa(e.localStore, s) ];
  15776. case 3:
  15777. return c = p.sent(), [ 4 /*yield*/ , Bs(e, lc(s), c.targetId,
  15778. /*current=*/ !1, c.resumeToken) ];
  15779. case 4:
  15780. p.sent(), Qa(e.remoteStore, c), p.label = 5;
  15781. case 5:
  15782. return o++, [ 3 /*break*/ , 1 ];
  15783. case 6:
  15784. l = function(t) {
  15785. return n(this, (function(n) {
  15786. switch (n.label) {
  15787. case 0:
  15788. return e._c.has(t) ? [ 4 /*yield*/ , ca(e.localStore, t,
  15789. /* keepPersistedTargetData */ !1).then((function() {
  15790. Wa(e.remoteStore, t), Js(e, t);
  15791. })).catch(xt) ] : [ 3 /*break*/ , 2 ];
  15792. // Release queries that are still active.
  15793. case 1:
  15794. // Release queries that are still active.
  15795. n.sent(), n.label = 2;
  15796. case 2:
  15797. return [ 2 /*return*/ ];
  15798. }
  15799. }));
  15800. }, h = 0, f = i, p.label = 7;
  15801. case 7:
  15802. return h < f.length ? (d = f[h], [ 5 /*yield**/ , l(d) ]) : [ 3 /*break*/ , 10 ];
  15803. case 8:
  15804. p.sent(), p.label = 9;
  15805. case 9:
  15806. return h++, [ 3 /*break*/ , 7 ];
  15807. case 10:
  15808. return [ 2 /*return*/ ];
  15809. }
  15810. }));
  15811. }));
  15812. }
  15813. function pc(t) {
  15814. var e = j(t);
  15815. return e.remoteStore.remoteSyncer.applyRemoteEvent = Gs.bind(null, e), e.remoteStore.remoteSyncer.getRemoteKeysForTarget = ic.bind(null, e),
  15816. e.remoteStore.remoteSyncer.rejectListen = Ks.bind(null, e), e.dc.nu = _s.bind(null, e.eventManager),
  15817. e.dc.Pc = Ds.bind(null, e.eventManager), e;
  15818. }
  15819. function vc(t) {
  15820. var e = j(t);
  15821. return e.remoteStore.remoteSyncer.applySuccessfulWrite = Qs.bind(null, e), e.remoteStore.remoteSyncer.rejectFailedWrite = Ws.bind(null, e),
  15822. e
  15823. /**
  15824. * Loads a Firestore bundle into the SDK. The returned promise resolves when
  15825. * the bundle finished loading.
  15826. *
  15827. * @param syncEngine - SyncEngine to use.
  15828. * @param bundleReader - Bundle to load into the SDK.
  15829. * @param task - LoadBundleTask used to update the loading progress to public API.
  15830. */;
  15831. }
  15832. function mc(t, r, i) {
  15833. var o = j(t);
  15834. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  15835. /** Loads a bundle and returns the list of affected collection groups. */
  15836. (function(t, r, i) {
  15837. return e(this, void 0, void 0, (function() {
  15838. var e, o, u, a, s, c;
  15839. return n(this, (function(n) {
  15840. switch (n.label) {
  15841. case 0:
  15842. return n.trys.push([ 0, 14, , 15 ]), [ 4 /*yield*/ , r.getMetadata() ];
  15843. case 1:
  15844. return e = n.sent(), [ 4 /*yield*/ , function(t, e) {
  15845. var n = j(t), r = Vi(e.createTime);
  15846. return n.persistence.runTransaction("hasNewerBundle", "readonly", (function(t) {
  15847. return n.qs.getBundleMetadata(t, e.id);
  15848. })).then((function(t) {
  15849. return !!t && t.createTime.compareTo(r) >= 0;
  15850. }));
  15851. }(t.localStore, e) ];
  15852. case 2:
  15853. return n.sent() ? [ 4 /*yield*/ , r.close() ] : [ 3 /*break*/ , 4 ];
  15854. case 3:
  15855. return [ 2 /*return*/ , (n.sent(), i._completeWith(function(t) {
  15856. return {
  15857. taskState: "Success",
  15858. documentsLoaded: t.totalDocuments,
  15859. bytesLoaded: t.totalBytes,
  15860. totalDocuments: t.totalDocuments,
  15861. totalBytes: t.totalBytes
  15862. };
  15863. }(e)), Promise.resolve(new Set)) ];
  15864. case 4:
  15865. return i._updateProgress(Os(e)), o = new ks(e, t.localStore, r.serializer), [ 4 /*yield*/ , r.bc() ];
  15866. case 5:
  15867. u = n.sent(), n.label = 6;
  15868. case 6:
  15869. return u ? [ 4 /*yield*/ , o.zu(u) ] : [ 3 /*break*/ , 10 ];
  15870. case 7:
  15871. return (a = n.sent()) && i._updateProgress(a), [ 4 /*yield*/ , r.bc() ];
  15872. case 8:
  15873. u = n.sent(), n.label = 9;
  15874. case 9:
  15875. return [ 3 /*break*/ , 6 ];
  15876. case 10:
  15877. return [ 4 /*yield*/ , o.complete() ];
  15878. case 11:
  15879. return s = n.sent(), [ 4 /*yield*/ , nc(t, s.Ju,
  15880. /* remoteEvent */ void 0) ];
  15881. case 12:
  15882. // Save metadata, so loading the same bundle will skip.
  15883. return n.sent(), [ 4 /*yield*/ , function(t, e) {
  15884. var n = j(t);
  15885. return n.persistence.runTransaction("Save bundle", "readwrite", (function(t) {
  15886. return n.qs.saveBundleMetadata(t, e);
  15887. }));
  15888. }(t.localStore, e) ];
  15889. case 13:
  15890. return [ 2 /*return*/ , (
  15891. // Save metadata, so loading the same bundle will skip.
  15892. n.sent(), i._completeWith(s.progress), Promise.resolve(s.Hu)) ];
  15893. case 14:
  15894. return c = n.sent(), [ 2 /*return*/ , (q("SyncEngine", "Loading bundle failed with ".concat(c)),
  15895. i._failWith(c), Promise.resolve(new Set)) ];
  15896. case 15:
  15897. return [ 2 /*return*/ ];
  15898. }
  15899. }));
  15900. }));
  15901. }
  15902. /**
  15903. * @license
  15904. * Copyright 2020 Google LLC
  15905. *
  15906. * Licensed under the Apache License, Version 2.0 (the "License");
  15907. * you may not use this file except in compliance with the License.
  15908. * You may obtain a copy of the License at
  15909. *
  15910. * http://www.apache.org/licenses/LICENSE-2.0
  15911. *
  15912. * Unless required by applicable law or agreed to in writing, software
  15913. * distributed under the License is distributed on an "AS IS" BASIS,
  15914. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15915. * See the License for the specific language governing permissions and
  15916. * limitations under the License.
  15917. */
  15918. /**
  15919. * Provides all components needed for Firestore with in-memory persistence.
  15920. * Uses EagerGC garbage collection.
  15921. */)(o, r, i).then((function(t) {
  15922. o.sharedClientState.notifyBundleLoaded(t);
  15923. }));
  15924. }
  15925. var yc = /** @class */ function() {
  15926. function t() {
  15927. this.synchronizeTabs = !1;
  15928. }
  15929. return t.prototype.initialize = function(t) {
  15930. return e(this, void 0, void 0, (function() {
  15931. return n(this, (function(e) {
  15932. switch (e.label) {
  15933. case 0:
  15934. return this.serializer = Va(t.databaseInfo.databaseId), this.sharedClientState = this.createSharedClientState(t),
  15935. this.persistence = this.createPersistence(t), [ 4 /*yield*/ , this.persistence.start() ];
  15936. case 1:
  15937. return e.sent(), this.localStore = this.createLocalStore(t), this.gcScheduler = this.createGarbageCollectionScheduler(t, this.localStore),
  15938. this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(t, this.localStore),
  15939. [ 2 /*return*/ ];
  15940. }
  15941. }));
  15942. }));
  15943. }, t.prototype.createGarbageCollectionScheduler = function(t, e) {
  15944. return null;
  15945. }, t.prototype.createIndexBackfillerScheduler = function(t, e) {
  15946. return null;
  15947. }, t.prototype.createLocalStore = function(t) {
  15948. return ea(this.persistence, new $u, t.initialUser, this.serializer);
  15949. }, t.prototype.createPersistence = function(t) {
  15950. return new Uu(Gu.zs, this.serializer);
  15951. }, t.prototype.createSharedClientState = function(t) {
  15952. return new _a;
  15953. }, t.prototype.terminate = function() {
  15954. return e(this, void 0, void 0, (function() {
  15955. return n(this, (function(t) {
  15956. switch (t.label) {
  15957. case 0:
  15958. return this.gcScheduler && this.gcScheduler.stop(), [ 4 /*yield*/ , this.sharedClientState.shutdown() ];
  15959. case 1:
  15960. return t.sent(), [ 4 /*yield*/ , this.persistence.shutdown() ];
  15961. case 2:
  15962. return t.sent(), [ 2 /*return*/ ];
  15963. }
  15964. }));
  15965. }));
  15966. }, t;
  15967. }(), gc = /** @class */ function(e) {
  15968. function n(t) {
  15969. var n = this;
  15970. return (n = e.call(this) || this).cacheSizeBytes = t, n;
  15971. }
  15972. return t(n, e), n.prototype.createGarbageCollectionScheduler = function(t, e) {
  15973. z(this.persistence.referenceDelegate instanceof ju);
  15974. var n = this.persistence.referenceDelegate.garbageCollector;
  15975. return new yu(n, t.asyncQueue, e);
  15976. }, n.prototype.createPersistence = function(t) {
  15977. var e = void 0 !== this.cacheSizeBytes ? nu.withCacheSize(this.cacheSizeBytes) : nu.DEFAULT;
  15978. return new Uu((function(t) {
  15979. return ju.zs(t, e);
  15980. }), this.serializer);
  15981. }, n;
  15982. }(yc), wc = /** @class */ function(r) {
  15983. function i(t, e, n) {
  15984. var i = this;
  15985. return (i = r.call(this) || this).Vc = t, i.cacheSizeBytes = e, i.forceOwnership = n,
  15986. i.synchronizeTabs = !1, i;
  15987. }
  15988. return t(i, r), i.prototype.initialize = function(t) {
  15989. return e(this, void 0, void 0, (function() {
  15990. var e = this;
  15991. return n(this, (function(n) {
  15992. switch (n.label) {
  15993. case 0:
  15994. return [ 4 /*yield*/ , r.prototype.initialize.call(this, t) ];
  15995. case 1:
  15996. return n.sent(), [ 4 /*yield*/ , this.Vc.initialize(this, t) ];
  15997. case 2:
  15998. // Enqueue writes from a previous session
  15999. return n.sent(), [ 4 /*yield*/ , vc(this.Vc.syncEngine) ];
  16000. case 3:
  16001. // Enqueue writes from a previous session
  16002. return n.sent(), [ 4 /*yield*/ , os(this.Vc.remoteStore) ];
  16003. case 4:
  16004. // NOTE: This will immediately call the listener, so we make sure to
  16005. // set it after localStore / remoteStore are started.
  16006. return n.sent(), [ 4 /*yield*/ , this.persistence.Ii((function() {
  16007. return e.gcScheduler && !e.gcScheduler.started && e.gcScheduler.start(), e.indexBackfillerScheduler && !e.indexBackfillerScheduler.started && e.indexBackfillerScheduler.start(),
  16008. Promise.resolve();
  16009. })) ];
  16010. case 5:
  16011. // NOTE: This will immediately call the listener, so we make sure to
  16012. // set it after localStore / remoteStore are started.
  16013. return n.sent(), [ 2 /*return*/ ];
  16014. }
  16015. }));
  16016. }));
  16017. }, i.prototype.createLocalStore = function(t) {
  16018. return ea(this.persistence, new $u, t.initialUser, this.serializer);
  16019. }, i.prototype.createGarbageCollectionScheduler = function(t, e) {
  16020. var n = this.persistence.referenceDelegate.garbageCollector;
  16021. return new yu(n, t.asyncQueue, e);
  16022. }, i.prototype.createIndexBackfillerScheduler = function(t, e) {
  16023. var n = new Bt(e, this.persistence);
  16024. return new qt(t.asyncQueue, n);
  16025. }, i.prototype.createPersistence = function(t) {
  16026. var e = Ju(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? nu.withCacheSize(this.cacheSizeBytes) : nu.DEFAULT;
  16027. return new Hu(this.synchronizeTabs, e, t.clientId, n, t.asyncQueue, Pa(), Ra(), this.serializer, this.sharedClientState, !!this.forceOwnership);
  16028. }, i.prototype.createSharedClientState = function(t) {
  16029. return new _a;
  16030. }, i;
  16031. }(yc), bc = /** @class */ function(r) {
  16032. function i(t, e) {
  16033. var n = this;
  16034. return (n = r.call(this, t, e, /* forceOwnership= */ !1) || this).Vc = t, n.cacheSizeBytes = e,
  16035. n.synchronizeTabs = !0, n;
  16036. }
  16037. return t(i, r), i.prototype.initialize = function(t) {
  16038. return e(this, void 0, void 0, (function() {
  16039. var i, o = this;
  16040. return n(this, (function(u) {
  16041. switch (u.label) {
  16042. case 0:
  16043. return [ 4 /*yield*/ , r.prototype.initialize.call(this, t) ];
  16044. case 1:
  16045. return u.sent(), i = this.Vc.syncEngine, this.sharedClientState instanceof Sa ? (this.sharedClientState.syncEngine = {
  16046. jr: ac.bind(null, i),
  16047. zr: fc.bind(null, i),
  16048. Wr: dc.bind(null, i),
  16049. $i: hc.bind(null, i),
  16050. Qr: uc.bind(null, i)
  16051. }, [ 4 /*yield*/ , this.sharedClientState.start() ]) : [ 3 /*break*/ , 3 ];
  16052. case 2:
  16053. u.sent(), u.label = 3;
  16054. case 3:
  16055. // NOTE: This will immediately call the listener, so we make sure to
  16056. // set it after localStore / remoteStore are started.
  16057. return [ 4 /*yield*/ , this.persistence.Ii((function(t) {
  16058. return e(o, void 0, void 0, (function() {
  16059. return n(this, (function(e) {
  16060. switch (e.label) {
  16061. case 0:
  16062. return [ 4 /*yield*/ , sc(this.Vc.syncEngine, t) ];
  16063. case 1:
  16064. return e.sent(), this.gcScheduler && (t && !this.gcScheduler.started ? this.gcScheduler.start() : t || this.gcScheduler.stop()),
  16065. this.indexBackfillerScheduler && (t && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : t || this.indexBackfillerScheduler.stop()),
  16066. [ 2 /*return*/ ];
  16067. }
  16068. }));
  16069. }));
  16070. })) ];
  16071. case 4:
  16072. // NOTE: This will immediately call the listener, so we make sure to
  16073. // set it after localStore / remoteStore are started.
  16074. return u.sent(), [ 2 /*return*/ ];
  16075. }
  16076. }));
  16077. }));
  16078. }, i.prototype.createSharedClientState = function(t) {
  16079. var e = Pa();
  16080. if (!Sa.D(e)) throw new Q(K.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
  16081. var n = Ju(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey);
  16082. return new Sa(e, t.asyncQueue, n, t.clientId, t.initialUser);
  16083. }, i;
  16084. }(wc), Ic = /** @class */ function() {
  16085. function t() {}
  16086. return t.prototype.initialize = function(t, r) {
  16087. return e(this, void 0, void 0, (function() {
  16088. var e = this;
  16089. return n(this, (function(n) {
  16090. switch (n.label) {
  16091. case 0:
  16092. return this.localStore ? [ 3 /*break*/ , 2 ] : (this.localStore = t.localStore,
  16093. this.sharedClientState = t.sharedClientState, this.datastore = this.createDatastore(r),
  16094. this.remoteStore = this.createRemoteStore(r), this.eventManager = this.createEventManager(r),
  16095. this.syncEngine = this.createSyncEngine(r,
  16096. /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = function(t) {
  16097. return js(e.syncEngine, t, 1 /* OnlineStateSource.SharedClientState */);
  16098. }, this.remoteStore.remoteSyncer.handleCredentialChange = rc.bind(null, this.syncEngine),
  16099. [ 4 /*yield*/ , ds(this.remoteStore, this.syncEngine.isPrimaryClient) ]);
  16100. case 1:
  16101. n.sent(), n.label = 2;
  16102. case 2:
  16103. return [ 2 /*return*/ ];
  16104. }
  16105. }));
  16106. }));
  16107. }, t.prototype.createEventManager = function(t) {
  16108. return new Es;
  16109. }, t.prototype.createDatastore = function(t) {
  16110. var e, n = Va(t.databaseInfo.databaseId), r = (e = t.databaseInfo, new Fa(e));
  16111. /** Return the Platform-specific connectivity monitor. */ return function(t, e, n, r) {
  16112. return new Ua(t, e, n, r);
  16113. }(t.authCredentials, t.appCheckCredentials, r, n);
  16114. }, t.prototype.createRemoteStore = function(t) {
  16115. var e, n, r, i, o, u = this;
  16116. return e = this.localStore, n = this.datastore, r = t.asyncQueue, i = function(t) {
  16117. return js(u.syncEngine, t, 0 /* OnlineStateSource.RemoteStore */);
  16118. }, o = Ca.D() ? new Ca : new Da, new Ga(e, n, r, i, o);
  16119. }, t.prototype.createSyncEngine = function(t, e) {
  16120. return function(t, e, n,
  16121. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  16122. r, i, o, u) {
  16123. var a = new Ls(t, e, n, r, i, o);
  16124. return u && (a.vc = !0), a;
  16125. }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);
  16126. }, t.prototype.terminate = function() {
  16127. return function(t) {
  16128. return e(this, void 0, void 0, (function() {
  16129. var e;
  16130. return n(this, (function(n) {
  16131. switch (n.label) {
  16132. case 0:
  16133. return e = j(t), M("RemoteStore", "RemoteStore shutting down."), e.vu.add(5 /* OfflineCause.Shutdown */),
  16134. [ 4 /*yield*/ , Ka(e) ];
  16135. case 1:
  16136. return n.sent(), e.Pu.shutdown(),
  16137. // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
  16138. // triggering spurious listener events with cached data, etc.
  16139. e.bu.set("Unknown" /* OnlineState.Unknown */), [ 2 /*return*/ ];
  16140. }
  16141. }));
  16142. }));
  16143. }(this.remoteStore);
  16144. }, t;
  16145. }();
  16146. /**
  16147. * @license
  16148. * Copyright 2020 Google LLC
  16149. *
  16150. * Licensed under the Apache License, Version 2.0 (the "License");
  16151. * you may not use this file except in compliance with the License.
  16152. * You may obtain a copy of the License at
  16153. *
  16154. * http://www.apache.org/licenses/LICENSE-2.0
  16155. *
  16156. * Unless required by applicable law or agreed to in writing, software
  16157. * distributed under the License is distributed on an "AS IS" BASIS,
  16158. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16159. * See the License for the specific language governing permissions and
  16160. * limitations under the License.
  16161. */
  16162. /**
  16163. * How many bytes to read each time when `ReadableStreamReader.read()` is
  16164. * called. Only applicable for byte streams that we control (e.g. those backed
  16165. * by an UInt8Array).
  16166. */
  16167. /**
  16168. * Builds a `ByteStreamReader` from a UInt8Array.
  16169. * @param source - The data source to use.
  16170. * @param bytesPerRead - How many bytes each `read()` from the returned reader
  16171. * will read.
  16172. */
  16173. function Ec(t, r) {
  16174. void 0 === r && (r = 10240);
  16175. var i = 0;
  16176. // The TypeScript definition for ReadableStreamReader changed. We use
  16177. // `any` here to allow this code to compile with different versions.
  16178. // See https://github.com/microsoft/TypeScript/issues/42970
  16179. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16180. return {
  16181. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16182. read: function() {
  16183. return e(this, void 0, void 0, (function() {
  16184. var e;
  16185. return n(this, (function(n) {
  16186. return i < t.byteLength ? (e = {
  16187. value: t.slice(i, i + r),
  16188. done: !1
  16189. }, [ 2 /*return*/ , (i += r, e) ]) : [ 2 /*return*/ , {
  16190. done: !0
  16191. } ];
  16192. }));
  16193. }));
  16194. },
  16195. cancel: function() {
  16196. return e(this, void 0, void 0, (function() {
  16197. return n(this, (function(t) {
  16198. return [ 2 /*return*/ ];
  16199. }));
  16200. }));
  16201. },
  16202. releaseLock: function() {},
  16203. closed: Promise.resolve()
  16204. };
  16205. }
  16206. /**
  16207. * @license
  16208. * Copyright 2020 Google LLC
  16209. *
  16210. * Licensed under the Apache License, Version 2.0 (the "License");
  16211. * you may not use this file except in compliance with the License.
  16212. * You may obtain a copy of the License at
  16213. *
  16214. * http://www.apache.org/licenses/LICENSE-2.0
  16215. *
  16216. * Unless required by applicable law or agreed to in writing, software
  16217. * distributed under the License is distributed on an "AS IS" BASIS,
  16218. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16219. * See the License for the specific language governing permissions and
  16220. * limitations under the License.
  16221. */
  16222. /**
  16223. * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.
  16224. */
  16225. /**
  16226. * @license
  16227. * Copyright 2017 Google LLC
  16228. *
  16229. * Licensed under the Apache License, Version 2.0 (the "License");
  16230. * you may not use this file except in compliance with the License.
  16231. * You may obtain a copy of the License at
  16232. *
  16233. * http://www.apache.org/licenses/LICENSE-2.0
  16234. *
  16235. * Unless required by applicable law or agreed to in writing, software
  16236. * distributed under the License is distributed on an "AS IS" BASIS,
  16237. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16238. * See the License for the specific language governing permissions and
  16239. * limitations under the License.
  16240. */
  16241. /*
  16242. * A wrapper implementation of Observer<T> that will dispatch events
  16243. * asynchronously. To allow immediate silencing, a mute call is added which
  16244. * causes events scheduled to no longer be raised.
  16245. */ var Tc = /** @class */ function() {
  16246. function t(t) {
  16247. this.observer = t,
  16248. /**
  16249. * When set to true, will not raise future events. Necessary to deal with
  16250. * async detachment of listener.
  16251. */
  16252. this.muted = !1;
  16253. }
  16254. return t.prototype.next = function(t) {
  16255. this.observer.next && this.Sc(this.observer.next, t);
  16256. }, t.prototype.error = function(t) {
  16257. this.observer.error ? this.Sc(this.observer.error, t) : L("Uncaught Error in snapshot listener:", t.toString());
  16258. }, t.prototype.Dc = function() {
  16259. this.muted = !0;
  16260. }, t.prototype.Sc = function(t, e) {
  16261. var n = this;
  16262. this.muted || setTimeout((function() {
  16263. n.muted || t(e);
  16264. }), 0);
  16265. }, t;
  16266. }(), Sc = /** @class */ function() {
  16267. function t(
  16268. /** The reader to read from underlying binary bundle data source. */
  16269. t, e) {
  16270. var n = this;
  16271. this.Cc = t, this.serializer = e,
  16272. /** Cached bundle metadata. */
  16273. this.metadata = new W,
  16274. /**
  16275. * Internal buffer to hold bundle content, accumulating incomplete element
  16276. * content.
  16277. */
  16278. this.buffer = new Uint8Array, this.xc = new TextDecoder("utf-8"),
  16279. // Read the metadata (which is the first element).
  16280. this.Nc().then((function(t) {
  16281. t && t.Qu() ? n.metadata.resolve(t.Gu.metadata) : n.metadata.reject(new Error("The first element of the bundle is not a metadata, it is\n ".concat(JSON.stringify(null == t ? void 0 : t.Gu))));
  16282. }), (function(t) {
  16283. return n.metadata.reject(t);
  16284. }));
  16285. }
  16286. return t.prototype.close = function() {
  16287. return this.Cc.cancel();
  16288. }, t.prototype.getMetadata = function() {
  16289. return e(this, void 0, void 0, (function() {
  16290. return n(this, (function(t) {
  16291. return [ 2 /*return*/ , this.metadata.promise ];
  16292. }));
  16293. }));
  16294. }, t.prototype.bc = function() {
  16295. return e(this, void 0, void 0, (function() {
  16296. return n(this, (function(t) {
  16297. switch (t.label) {
  16298. case 0:
  16299. return [ 4 /*yield*/ , this.getMetadata() ];
  16300. case 1:
  16301. // Makes sure metadata is read before proceeding.
  16302. return [ 2 /*return*/ , (t.sent(), this.Nc()) ];
  16303. }
  16304. }));
  16305. }));
  16306. },
  16307. /**
  16308. * Reads from the head of internal buffer, and pulling more data from
  16309. * underlying stream if a complete element cannot be found, until an
  16310. * element(including the prefixed length and the JSON string) is found.
  16311. *
  16312. * Once a complete element is read, it is dropped from internal buffer.
  16313. *
  16314. * Returns either the bundled element, or null if we have reached the end of
  16315. * the stream.
  16316. */
  16317. t.prototype.Nc = function() {
  16318. return e(this, void 0, void 0, (function() {
  16319. var t, e, r, i;
  16320. return n(this, (function(n) {
  16321. switch (n.label) {
  16322. case 0:
  16323. return [ 4 /*yield*/ , this.kc() ];
  16324. case 1:
  16325. return null === (t = n.sent()) ? [ 2 /*return*/ , null ] : (e = this.xc.decode(t),
  16326. r = Number(e), isNaN(r) && this.Mc("length string (".concat(e, ") is not valid number")),
  16327. [ 4 /*yield*/ , this.$c(r) ]);
  16328. case 2:
  16329. return i = n.sent(), [ 2 /*return*/ , new Ns(JSON.parse(i), t.length + r) ];
  16330. }
  16331. }));
  16332. }));
  16333. },
  16334. /** First index of '{' from the underlying buffer. */ t.prototype.Oc = function() {
  16335. return this.buffer.findIndex((function(t) {
  16336. return t === "{".charCodeAt(0);
  16337. }));
  16338. },
  16339. /**
  16340. * Reads from the beginning of the internal buffer, until the first '{', and
  16341. * return the content.
  16342. *
  16343. * If reached end of the stream, returns a null.
  16344. */
  16345. t.prototype.kc = function() {
  16346. return e(this, void 0, void 0, (function() {
  16347. var t, e;
  16348. return n(this, (function(n) {
  16349. switch (n.label) {
  16350. case 0:
  16351. return this.Oc() < 0 ? [ 4 /*yield*/ , this.Fc() ] : [ 3 /*break*/ , 3 ];
  16352. case 1:
  16353. if (n.sent()) return [ 3 /*break*/ , 3 ];
  16354. n.label = 2;
  16355. case 2:
  16356. return [ 3 /*break*/ , 0 ];
  16357. case 3:
  16358. // Broke out of the loop because underlying stream is closed, and there
  16359. // happens to be no more data to process.
  16360. return 0 === this.buffer.length ? [ 2 /*return*/ , null ] : (
  16361. // Broke out of the loop because underlying stream is closed, but still
  16362. // cannot find an open bracket.
  16363. (t = this.Oc()) < 0 && this.Mc("Reached the end of bundle when a length string is expected."),
  16364. e = this.buffer.slice(0, t), [ 2 /*return*/ , (this.buffer = this.buffer.slice(t),
  16365. e) ]);
  16366. }
  16367. }));
  16368. }));
  16369. },
  16370. /**
  16371. * Reads from a specified position from the internal buffer, for a specified
  16372. * number of bytes, pulling more data from the underlying stream if needed.
  16373. *
  16374. * Returns a string decoded from the read bytes.
  16375. */
  16376. t.prototype.$c = function(t) {
  16377. return e(this, void 0, void 0, (function() {
  16378. var e;
  16379. return n(this, (function(n) {
  16380. switch (n.label) {
  16381. case 0:
  16382. return this.buffer.length < t ? [ 4 /*yield*/ , this.Fc() ] : [ 3 /*break*/ , 3 ];
  16383. case 1:
  16384. n.sent() && this.Mc("Reached the end of bundle when more is expected."), n.label = 2;
  16385. case 2:
  16386. return [ 3 /*break*/ , 0 ];
  16387. case 3:
  16388. // Update the internal buffer to drop the read json string.
  16389. return e = this.xc.decode(this.buffer.slice(0, t)), [ 2 /*return*/ , (this.buffer = this.buffer.slice(t),
  16390. e) ];
  16391. }
  16392. }));
  16393. }));
  16394. }, t.prototype.Mc = function(t) {
  16395. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16396. throw this.Cc.cancel(), new Error("Invalid bundle format: ".concat(t));
  16397. },
  16398. /**
  16399. * Pulls more data from underlying stream to internal buffer.
  16400. * Returns a boolean indicating whether the stream is finished.
  16401. */
  16402. t.prototype.Fc = function() {
  16403. return e(this, void 0, void 0, (function() {
  16404. var t, e;
  16405. return n(this, (function(n) {
  16406. switch (n.label) {
  16407. case 0:
  16408. return [ 4 /*yield*/ , this.Cc.read() ];
  16409. case 1:
  16410. return (t = n.sent()).done || ((e = new Uint8Array(this.buffer.length + t.value.length)).set(this.buffer),
  16411. e.set(t.value, this.buffer.length), this.buffer = e), [ 2 /*return*/ , t.done ];
  16412. }
  16413. }));
  16414. }));
  16415. }, t;
  16416. }(), _c = /** @class */ function() {
  16417. function t(t) {
  16418. this.datastore = t,
  16419. // The version of each document that was read during this transaction.
  16420. this.readVersions = new Map, this.mutations = [], this.committed = !1,
  16421. /**
  16422. * A deferred usage error that occurred previously in this transaction that
  16423. * will cause the transaction to fail once it actually commits.
  16424. */
  16425. this.lastWriteError = null,
  16426. /**
  16427. * Set of documents that have been written in the transaction.
  16428. *
  16429. * When there's more than one write to the same key in a transaction, any
  16430. * writes after the first are handled differently.
  16431. */
  16432. this.writtenDocs = new Set;
  16433. }
  16434. return t.prototype.lookup = function(t) {
  16435. return e(this, void 0, void 0, (function() {
  16436. var r, i = this;
  16437. return n(this, (function(o) {
  16438. switch (o.label) {
  16439. case 0:
  16440. if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new Q(K.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes.");
  16441. return [ 4 /*yield*/ , function(t, r) {
  16442. return e(this, void 0, void 0, (function() {
  16443. var e, i, o, u, a, s;
  16444. return n(this, (function(n) {
  16445. switch (n.label) {
  16446. case 0:
  16447. return e = j(t), i = Gi(e.serializer) + "/documents", o = {
  16448. documents: r.map((function(t) {
  16449. return qi(e.serializer, t);
  16450. }))
  16451. }, [ 4 /*yield*/ , e.vo("BatchGetDocuments", i, o, r.length) ];
  16452. case 1:
  16453. return u = n.sent(), a = new Map, u.forEach((function(t) {
  16454. var n = function(t, e) {
  16455. return "found" in e ? function(t, e) {
  16456. z(!!e.found), e.found.name, e.found.updateTime;
  16457. var n = Bi(t, e.found.name), r = Vi(e.found.updateTime), i = e.found.createTime ? Vi(e.found.createTime) : ct.min(), o = new hn({
  16458. mapValue: {
  16459. fields: e.found.fields
  16460. }
  16461. });
  16462. return dn.newFoundDocument(n, r, i, o);
  16463. }(t, e) : "missing" in e ? function(t, e) {
  16464. z(!!e.missing), z(!!e.readTime);
  16465. var n = Bi(t, e.missing), r = Vi(e.readTime);
  16466. return dn.newNoDocument(n, r);
  16467. }(t, e) : U();
  16468. }(e.serializer, t);
  16469. a.set(n.key.toString(), n);
  16470. })), s = [], [ 2 /*return*/ , (r.forEach((function(t) {
  16471. var e = a.get(t.toString());
  16472. z(!!e), s.push(e);
  16473. })), s) ];
  16474. }
  16475. }));
  16476. }));
  16477. }(this.datastore, t) ];
  16478. case 1:
  16479. return [ 2 /*return*/ , ((r = o.sent()).forEach((function(t) {
  16480. return i.recordVersion(t);
  16481. })), r) ];
  16482. }
  16483. }));
  16484. }));
  16485. }, t.prototype.set = function(t, e) {
  16486. this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16487. }, t.prototype.update = function(t, e) {
  16488. try {
  16489. this.write(e.toMutation(t, this.preconditionForUpdate(t)));
  16490. } catch (t) {
  16491. this.lastWriteError = t;
  16492. }
  16493. this.writtenDocs.add(t.toString());
  16494. }, t.prototype.delete = function(t) {
  16495. this.write(new ni(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16496. }, t.prototype.commit = function() {
  16497. return e(this, void 0, void 0, (function() {
  16498. var t, r = this;
  16499. return n(this, (function(i) {
  16500. switch (i.label) {
  16501. case 0:
  16502. if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;
  16503. return t = this.readVersions,
  16504. // For each mutation, note that the doc was written.
  16505. this.mutations.forEach((function(e) {
  16506. t.delete(e.key.toString());
  16507. })),
  16508. // For each document that was read but not written to, we want to perform
  16509. // a `verify` operation.
  16510. t.forEach((function(t, e) {
  16511. var n = pt.fromPath(e);
  16512. r.mutations.push(new ri(n, r.precondition(n)));
  16513. })), [ 4 /*yield*/ , function(t, r) {
  16514. return e(this, void 0, void 0, (function() {
  16515. var e, i, o;
  16516. return n(this, (function(n) {
  16517. switch (n.label) {
  16518. case 0:
  16519. return e = j(t), i = Gi(e.serializer) + "/documents", o = {
  16520. writes: r.map((function(t) {
  16521. return Wi(e.serializer, t);
  16522. }))
  16523. }, [ 4 /*yield*/ , e.Io("Commit", i, o) ];
  16524. case 1:
  16525. return n.sent(), [ 2 /*return*/ ];
  16526. }
  16527. }));
  16528. }));
  16529. }(this.datastore, this.mutations) ];
  16530. case 1:
  16531. // For each mutation, note that the doc was written.
  16532. return i.sent(), this.committed = !0, [ 2 /*return*/ ];
  16533. }
  16534. }));
  16535. }));
  16536. }, t.prototype.recordVersion = function(t) {
  16537. var e;
  16538. if (t.isFoundDocument()) e = t.version; else {
  16539. if (!t.isNoDocument()) throw U();
  16540. // Represent a deleted doc using SnapshotVersion.min().
  16541. e = ct.min();
  16542. }
  16543. var n = this.readVersions.get(t.key.toString());
  16544. if (n) {
  16545. if (!e.isEqual(n))
  16546. // This transaction will fail no matter what.
  16547. throw new Q(K.ABORTED, "Document version changed between two reads.");
  16548. } else this.readVersions.set(t.key.toString(), e);
  16549. },
  16550. /**
  16551. * Returns the version of this document when it was read in this transaction,
  16552. * as a precondition, or no precondition if it was not read.
  16553. */
  16554. t.prototype.precondition = function(t) {
  16555. var e = this.readVersions.get(t.toString());
  16556. return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(ct.min()) ? Ur.exists(!1) : Ur.updateTime(e) : Ur.none();
  16557. },
  16558. /**
  16559. * Returns the precondition for a document if the operation is an update.
  16560. */
  16561. t.prototype.preconditionForUpdate = function(t) {
  16562. var e = this.readVersions.get(t.toString());
  16563. // The first time a document is written, we want to take into account the
  16564. // read time and existence
  16565. if (!this.writtenDocs.has(t.toString()) && e) {
  16566. if (e.isEqual(ct.min()))
  16567. // The document doesn't exist, so fail the transaction.
  16568. // This has to be validated locally because you can't send a
  16569. // precondition that a document does not exist without changing the
  16570. // semantics of the backend write to be an insert. This is the reverse
  16571. // of what we want, since we want to assert that the document doesn't
  16572. // exist but then send the update and have it fail. Since we can't
  16573. // express that to the backend, we have to validate locally.
  16574. // Note: this can change once we can send separate verify writes in the
  16575. // transaction.
  16576. throw new Q(K.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
  16577. // Document exists, base precondition on document update time.
  16578. return Ur.updateTime(e);
  16579. }
  16580. // Document was not read, so we just use the preconditions for a blind
  16581. // update.
  16582. return Ur.exists(!0);
  16583. }, t.prototype.write = function(t) {
  16584. this.ensureCommitNotCalled(), this.mutations.push(t);
  16585. }, t.prototype.ensureCommitNotCalled = function() {}, t;
  16586. }(), Dc = /** @class */ function() {
  16587. function t(t, e, n, r, i) {
  16588. this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = r,
  16589. this.deferred = i, this.Bc = n.maxAttempts, this.qo = new Ma(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */)
  16590. /** Runs the transaction and sets the result on deferred. */;
  16591. }
  16592. return t.prototype.run = function() {
  16593. this.Bc -= 1, this.Lc();
  16594. }, t.prototype.Lc = function() {
  16595. var t = this;
  16596. this.qo.No((function() {
  16597. return e(t, void 0, void 0, (function() {
  16598. var t, e, r = this;
  16599. return n(this, (function(n) {
  16600. return t = new _c(this.datastore), (e = this.qc(t)) && e.then((function(e) {
  16601. r.asyncQueue.enqueueAndForget((function() {
  16602. return t.commit().then((function() {
  16603. r.deferred.resolve(e);
  16604. })).catch((function(t) {
  16605. r.Uc(t);
  16606. }));
  16607. }));
  16608. })).catch((function(t) {
  16609. r.Uc(t);
  16610. })), [ 2 /*return*/ ];
  16611. }));
  16612. }));
  16613. }));
  16614. }, t.prototype.qc = function(t) {
  16615. try {
  16616. var e = this.updateFunction(t);
  16617. return !zt(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")),
  16618. null);
  16619. } catch (t) {
  16620. // Do not retry errors thrown by user provided updateFunction.
  16621. return this.deferred.reject(t), null;
  16622. }
  16623. }, t.prototype.Uc = function(t) {
  16624. var e = this;
  16625. this.Bc > 0 && this.Kc(t) ? (this.Bc -= 1, this.asyncQueue.enqueueAndForget((function() {
  16626. return e.Lc(), Promise.resolve();
  16627. }))) : this.deferred.reject(t);
  16628. }, t.prototype.Kc = function(t) {
  16629. if ("FirebaseError" === t.name) {
  16630. // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
  16631. // non-matching document versions with ABORTED. These errors should be retried.
  16632. var e = t.code;
  16633. return "aborted" === e || "failed-precondition" === e || "already-exists" === e || !ci(e);
  16634. }
  16635. return !1;
  16636. }, t;
  16637. }(), Cc = /** @class */ function() {
  16638. function t(t, r,
  16639. /**
  16640. * Asynchronous queue responsible for all of our internal processing. When
  16641. * we get incoming work from the user (via public API) or the network
  16642. * (incoming GRPC messages), we should always schedule onto this queue.
  16643. * This ensures all of our work is properly serialized (e.g. we don't
  16644. * start processing a new operation while the previous one is waiting for
  16645. * an async I/O to complete).
  16646. */
  16647. i, o) {
  16648. var u = this;
  16649. this.authCredentials = t, this.appCheckCredentials = r, this.asyncQueue = i, this.databaseInfo = o,
  16650. this.user = O.UNAUTHENTICATED, this.clientId = it.A(), this.authCredentialListener = function() {
  16651. return Promise.resolve();
  16652. }, this.appCheckCredentialListener = function() {
  16653. return Promise.resolve();
  16654. }, this.authCredentials.start(i, (function(t) {
  16655. return e(u, void 0, void 0, (function() {
  16656. return n(this, (function(e) {
  16657. switch (e.label) {
  16658. case 0:
  16659. return M("FirestoreClient", "Received user=", t.uid), [ 4 /*yield*/ , this.authCredentialListener(t) ];
  16660. case 1:
  16661. return e.sent(), this.user = t, [ 2 /*return*/ ];
  16662. }
  16663. }));
  16664. }));
  16665. })), this.appCheckCredentials.start(i, (function(t) {
  16666. return M("FirestoreClient", "Received new app check token=", t), u.appCheckCredentialListener(t, u.user);
  16667. }));
  16668. }
  16669. return t.prototype.getConfiguration = function() {
  16670. return e(this, void 0, void 0, (function() {
  16671. return n(this, (function(t) {
  16672. return [ 2 /*return*/ , {
  16673. asyncQueue: this.asyncQueue,
  16674. databaseInfo: this.databaseInfo,
  16675. clientId: this.clientId,
  16676. authCredentials: this.authCredentials,
  16677. appCheckCredentials: this.appCheckCredentials,
  16678. initialUser: this.user,
  16679. maxConcurrentLimboResolutions: 100
  16680. } ];
  16681. }));
  16682. }));
  16683. }, t.prototype.setCredentialChangeListener = function(t) {
  16684. this.authCredentialListener = t;
  16685. }, t.prototype.setAppCheckTokenChangeListener = function(t) {
  16686. this.appCheckCredentialListener = t;
  16687. },
  16688. /**
  16689. * Checks that the client has not been terminated. Ensures that other methods on //
  16690. * this class cannot be called after the client is terminated. //
  16691. */
  16692. t.prototype.verifyNotTerminated = function() {
  16693. if (this.asyncQueue.isShuttingDown) throw new Q(K.FAILED_PRECONDITION, "The client has already been terminated.");
  16694. }, t.prototype.terminate = function() {
  16695. var t = this;
  16696. this.asyncQueue.enterRestrictedMode();
  16697. var r = new W;
  16698. return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((function() {
  16699. return e(t, void 0, void 0, (function() {
  16700. var t, e;
  16701. return n(this, (function(n) {
  16702. switch (n.label) {
  16703. case 0:
  16704. return n.trys.push([ 0, 5, , 6 ]), this._onlineComponents ? [ 4 /*yield*/ , this._onlineComponents.terminate() ] : [ 3 /*break*/ , 2 ];
  16705. case 1:
  16706. n.sent(), n.label = 2;
  16707. case 2:
  16708. return this._offlineComponents ? [ 4 /*yield*/ , this._offlineComponents.terminate() ] : [ 3 /*break*/ , 4 ];
  16709. case 3:
  16710. n.sent(), n.label = 4;
  16711. case 4:
  16712. // The credentials provider must be terminated after shutting down the
  16713. // RemoteStore as it will prevent the RemoteStore from retrieving auth
  16714. // tokens.
  16715. return this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), r.resolve(),
  16716. [ 3 /*break*/ , 6 ];
  16717. case 5:
  16718. return t = n.sent(), e = ys(t, "Failed to shutdown persistence"), r.reject(e), [ 3 /*break*/ , 6 ];
  16719. case 6:
  16720. return [ 2 /*return*/ ];
  16721. }
  16722. }));
  16723. }));
  16724. })), r.promise;
  16725. }, t;
  16726. }();
  16727. /**
  16728. * @license
  16729. * Copyright 2020 Google LLC
  16730. *
  16731. * Licensed under the Apache License, Version 2.0 (the "License");
  16732. * you may not use this file except in compliance with the License.
  16733. * You may obtain a copy of the License at
  16734. *
  16735. * http://www.apache.org/licenses/LICENSE-2.0
  16736. *
  16737. * Unless required by applicable law or agreed to in writing, software
  16738. * distributed under the License is distributed on an "AS IS" BASIS,
  16739. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16740. * See the License for the specific language governing permissions and
  16741. * limitations under the License.
  16742. */
  16743. /**
  16744. * A class representing a bundle.
  16745. *
  16746. * Takes a bundle stream or buffer, and presents abstractions to read bundled
  16747. * elements out of the underlying content.
  16748. */ function xc(t, r) {
  16749. return e(this, void 0, void 0, (function() {
  16750. var i, o, u = this;
  16751. return n(this, (function(a) {
  16752. switch (a.label) {
  16753. case 0:
  16754. return t.asyncQueue.verifyOperationInProgress(), M("FirestoreClient", "Initializing OfflineComponentProvider"),
  16755. [ 4 /*yield*/ , t.getConfiguration() ];
  16756. case 1:
  16757. return i = a.sent(), [ 4 /*yield*/ , r.initialize(i) ];
  16758. case 2:
  16759. return a.sent(), o = i.initialUser, t.setCredentialChangeListener((function(t) {
  16760. return e(u, void 0, void 0, (function() {
  16761. return n(this, (function(e) {
  16762. switch (e.label) {
  16763. case 0:
  16764. return o.isEqual(t) ? [ 3 /*break*/ , 2 ] : [ 4 /*yield*/ , na(r.localStore, t) ];
  16765. case 1:
  16766. e.sent(), o = t, e.label = 2;
  16767. case 2:
  16768. return [ 2 /*return*/ ];
  16769. }
  16770. }));
  16771. }));
  16772. })),
  16773. // When a user calls clearPersistence() in one client, all other clients
  16774. // need to be terminated to allow the delete to succeed.
  16775. r.persistence.setDatabaseDeletedListener((function() {
  16776. return t.terminate();
  16777. })), t._offlineComponents = r, [ 2 /*return*/ ];
  16778. }
  16779. }));
  16780. }));
  16781. }
  16782. function Nc(t, r) {
  16783. return e(this, void 0, void 0, (function() {
  16784. var e, i;
  16785. return n(this, (function(n) {
  16786. switch (n.label) {
  16787. case 0:
  16788. return t.asyncQueue.verifyOperationInProgress(), [ 4 /*yield*/ , kc(t) ];
  16789. case 1:
  16790. return e = n.sent(), M("FirestoreClient", "Initializing OnlineComponentProvider"),
  16791. [ 4 /*yield*/ , t.getConfiguration() ];
  16792. case 2:
  16793. return i = n.sent(), [ 4 /*yield*/ , r.initialize(e, i) ];
  16794. case 3:
  16795. return n.sent(),
  16796. // The CredentialChangeListener of the online component provider takes
  16797. // precedence over the offline component provider.
  16798. t.setCredentialChangeListener((function(t) {
  16799. return fs(r.remoteStore, t);
  16800. })), t.setAppCheckTokenChangeListener((function(t, e) {
  16801. return fs(r.remoteStore, e);
  16802. })), t._onlineComponents = r, [ 2 /*return*/ ];
  16803. }
  16804. }));
  16805. }));
  16806. }
  16807. /**
  16808. * Decides whether the provided error allows us to gracefully disable
  16809. * persistence (as opposed to crashing the client).
  16810. */ function Ac(t) {
  16811. return "FirebaseError" === t.name ? t.code === K.FAILED_PRECONDITION || t.code === K.UNIMPLEMENTED : !("undefined" != typeof DOMException && t instanceof DOMException) ||
  16812. // When the browser is out of quota we could get either quota exceeded
  16813. // or an aborted error depending on whether the error happened during
  16814. // schema migration.
  16815. 22 === t.code || 20 === t.code ||
  16816. // Firefox Private Browsing mode disables IndexedDb and returns
  16817. // INVALID_STATE for any usage.
  16818. 11 === t.code;
  16819. }
  16820. function kc(t) {
  16821. return e(this, void 0, void 0, (function() {
  16822. var e, r;
  16823. return n(this, (function(n) {
  16824. switch (n.label) {
  16825. case 0:
  16826. if (t._offlineComponents) return [ 3 /*break*/ , 8 ];
  16827. if (!t._uninitializedComponentsProvider) return [ 3 /*break*/ , 6 ];
  16828. M("FirestoreClient", "Using user provided OfflineComponentProvider"), n.label = 1;
  16829. case 1:
  16830. return n.trys.push([ 1, 3, , 5 ]), [ 4 /*yield*/ , xc(t, t._uninitializedComponentsProvider._offline) ];
  16831. case 2:
  16832. return n.sent(), [ 3 /*break*/ , 5 ];
  16833. case 3:
  16834. if (e = n.sent(), !Ac(r = e)) throw r;
  16835. return q("Error using user provided cache. Falling back to memory cache: " + r),
  16836. [ 4 /*yield*/ , xc(t, new yc) ];
  16837. case 4:
  16838. return n.sent(), [ 3 /*break*/ , 5 ];
  16839. case 5:
  16840. return [ 3 /*break*/ , 8 ];
  16841. case 6:
  16842. return M("FirestoreClient", "Using default OfflineComponentProvider"), [ 4 /*yield*/ , xc(t, new yc) ];
  16843. case 7:
  16844. n.sent(), n.label = 8;
  16845. case 8:
  16846. return [ 2 /*return*/ , t._offlineComponents ];
  16847. }
  16848. }));
  16849. }));
  16850. }
  16851. function Oc(t) {
  16852. return e(this, void 0, void 0, (function() {
  16853. var e;
  16854. return n(this, (function(n) {
  16855. switch (n.label) {
  16856. case 0:
  16857. return t._onlineComponents ? [ 3 /*break*/ , 5 ] : t._uninitializedComponentsProvider ? (M("FirestoreClient", "Using user provided OnlineComponentProvider"),
  16858. [ 4 /*yield*/ , Nc(t, t._uninitializedComponentsProvider._online) ]) : [ 3 /*break*/ , 2 ];
  16859. case 1:
  16860. return e = n.sent(), [ 3 /*break*/ , 4 ];
  16861. case 2:
  16862. return M("FirestoreClient", "Using default OnlineComponentProvider"), [ 4 /*yield*/ , Nc(t, new Ic) ];
  16863. case 3:
  16864. e = n.sent(), n.label = 4;
  16865. case 4:
  16866. e, n.label = 5;
  16867. case 5:
  16868. return [ 2 /*return*/ , t._onlineComponents ];
  16869. }
  16870. }));
  16871. }));
  16872. }
  16873. function Fc(t) {
  16874. return kc(t).then((function(t) {
  16875. return t.persistence;
  16876. }));
  16877. }
  16878. function Pc(t) {
  16879. return kc(t).then((function(t) {
  16880. return t.localStore;
  16881. }));
  16882. }
  16883. function Rc(t) {
  16884. return Oc(t).then((function(t) {
  16885. return t.remoteStore;
  16886. }));
  16887. }
  16888. function Vc(t) {
  16889. return Oc(t).then((function(t) {
  16890. return t.syncEngine;
  16891. }));
  16892. }
  16893. function Mc(t) {
  16894. return Oc(t).then((function(t) {
  16895. return t.datastore;
  16896. }));
  16897. }
  16898. function Lc(t) {
  16899. return e(this, void 0, void 0, (function() {
  16900. var e, r;
  16901. return n(this, (function(n) {
  16902. switch (n.label) {
  16903. case 0:
  16904. return [ 4 /*yield*/ , Oc(t) ];
  16905. case 1:
  16906. return e = n.sent(), [ 2 /*return*/ , ((r = e.eventManager).onListen = qs.bind(null, e.syncEngine),
  16907. r.onUnlisten = Us.bind(null, e.syncEngine), r) ];
  16908. }
  16909. }));
  16910. }));
  16911. }
  16912. /** Enables the network connection and re-enqueues all pending operations. */ function qc(t, r, i) {
  16913. var o = this;
  16914. void 0 === i && (i = {});
  16915. var u = new W;
  16916. return t.asyncQueue.enqueueAndForget((function() {
  16917. return e(o, void 0, void 0, (function() {
  16918. var e;
  16919. return n(this, (function(n) {
  16920. switch (n.label) {
  16921. case 0:
  16922. return e = function(t, e, n, r, i) {
  16923. var o = new Tc({
  16924. next: function(o) {
  16925. // Remove query first before passing event to user to avoid
  16926. // user actions affecting the now stale query.
  16927. e.enqueueAndForget((function() {
  16928. return Ss(t, u);
  16929. }));
  16930. var a = o.docs.has(n);
  16931. !a && o.fromCache ?
  16932. // TODO(dimond): If we're online and the document doesn't
  16933. // exist then we resolve with a doc.exists set to false. If
  16934. // we're offline however, we reject the Promise in this
  16935. // case. Two options: 1) Cache the negative response from
  16936. // the server so we can deliver that even when you're
  16937. // offline 2) Actually reject the Promise in the online case
  16938. // if the document doesn't exist.
  16939. i.reject(new Q(K.UNAVAILABLE, "Failed to get document because the client is offline.")) : a && o.fromCache && r && "server" === r.source ? i.reject(new Q(K.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(o);
  16940. },
  16941. error: function(t) {
  16942. return i.reject(t);
  16943. }
  16944. }), u = new xs(Hn(n.path), o, {
  16945. includeMetadataChanges: !0,
  16946. Ku: !0
  16947. });
  16948. return Ts(t, u);
  16949. }, [ 4 /*yield*/ , Lc(t) ];
  16950. case 1:
  16951. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), t.asyncQueue, r, i, u ]) ];
  16952. }
  16953. }));
  16954. }));
  16955. })), u.promise;
  16956. }
  16957. function Bc(t, r, i) {
  16958. var o = this;
  16959. void 0 === i && (i = {});
  16960. var u = new W;
  16961. return t.asyncQueue.enqueueAndForget((function() {
  16962. return e(o, void 0, void 0, (function() {
  16963. var e;
  16964. return n(this, (function(n) {
  16965. switch (n.label) {
  16966. case 0:
  16967. return e = function(t, e, n, r, i) {
  16968. var o = new Tc({
  16969. next: function(n) {
  16970. // Remove query first before passing event to user to avoid
  16971. // user actions affecting the now stale query.
  16972. e.enqueueAndForget((function() {
  16973. return Ss(t, u);
  16974. })), n.fromCache && "server" === r.source ? i.reject(new Q(K.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);
  16975. },
  16976. error: function(t) {
  16977. return i.reject(t);
  16978. }
  16979. }), u = new xs(n, o, {
  16980. includeMetadataChanges: !0,
  16981. Ku: !0
  16982. });
  16983. return Ts(t, u);
  16984. }, [ 4 /*yield*/ , Lc(t) ];
  16985. case 1:
  16986. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), t.asyncQueue, r, i, u ]) ];
  16987. }
  16988. }));
  16989. }));
  16990. })), u.promise;
  16991. }
  16992. /**
  16993. * @license
  16994. * Copyright 2023 Google LLC
  16995. *
  16996. * Licensed under the Apache License, Version 2.0 (the "License");
  16997. * you may not use this file except in compliance with the License.
  16998. * You may obtain a copy of the License at
  16999. *
  17000. * http://www.apache.org/licenses/LICENSE-2.0
  17001. *
  17002. * Unless required by applicable law or agreed to in writing, software
  17003. * distributed under the License is distributed on an "AS IS" BASIS,
  17004. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17005. * See the License for the specific language governing permissions and
  17006. * limitations under the License.
  17007. */
  17008. /**
  17009. * Compares two `ExperimentalLongPollingOptions` objects for equality.
  17010. */
  17011. /**
  17012. * Creates and returns a new `ExperimentalLongPollingOptions` with the same
  17013. * option values as the given instance.
  17014. */
  17015. function Uc(t) {
  17016. var e = {};
  17017. return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e
  17018. /**
  17019. * @license
  17020. * Copyright 2020 Google LLC
  17021. *
  17022. * Licensed under the Apache License, Version 2.0 (the "License");
  17023. * you may not use this file except in compliance with the License.
  17024. * You may obtain a copy of the License at
  17025. *
  17026. * http://www.apache.org/licenses/LICENSE-2.0
  17027. *
  17028. * Unless required by applicable law or agreed to in writing, software
  17029. * distributed under the License is distributed on an "AS IS" BASIS,
  17030. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17031. * See the License for the specific language governing permissions and
  17032. * limitations under the License.
  17033. */;
  17034. }
  17035. var zc = new Map;
  17036. /**
  17037. * An instance map that ensures only one Datastore exists per Firestore
  17038. * instance.
  17039. */
  17040. /**
  17041. * @license
  17042. * Copyright 2017 Google LLC
  17043. *
  17044. * Licensed under the Apache License, Version 2.0 (the "License");
  17045. * you may not use this file except in compliance with the License.
  17046. * You may obtain a copy of the License at
  17047. *
  17048. * http://www.apache.org/licenses/LICENSE-2.0
  17049. *
  17050. * Unless required by applicable law or agreed to in writing, software
  17051. * distributed under the License is distributed on an "AS IS" BASIS,
  17052. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17053. * See the License for the specific language governing permissions and
  17054. * limitations under the License.
  17055. */ function Gc(t, e, n) {
  17056. if (!n) throw new Q(K.INVALID_ARGUMENT, "Function ".concat(t, "() cannot be called with an empty ").concat(e, "."));
  17057. }
  17058. /**
  17059. * Validates that two boolean options are not set at the same time.
  17060. * @internal
  17061. */ function jc(t, e, n, r) {
  17062. if (!0 === e && !0 === r) throw new Q(K.INVALID_ARGUMENT, "".concat(t, " and ").concat(n, " cannot be used together."));
  17063. }
  17064. /**
  17065. * Validates that `path` refers to a document (indicated by the fact it contains
  17066. * an even numbers of segments).
  17067. */ function Kc(t) {
  17068. if (!pt.isDocumentKey(t)) throw new Q(K.INVALID_ARGUMENT, "Invalid document reference. Document references must have an even number of segments, but ".concat(t, " has ").concat(t.length, "."));
  17069. }
  17070. /**
  17071. * Validates that `path` refers to a collection (indicated by the fact it
  17072. * contains an odd numbers of segments).
  17073. */ function Qc(t) {
  17074. if (pt.isDocumentKey(t)) throw new Q(K.INVALID_ARGUMENT, "Invalid collection reference. Collection references must have an odd number of segments, but ".concat(t, " has ").concat(t.length, "."));
  17075. }
  17076. /**
  17077. * Returns true if it's a non-null object without a custom prototype
  17078. * (i.e. excludes Array, Date, etc.).
  17079. */
  17080. /** Returns a string describing the type / value of the provided input. */ function Wc(t) {
  17081. if (void 0 === t) return "undefined";
  17082. if (null === t) return "null";
  17083. if ("string" == typeof t) return t.length > 20 && (t = "".concat(t.substring(0, 20), "...")),
  17084. JSON.stringify(t);
  17085. if ("number" == typeof t || "boolean" == typeof t) return "" + t;
  17086. if ("object" == typeof t) {
  17087. if (t instanceof Array) return "an array";
  17088. var e =
  17089. /** try to get the constructor name for an object. */
  17090. function(t) {
  17091. return t.constructor ? t.constructor.name : null;
  17092. }(t);
  17093. return e ? "a custom ".concat(e, " object") : "an object";
  17094. }
  17095. return "function" == typeof t ? "a function" : U();
  17096. }
  17097. function Hc(t,
  17098. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  17099. e) {
  17100. if ("_delegate" in t && (
  17101. // Unwrap Compat types
  17102. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  17103. t = t._delegate), !(t instanceof e)) {
  17104. if (e.name === t.constructor.name) throw new Q(K.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
  17105. var n = Wc(t);
  17106. throw new Q(K.INVALID_ARGUMENT, "Expected type '".concat(e.name, "', but it was: ").concat(n));
  17107. }
  17108. return t;
  17109. }
  17110. function Yc(t, e) {
  17111. if (e <= 0) throw new Q(K.INVALID_ARGUMENT, "Function ".concat(t, "() requires a positive number, but it was: ").concat(e, "."));
  17112. }
  17113. /**
  17114. * @license
  17115. * Copyright 2020 Google LLC
  17116. *
  17117. * Licensed under the Apache License, Version 2.0 (the "License");
  17118. * you may not use this file except in compliance with the License.
  17119. * You may obtain a copy of the License at
  17120. *
  17121. * http://www.apache.org/licenses/LICENSE-2.0
  17122. *
  17123. * Unless required by applicable law or agreed to in writing, software
  17124. * distributed under the License is distributed on an "AS IS" BASIS,
  17125. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17126. * See the License for the specific language governing permissions and
  17127. * limitations under the License.
  17128. */
  17129. // settings() defaults:
  17130. /**
  17131. * A concrete type describing all the values that can be applied via a
  17132. * user-supplied `FirestoreSettings` object. This is a separate type so that
  17133. * defaults can be supplied and the value can be checked for equality.
  17134. */ var Xc = /** @class */ function() {
  17135. function t(t) {
  17136. var e, n;
  17137. if (void 0 === t.host) {
  17138. if (void 0 !== t.ssl) throw new Q(K.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
  17139. this.host = "firestore.googleapis.com", this.ssl = !0;
  17140. } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;
  17141. if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties,
  17142. this.cache = t.localCache, void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {
  17143. if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new Q(K.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  17144. this.cacheSizeBytes = t.cacheSizeBytes;
  17145. }
  17146. jc("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling),
  17147. this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = !0 :
  17148. // For backwards compatibility, coerce the value to boolean even though
  17149. // the TypeScript compiler has narrowed the type to boolean already.
  17150. // noinspection PointlessBooleanExpressionJS
  17151. this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling,
  17152. this.experimentalLongPollingOptions = Uc(null !== (n = t.experimentalLongPollingOptions) && void 0 !== n ? n : {}),
  17153. function(t) {
  17154. if (void 0 !== t.timeoutSeconds) {
  17155. if (isNaN(t.timeoutSeconds)) throw new Q(K.INVALID_ARGUMENT, "invalid long polling timeout: ".concat(t.timeoutSeconds, " (must not be NaN)"));
  17156. if (t.timeoutSeconds < 5) throw new Q(K.INVALID_ARGUMENT, "invalid long polling timeout: ".concat(t.timeoutSeconds, " (minimum allowed value is 5)"));
  17157. if (t.timeoutSeconds > 30) throw new Q(K.INVALID_ARGUMENT, "invalid long polling timeout: ".concat(t.timeoutSeconds, " (maximum allowed value is 30)"));
  17158. }
  17159. }(this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams;
  17160. }
  17161. return t.prototype.isEqual = function(t) {
  17162. 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,
  17163. n = t.experimentalLongPollingOptions, e.timeoutSeconds === n.timeoutSeconds) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;
  17164. var e, n;
  17165. }, t;
  17166. }(), Jc = /** @class */ function() {
  17167. /** @hideconstructor */
  17168. function t(t, e, n, r) {
  17169. this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n,
  17170. this._app = r,
  17171. /**
  17172. * Whether it's a Firestore or Firestore Lite instance.
  17173. */
  17174. this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new Xc({}),
  17175. this._settingsFrozen = !1;
  17176. }
  17177. return Object.defineProperty(t.prototype, "app", {
  17178. /**
  17179. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  17180. * instance.
  17181. */
  17182. get: function() {
  17183. if (!this._app) throw new Q(K.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
  17184. return this._app;
  17185. },
  17186. enumerable: !1,
  17187. configurable: !0
  17188. }), Object.defineProperty(t.prototype, "_initialized", {
  17189. get: function() {
  17190. return this._settingsFrozen;
  17191. },
  17192. enumerable: !1,
  17193. configurable: !0
  17194. }), Object.defineProperty(t.prototype, "_terminated", {
  17195. get: function() {
  17196. return void 0 !== this._terminateTask;
  17197. },
  17198. enumerable: !1,
  17199. configurable: !0
  17200. }), t.prototype._setSettings = function(t) {
  17201. if (this._settingsFrozen) throw new Q(K.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.");
  17202. this._settings = new Xc(t), void 0 !== t.credentials && (this._authCredentials = function(t) {
  17203. if (!t) return new Y;
  17204. switch (t.type) {
  17205. case "firstParty":
  17206. return new $(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null);
  17207. case "provider":
  17208. return t.client;
  17209. default:
  17210. throw new Q(K.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type");
  17211. }
  17212. }(t.credentials));
  17213. }, t.prototype._getSettings = function() {
  17214. return this._settings;
  17215. }, t.prototype._freezeSettings = function() {
  17216. return this._settingsFrozen = !0, this._settings;
  17217. }, t.prototype._delete = function() {
  17218. return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;
  17219. },
  17220. /** Returns a JSON-serializable representation of this `Firestore` instance. */ t.prototype.toJSON = function() {
  17221. return {
  17222. app: this._app,
  17223. databaseId: this._databaseId,
  17224. settings: this._settings
  17225. };
  17226. },
  17227. /**
  17228. * Terminates all components used by this client. Subclasses can override
  17229. * this method to clean up their own dependencies, but must also call this
  17230. * method.
  17231. *
  17232. * Only ever called once.
  17233. */
  17234. t.prototype._terminate = function() {
  17235. /**
  17236. * Removes all components associated with the provided instance. Must be called
  17237. * when the `Firestore` instance is terminated.
  17238. */
  17239. return t = this, (e = zc.get(t)) && (M("ComponentProvider", "Removing Datastore"),
  17240. zc.delete(t), e.terminate()), Promise.resolve();
  17241. var t, e;
  17242. }, t;
  17243. }();
  17244. /**
  17245. * Modify this instance to communicate with the Cloud Firestore emulator.
  17246. *
  17247. * Note: This must be called before this instance has been used to do any
  17248. * operations.
  17249. *
  17250. * @param firestore - The `Firestore` instance to configure to connect to the
  17251. * emulator.
  17252. * @param host - the emulator host (ex: localhost).
  17253. * @param port - the emulator port (ex: 9000).
  17254. * @param options.mockUserToken - the mock auth token to use for unit testing
  17255. * Security Rules.
  17256. */
  17257. function Zc(t, e, n, r) {
  17258. var i;
  17259. void 0 === r && (r = {});
  17260. var o = (t = Hc(t, Jc))._getSettings(), u = "".concat(e, ":").concat(n);
  17261. if ("firestore.googleapis.com" !== o.host && o.host !== u && q("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),
  17262. t._setSettings(Object.assign(Object.assign({}, o), {
  17263. host: u,
  17264. ssl: !1
  17265. })), r.mockUserToken) {
  17266. var a, s;
  17267. if ("string" == typeof r.mockUserToken) a = r.mockUserToken, s = O.MOCK_USER; else {
  17268. // Let createMockUserToken validate first (catches common mistakes like
  17269. // invalid field "uid" and missing field "sub" / "user_id".)
  17270. a = y(r.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId);
  17271. var c = r.mockUserToken.sub || r.mockUserToken.user_id;
  17272. if (!c) throw new Q(K.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
  17273. s = new O(c);
  17274. }
  17275. t._authCredentials = new X(new H(a, s));
  17276. }
  17277. }
  17278. /**
  17279. * @license
  17280. * Copyright 2020 Google LLC
  17281. *
  17282. * Licensed under the Apache License, Version 2.0 (the "License");
  17283. * you may not use this file except in compliance with the License.
  17284. * You may obtain a copy of the License at
  17285. *
  17286. * http://www.apache.org/licenses/LICENSE-2.0
  17287. *
  17288. * Unless required by applicable law or agreed to in writing, software
  17289. * distributed under the License is distributed on an "AS IS" BASIS,
  17290. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17291. * See the License for the specific language governing permissions and
  17292. * limitations under the License.
  17293. */
  17294. /**
  17295. * A `DocumentReference` refers to a document location in a Firestore database
  17296. * and can be used to write, read, or listen to the location. The document at
  17297. * the referenced location may or may not exist.
  17298. */ var $c = /** @class */ function() {
  17299. /** @hideconstructor */
  17300. function t(t,
  17301. /**
  17302. * If provided, the `FirestoreDataConverter` associated with this instance.
  17303. */
  17304. e, n) {
  17305. this.converter = e, this._key = n,
  17306. /** The type of this Firestore reference. */
  17307. this.type = "document", this.firestore = t;
  17308. }
  17309. return Object.defineProperty(t.prototype, "_path", {
  17310. get: function() {
  17311. return this._key.path;
  17312. },
  17313. enumerable: !1,
  17314. configurable: !0
  17315. }), Object.defineProperty(t.prototype, "id", {
  17316. /**
  17317. * The document's identifier within its collection.
  17318. */
  17319. get: function() {
  17320. return this._key.path.lastSegment();
  17321. },
  17322. enumerable: !1,
  17323. configurable: !0
  17324. }), Object.defineProperty(t.prototype, "path", {
  17325. /**
  17326. * A string representing the path of the referenced document (relative
  17327. * to the root of the database).
  17328. */
  17329. get: function() {
  17330. return this._key.path.canonicalString();
  17331. },
  17332. enumerable: !1,
  17333. configurable: !0
  17334. }), Object.defineProperty(t.prototype, "parent", {
  17335. /**
  17336. * The collection this `DocumentReference` belongs to.
  17337. */
  17338. get: function() {
  17339. return new el(this.firestore, this.converter, this._key.path.popLast());
  17340. },
  17341. enumerable: !1,
  17342. configurable: !0
  17343. }), t.prototype.withConverter = function(e) {
  17344. return new t(this.firestore, e, this._key);
  17345. }, t;
  17346. }(), tl = /** @class */ function() {
  17347. // This is the lite version of the Query class in the main SDK.
  17348. /** @hideconstructor protected */
  17349. function t(t,
  17350. /**
  17351. * If provided, the `FirestoreDataConverter` associated with this instance.
  17352. */
  17353. e, n) {
  17354. this.converter = e, this._query = n,
  17355. /** The type of this Firestore reference. */
  17356. this.type = "query", this.firestore = t;
  17357. }
  17358. return t.prototype.withConverter = function(e) {
  17359. return new t(this.firestore, e, this._query);
  17360. }, t;
  17361. }(), el = /** @class */ function(e) {
  17362. /** @hideconstructor */
  17363. function n(t, n, r) {
  17364. var i = this;
  17365. return (i = e.call(this, t, n, Hn(r)) || this)._path = r,
  17366. /** The type of this Firestore reference. */
  17367. i.type = "collection", i;
  17368. }
  17369. return t(n, e), Object.defineProperty(n.prototype, "id", {
  17370. /** The collection's identifier. */ get: function() {
  17371. return this._query.path.lastSegment();
  17372. },
  17373. enumerable: !1,
  17374. configurable: !0
  17375. }), Object.defineProperty(n.prototype, "path", {
  17376. /**
  17377. * A string representing the path of the referenced collection (relative
  17378. * to the root of the database).
  17379. */
  17380. get: function() {
  17381. return this._query.path.canonicalString();
  17382. },
  17383. enumerable: !1,
  17384. configurable: !0
  17385. }), Object.defineProperty(n.prototype, "parent", {
  17386. /**
  17387. * A reference to the containing `DocumentReference` if this is a
  17388. * subcollection. If this isn't a subcollection, the reference is null.
  17389. */
  17390. get: function() {
  17391. var t = this._path.popLast();
  17392. return t.isEmpty() ? null : new $c(this.firestore,
  17393. /* converter= */ null, new pt(t));
  17394. },
  17395. enumerable: !1,
  17396. configurable: !0
  17397. }), n.prototype.withConverter = function(t) {
  17398. return new n(this.firestore, t, this._path);
  17399. }, n;
  17400. }(tl);
  17401. /**
  17402. * A `Query` refers to a query which you can read or listen to. You can also
  17403. * construct refined `Query` objects by adding filters and ordering.
  17404. */ function nl(t, e) {
  17405. for (var n = [], i = 2; i < arguments.length; i++) n[i - 2] = arguments[i];
  17406. if (t = v(t), Gc("collection", "path", e), t instanceof Jc) {
  17407. var o = ht.fromString.apply(ht, r([ e ], n, !1));
  17408. return Qc(o), new el(t, /* converter= */ null, o);
  17409. }
  17410. if (!(t instanceof $c || t instanceof el)) throw new Q(K.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  17411. var u = t._path.child(ht.fromString.apply(ht, r([ e ], n, !1)));
  17412. return Qc(u), new el(t.firestore,
  17413. /* converter= */ null, u);
  17414. }
  17415. // TODO(firestorelite): Consider using ErrorFactory -
  17416. // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
  17417. /**
  17418. * Creates and returns a new `Query` instance that includes all documents in the
  17419. * database that are contained in a collection or subcollection with the
  17420. * given `collectionId`.
  17421. *
  17422. * @param firestore - A reference to the root `Firestore` instance.
  17423. * @param collectionId - Identifies the collections to query over. Every
  17424. * collection or subcollection with this ID as the last segment of its path
  17425. * will be included. Cannot contain a slash.
  17426. * @returns The created `Query`.
  17427. */ function rl(t, e) {
  17428. if (t = Hc(t, Jc), Gc("collectionGroup", "collection id", e), e.indexOf("/") >= 0) throw new Q(K.INVALID_ARGUMENT, "Invalid collection ID '".concat(e, "' passed to function collectionGroup(). Collection IDs must not contain '/'."));
  17429. return new tl(t,
  17430. /* converter= */ null, function(t) {
  17431. return new Qn(ht.emptyPath(), t);
  17432. }(e));
  17433. }
  17434. function il(t, e) {
  17435. for (var n = [], i = 2; i < arguments.length; i++) n[i - 2] = arguments[i];
  17436. if (t = v(t),
  17437. // We allow omission of 'pathString' but explicitly prohibit passing in both
  17438. // 'undefined' and 'null'.
  17439. 1 === arguments.length && (e = it.A()), Gc("doc", "path", e), t instanceof Jc) {
  17440. var o = ht.fromString.apply(ht, r([ e ], n, !1));
  17441. return Kc(o), new $c(t,
  17442. /* converter= */ null, new pt(o));
  17443. }
  17444. if (!(t instanceof $c || t instanceof el)) throw new Q(K.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  17445. var u = t._path.child(ht.fromString.apply(ht, r([ e ], n, !1)));
  17446. return Kc(u), new $c(t.firestore, t instanceof el ? t.converter : null, new pt(u));
  17447. }
  17448. /**
  17449. * Returns true if the provided references are equal.
  17450. *
  17451. * @param left - A reference to compare.
  17452. * @param right - A reference to compare.
  17453. * @returns true if the references point to the same location in the same
  17454. * Firestore database.
  17455. */ function ol(t, e) {
  17456. return t = v(t), e = v(e), (t instanceof $c || t instanceof el) && (e instanceof $c || e instanceof el) && t.firestore === e.firestore && t.path === e.path && t.converter === e.converter
  17457. /**
  17458. * Returns true if the provided queries point to the same collection and apply
  17459. * the same constraints.
  17460. *
  17461. * @param left - A `Query` to compare.
  17462. * @param right - A `Query` to compare.
  17463. * @returns true if the references point to the same location in the same
  17464. * Firestore database.
  17465. */;
  17466. }
  17467. function ul(t, e) {
  17468. return t = v(t), e = v(e), t instanceof tl && e instanceof tl && t.firestore === e.firestore && rr(t._query, e._query) && t.converter === e.converter
  17469. /**
  17470. * @license
  17471. * Copyright 2020 Google LLC
  17472. *
  17473. * Licensed under the Apache License, Version 2.0 (the "License");
  17474. * you may not use this file except in compliance with the License.
  17475. * You may obtain a copy of the License at
  17476. *
  17477. * http://www.apache.org/licenses/LICENSE-2.0
  17478. *
  17479. * Unless required by applicable law or agreed to in writing, software
  17480. * distributed under the License is distributed on an "AS IS" BASIS,
  17481. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17482. * See the License for the specific language governing permissions and
  17483. * limitations under the License.
  17484. */;
  17485. }
  17486. var al = /** @class */ function() {
  17487. function t() {
  17488. var t = this;
  17489. // The last promise in the queue.
  17490. this.Gc = Promise.resolve(),
  17491. // A list of retryable operations. Retryable operations are run in order and
  17492. // retried with backoff.
  17493. this.Qc = [],
  17494. // Is this AsyncQueue being shut down? Once it is set to true, it will not
  17495. // be changed again.
  17496. this.jc = !1,
  17497. // Operations scheduled to be queued in the future. Operations are
  17498. // automatically removed after they are run or canceled.
  17499. this.zc = [],
  17500. // visible for testing
  17501. this.Wc = null,
  17502. // Flag set while there's an outstanding AsyncQueue operation, used for
  17503. // assertion sanity-checks.
  17504. this.Hc = !1,
  17505. // Enabled during shutdown on Safari to prevent future access to IndexedDB.
  17506. this.Jc = !1,
  17507. // List of TimerIds to fast-forward delays for.
  17508. this.Yc = [],
  17509. // Backoff timer used to schedule retries for retryable operations
  17510. this.qo = new Ma(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */),
  17511. // Visibility handler that triggers an immediate retry of all retryable
  17512. // operations. Meant to speed up recovery when we regain file system access
  17513. // after page comes into foreground.
  17514. this.Xc = function() {
  17515. var e = Ra();
  17516. e && M("AsyncQueue", "Visibility state changed to " + e.visibilityState), t.qo.Mo();
  17517. };
  17518. var e = Ra();
  17519. e && "function" == typeof e.addEventListener && e.addEventListener("visibilitychange", this.Xc);
  17520. }
  17521. return Object.defineProperty(t.prototype, "isShuttingDown", {
  17522. get: function() {
  17523. return this.jc;
  17524. },
  17525. enumerable: !1,
  17526. configurable: !0
  17527. }),
  17528. /**
  17529. * Adds a new operation to the queue without waiting for it to complete (i.e.
  17530. * we ignore the Promise result).
  17531. */
  17532. t.prototype.enqueueAndForget = function(t) {
  17533. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  17534. this.enqueue(t);
  17535. }, t.prototype.enqueueAndForgetEvenWhileRestricted = function(t) {
  17536. this.Zc(),
  17537. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  17538. this.ta(t);
  17539. }, t.prototype.enterRestrictedMode = function(t) {
  17540. if (!this.jc) {
  17541. this.jc = !0, this.Jc = t || !1;
  17542. var e = Ra();
  17543. e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Xc);
  17544. }
  17545. }, t.prototype.enqueue = function(t) {
  17546. var e = this;
  17547. if (this.Zc(), this.jc)
  17548. // Return a Promise which never resolves.
  17549. return new Promise((function() {}));
  17550. // Create a deferred Promise that we can return to the callee. This
  17551. // allows us to return a "hanging Promise" only to the callee and still
  17552. // advance the queue even when the operation is not run.
  17553. var n = new W;
  17554. return this.ta((function() {
  17555. return e.jc && e.Jc ? Promise.resolve() : (t().then(n.resolve, n.reject), n.promise);
  17556. })).then((function() {
  17557. return n.promise;
  17558. }));
  17559. }, t.prototype.enqueueRetryable = function(t) {
  17560. var e = this;
  17561. this.enqueueAndForget((function() {
  17562. return e.Qc.push(t), e.ea();
  17563. }));
  17564. },
  17565. /**
  17566. * Runs the next operation from the retryable queue. If the operation fails,
  17567. * reschedules with backoff.
  17568. */
  17569. t.prototype.ea = function() {
  17570. return e(this, void 0, void 0, (function() {
  17571. var t, e = this;
  17572. return n(this, (function(n) {
  17573. switch (n.label) {
  17574. case 0:
  17575. if (0 === this.Qc.length) return [ 3 /*break*/ , 5 ];
  17576. n.label = 1;
  17577. case 1:
  17578. return n.trys.push([ 1, 3, , 4 ]), [ 4 /*yield*/ , this.Qc[0]() ];
  17579. case 2:
  17580. return n.sent(), this.Qc.shift(), this.qo.reset(), [ 3 /*break*/ , 4 ];
  17581. case 3:
  17582. if (!Pt(t = n.sent())) throw t;
  17583. // Failure will be handled by AsyncQueue
  17584. return M("AsyncQueue", "Operation failed with retryable error: " + t),
  17585. [ 3 /*break*/ , 4 ];
  17586. case 4:
  17587. this.Qc.length > 0 &&
  17588. // If there are additional operations, we re-schedule `retryNextOp()`.
  17589. // This is necessary to run retryable operations that failed during
  17590. // their initial attempt since we don't know whether they are already
  17591. // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
  17592. // needs to be re-run, we will run `op1`, `op1`, `op2` using the
  17593. // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
  17594. // call scheduled here.
  17595. // Since `backoffAndRun()` cancels an existing backoff and schedules a
  17596. // new backoff on every call, there is only ever a single additional
  17597. // operation in the queue.
  17598. this.qo.No((function() {
  17599. return e.ea();
  17600. })), n.label = 5;
  17601. case 5:
  17602. return [ 2 /*return*/ ];
  17603. }
  17604. }));
  17605. }));
  17606. }, t.prototype.ta = function(t) {
  17607. var e = this, n = this.Gc.then((function() {
  17608. return e.Hc = !0, t().catch((function(t) {
  17609. e.Wc = t, e.Hc = !1;
  17610. var n =
  17611. /**
  17612. * Chrome includes Error.message in Error.stack. Other browsers do not.
  17613. * This returns expected output of message + stack when available.
  17614. * @param error - Error or FirestoreError
  17615. */
  17616. function(t) {
  17617. var e = t.message || "";
  17618. return t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack),
  17619. e;
  17620. }(t);
  17621. // Re-throw the error so that this.tail becomes a rejected Promise and
  17622. // all further attempts to chain (via .then) will just short-circuit
  17623. // and return the rejected Promise.
  17624. throw L("INTERNAL UNHANDLED ERROR: ", n), t;
  17625. })).then((function(t) {
  17626. return e.Hc = !1, t;
  17627. }));
  17628. }));
  17629. return this.Gc = n, n;
  17630. }, t.prototype.enqueueAfterDelay = function(t, e, n) {
  17631. var r = this;
  17632. this.Zc(),
  17633. // Fast-forward delays for timerIds that have been overriden.
  17634. this.Yc.indexOf(t) > -1 && (e = 0);
  17635. var i = ms.createAndSchedule(this, t, e, n, (function(t) {
  17636. return r.na(t);
  17637. }));
  17638. return this.zc.push(i), i;
  17639. }, t.prototype.Zc = function() {
  17640. this.Wc && U();
  17641. }, t.prototype.verifyOperationInProgress = function() {},
  17642. /**
  17643. * Waits until all currently queued tasks are finished executing. Delayed
  17644. * operations are not run.
  17645. */
  17646. t.prototype.sa = function() {
  17647. return e(this, void 0, void 0, (function() {
  17648. var t;
  17649. return n(this, (function(e) {
  17650. switch (e.label) {
  17651. case 0:
  17652. return [ 4 /*yield*/ , t = this.Gc ];
  17653. case 1:
  17654. e.sent(), e.label = 2;
  17655. case 2:
  17656. if (t !== this.Gc) return [ 3 /*break*/ , 0 ];
  17657. e.label = 3;
  17658. case 3:
  17659. return [ 2 /*return*/ ];
  17660. }
  17661. }));
  17662. }));
  17663. },
  17664. /**
  17665. * For Tests: Determine if a delayed operation with a particular TimerId
  17666. * exists.
  17667. */
  17668. t.prototype.ia = function(t) {
  17669. for (var e = 0, n = this.zc; e < n.length; e++) {
  17670. if (n[e].timerId === t) return !0;
  17671. }
  17672. return !1;
  17673. },
  17674. /**
  17675. * For Tests: Runs some or all delayed operations early.
  17676. *
  17677. * @param lastTimerId - Delayed operations up to and including this TimerId
  17678. * will be drained. Pass TimerId.All to run all delayed operations.
  17679. * @returns a Promise that resolves once all operations have been run.
  17680. */
  17681. t.prototype.ra = function(t) {
  17682. var e = this;
  17683. // Note that draining may generate more delayed ops, so we do that first.
  17684. return this.sa().then((function() {
  17685. // Run ops in the same order they'd run if they ran naturally.
  17686. e.zc.sort((function(t, e) {
  17687. return t.targetTimeMs - e.targetTimeMs;
  17688. }));
  17689. for (var n = 0, r = e.zc; n < r.length; n++) {
  17690. var i = r[n];
  17691. if (i.skipDelay(), "all" /* TimerId.All */ !== t && i.timerId === t) break;
  17692. }
  17693. return e.sa();
  17694. }));
  17695. },
  17696. /**
  17697. * For Tests: Skip all subsequent delays for a timer id.
  17698. */
  17699. t.prototype.oa = function(t) {
  17700. this.Yc.push(t);
  17701. },
  17702. /** Called once a DelayedOperation is run or canceled. */ t.prototype.na = function(t) {
  17703. // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
  17704. var e = this.zc.indexOf(t);
  17705. this.zc.splice(e, 1);
  17706. }, t;
  17707. }();
  17708. function sl(t) {
  17709. /**
  17710. * Returns true if obj is an object and contains at least one of the specified
  17711. * methods.
  17712. */
  17713. return function(t, e) {
  17714. if ("object" != typeof t || null === t) return !1;
  17715. for (var n = t, r = 0, i = [ "next", "error", "complete" ]; r < i.length; r++) {
  17716. var o = i[r];
  17717. if (o in n && "function" == typeof n[o]) return !0;
  17718. }
  17719. return !1;
  17720. }(t);
  17721. }
  17722. var cl = /** @class */ function() {
  17723. function t() {
  17724. this._progressObserver = {}, this._taskCompletionResolver = new W, this._lastProgress = {
  17725. taskState: "Running",
  17726. totalBytes: 0,
  17727. totalDocuments: 0,
  17728. bytesLoaded: 0,
  17729. documentsLoaded: 0
  17730. }
  17731. /**
  17732. * Registers functions to listen to bundle loading progress events.
  17733. * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
  17734. * each time a Firestore document is loaded from the bundle.
  17735. * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
  17736. * error, and there should be no more updates after this.
  17737. * @param complete - Called when the loading task is complete.
  17738. */;
  17739. }
  17740. return t.prototype.onProgress = function(t, e, n) {
  17741. this._progressObserver = {
  17742. next: t,
  17743. error: e,
  17744. complete: n
  17745. };
  17746. },
  17747. /**
  17748. * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
  17749. *
  17750. * @param onRejected - Called when an error occurs during bundle loading.
  17751. */
  17752. t.prototype.catch = function(t) {
  17753. return this._taskCompletionResolver.promise.catch(t);
  17754. },
  17755. /**
  17756. * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
  17757. *
  17758. * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
  17759. * The update will always have its `taskState` set to `"Success"`.
  17760. * @param onRejected - Called when an error occurs during bundle loading.
  17761. */
  17762. t.prototype.then = function(t, e) {
  17763. return this._taskCompletionResolver.promise.then(t, e);
  17764. },
  17765. /**
  17766. * Notifies all observers that bundle loading has completed, with a provided
  17767. * `LoadBundleTaskProgress` object.
  17768. *
  17769. * @private
  17770. */
  17771. t.prototype._completeWith = function(t) {
  17772. this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(),
  17773. this._taskCompletionResolver.resolve(t);
  17774. },
  17775. /**
  17776. * Notifies all observers that bundle loading has failed, with a provided
  17777. * `Error` as the reason.
  17778. *
  17779. * @private
  17780. */
  17781. t.prototype._failWith = function(t) {
  17782. this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress),
  17783. this._progressObserver.error && this._progressObserver.error(t), this._taskCompletionResolver.reject(t);
  17784. },
  17785. /**
  17786. * Notifies a progress update of loading a bundle.
  17787. * @param progress - The new progress.
  17788. *
  17789. * @private
  17790. */
  17791. t.prototype._updateProgress = function(t) {
  17792. this._lastProgress = t, this._progressObserver.next && this._progressObserver.next(t);
  17793. }, t;
  17794. }(), ll = -1, hl = /** @class */ function(e) {
  17795. /** @hideconstructor */
  17796. function n(t, n, r, i) {
  17797. var o = this;
  17798. /**
  17799. * Whether it's a {@link Firestore} or Firestore Lite instance.
  17800. */
  17801. return (o = e.call(this, t, n, r, i) || this).type = "firestore", o._queue = new al,
  17802. o._persistenceKey = (null == i ? void 0 : i.name) || "[DEFAULT]", o;
  17803. }
  17804. return t(n, e), n.prototype._terminate = function() {
  17805. return this._firestoreClient ||
  17806. // The client must be initialized to ensure that all subsequent API
  17807. // usage throws an exception.
  17808. vl(this), this._firestoreClient.terminate();
  17809. }, n;
  17810. }(Jc);
  17811. /**
  17812. * @license
  17813. * Copyright 2020 Google LLC
  17814. *
  17815. * Licensed under the Apache License, Version 2.0 (the "License");
  17816. * you may not use this file except in compliance with the License.
  17817. * You may obtain a copy of the License at
  17818. *
  17819. * http://www.apache.org/licenses/LICENSE-2.0
  17820. *
  17821. * Unless required by applicable law or agreed to in writing, software
  17822. * distributed under the License is distributed on an "AS IS" BASIS,
  17823. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17824. * See the License for the specific language governing permissions and
  17825. * limitations under the License.
  17826. */
  17827. /**
  17828. * Constant used to indicate the LRU garbage collection should be disabled.
  17829. * Set this value as the `cacheSizeBytes` on the settings passed to the
  17830. * {@link Firestore} instance.
  17831. */
  17832. /**
  17833. * Initializes a new instance of {@link Firestore} with the provided settings.
  17834. * Can only be called before any other function, including
  17835. * {@link (getFirestore:1)}. If the custom settings are empty, this function is
  17836. * equivalent to calling {@link (getFirestore:1)}.
  17837. *
  17838. * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
  17839. * be associated.
  17840. * @param settings - A settings object to configure the {@link Firestore} instance.
  17841. * @param databaseId - The name of the database.
  17842. * @returns A newly initialized {@link Firestore} instance.
  17843. */
  17844. function fl(t, e, n) {
  17845. n || (n = "(default)");
  17846. var r = _getProvider(t, "firestore");
  17847. if (r.isInitialized(n)) {
  17848. var i = r.getImmediate({
  17849. identifier: n
  17850. }), o = r.getOptions(n);
  17851. if (g(o, e)) return i;
  17852. throw new Q(K.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.");
  17853. }
  17854. if (void 0 !== e.cacheSizeBytes && void 0 !== e.localCache) throw new Q(K.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");
  17855. if (void 0 !== e.cacheSizeBytes && -1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new Q(K.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  17856. return r.initialize({
  17857. options: e,
  17858. instanceIdentifier: n
  17859. });
  17860. }
  17861. function dl(t, e) {
  17862. var n = "object" == typeof t ? t : a(), i = "string" == typeof t ? t : e || "(default)", o = _getProvider(n, "firestore").getImmediate({
  17863. identifier: i
  17864. });
  17865. if (!o._initialized) {
  17866. var u = w("firestore");
  17867. u && Zc.apply(void 0, r([ o ], u, !1));
  17868. }
  17869. return o;
  17870. }
  17871. /**
  17872. * @internal
  17873. */ function pl(t) {
  17874. return t._firestoreClient || vl(t), t._firestoreClient.verifyNotTerminated(), t._firestoreClient;
  17875. }
  17876. function vl(t) {
  17877. var e, n, r, i = t._freezeSettings(), o = function(t, e, n, r) {
  17878. return new Be(t, e, n, r.host, r.ssl, r.experimentalForceLongPolling, r.experimentalAutoDetectLongPolling, Uc(r.experimentalLongPollingOptions), r.useFetchStreams);
  17879. }(t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || "", t._persistenceKey, i);
  17880. t._firestoreClient = new Cc(t._authCredentials, t._appCheckCredentials, t._queue, o),
  17881. (null === (n = i.cache) || void 0 === n ? void 0 : n._offlineComponentProvider) && (null === (r = i.cache) || void 0 === r ? void 0 : r._onlineComponentProvider) && (t._firestoreClient._uninitializedComponentsProvider = {
  17882. _offlineKind: i.cache.kind,
  17883. _offline: i.cache._offlineComponentProvider,
  17884. _online: i.cache._onlineComponentProvider
  17885. });
  17886. }
  17887. /**
  17888. * Attempts to enable persistent storage, if possible.
  17889. *
  17890. * Must be called before any other functions (other than
  17891. * {@link initializeFirestore}, {@link (getFirestore:1)} or
  17892. * {@link clearIndexedDbPersistence}.
  17893. *
  17894. * If this fails, `enableIndexedDbPersistence()` will reject the promise it
  17895. * returns. Note that even after this failure, the {@link Firestore} instance will
  17896. * remain usable, however offline persistence will be disabled.
  17897. *
  17898. * There are several reasons why this can fail, which can be identified by
  17899. * the `code` on the error.
  17900. *
  17901. * * failed-precondition: The app is already open in another browser tab.
  17902. * * unimplemented: The browser is incompatible with the offline
  17903. * persistence implementation.
  17904. *
  17905. * Persistence cannot be used in a Node.js environment.
  17906. *
  17907. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17908. * @param persistenceSettings - Optional settings object to configure
  17909. * persistence.
  17910. * @returns A `Promise` that represents successfully enabling persistent storage.
  17911. * @deprecated This function will be removed in a future major release. Instead, set
  17912. * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to
  17913. * turn on IndexedDb cache. Calling this function when `FirestoreSettings.cache`
  17914. * is already specified will throw an exception.
  17915. */ function ml(t, e) {
  17916. Dl(t = Hc(t, hl));
  17917. var n = pl(t);
  17918. if (n._uninitializedComponentsProvider) throw new Q(K.FAILED_PRECONDITION, "SDK cache is already specified.");
  17919. q("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
  17920. var r = t._freezeSettings(), i = new Ic;
  17921. return gl(n, i, new wc(i, r.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));
  17922. }
  17923. /**
  17924. * Attempts to enable multi-tab persistent storage, if possible. If enabled
  17925. * across all tabs, all operations share access to local persistence, including
  17926. * shared execution of queries and latency-compensated local document updates
  17927. * across all connected instances.
  17928. *
  17929. * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
  17930. * it returns. Note that even after this failure, the {@link Firestore} instance will
  17931. * remain usable, however offline persistence will be disabled.
  17932. *
  17933. * There are several reasons why this can fail, which can be identified by
  17934. * the `code` on the error.
  17935. *
  17936. * * failed-precondition: The app is already open in another browser tab and
  17937. * multi-tab is not enabled.
  17938. * * unimplemented: The browser is incompatible with the offline
  17939. * persistence implementation.
  17940. *
  17941. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17942. * @returns A `Promise` that represents successfully enabling persistent
  17943. * storage.
  17944. * @deprecated This function will be removed in a future major release. Instead, set
  17945. * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to
  17946. * turn on indexeddb cache. Calling this function when `FirestoreSettings.cache`
  17947. * is already specified will throw an exception.
  17948. */ function yl(t) {
  17949. Dl(t = Hc(t, hl));
  17950. var e = pl(t);
  17951. if (e._uninitializedComponentsProvider) throw new Q(K.FAILED_PRECONDITION, "SDK cache is already specified.");
  17952. q("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
  17953. var n = t._freezeSettings(), r = new Ic;
  17954. return gl(e, r, new bc(r, n.cacheSizeBytes));
  17955. }
  17956. /**
  17957. * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.
  17958. * If the operation fails with a recoverable error (see
  17959. * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected
  17960. * but the client remains usable.
  17961. */ function gl(t, r, i) {
  17962. var o = this, u = new W;
  17963. return t.asyncQueue.enqueue((function() {
  17964. return e(o, void 0, void 0, (function() {
  17965. var e, o;
  17966. return n(this, (function(n) {
  17967. switch (n.label) {
  17968. case 0:
  17969. return n.trys.push([ 0, 3, , 4 ]), [ 4 /*yield*/ , xc(t, i) ];
  17970. case 1:
  17971. return n.sent(), [ 4 /*yield*/ , Nc(t, r) ];
  17972. case 2:
  17973. return n.sent(), u.resolve(), [ 3 /*break*/ , 4 ];
  17974. case 3:
  17975. if (e = n.sent(), !Ac(o = e)) throw o;
  17976. return q("Error enabling indexeddb cache. Falling back to memory cache: " + o),
  17977. u.reject(o), [ 3 /*break*/ , 4 ];
  17978. case 4:
  17979. return [ 2 /*return*/ ];
  17980. }
  17981. }));
  17982. }));
  17983. })).then((function() {
  17984. return u.promise;
  17985. }));
  17986. }
  17987. /**
  17988. * Clears the persistent storage. This includes pending writes and cached
  17989. * documents.
  17990. *
  17991. * Must be called while the {@link Firestore} instance is not started (after the app is
  17992. * terminated or when the app is first initialized). On startup, this function
  17993. * must be called before other functions (other than {@link
  17994. * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}
  17995. * instance is still running, the promise will be rejected with the error code
  17996. * of `failed-precondition`.
  17997. *
  17998. * Note: `clearIndexedDbPersistence()` is primarily intended to help write
  17999. * reliable tests that use Cloud Firestore. It uses an efficient mechanism for
  18000. * dropping existing data but does not attempt to securely overwrite or
  18001. * otherwise make cached data unrecoverable. For applications that are sensitive
  18002. * to the disclosure of cached data in between user sessions, we strongly
  18003. * recommend not enabling persistence at all.
  18004. *
  18005. * @param firestore - The {@link Firestore} instance to clear persistence for.
  18006. * @returns A `Promise` that is resolved when the persistent storage is
  18007. * cleared. Otherwise, the promise is rejected with an error.
  18008. */ function wl(t) {
  18009. var r = this;
  18010. if (t._initialized && !t._terminated) throw new Q(K.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");
  18011. var i = new W;
  18012. return t._queue.enqueueAndForgetEvenWhileRestricted((function() {
  18013. return e(r, void 0, void 0, (function() {
  18014. var r;
  18015. return n(this, (function(o) {
  18016. switch (o.label) {
  18017. case 0:
  18018. return o.trys.push([ 0, 2, , 3 ]), [ 4 /*yield*/ , function(t) {
  18019. return e(this, void 0, void 0, (function() {
  18020. var e;
  18021. return n(this, (function(n) {
  18022. switch (n.label) {
  18023. case 0:
  18024. return kt.D() ? (e = t + "main", [ 4 /*yield*/ , kt.delete(e) ]) : [ 2 /*return*/ , Promise.resolve() ];
  18025. case 1:
  18026. return n.sent(), [ 2 /*return*/ ];
  18027. }
  18028. }));
  18029. }));
  18030. }(Ju(t._databaseId, t._persistenceKey)) ];
  18031. case 1:
  18032. return o.sent(), i.resolve(), [ 3 /*break*/ , 3 ];
  18033. case 2:
  18034. return r = o.sent(), i.reject(r), [ 3 /*break*/ , 3 ];
  18035. case 3:
  18036. return [ 2 /*return*/ ];
  18037. }
  18038. }));
  18039. }));
  18040. })), i.promise
  18041. /**
  18042. * Waits until all currently pending writes for the active user have been
  18043. * acknowledged by the backend.
  18044. *
  18045. * The returned promise resolves immediately if there are no outstanding writes.
  18046. * Otherwise, the promise waits for all previously issued writes (including
  18047. * those written in a previous app session), but it does not wait for writes
  18048. * that were added after the function is called. If you want to wait for
  18049. * additional writes, call `waitForPendingWrites()` again.
  18050. *
  18051. * Any outstanding `waitForPendingWrites()` promises are rejected during user
  18052. * changes.
  18053. *
  18054. * @returns A `Promise` which resolves when all currently pending writes have been
  18055. * acknowledged by the backend.
  18056. */;
  18057. }
  18058. function bl(t) {
  18059. return function(t) {
  18060. var r = this, i = new W;
  18061. return t.asyncQueue.enqueueAndForget((function() {
  18062. return e(r, void 0, void 0, (function() {
  18063. var e;
  18064. return n(this, (function(n) {
  18065. switch (n.label) {
  18066. case 0:
  18067. return e = Hs, [ 4 /*yield*/ , Vc(t) ];
  18068. case 1:
  18069. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), i ]) ];
  18070. }
  18071. }));
  18072. }));
  18073. })), i.promise;
  18074. }(pl(t = Hc(t, hl)));
  18075. }
  18076. /**
  18077. * Re-enables use of the network for this {@link Firestore} instance after a prior
  18078. * call to {@link disableNetwork}.
  18079. *
  18080. * @returns A `Promise` that is resolved once the network has been enabled.
  18081. */ function Il(t) {
  18082. return function(t) {
  18083. var r = this;
  18084. return t.asyncQueue.enqueue((function() {
  18085. return e(r, void 0, void 0, (function() {
  18086. var e, r;
  18087. return n(this, (function(n) {
  18088. switch (n.label) {
  18089. case 0:
  18090. return [ 4 /*yield*/ , Fc(t) ];
  18091. case 1:
  18092. return e = n.sent(), [ 4 /*yield*/ , Rc(t) ];
  18093. case 2:
  18094. return r = n.sent(), [ 2 /*return*/ , (e.setNetworkEnabled(!0), function(t) {
  18095. var e = j(t);
  18096. return e.vu.delete(0 /* OfflineCause.UserDisabled */), ja(e);
  18097. }(r)) ];
  18098. }
  18099. }));
  18100. }));
  18101. }));
  18102. }
  18103. /** Disables the network connection. Pending operations will not complete. */ (pl(t = Hc(t, hl)));
  18104. }
  18105. /**
  18106. * Disables network usage for this instance. It can be re-enabled via {@link
  18107. * enableNetwork}. While the network is disabled, any snapshot listeners,
  18108. * `getDoc()` or `getDocs()` calls will return results from cache, and any write
  18109. * operations will be queued until the network is restored.
  18110. *
  18111. * @returns A `Promise` that is resolved once the network has been disabled.
  18112. */ function El(t) {
  18113. return function(t) {
  18114. var r = this;
  18115. return t.asyncQueue.enqueue((function() {
  18116. return e(r, void 0, void 0, (function() {
  18117. var r, i;
  18118. return n(this, (function(o) {
  18119. switch (o.label) {
  18120. case 0:
  18121. return [ 4 /*yield*/ , Fc(t) ];
  18122. case 1:
  18123. return r = o.sent(), [ 4 /*yield*/ , Rc(t) ];
  18124. case 2:
  18125. return i = o.sent(), [ 2 /*return*/ , (r.setNetworkEnabled(!1), function(t) {
  18126. return e(this, void 0, void 0, (function() {
  18127. var e;
  18128. return n(this, (function(n) {
  18129. switch (n.label) {
  18130. case 0:
  18131. return (e = j(t)).vu.add(0 /* OfflineCause.UserDisabled */), [ 4 /*yield*/ , Ka(e) ];
  18132. case 1:
  18133. return n.sent(),
  18134. // Set the OnlineState to Offline so get()s return from cache, etc.
  18135. e.bu.set("Offline" /* OnlineState.Offline */), [ 2 /*return*/ ];
  18136. }
  18137. }));
  18138. }));
  18139. }(i)) ];
  18140. }
  18141. }));
  18142. }));
  18143. }));
  18144. }
  18145. /**
  18146. * Returns a Promise that resolves when all writes that were pending at the time
  18147. * this method was called received server acknowledgement. An acknowledgement
  18148. * can be either acceptance or rejection.
  18149. */ (pl(t = Hc(t, hl)));
  18150. }
  18151. /**
  18152. * Terminates the provided {@link Firestore} instance.
  18153. *
  18154. * After calling `terminate()` only the `clearIndexedDbPersistence()` function
  18155. * may be used. Any other function will throw a `FirestoreError`.
  18156. *
  18157. * To restart after termination, create a new instance of FirebaseFirestore with
  18158. * {@link (getFirestore:1)}.
  18159. *
  18160. * Termination does not cancel any pending writes, and any promises that are
  18161. * awaiting a response from the server will not be resolved. If you have
  18162. * persistence enabled, the next time you start this instance, it will resume
  18163. * sending these writes to the server.
  18164. *
  18165. * Note: Under normal circumstances, calling `terminate()` is not required. This
  18166. * function is useful only when you want to force this instance to release all
  18167. * of its resources or in combination with `clearIndexedDbPersistence()` to
  18168. * ensure that all local state is destroyed between test runs.
  18169. *
  18170. * @returns A `Promise` that is resolved when the instance has been successfully
  18171. * terminated.
  18172. */ function Tl(t) {
  18173. return s(t.app, "firestore", t._databaseId.database), t._delete()
  18174. /**
  18175. * Loads a Firestore bundle into the local cache.
  18176. *
  18177. * @param firestore - The {@link Firestore} instance to load bundles for.
  18178. * @param bundleData - An object representing the bundle to be loaded. Valid
  18179. * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.
  18180. *
  18181. * @returns A `LoadBundleTask` object, which notifies callers with progress
  18182. * updates, and completion or error events. It can be used as a
  18183. * `Promise<LoadBundleTaskProgress>`.
  18184. */;
  18185. }
  18186. function Sl(t, r) {
  18187. var i = pl(t = Hc(t, hl)), o = new cl;
  18188. /**
  18189. * Takes an updateFunction in which a set of reads and writes can be performed
  18190. * atomically. In the updateFunction, the client can read and write values
  18191. * using the supplied transaction object. After the updateFunction, all
  18192. * changes will be committed. If a retryable error occurs (ex: some other
  18193. * client has changed any of the data referenced), then the updateFunction
  18194. * will be called again after a backoff. If the updateFunction still fails
  18195. * after all retries, then the transaction will be rejected.
  18196. *
  18197. * The transaction object passed to the updateFunction contains methods for
  18198. * accessing documents and collections. Unlike other datastore access, data
  18199. * accessed with the transaction will not reflect local changes that have not
  18200. * been committed. For this reason, it is required that all reads are
  18201. * performed before any writes. Transactions must be performed while online.
  18202. */
  18203. return function(t, r, i, o) {
  18204. var u = this, a = function(t, e) {
  18205. return function(t, e) {
  18206. return new Sc(t, e);
  18207. }(function(t, e) {
  18208. if (t instanceof Uint8Array) return Ec(t, e);
  18209. if (t instanceof ArrayBuffer) return Ec(new Uint8Array(t), e);
  18210. if (t instanceof ReadableStream) return t.getReader();
  18211. throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream");
  18212. }("string" == typeof t ? di().encode(t) : t), e);
  18213. }(i, Va(r));
  18214. t.asyncQueue.enqueueAndForget((function() {
  18215. return e(u, void 0, void 0, (function() {
  18216. var e;
  18217. return n(this, (function(n) {
  18218. switch (n.label) {
  18219. case 0:
  18220. return e = mc, [ 4 /*yield*/ , Vc(t) ];
  18221. case 1:
  18222. return e.apply(void 0, [ n.sent(), a, o ]), [ 2 /*return*/ ];
  18223. }
  18224. }));
  18225. }));
  18226. }));
  18227. }(i, t._databaseId, r, o), o
  18228. /**
  18229. * Reads a Firestore {@link Query} from local cache, identified by the given
  18230. * name.
  18231. *
  18232. * The named queries are packaged into bundles on the server side (along
  18233. * with resulting documents), and loaded to local cache using `loadBundle`. Once
  18234. * in local cache, use this method to extract a {@link Query} by name.
  18235. *
  18236. * @param firestore - The {@link Firestore} instance to read the query from.
  18237. * @param name - The name of the query.
  18238. * @returns A `Promise` that is resolved with the Query or `null`.
  18239. */;
  18240. }
  18241. function _l(t, r) {
  18242. return function(t, r) {
  18243. var i = this;
  18244. return t.asyncQueue.enqueue((function() {
  18245. return e(i, void 0, void 0, (function() {
  18246. var e;
  18247. return n(this, (function(n) {
  18248. switch (n.label) {
  18249. case 0:
  18250. return e = function(t, e) {
  18251. var n = j(t);
  18252. return n.persistence.runTransaction("Get named query", "readonly", (function(t) {
  18253. return n.qs.getNamedQuery(t, e);
  18254. }));
  18255. }, [ 4 /*yield*/ , Pc(t) ];
  18256. case 1:
  18257. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), r ]) ];
  18258. }
  18259. }));
  18260. }));
  18261. }));
  18262. }(pl(t = Hc(t, hl)), r).then((function(e) {
  18263. return e ? new tl(t, null, e.query) : null;
  18264. }));
  18265. }
  18266. function Dl(t) {
  18267. if (t._initialized || t._terminated) throw new Q(K.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.");
  18268. }
  18269. /**
  18270. * @license
  18271. * Copyright 2020 Google LLC
  18272. *
  18273. * Licensed under the Apache License, Version 2.0 (the "License");
  18274. * you may not use this file except in compliance with the License.
  18275. * You may obtain a copy of the License at
  18276. *
  18277. * http://www.apache.org/licenses/LICENSE-2.0
  18278. *
  18279. * Unless required by applicable law or agreed to in writing, software
  18280. * distributed under the License is distributed on an "AS IS" BASIS,
  18281. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18282. * See the License for the specific language governing permissions and
  18283. * limitations under the License.
  18284. */
  18285. /**
  18286. * @license
  18287. * Copyright 2022 Google LLC
  18288. *
  18289. * Licensed under the Apache License, Version 2.0 (the "License");
  18290. * you may not use this file except in compliance with the License.
  18291. * You may obtain a copy of the License at
  18292. *
  18293. * http://www.apache.org/licenses/LICENSE-2.0
  18294. *
  18295. * Unless required by applicable law or agreed to in writing, software
  18296. * distributed under the License is distributed on an "AS IS" BASIS,
  18297. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18298. * See the License for the specific language governing permissions and
  18299. * limitations under the License.
  18300. */
  18301. /**
  18302. * Represents an aggregation that can be performed by Firestore.
  18303. */
  18304. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  18305. var Cl =
  18306. /**
  18307. * Create a new AggregateField<T>
  18308. * @param _aggregateType Specifies the type of aggregation operation to perform.
  18309. * @param _internalFieldPath Optionally specifies the field that is aggregated.
  18310. * @internal
  18311. */
  18312. function(
  18313. // TODO (sum/avg) make aggregateType public when the feature is supported
  18314. t, e) {
  18315. void 0 === t && (t = "count"), this._aggregateType = t, this._internalFieldPath = e,
  18316. /** A type string to uniquely identify instances of this class. */
  18317. this.type = "AggregateField";
  18318. }, xl = /** @class */ function() {
  18319. /** @hideconstructor */
  18320. function t(t, e, n) {
  18321. this._userDataWriter = e, this._data = n,
  18322. /** A type string to uniquely identify instances of this class. */
  18323. this.type = "AggregateQuerySnapshot", this.query = t
  18324. /**
  18325. * Returns the results of the aggregations performed over the underlying
  18326. * query.
  18327. *
  18328. * The keys of the returned object will be the same as those of the
  18329. * `AggregateSpec` object specified to the aggregation method, and the values
  18330. * will be the corresponding aggregation result.
  18331. *
  18332. * @returns The results of the aggregations performed over the underlying
  18333. * query.
  18334. */;
  18335. }
  18336. return t.prototype.data = function() {
  18337. return this._userDataWriter.convertObjectMap(this._data);
  18338. }, t;
  18339. }(), Nl = /** @class */ function() {
  18340. /** @hideconstructor */
  18341. function t(t) {
  18342. this._byteString = t;
  18343. }
  18344. /**
  18345. * Creates a new `Bytes` object from the given Base64 string, converting it to
  18346. * bytes.
  18347. *
  18348. * @param base64 - The Base64 string used to create the `Bytes` object.
  18349. */ return t.fromBase64String = function(e) {
  18350. try {
  18351. return new t(Oe.fromBase64String(e));
  18352. } catch (e) {
  18353. throw new Q(K.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + e);
  18354. }
  18355. },
  18356. /**
  18357. * Creates a new `Bytes` object from the given Uint8Array.
  18358. *
  18359. * @param array - The Uint8Array used to create the `Bytes` object.
  18360. */
  18361. t.fromUint8Array = function(e) {
  18362. return new t(Oe.fromUint8Array(e));
  18363. },
  18364. /**
  18365. * Returns the underlying bytes as a Base64-encoded string.
  18366. *
  18367. * @returns The Base64-encoded string created from the `Bytes` object.
  18368. */
  18369. t.prototype.toBase64 = function() {
  18370. return this._byteString.toBase64();
  18371. },
  18372. /**
  18373. * Returns the underlying bytes in a new `Uint8Array`.
  18374. *
  18375. * @returns The Uint8Array created from the `Bytes` object.
  18376. */
  18377. t.prototype.toUint8Array = function() {
  18378. return this._byteString.toUint8Array();
  18379. },
  18380. /**
  18381. * Returns a string representation of the `Bytes` object.
  18382. *
  18383. * @returns A string representation of the `Bytes` object.
  18384. */
  18385. t.prototype.toString = function() {
  18386. return "Bytes(base64: " + this.toBase64() + ")";
  18387. },
  18388. /**
  18389. * Returns true if this `Bytes` object is equal to the provided one.
  18390. *
  18391. * @param other - The `Bytes` object to compare against.
  18392. * @returns true if this `Bytes` object is equal to the provided one.
  18393. */
  18394. t.prototype.isEqual = function(t) {
  18395. return this._byteString.isEqual(t._byteString);
  18396. }, t;
  18397. }(), Al = /** @class */ function() {
  18398. /**
  18399. * Creates a `FieldPath` from the provided field names. If more than one field
  18400. * name is provided, the path will point to a nested field in a document.
  18401. *
  18402. * @param fieldNames - A list of field names.
  18403. */
  18404. function t() {
  18405. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  18406. for (var n = 0; n < t.length; ++n) if (0 === t[n].length) throw new Q(K.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
  18407. this._internalPath = new dt(t);
  18408. }
  18409. /**
  18410. * Returns true if this `FieldPath` is equal to the provided one.
  18411. *
  18412. * @param other - The `FieldPath` to compare against.
  18413. * @returns true if this `FieldPath` is equal to the provided one.
  18414. */ return t.prototype.isEqual = function(t) {
  18415. return this._internalPath.isEqual(t._internalPath);
  18416. }, t;
  18417. }();
  18418. /**
  18419. * The results of executing an aggregation query.
  18420. */
  18421. /**
  18422. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  18423. * It can be used in queries to sort or filter by the document ID.
  18424. */
  18425. function kl() {
  18426. return new Al("__name__");
  18427. }
  18428. /**
  18429. * @license
  18430. * Copyright 2020 Google LLC
  18431. *
  18432. * Licensed under the Apache License, Version 2.0 (the "License");
  18433. * you may not use this file except in compliance with the License.
  18434. * You may obtain a copy of the License at
  18435. *
  18436. * http://www.apache.org/licenses/LICENSE-2.0
  18437. *
  18438. * Unless required by applicable law or agreed to in writing, software
  18439. * distributed under the License is distributed on an "AS IS" BASIS,
  18440. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18441. * See the License for the specific language governing permissions and
  18442. * limitations under the License.
  18443. */
  18444. /**
  18445. * Sentinel values that can be used when writing document fields with `set()`
  18446. * or `update()`.
  18447. */ var Ol =
  18448. /**
  18449. * @param _methodName - The public API endpoint that returns this class.
  18450. * @hideconstructor
  18451. */
  18452. function(t) {
  18453. this._methodName = t;
  18454. }, Fl = /** @class */ function() {
  18455. /**
  18456. * Creates a new immutable `GeoPoint` object with the provided latitude and
  18457. * longitude values.
  18458. * @param latitude - The latitude as number between -90 and 90.
  18459. * @param longitude - The longitude as number between -180 and 180.
  18460. */
  18461. function t(t, e) {
  18462. if (!isFinite(t) || t < -90 || t > 90) throw new Q(K.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + t);
  18463. if (!isFinite(e) || e < -180 || e > 180) throw new Q(K.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + e);
  18464. this._lat = t, this._long = e;
  18465. }
  18466. return Object.defineProperty(t.prototype, "latitude", {
  18467. /**
  18468. * The latitude of this `GeoPoint` instance.
  18469. */
  18470. get: function() {
  18471. return this._lat;
  18472. },
  18473. enumerable: !1,
  18474. configurable: !0
  18475. }), Object.defineProperty(t.prototype, "longitude", {
  18476. /**
  18477. * The longitude of this `GeoPoint` instance.
  18478. */
  18479. get: function() {
  18480. return this._long;
  18481. },
  18482. enumerable: !1,
  18483. configurable: !0
  18484. }),
  18485. /**
  18486. * Returns true if this `GeoPoint` is equal to the provided one.
  18487. *
  18488. * @param other - The `GeoPoint` to compare against.
  18489. * @returns true if this `GeoPoint` is equal to the provided one.
  18490. */
  18491. t.prototype.isEqual = function(t) {
  18492. return this._lat === t._lat && this._long === t._long;
  18493. },
  18494. /** Returns a JSON-serializable representation of this GeoPoint. */ t.prototype.toJSON = function() {
  18495. return {
  18496. latitude: this._lat,
  18497. longitude: this._long
  18498. };
  18499. },
  18500. /**
  18501. * Actually private to JS consumers of our API, so this function is prefixed
  18502. * with an underscore.
  18503. */
  18504. t.prototype._compareTo = function(t) {
  18505. return ot(this._lat, t._lat) || ot(this._long, t._long);
  18506. }, t;
  18507. }(), Pl = /^__.*__$/, Rl = /** @class */ function() {
  18508. function t(t, e, n) {
  18509. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  18510. }
  18511. return t.prototype.toMutation = function(t, e) {
  18512. return null !== this.fieldMask ? new Xr(t, this.data, this.fieldMask, e, this.fieldTransforms) : new Yr(t, this.data, e, this.fieldTransforms);
  18513. }, t;
  18514. }(), Vl = /** @class */ function() {
  18515. function t(t,
  18516. // The fieldMask does not include document transforms.
  18517. e, n) {
  18518. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  18519. }
  18520. return t.prototype.toMutation = function(t, e) {
  18521. return new Xr(t, this.data, this.fieldMask, e, this.fieldTransforms);
  18522. }, t;
  18523. }();
  18524. /**
  18525. * @license
  18526. * Copyright 2017 Google LLC
  18527. *
  18528. * Licensed under the Apache License, Version 2.0 (the "License");
  18529. * you may not use this file except in compliance with the License.
  18530. * You may obtain a copy of the License at
  18531. *
  18532. * http://www.apache.org/licenses/LICENSE-2.0
  18533. *
  18534. * Unless required by applicable law or agreed to in writing, software
  18535. * distributed under the License is distributed on an "AS IS" BASIS,
  18536. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18537. * See the License for the specific language governing permissions and
  18538. * limitations under the License.
  18539. */
  18540. /**
  18541. * An immutable object representing a geographic location in Firestore. The
  18542. * location is represented as latitude/longitude pair.
  18543. *
  18544. * Latitude values are in the range of [-90, 90].
  18545. * Longitude values are in the range of [-180, 180].
  18546. */ function Ml(t) {
  18547. switch (t) {
  18548. case 0 /* UserDataSource.Set */ :
  18549. // fall through
  18550. case 2 /* UserDataSource.MergeSet */ :
  18551. // fall through
  18552. case 1 /* UserDataSource.Update */ :
  18553. return !0;
  18554. case 3 /* UserDataSource.Argument */ :
  18555. case 4 /* UserDataSource.ArrayArgument */ :
  18556. return !1;
  18557. default:
  18558. throw U();
  18559. }
  18560. }
  18561. /** A "context" object passed around while parsing user data. */ var Ll = /** @class */ function() {
  18562. /**
  18563. * Initializes a ParseContext with the given source and path.
  18564. *
  18565. * @param settings - The settings for the parser.
  18566. * @param databaseId - The database ID of the Firestore instance.
  18567. * @param serializer - The serializer to use to generate the Value proto.
  18568. * @param ignoreUndefinedProperties - Whether to ignore undefined properties
  18569. * rather than throw.
  18570. * @param fieldTransforms - A mutable list of field transforms encountered
  18571. * while parsing the data.
  18572. * @param fieldMask - A mutable list of field paths encountered while parsing
  18573. * the data.
  18574. *
  18575. * TODO(b/34871131): We don't support array paths right now, so path can be
  18576. * null to indicate the context represents any location within an array (in
  18577. * which case certain features will not work and errors will be somewhat
  18578. * compromised).
  18579. */
  18580. function t(t, e, n, r, i, o) {
  18581. this.settings = t, this.databaseId = e, this.serializer = n, this.ignoreUndefinedProperties = r,
  18582. // Minor hack: If fieldTransforms is undefined, we assume this is an
  18583. // external call and we need to validate the entire path.
  18584. void 0 === i && this.ua(), this.fieldTransforms = i || [], this.fieldMask = o || [];
  18585. }
  18586. return Object.defineProperty(t.prototype, "path", {
  18587. get: function() {
  18588. return this.settings.path;
  18589. },
  18590. enumerable: !1,
  18591. configurable: !0
  18592. }), Object.defineProperty(t.prototype, "ca", {
  18593. get: function() {
  18594. return this.settings.ca;
  18595. },
  18596. enumerable: !1,
  18597. configurable: !0
  18598. }),
  18599. /** Returns a new context with the specified settings overwritten. */ t.prototype.aa = function(e) {
  18600. return new t(Object.assign(Object.assign({}, this.settings), e), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  18601. }, t.prototype.ha = function(t) {
  18602. var e, n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), r = this.aa({
  18603. path: n,
  18604. la: !1
  18605. });
  18606. return r.fa(t), r;
  18607. }, t.prototype.da = function(t) {
  18608. var e, n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), r = this.aa({
  18609. path: n,
  18610. la: !1
  18611. });
  18612. return r.ua(), r;
  18613. }, t.prototype.wa = function(t) {
  18614. // TODO(b/34871131): We don't support array paths right now; so make path
  18615. // undefined.
  18616. return this.aa({
  18617. path: void 0,
  18618. la: !0
  18619. });
  18620. }, t.prototype._a = function(t) {
  18621. return ih(t, this.settings.methodName, this.settings.ma || !1, this.path, this.settings.ga);
  18622. },
  18623. /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ t.prototype.contains = function(t) {
  18624. return void 0 !== this.fieldMask.find((function(e) {
  18625. return t.isPrefixOf(e);
  18626. })) || void 0 !== this.fieldTransforms.find((function(e) {
  18627. return t.isPrefixOf(e.field);
  18628. }));
  18629. }, t.prototype.ua = function() {
  18630. // TODO(b/34871131): Remove null check once we have proper paths for fields
  18631. // within arrays.
  18632. if (this.path) for (var t = 0; t < this.path.length; t++) this.fa(this.path.get(t));
  18633. }, t.prototype.fa = function(t) {
  18634. if (0 === t.length) throw this._a("Document fields must not be empty");
  18635. if (Ml(this.ca) && Pl.test(t)) throw this._a('Document fields cannot begin and end with "__"');
  18636. }, t;
  18637. }(), ql = /** @class */ function() {
  18638. function t(t, e, n) {
  18639. this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = n || Va(t)
  18640. /** Creates a new top-level parse context. */;
  18641. }
  18642. return t.prototype.ya = function(t, e, n, r) {
  18643. return void 0 === r && (r = !1), new Ll({
  18644. ca: t,
  18645. methodName: e,
  18646. ga: n,
  18647. path: dt.emptyPath(),
  18648. la: !1,
  18649. ma: r
  18650. }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);
  18651. }, t;
  18652. }();
  18653. /**
  18654. * Helper for parsing raw user input (provided via the API) into internal model
  18655. * classes.
  18656. */ function Bl(t) {
  18657. var e = t._freezeSettings(), n = Va(t._databaseId);
  18658. return new ql(t._databaseId, !!e.ignoreUndefinedProperties, n);
  18659. }
  18660. /** Parse document data from a set() call. */ function Ul(t, e, n, r, i, o) {
  18661. void 0 === o && (o = {});
  18662. var u = t.ya(o.merge || o.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, i);
  18663. th("Data must be an object, but it was:", u, r);
  18664. var a, s, c = Zl(r, u);
  18665. if (o.merge) a = new Ne(u.fieldMask), s = u.fieldTransforms; else if (o.mergeFields) {
  18666. for (var l = [], h = 0, f = o.mergeFields; h < f.length; h++) {
  18667. var d = eh(e, f[h], n);
  18668. if (!u.contains(d)) throw new Q(K.INVALID_ARGUMENT, "Field '".concat(d, "' is specified in your field mask but missing from your input data."));
  18669. oh(l, d) || l.push(d);
  18670. }
  18671. a = new Ne(l), s = u.fieldTransforms.filter((function(t) {
  18672. return a.covers(t.field);
  18673. }));
  18674. } else a = null, s = u.fieldTransforms;
  18675. return new Rl(new hn(c), a, s);
  18676. }
  18677. var zl = /** @class */ function(e) {
  18678. function n() {
  18679. return null !== e && e.apply(this, arguments) || this;
  18680. }
  18681. return t(n, e), n.prototype._toFieldTransform = function(t) {
  18682. if (2 /* UserDataSource.MergeSet */ !== t.ca) throw 1 /* UserDataSource.Update */ === t.ca ? t._a("".concat(this._methodName, "() can only appear at the top level of your update data")) : t._a("".concat(this._methodName, "() cannot be used with set() unless you pass {merge:true}"));
  18683. // No transform to add for a delete, but we need to add it to our
  18684. // fieldMask so it gets deleted.
  18685. return t.fieldMask.push(t.path), null;
  18686. }, n.prototype.isEqual = function(t) {
  18687. return t instanceof n;
  18688. }, n;
  18689. }(Ol);
  18690. /**
  18691. * Creates a child context for parsing SerializableFieldValues.
  18692. *
  18693. * This is different than calling `ParseContext.contextWith` because it keeps
  18694. * the fieldTransforms and fieldMask separate.
  18695. *
  18696. * The created context has its `dataSource` set to `UserDataSource.Argument`.
  18697. * Although these values are used with writes, any elements in these FieldValues
  18698. * are not considered writes since they cannot contain any FieldValue sentinels,
  18699. * etc.
  18700. *
  18701. * @param fieldValue - The sentinel FieldValue for which to create a child
  18702. * context.
  18703. * @param context - The parent context.
  18704. * @param arrayElement - Whether or not the FieldValue has an array.
  18705. */ function Gl(t, e, n) {
  18706. return new Ll({
  18707. ca: 3 /* UserDataSource.Argument */ ,
  18708. ga: e.settings.ga,
  18709. methodName: t._methodName,
  18710. la: n
  18711. }, e.databaseId, e.serializer, e.ignoreUndefinedProperties);
  18712. }
  18713. var jl = /** @class */ function(e) {
  18714. function n() {
  18715. return null !== e && e.apply(this, arguments) || this;
  18716. }
  18717. return t(n, e), n.prototype._toFieldTransform = function(t) {
  18718. return new qr(t.path, new kr);
  18719. }, n.prototype.isEqual = function(t) {
  18720. return t instanceof n;
  18721. }, n;
  18722. }(Ol), Kl = /** @class */ function(e) {
  18723. function n(t, n) {
  18724. var r = this;
  18725. return (r = e.call(this, t) || this).pa = n, r;
  18726. }
  18727. return t(n, e), n.prototype._toFieldTransform = function(t) {
  18728. var e = Gl(this, t,
  18729. /*array=*/ !0), n = this.pa.map((function(t) {
  18730. return Jl(t, e);
  18731. })), r = new Or(n);
  18732. return new qr(t.path, r);
  18733. }, n.prototype.isEqual = function(t) {
  18734. // TODO(mrschmidt): Implement isEquals
  18735. return this === t;
  18736. }, n;
  18737. }(Ol), Ql = /** @class */ function(e) {
  18738. function n(t, n) {
  18739. var r = this;
  18740. return (r = e.call(this, t) || this).pa = n, r;
  18741. }
  18742. return t(n, e), n.prototype._toFieldTransform = function(t) {
  18743. var e = Gl(this, t,
  18744. /*array=*/ !0), n = this.pa.map((function(t) {
  18745. return Jl(t, e);
  18746. })), r = new Pr(n);
  18747. return new qr(t.path, r);
  18748. }, n.prototype.isEqual = function(t) {
  18749. // TODO(mrschmidt): Implement isEquals
  18750. return this === t;
  18751. }, n;
  18752. }(Ol), Wl = /** @class */ function(e) {
  18753. function n(t, n) {
  18754. var r = this;
  18755. return (r = e.call(this, t) || this).Ia = n, r;
  18756. }
  18757. return t(n, e), n.prototype._toFieldTransform = function(t) {
  18758. var e = new Vr(t.serializer, Dr(t.serializer, this.Ia));
  18759. return new qr(t.path, e);
  18760. }, n.prototype.isEqual = function(t) {
  18761. // TODO(mrschmidt): Implement isEquals
  18762. return this === t;
  18763. }, n;
  18764. }(Ol);
  18765. /** Parse update data from an update() call. */ function Hl(t, e, n, r) {
  18766. var i = t.ya(1 /* UserDataSource.Update */ , e, n);
  18767. th("Data must be an object, but it was:", i, r);
  18768. var o = [], u = hn.empty();
  18769. Ie(r, (function(t, r) {
  18770. var a = rh(e, t, n);
  18771. // For Compat types, we have to "extract" the underlying types before
  18772. // performing validation.
  18773. r = v(r);
  18774. var s = i.da(a);
  18775. if (r instanceof zl)
  18776. // Add it to the field mask, but don't add anything to updateData.
  18777. o.push(a); else {
  18778. var c = Jl(r, s);
  18779. null != c && (o.push(a), u.set(a, c));
  18780. }
  18781. }));
  18782. var a = new Ne(o);
  18783. return new Vl(u, a, i.fieldTransforms);
  18784. }
  18785. /** Parse update data from a list of field/value arguments. */ function Yl(t, e, n, r, i, o) {
  18786. var u = t.ya(1 /* UserDataSource.Update */ , e, n), a = [ eh(e, r, n) ], s = [ i ];
  18787. if (o.length % 2 != 0) throw new Q(K.INVALID_ARGUMENT, "Function ".concat(e, "() needs to be called with an even number of arguments that alternate between field names and values."));
  18788. for (var c = 0; c < o.length; c += 2) a.push(eh(e, o[c])), s.push(o[c + 1]);
  18789. // We iterate in reverse order to pick the last value for a field if the
  18790. // user specified the field multiple times.
  18791. for (var l = [], h = hn.empty(), f = a.length - 1; f >= 0; --f) if (!oh(l, a[f])) {
  18792. var d = a[f], p = s[f];
  18793. // For Compat types, we have to "extract" the underlying types before
  18794. // performing validation.
  18795. p = v(p);
  18796. var m = u.da(d);
  18797. if (p instanceof zl)
  18798. // Add it to the field mask, but don't add anything to updateData.
  18799. l.push(d); else {
  18800. var y = Jl(p, m);
  18801. null != y && (l.push(d), h.set(d, y));
  18802. }
  18803. }
  18804. var g = new Ne(l);
  18805. return new Vl(h, g, u.fieldTransforms);
  18806. }
  18807. /**
  18808. * Parse a "query value" (e.g. value in a where filter or a value in a cursor
  18809. * bound).
  18810. *
  18811. * @param allowArrays - Whether the query value is an array that may directly
  18812. * contain additional arrays (e.g. the operand of an `in` query).
  18813. */ function Xl(t, e, n, r) {
  18814. return void 0 === r && (r = !1), Jl(n, t.ya(r ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));
  18815. }
  18816. /**
  18817. * Parses user data to Protobuf Values.
  18818. *
  18819. * @param input - Data to be parsed.
  18820. * @param context - A context object representing the current path being parsed,
  18821. * the source of the data being parsed, etc.
  18822. * @returns The parsed value, or null if the value was a FieldValue sentinel
  18823. * that should not be included in the resulting parsed data.
  18824. */ function Jl(t, e) {
  18825. if ($l(
  18826. // Unwrap the API type from the Compat SDK. This will return the API type
  18827. // from firestore-exp.
  18828. t = v(t))) return th("Unsupported field value:", e, t), Zl(t, e);
  18829. if (t instanceof Ol)
  18830. // FieldValues usually parse into transforms (except deleteField())
  18831. // in which case we do not want to include this field in our parsed data
  18832. // (as doing so will overwrite the field directly prior to the transform
  18833. // trying to transform it). So we don't add this location to
  18834. // context.fieldMask and we return null as our parsing result.
  18835. /**
  18836. * "Parses" the provided FieldValueImpl, adding any necessary transforms to
  18837. * context.fieldTransforms.
  18838. */
  18839. return function(t, e) {
  18840. // Sentinels are only supported with writes, and not within arrays.
  18841. if (!Ml(e.ca)) throw e._a("".concat(t._methodName, "() can only be used with update() and set()"));
  18842. if (!e.path) throw e._a("".concat(t._methodName, "() is not currently supported inside arrays"));
  18843. var n = t._toFieldTransform(e);
  18844. n && e.fieldTransforms.push(n);
  18845. }(t, e), null;
  18846. if (void 0 === t && e.ignoreUndefinedProperties)
  18847. // If the input is undefined it can never participate in the fieldMask, so
  18848. // don't handle this below. If `ignoreUndefinedProperties` is false,
  18849. // `parseScalarValue` will reject an undefined value.
  18850. return null;
  18851. if (
  18852. // If context.path is null we are inside an array and we don't support
  18853. // field mask paths more granular than the top-level array.
  18854. e.path && e.fieldMask.push(e.path), t instanceof Array) {
  18855. // TODO(b/34871131): Include the path containing the array in the error
  18856. // message.
  18857. // In the case of IN queries, the parsed data is an array (representing
  18858. // the set of values to be included for the IN query) that may directly
  18859. // contain additional arrays (each representing an individual field
  18860. // value), so we disable this validation.
  18861. if (e.settings.la && 4 /* UserDataSource.ArrayArgument */ !== e.ca) throw e._a("Nested arrays are not supported");
  18862. return function(t, e) {
  18863. for (var n = [], r = 0, i = 0, o = t; i < o.length; i++) {
  18864. var u = Jl(o[i], e.wa(r));
  18865. null == u && (
  18866. // Just include nulls in the array for fields being replaced with a
  18867. // sentinel.
  18868. u = {
  18869. nullValue: "NULL_VALUE"
  18870. }), n.push(u), r++;
  18871. }
  18872. return {
  18873. arrayValue: {
  18874. values: n
  18875. }
  18876. };
  18877. }(t, e);
  18878. }
  18879. return function(t, e) {
  18880. if (null === (t = v(t))) return {
  18881. nullValue: "NULL_VALUE"
  18882. };
  18883. if ("number" == typeof t) return Dr(e.serializer, t);
  18884. if ("boolean" == typeof t) return {
  18885. booleanValue: t
  18886. };
  18887. if ("string" == typeof t) return {
  18888. stringValue: t
  18889. };
  18890. if (t instanceof Date) {
  18891. var n = st.fromDate(t);
  18892. return {
  18893. timestampValue: Fi(e.serializer, n)
  18894. };
  18895. }
  18896. if (t instanceof st) {
  18897. // Firestore backend truncates precision down to microseconds. To ensure
  18898. // offline mode works the same with regards to truncation, perform the
  18899. // truncation immediately without waiting for the backend to do that.
  18900. var r = new st(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
  18901. return {
  18902. timestampValue: Fi(e.serializer, r)
  18903. };
  18904. }
  18905. if (t instanceof Fl) return {
  18906. geoPointValue: {
  18907. latitude: t.latitude,
  18908. longitude: t.longitude
  18909. }
  18910. };
  18911. if (t instanceof Nl) return {
  18912. bytesValue: Pi(e.serializer, t._byteString)
  18913. };
  18914. if (t instanceof $c) {
  18915. var i = e.databaseId, o = t.firestore._databaseId;
  18916. if (!o.isEqual(i)) throw e._a("Document reference is for database ".concat(o.projectId, "/").concat(o.database, " but should be for database ").concat(i.projectId, "/").concat(i.database));
  18917. return {
  18918. referenceValue: Mi(t.firestore._databaseId || e.databaseId, t._key.path)
  18919. };
  18920. }
  18921. throw e._a("Unsupported field value: ".concat(Wc(t)));
  18922. }(t, e);
  18923. }
  18924. function Zl(t, e) {
  18925. var n = {};
  18926. return Ee(t) ?
  18927. // If we encounter an empty object, we explicitly add it to the update
  18928. // mask to ensure that the server creates a map entry.
  18929. e.path && e.path.length > 0 && e.fieldMask.push(e.path) : Ie(t, (function(t, r) {
  18930. var i = Jl(r, e.ha(t));
  18931. null != i && (n[t] = i);
  18932. })), {
  18933. mapValue: {
  18934. fields: n
  18935. }
  18936. };
  18937. }
  18938. function $l(t) {
  18939. return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof st || t instanceof Fl || t instanceof Nl || t instanceof $c || t instanceof Ol);
  18940. }
  18941. function th(t, e, n) {
  18942. if (!$l(n) || !function(t) {
  18943. return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));
  18944. }(n)) {
  18945. var r = Wc(n);
  18946. throw "an object" === r ? e._a(t + " a custom object") : e._a(t + " " + r);
  18947. }
  18948. }
  18949. /**
  18950. * Helper that calls fromDotSeparatedString() but wraps any error thrown.
  18951. */ function eh(t, e, n) {
  18952. if (
  18953. // If required, replace the FieldPath Compat class with with the firestore-exp
  18954. // FieldPath.
  18955. (e = v(e)) instanceof Al) return e._internalPath;
  18956. if ("string" == typeof e) return rh(t, e);
  18957. throw ih("Field path arguments must be of type string or ", t,
  18958. /* hasConverter= */ !1,
  18959. /* path= */ void 0, n);
  18960. }
  18961. /**
  18962. * Matches any characters in a field path string that are reserved.
  18963. */ var nh = new RegExp("[~\\*/\\[\\]]");
  18964. /**
  18965. * Wraps fromDotSeparatedString with an error message about the method that
  18966. * was thrown.
  18967. * @param methodName - The publicly visible method name
  18968. * @param path - The dot-separated string form of a field path which will be
  18969. * split on dots.
  18970. * @param targetDoc - The document against which the field path will be
  18971. * evaluated.
  18972. */ function rh(t, e, n) {
  18973. if (e.search(nh) >= 0) throw ih("Invalid field path (".concat(e, "). Paths must not contain '~', '*', '/', '[', or ']'"), t,
  18974. /* hasConverter= */ !1,
  18975. /* path= */ void 0, n);
  18976. try {
  18977. return (new (Al.bind.apply(Al, r([ void 0 ], e.split("."), !1))))._internalPath;
  18978. } catch (r) {
  18979. throw ih("Invalid field path (".concat(e, "). Paths must not be empty, begin with '.', end with '.', or contain '..'"), t,
  18980. /* hasConverter= */ !1,
  18981. /* path= */ void 0, n);
  18982. }
  18983. }
  18984. function ih(t, e, n, r, i) {
  18985. var o = r && !r.isEmpty(), u = void 0 !== i, a = "Function ".concat(e, "() called with invalid data");
  18986. n && (a += " (via `toFirestore()`)"), a += ". ";
  18987. var s = "";
  18988. return (o || u) && (s += " (found", o && (s += " in field ".concat(r)), u && (s += " in document ".concat(i)),
  18989. s += ")"), new Q(K.INVALID_ARGUMENT, a + t + s)
  18990. /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */;
  18991. }
  18992. function oh(t, e) {
  18993. return t.some((function(t) {
  18994. return t.isEqual(e);
  18995. }));
  18996. }
  18997. /**
  18998. * @license
  18999. * Copyright 2020 Google LLC
  19000. *
  19001. * Licensed under the Apache License, Version 2.0 (the "License");
  19002. * you may not use this file except in compliance with the License.
  19003. * You may obtain a copy of the License at
  19004. *
  19005. * http://www.apache.org/licenses/LICENSE-2.0
  19006. *
  19007. * Unless required by applicable law or agreed to in writing, software
  19008. * distributed under the License is distributed on an "AS IS" BASIS,
  19009. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19010. * See the License for the specific language governing permissions and
  19011. * limitations under the License.
  19012. */
  19013. /**
  19014. * A `DocumentSnapshot` contains data read from a document in your Firestore
  19015. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  19016. * get a specific field.
  19017. *
  19018. * For a `DocumentSnapshot` that points to a non-existing document, any data
  19019. * access will return 'undefined'. You can use the `exists()` method to
  19020. * explicitly verify a document's existence.
  19021. */ var uh = /** @class */ function() {
  19022. // Note: This class is stripped down version of the DocumentSnapshot in
  19023. // the legacy SDK. The changes are:
  19024. // - No support for SnapshotMetadata.
  19025. // - No support for SnapshotOptions.
  19026. /** @hideconstructor protected */
  19027. function t(t, e, n, r, i) {
  19028. this._firestore = t, this._userDataWriter = e, this._key = n, this._document = r,
  19029. this._converter = i;
  19030. }
  19031. return Object.defineProperty(t.prototype, "id", {
  19032. /** Property of the `DocumentSnapshot` that provides the document's ID. */ get: function() {
  19033. return this._key.path.lastSegment();
  19034. },
  19035. enumerable: !1,
  19036. configurable: !0
  19037. }), Object.defineProperty(t.prototype, "ref", {
  19038. /**
  19039. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  19040. */
  19041. get: function() {
  19042. return new $c(this._firestore, this._converter, this._key);
  19043. },
  19044. enumerable: !1,
  19045. configurable: !0
  19046. }),
  19047. /**
  19048. * Signals whether or not the document at the snapshot's location exists.
  19049. *
  19050. * @returns true if the document exists.
  19051. */
  19052. t.prototype.exists = function() {
  19053. return null !== this._document;
  19054. },
  19055. /**
  19056. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  19057. * the document doesn't exist.
  19058. *
  19059. * @returns An `Object` containing all fields in the document or `undefined`
  19060. * if the document doesn't exist.
  19061. */
  19062. t.prototype.data = function() {
  19063. if (this._document) {
  19064. if (this._converter) {
  19065. // We only want to use the converter and create a new DocumentSnapshot
  19066. // if a converter has been provided.
  19067. var t = new ah(this._firestore, this._userDataWriter, this._key, this._document,
  19068. /* converter= */ null);
  19069. return this._converter.fromFirestore(t);
  19070. }
  19071. return this._userDataWriter.convertValue(this._document.data.value);
  19072. }
  19073. },
  19074. /**
  19075. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  19076. * document or field doesn't exist.
  19077. *
  19078. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  19079. * field.
  19080. * @returns The data at the specified field location or undefined if no such
  19081. * field exists in the document.
  19082. */
  19083. // We are using `any` here to avoid an explicit cast by our users.
  19084. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19085. t.prototype.get = function(t) {
  19086. if (this._document) {
  19087. var e = this._document.data.field(sh("DocumentSnapshot.get", t));
  19088. if (null !== e) return this._userDataWriter.convertValue(e);
  19089. }
  19090. }, t;
  19091. }(), ah = /** @class */ function(e) {
  19092. function n() {
  19093. return null !== e && e.apply(this, arguments) || this;
  19094. }
  19095. /**
  19096. * Retrieves all fields in the document as an `Object`.
  19097. *
  19098. * @override
  19099. * @returns An `Object` containing all fields in the document.
  19100. */ return t(n, e), n.prototype.data = function() {
  19101. return e.prototype.data.call(this);
  19102. }, n;
  19103. }(uh);
  19104. /**
  19105. * A `QueryDocumentSnapshot` contains data read from a document in your
  19106. * Firestore database as part of a query. The document is guaranteed to exist
  19107. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  19108. * specific field.
  19109. *
  19110. * A `QueryDocumentSnapshot` offers the same API surface as a
  19111. * `DocumentSnapshot`. Since query results contain only existing documents, the
  19112. * `exists` property will always be true and `data()` will never return
  19113. * 'undefined'.
  19114. */
  19115. /**
  19116. * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
  19117. */
  19118. function sh(t, e) {
  19119. return "string" == typeof e ? rh(t, e) : e instanceof Al ? e._internalPath : e._delegate._internalPath;
  19120. }
  19121. /**
  19122. * @license
  19123. * Copyright 2020 Google LLC
  19124. *
  19125. * Licensed under the Apache License, Version 2.0 (the "License");
  19126. * you may not use this file except in compliance with the License.
  19127. * You may obtain a copy of the License at
  19128. *
  19129. * http://www.apache.org/licenses/LICENSE-2.0
  19130. *
  19131. * Unless required by applicable law or agreed to in writing, software
  19132. * distributed under the License is distributed on an "AS IS" BASIS,
  19133. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19134. * See the License for the specific language governing permissions and
  19135. * limitations under the License.
  19136. */ function ch(t) {
  19137. if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new Q(K.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
  19138. }
  19139. /**
  19140. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  19141. * to a Firestore query.
  19142. */ var lh = function() {}, hh = /** @class */ function(e) {
  19143. function n() {
  19144. return null !== e && e.apply(this, arguments) || this;
  19145. }
  19146. return t(n, e), n;
  19147. }(lh);
  19148. /**
  19149. * A `QueryConstraint` is used to narrow the set of documents returned by a
  19150. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  19151. * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
  19152. * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and
  19153. * can then be passed to {@link (query:1)} to create a new query instance that
  19154. * also contains this `QueryConstraint`.
  19155. */ function fh(t, e) {
  19156. for (var n = [], r = 2; r < arguments.length; r++) n[r - 2] = arguments[r];
  19157. var i = [];
  19158. e instanceof lh && i.push(e), function(t) {
  19159. var e = t.filter((function(t) {
  19160. return t instanceof vh;
  19161. })).length, n = t.filter((function(t) {
  19162. return t instanceof dh;
  19163. })).length;
  19164. if (e > 1 || e > 0 && n > 0) throw new Q(K.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(...)))`.");
  19165. }(i = i.concat(n));
  19166. for (var o = 0, u = i; o < u.length; o++) {
  19167. var a = u[o];
  19168. t = a._apply(t);
  19169. }
  19170. return t;
  19171. }
  19172. /**
  19173. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  19174. * a Firestore query by filtering on one or more document fields.
  19175. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  19176. * be passed to {@link (query:1)} to create a new query instance that also contains
  19177. * this `QueryFieldFilterConstraint`.
  19178. */ var dh = /** @class */ function(e) {
  19179. /**
  19180. * @internal
  19181. */
  19182. function n(t, n, r) {
  19183. var i = this;
  19184. return (i = e.call(this) || this)._field = t, i._op = n, i._value = r,
  19185. /** The type of this query constraint */
  19186. i.type = "where", i;
  19187. }
  19188. return t(n, e), n._create = function(t, e, r) {
  19189. return new n(t, e, r);
  19190. }, n.prototype._apply = function(t) {
  19191. var e = this._parse(t);
  19192. return Oh(t._query, e), new tl(t.firestore, t.converter, er(t._query, e));
  19193. }, n.prototype._parse = function(t) {
  19194. var e = Bl(t.firestore), n = function(t, e, n, r, i, o, u) {
  19195. var a;
  19196. if (i.isKeyField()) {
  19197. if ("array-contains" /* Operator.ARRAY_CONTAINS */ === o || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === o) throw new Q(K.INVALID_ARGUMENT, "Invalid Query. You can't perform '".concat(o, "' queries on documentId()."));
  19198. if ("in" /* Operator.IN */ === o || "not-in" /* Operator.NOT_IN */ === o) {
  19199. kh(u, o);
  19200. for (var s = [], c = 0, l = u; c < l.length; c++) {
  19201. var h = l[c];
  19202. s.push(Ah(r, t, h));
  19203. }
  19204. a = {
  19205. arrayValue: {
  19206. values: s
  19207. }
  19208. };
  19209. } else a = Ah(r, t, u);
  19210. } else "in" /* Operator.IN */ !== o && "not-in" /* Operator.NOT_IN */ !== o && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== o || kh(u, o),
  19211. a = Xl(n, "where", u,
  19212. /* allowArrays= */ "in" /* Operator.IN */ === o || "not-in" /* Operator.NOT_IN */ === o);
  19213. return bn.create(i, o, a);
  19214. }(t._query, 0, e, t.firestore._databaseId, this._field, this._op, this._value);
  19215. return n;
  19216. }, n;
  19217. }(hh);
  19218. /**
  19219. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  19220. * must contain the specified field and that the value should satisfy the
  19221. * relation constraint provided.
  19222. *
  19223. * @param fieldPath - The path to compare
  19224. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  19225. * "&lt;=", "!=").
  19226. * @param value - The value for comparison
  19227. * @returns The created {@link QueryFieldFilterConstraint}.
  19228. */ function ph(t, e, n) {
  19229. var r = e, i = sh("where", t);
  19230. return dh._create(i, r, n);
  19231. }
  19232. /**
  19233. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  19234. * returned by a Firestore query by performing the logical OR or AND of multiple
  19235. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  19236. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  19237. * {@link and} and can then be passed to {@link (query:1)} to create a new query
  19238. * instance that also contains the `QueryCompositeFilterConstraint`.
  19239. */ var vh = /** @class */ function(e) {
  19240. /**
  19241. * @internal
  19242. */
  19243. function n(
  19244. /** The type of this query constraint */
  19245. t, n) {
  19246. var r = this;
  19247. return (r = e.call(this) || this).type = t, r._queryConstraints = n, r;
  19248. }
  19249. return t(n, e), n._create = function(t, e) {
  19250. return new n(t, e);
  19251. }, n.prototype._parse = function(t) {
  19252. var e = this._queryConstraints.map((function(e) {
  19253. return e._parse(t);
  19254. })).filter((function(t) {
  19255. return t.getFilters().length > 0;
  19256. }));
  19257. return 1 === e.length ? e[0] : In.create(e, this._getOperator());
  19258. }, n.prototype._apply = function(t) {
  19259. var e = this._parse(t);
  19260. return 0 === e.getFilters().length ? t : (function(t, e) {
  19261. for (var n = t, r = 0, i = e.getFlattenedFilters(); r < i.length; r++) {
  19262. var o = i[r];
  19263. Oh(n, o), n = er(n, o);
  19264. }
  19265. }(t._query, e), new tl(t.firestore, t.converter, er(t._query, e)));
  19266. }, n.prototype._getQueryConstraints = function() {
  19267. return this._queryConstraints;
  19268. }, n.prototype._getOperator = function() {
  19269. return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
  19270. }, n;
  19271. }(lh);
  19272. /**
  19273. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  19274. * the given filter constraints. A disjunction filter includes a document if it
  19275. * satisfies any of the given filters.
  19276. *
  19277. * @param queryConstraints - Optional. The list of
  19278. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  19279. * created with calls to {@link where}, {@link or}, or {@link and}.
  19280. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  19281. */ function mh() {
  19282. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  19283. // Only support QueryFilterConstraints
  19284. return t.forEach((function(t) {
  19285. return Ph("or", t);
  19286. })), vh._create("or" /* CompositeOperator.OR */ , t)
  19287. /**
  19288. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  19289. * the given filter constraints. A conjunction filter includes a document if it
  19290. * satisfies all of the given filters.
  19291. *
  19292. * @param queryConstraints - Optional. The list of
  19293. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  19294. * created with calls to {@link where}, {@link or}, or {@link and}.
  19295. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  19296. */;
  19297. }
  19298. function yh() {
  19299. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  19300. // Only support QueryFilterConstraints
  19301. return t.forEach((function(t) {
  19302. return Ph("and", t);
  19303. })), vh._create("and" /* CompositeOperator.AND */ , t)
  19304. /**
  19305. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  19306. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  19307. * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query
  19308. * instance that also contains this `QueryOrderByConstraint`.
  19309. *
  19310. * Note: Documents that do not contain the orderBy field will not be present in
  19311. * the query result.
  19312. */;
  19313. }
  19314. var gh = /** @class */ function(e) {
  19315. /**
  19316. * @internal
  19317. */
  19318. function n(t, n) {
  19319. var r = this;
  19320. return (r = e.call(this) || this)._field = t, r._direction = n,
  19321. /** The type of this query constraint */
  19322. r.type = "orderBy", r;
  19323. }
  19324. return t(n, e), n._create = function(t, e) {
  19325. return new n(t, e);
  19326. }, n.prototype._apply = function(t) {
  19327. var e = function(t, e, n) {
  19328. if (null !== t.startAt) throw new Q(K.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
  19329. if (null !== t.endAt) throw new Q(K.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
  19330. var r = new yn(e, n);
  19331. return function(t, e) {
  19332. if (null === Xn(t)) {
  19333. // This is the first order by. It must match any inequality.
  19334. var n = Jn(t);
  19335. null !== n && Fh(t, n, e.field);
  19336. }
  19337. }(t, r), r;
  19338. }(t._query, this._field, this._direction);
  19339. return new tl(t.firestore, t.converter, function(t, e) {
  19340. // TODO(dimond): validate that orderBy does not list the same key twice.
  19341. var n = t.explicitOrderBy.concat([ e ]);
  19342. return new Qn(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  19343. }(t._query, e));
  19344. }, n;
  19345. }(hh);
  19346. /**
  19347. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  19348. * specified field, optionally in descending order instead of ascending.
  19349. *
  19350. * Note: Documents that do not contain the specified field will not be present
  19351. * in the query result.
  19352. *
  19353. * @param fieldPath - The field to sort by.
  19354. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  19355. * not specified, order will be ascending.
  19356. * @returns The created {@link QueryOrderByConstraint}.
  19357. */ function wh(t, e) {
  19358. void 0 === e && (e = "asc");
  19359. var n = e, r = sh("orderBy", t);
  19360. return gh._create(r, n);
  19361. }
  19362. /**
  19363. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  19364. * a Firestore query.
  19365. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  19366. * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new
  19367. * query instance that also contains this `QueryLimitConstraint`.
  19368. */ var bh = /** @class */ function(e) {
  19369. /**
  19370. * @internal
  19371. */
  19372. function n(
  19373. /** The type of this query constraint */
  19374. t, n, r) {
  19375. var i = this;
  19376. return (i = e.call(this) || this).type = t, i._limit = n, i._limitType = r, i;
  19377. }
  19378. return t(n, e), n._create = function(t, e, r) {
  19379. return new n(t, e, r);
  19380. }, n.prototype._apply = function(t) {
  19381. return new tl(t.firestore, t.converter, nr(t._query, this._limit, this._limitType));
  19382. }, n;
  19383. }(hh);
  19384. /**
  19385. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  19386. * documents.
  19387. *
  19388. * @param limit - The maximum number of items to return.
  19389. * @returns The created {@link QueryLimitConstraint}.
  19390. */ function Ih(t) {
  19391. return Yc("limit", t), bh._create("limit", t, "F" /* LimitType.First */)
  19392. /**
  19393. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  19394. * documents.
  19395. *
  19396. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  19397. * otherwise an exception will be thrown during execution.
  19398. *
  19399. * @param limit - The maximum number of items to return.
  19400. * @returns The created {@link QueryLimitConstraint}.
  19401. */;
  19402. }
  19403. function Eh(t) {
  19404. return Yc("limitToLast", t), bh._create("limitToLast", t, "L" /* LimitType.Last */)
  19405. /**
  19406. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  19407. * result set returned by a Firestore query.
  19408. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  19409. * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a
  19410. * new query instance that also contains this `QueryStartAtConstraint`.
  19411. */;
  19412. }
  19413. var Th = /** @class */ function(e) {
  19414. /**
  19415. * @internal
  19416. */
  19417. function n(
  19418. /** The type of this query constraint */
  19419. t, n, r) {
  19420. var i = this;
  19421. return (i = e.call(this) || this).type = t, i._docOrFields = n, i._inclusive = r,
  19422. i;
  19423. }
  19424. return t(n, e), n._create = function(t, e, r) {
  19425. return new n(t, e, r);
  19426. }, n.prototype._apply = function(t) {
  19427. var e = Nh(t, this.type, this._docOrFields, this._inclusive);
  19428. return new tl(t.firestore, t.converter, function(t, e) {
  19429. return new Qn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);
  19430. }(t._query, e));
  19431. }, n;
  19432. }(hh);
  19433. function Sh() {
  19434. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  19435. return Th._create("startAt", t,
  19436. /*inclusive=*/ !0);
  19437. }
  19438. function _h() {
  19439. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  19440. return Th._create("startAfter", t,
  19441. /*inclusive=*/ !1);
  19442. }
  19443. /**
  19444. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  19445. * result set returned by a Firestore query.
  19446. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  19447. * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new
  19448. * query instance that also contains this `QueryEndAtConstraint`.
  19449. */ var Dh = /** @class */ function(e) {
  19450. /**
  19451. * @internal
  19452. */
  19453. function n(
  19454. /** The type of this query constraint */
  19455. t, n, r) {
  19456. var i = this;
  19457. return (i = e.call(this) || this).type = t, i._docOrFields = n, i._inclusive = r,
  19458. i;
  19459. }
  19460. return t(n, e), n._create = function(t, e, r) {
  19461. return new n(t, e, r);
  19462. }, n.prototype._apply = function(t) {
  19463. var e = Nh(t, this.type, this._docOrFields, this._inclusive);
  19464. return new tl(t.firestore, t.converter, function(t, e) {
  19465. return new Qn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);
  19466. }(t._query, e));
  19467. }, n;
  19468. }(hh);
  19469. function Ch() {
  19470. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  19471. return Dh._create("endBefore", t,
  19472. /*inclusive=*/ !1);
  19473. }
  19474. function xh() {
  19475. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  19476. return Dh._create("endAt", t,
  19477. /*inclusive=*/ !0);
  19478. }
  19479. /** Helper function to create a bound from a document or fields */ function Nh(t, e, n, r) {
  19480. if (n[0] = v(n[0]), n[0] instanceof uh) return function(t, e, n, r, i) {
  19481. if (!r) throw new Q(K.NOT_FOUND, "Can't use a DocumentSnapshot that doesn't exist for ".concat(n, "()."));
  19482. // Because people expect to continue/end a query at the exact document
  19483. // provided, we need to use the implicit sort order rather than the explicit
  19484. // sort order, because it's guaranteed to contain the document key. That way
  19485. // the position becomes unambiguous and the query continues/ends exactly at
  19486. // the provided document. Without the key (by using the explicit sort
  19487. // orders), multiple documents could match the position, yielding duplicate
  19488. // results.
  19489. for (var o = [], u = 0, a = $n(t); u < a.length; u++) {
  19490. var s = a[u];
  19491. if (s.field.isKeyField()) o.push(Ze(e, r.key)); else {
  19492. var c = r.data.field(s.field);
  19493. if (Me(c)) throw new Q(K.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + s.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
  19494. if (null === c) {
  19495. var l = s.field.canonicalString();
  19496. throw new Q(K.INVALID_ARGUMENT, "Invalid query. You are trying to start or end a query using a document for which the field '".concat(l, "' (used as the orderBy) does not exist."));
  19497. }
  19498. o.push(c);
  19499. }
  19500. }
  19501. return new pn(o, i);
  19502. }(t._query, t.firestore._databaseId, e, n[0]._document, r);
  19503. var i = Bl(t.firestore);
  19504. return function(t, e, n, r, i, o) {
  19505. // Use explicit order by's because it has to match the query the user made
  19506. var u = t.explicitOrderBy;
  19507. if (i.length > u.length) throw new Q(K.INVALID_ARGUMENT, "Too many arguments provided to ".concat(r, "(). The number of arguments must be less than or equal to the number of orderBy() clauses"));
  19508. for (var a = [], s = 0; s < i.length; s++) {
  19509. var c = i[s];
  19510. if (u[s].field.isKeyField()) {
  19511. if ("string" != typeof c) throw new Q(K.INVALID_ARGUMENT, "Invalid query. Expected a string for document ID in ".concat(r, "(), but got a ").concat(typeof c));
  19512. if (!Zn(t) && -1 !== c.indexOf("/")) throw new Q(K.INVALID_ARGUMENT, "Invalid query. When querying a collection and ordering by documentId(), the value passed to ".concat(r, "() must be a plain document ID, but '").concat(c, "' contains a slash."));
  19513. var l = t.path.child(ht.fromString(c));
  19514. if (!pt.isDocumentKey(l)) throw new Q(K.INVALID_ARGUMENT, "Invalid query. When querying a collection group and ordering by documentId(), the value passed to ".concat(r, "() must result in a valid document path, but '").concat(l, "' is not because it contains an odd number of segments."));
  19515. var h = new pt(l);
  19516. a.push(Ze(e, h));
  19517. } else {
  19518. var f = Xl(n, r, c);
  19519. a.push(f);
  19520. }
  19521. }
  19522. return new pn(a, o);
  19523. }(t._query, t.firestore._databaseId, i, e, n, r);
  19524. }
  19525. function Ah(t, e, n) {
  19526. if ("string" == typeof (n = v(n))) {
  19527. if ("" === n) throw new Q(K.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");
  19528. if (!Zn(e) && -1 !== n.indexOf("/")) throw new Q(K.INVALID_ARGUMENT, "Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '".concat(n, "' contains a '/' character."));
  19529. var r = e.path.child(ht.fromString(n));
  19530. if (!pt.isDocumentKey(r)) throw new Q(K.INVALID_ARGUMENT, "Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '".concat(r, "' is not because it has an odd number of segments (").concat(r.length, ")."));
  19531. return Ze(t, new pt(r));
  19532. }
  19533. if (n instanceof $c) return Ze(t, n._key);
  19534. throw new Q(K.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ".concat(Wc(n), "."));
  19535. }
  19536. /**
  19537. * Validates that the value passed into a disjunctive filter satisfies all
  19538. * array requirements.
  19539. */ function kh(t, e) {
  19540. if (!Array.isArray(t) || 0 === t.length) throw new Q(K.INVALID_ARGUMENT, "Invalid Query. A non-empty array is required for '".concat(e.toString(), "' filters."));
  19541. }
  19542. /**
  19543. * Given an operator, returns the set of operators that cannot be used with it.
  19544. *
  19545. * This is not a comprehensive check, and this function should be removed in the
  19546. * long term. Validations should occur in the Firestore backend.
  19547. *
  19548. * Operators in a query must adhere to the following set of rules:
  19549. * 1. Only one inequality per query.
  19550. * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.
  19551. */ function Oh(t, e) {
  19552. if (e.isInequality()) {
  19553. var n = Jn(t), r = e.field;
  19554. if (null !== n && !n.isEqual(r)) throw new Q(K.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 '".concat(n.toString(), "' and '").concat(r.toString(), "'"));
  19555. var i = Xn(t);
  19556. null !== i && Fh(t, r, i);
  19557. }
  19558. var o = function(t, e) {
  19559. for (var n = 0, r = t; n < r.length; n++) for (var i = 0, o = r[n].getFlattenedFilters(); i < o.length; i++) {
  19560. var u = o[i];
  19561. if (e.indexOf(u.op) >= 0) return u.op;
  19562. }
  19563. return null;
  19564. }(t.filters, function(t) {
  19565. switch (t) {
  19566. case "!=" /* Operator.NOT_EQUAL */ :
  19567. return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ];
  19568. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  19569. case "in" /* Operator.IN */ :
  19570. return [ "not-in" /* Operator.NOT_IN */ ];
  19571. case "not-in" /* Operator.NOT_IN */ :
  19572. return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ];
  19573. default:
  19574. return [];
  19575. }
  19576. }(e.op));
  19577. if (null !== o)
  19578. // Special case when it's a duplicate op to give a slightly clearer error message.
  19579. throw o === e.op ? new Q(K.INVALID_ARGUMENT, "Invalid query. You cannot use more than one '".concat(e.op.toString(), "' filter.")) : new Q(K.INVALID_ARGUMENT, "Invalid query. You cannot use '".concat(e.op.toString(), "' filters with '").concat(o.toString(), "' filters."));
  19580. }
  19581. function Fh(t, e, n) {
  19582. if (!n.isEqual(e)) throw new Q(K.INVALID_ARGUMENT, "Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '".concat(e.toString(), "' and so you must also use '").concat(e.toString(), "' as your first argument to orderBy(), but your first orderBy() is on field '").concat(n.toString(), "' instead."));
  19583. }
  19584. function Ph(t, e) {
  19585. if (!(e instanceof dh || e instanceof vh)) throw new Q(K.INVALID_ARGUMENT, "Function ".concat(t, "() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'."));
  19586. }
  19587. var Rh = /** @class */ function() {
  19588. function t() {}
  19589. return t.prototype.convertValue = function(t, e) {
  19590. switch (void 0 === e && (e = "none"), je(t)) {
  19591. case 0 /* TypeOrder.NullValue */ :
  19592. return null;
  19593. case 1 /* TypeOrder.BooleanValue */ :
  19594. return t.booleanValue;
  19595. case 2 /* TypeOrder.NumberValue */ :
  19596. return Re(t.integerValue || t.doubleValue);
  19597. case 3 /* TypeOrder.TimestampValue */ :
  19598. return this.convertTimestamp(t.timestampValue);
  19599. case 4 /* TypeOrder.ServerTimestampValue */ :
  19600. return this.convertServerTimestamp(t, e);
  19601. case 5 /* TypeOrder.StringValue */ :
  19602. return t.stringValue;
  19603. case 6 /* TypeOrder.BlobValue */ :
  19604. return this.convertBytes(Ve(t.bytesValue));
  19605. case 7 /* TypeOrder.RefValue */ :
  19606. return this.convertReference(t.referenceValue);
  19607. case 8 /* TypeOrder.GeoPointValue */ :
  19608. return this.convertGeoPoint(t.geoPointValue);
  19609. case 9 /* TypeOrder.ArrayValue */ :
  19610. return this.convertArray(t.arrayValue, e);
  19611. case 10 /* TypeOrder.ObjectValue */ :
  19612. return this.convertObject(t.mapValue, e);
  19613. default:
  19614. throw U();
  19615. }
  19616. }, t.prototype.convertObject = function(t, e) {
  19617. return this.convertObjectMap(t.fields, e);
  19618. },
  19619. /**
  19620. * @internal
  19621. */
  19622. t.prototype.convertObjectMap = function(t, e) {
  19623. var n = this;
  19624. void 0 === e && (e = "none");
  19625. var r = {};
  19626. return Ie(t, (function(t, i) {
  19627. r[t] = n.convertValue(i, e);
  19628. })), r;
  19629. }, t.prototype.convertGeoPoint = function(t) {
  19630. return new Fl(Re(t.latitude), Re(t.longitude));
  19631. }, t.prototype.convertArray = function(t, e) {
  19632. var n = this;
  19633. return (t.values || []).map((function(t) {
  19634. return n.convertValue(t, e);
  19635. }));
  19636. }, t.prototype.convertServerTimestamp = function(t, e) {
  19637. switch (e) {
  19638. case "previous":
  19639. var n = Le(t);
  19640. return null == n ? null : this.convertValue(n, e);
  19641. case "estimate":
  19642. return this.convertTimestamp(qe(t));
  19643. default:
  19644. return null;
  19645. }
  19646. }, t.prototype.convertTimestamp = function(t) {
  19647. var e = Pe(t);
  19648. return new st(e.seconds, e.nanos);
  19649. }, t.prototype.convertDocumentKey = function(t, e) {
  19650. var n = ht.fromString(t);
  19651. z(uo(n));
  19652. var r = new Ue(n.get(1), n.get(3)), i = new pt(n.popFirst(5));
  19653. return r.isEqual(e) ||
  19654. // TODO(b/64130202): Somehow support foreign references.
  19655. L("Document ".concat(i, " contains a document reference within a different database (").concat(r.projectId, "/").concat(r.database, ") which is not supported. It will be treated as a reference in the current database (").concat(e.projectId, "/").concat(e.database, ") instead.")),
  19656. i;
  19657. }, t;
  19658. }();
  19659. /**
  19660. * @license
  19661. * Copyright 2020 Google LLC
  19662. *
  19663. * Licensed under the Apache License, Version 2.0 (the "License");
  19664. * you may not use this file except in compliance with the License.
  19665. * You may obtain a copy of the License at
  19666. *
  19667. * http://www.apache.org/licenses/LICENSE-2.0
  19668. *
  19669. * Unless required by applicable law or agreed to in writing, software
  19670. * distributed under the License is distributed on an "AS IS" BASIS,
  19671. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19672. * See the License for the specific language governing permissions and
  19673. * limitations under the License.
  19674. */
  19675. /**
  19676. * Converts custom model object of type T into `DocumentData` by applying the
  19677. * converter if it exists.
  19678. *
  19679. * This function is used when converting user objects to `DocumentData`
  19680. * because we want to provide the user with a more specific error message if
  19681. * their `set()` or fails due to invalid data originating from a `toFirestore()`
  19682. * call.
  19683. */ function Vh(t, e, n) {
  19684. // Cast to `any` in order to satisfy the union type constraint on
  19685. // toFirestore().
  19686. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19687. return t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e;
  19688. }
  19689. var Mh = /** @class */ function(e) {
  19690. function n(t) {
  19691. var n = this;
  19692. return (n = e.call(this) || this).firestore = t, n;
  19693. }
  19694. return t(n, e), n.prototype.convertBytes = function(t) {
  19695. return new Nl(t);
  19696. }, n.prototype.convertReference = function(t) {
  19697. var e = this.convertDocumentKey(t, this.firestore._databaseId);
  19698. return new $c(this.firestore, /* converter= */ null, e);
  19699. }, n;
  19700. }(Rh);
  19701. /**
  19702. * @license
  19703. * Copyright 2022 Google LLC
  19704. *
  19705. * Licensed under the Apache License, Version 2.0 (the "License");
  19706. * you may not use this file except in compliance with the License.
  19707. * You may obtain a copy of the License at
  19708. *
  19709. * http://www.apache.org/licenses/LICENSE-2.0
  19710. *
  19711. * Unless required by applicable law or agreed to in writing, software
  19712. * distributed under the License is distributed on an "AS IS" BASIS,
  19713. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19714. * See the License for the specific language governing permissions and
  19715. * limitations under the License.
  19716. */
  19717. /**
  19718. * Create an AggregateField object that can be used to compute the sum of
  19719. * a specified field over a range of documents in the result set of a query.
  19720. * @param field Specifies the field to sum across the result set.
  19721. * @internal TODO (sum/avg) remove when public
  19722. */ function Lh(t) {
  19723. return new Cl("sum", eh("sum", t));
  19724. }
  19725. /**
  19726. * Create an AggregateField object that can be used to compute the average of
  19727. * a specified field over a range of documents in the result set of a query.
  19728. * @param field Specifies the field to average across the result set.
  19729. * @internal TODO (sum/avg) remove when public
  19730. */ function qh(t) {
  19731. return new Cl("avg", eh("average", t));
  19732. }
  19733. /**
  19734. * Create an AggregateField object that can be used to compute the count of
  19735. * documents in the result set of a query.
  19736. * @internal TODO (sum/avg) remove when public
  19737. */ function Bh() {
  19738. return new Cl("count");
  19739. }
  19740. /**
  19741. * Compares two 'AggregateField` instances for equality.
  19742. *
  19743. * @param left Compare this AggregateField to the `right`.
  19744. * @param right Compare this AggregateField to the `left`.
  19745. * @internal TODO (sum/avg) remove when public
  19746. */ function Uh(t, e) {
  19747. var n, r;
  19748. return t instanceof Cl && e instanceof Cl && t._aggregateType === e._aggregateType && (null === (n = t._internalFieldPath) || void 0 === n ? void 0 : n.canonicalString()) === (null === (r = e._internalFieldPath) || void 0 === r ? void 0 : r.canonicalString());
  19749. }
  19750. /**
  19751. * Compares two `AggregateQuerySnapshot` instances for equality.
  19752. *
  19753. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  19754. * underlying queries that compare equal, and the same data.
  19755. *
  19756. * @param left - The first `AggregateQuerySnapshot` to compare.
  19757. * @param right - The second `AggregateQuerySnapshot` to compare.
  19758. *
  19759. * @returns `true` if the objects are "equal", as defined above, or `false`
  19760. * otherwise.
  19761. */ function zh(t, e) {
  19762. return ul(t.query, e.query) && g(t.data(), e.data());
  19763. }
  19764. /**
  19765. * @license
  19766. * Copyright 2020 Google LLC
  19767. *
  19768. * Licensed under the Apache License, Version 2.0 (the "License");
  19769. * you may not use this file except in compliance with the License.
  19770. * You may obtain a copy of the License at
  19771. *
  19772. * http://www.apache.org/licenses/LICENSE-2.0
  19773. *
  19774. * Unless required by applicable law or agreed to in writing, software
  19775. * distributed under the License is distributed on an "AS IS" BASIS,
  19776. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19777. * See the License for the specific language governing permissions and
  19778. * limitations under the License.
  19779. */
  19780. /**
  19781. * Metadata about a snapshot, describing the state of the snapshot.
  19782. */ var Gh = /** @class */ function() {
  19783. /** @hideconstructor */
  19784. function t(t, e) {
  19785. this.hasPendingWrites = t, this.fromCache = e
  19786. /**
  19787. * Returns true if this `SnapshotMetadata` is equal to the provided one.
  19788. *
  19789. * @param other - The `SnapshotMetadata` to compare against.
  19790. * @returns true if this `SnapshotMetadata` is equal to the provided one.
  19791. */;
  19792. }
  19793. return t.prototype.isEqual = function(t) {
  19794. return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;
  19795. }, t;
  19796. }(), jh = /** @class */ function(e) {
  19797. /** @hideconstructor protected */
  19798. function n(t, n, r, i, o, u) {
  19799. var a = this;
  19800. return (a = e.call(this, t, n, r, i, u) || this)._firestore = t, a._firestoreImpl = t,
  19801. a.metadata = o, a;
  19802. }
  19803. /**
  19804. * Returns whether or not the data exists. True if the document exists.
  19805. */ return t(n, e), n.prototype.exists = function() {
  19806. return e.prototype.exists.call(this);
  19807. },
  19808. /**
  19809. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  19810. * the document doesn't exist.
  19811. *
  19812. * By default, `serverTimestamp()` values that have not yet been
  19813. * set to their final value will be returned as `null`. You can override
  19814. * this by passing an options object.
  19815. *
  19816. * @param options - An options object to configure how data is retrieved from
  19817. * the snapshot (for example the desired behavior for server timestamps that
  19818. * have not yet been set to their final value).
  19819. * @returns An `Object` containing all fields in the document or `undefined` if
  19820. * the document doesn't exist.
  19821. */
  19822. n.prototype.data = function(t) {
  19823. if (void 0 === t && (t = {}), this._document) {
  19824. if (this._converter) {
  19825. // We only want to use the converter and create a new DocumentSnapshot
  19826. // if a converter has been provided.
  19827. var e = new Kh(this._firestore, this._userDataWriter, this._key, this._document, this.metadata,
  19828. /* converter= */ null);
  19829. return this._converter.fromFirestore(e, t);
  19830. }
  19831. return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);
  19832. }
  19833. },
  19834. /**
  19835. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  19836. * document or field doesn't exist.
  19837. *
  19838. * By default, a `serverTimestamp()` that has not yet been set to
  19839. * its final value will be returned as `null`. You can override this by
  19840. * passing an options object.
  19841. *
  19842. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  19843. * field.
  19844. * @param options - An options object to configure how the field is retrieved
  19845. * from the snapshot (for example the desired behavior for server timestamps
  19846. * that have not yet been set to their final value).
  19847. * @returns The data at the specified field location or undefined if no such
  19848. * field exists in the document.
  19849. */
  19850. // We are using `any` here to avoid an explicit cast by our users.
  19851. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19852. n.prototype.get = function(t, e) {
  19853. if (void 0 === e && (e = {}), this._document) {
  19854. var n = this._document.data.field(sh("DocumentSnapshot.get", t));
  19855. if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);
  19856. }
  19857. }, n;
  19858. }(uh), Kh = /** @class */ function(e) {
  19859. function n() {
  19860. return null !== e && e.apply(this, arguments) || this;
  19861. }
  19862. /**
  19863. * Retrieves all fields in the document as an `Object`.
  19864. *
  19865. * By default, `serverTimestamp()` values that have not yet been
  19866. * set to their final value will be returned as `null`. You can override
  19867. * this by passing an options object.
  19868. *
  19869. * @override
  19870. * @param options - An options object to configure how data is retrieved from
  19871. * the snapshot (for example the desired behavior for server timestamps that
  19872. * have not yet been set to their final value).
  19873. * @returns An `Object` containing all fields in the document.
  19874. */ return t(n, e), n.prototype.data = function(t) {
  19875. return void 0 === t && (t = {}), e.prototype.data.call(this, t);
  19876. }, n;
  19877. }(jh), Qh = /** @class */ function() {
  19878. /** @hideconstructor */
  19879. function t(t, e, n, r) {
  19880. this._firestore = t, this._userDataWriter = e, this._snapshot = r, this.metadata = new Gh(r.hasPendingWrites, r.fromCache),
  19881. this.query = n;
  19882. }
  19883. return Object.defineProperty(t.prototype, "docs", {
  19884. /** An array of all the documents in the `QuerySnapshot`. */ get: function() {
  19885. var t = [];
  19886. return this.forEach((function(e) {
  19887. return t.push(e);
  19888. })), t;
  19889. },
  19890. enumerable: !1,
  19891. configurable: !0
  19892. }), Object.defineProperty(t.prototype, "size", {
  19893. /** The number of documents in the `QuerySnapshot`. */ get: function() {
  19894. return this._snapshot.docs.size;
  19895. },
  19896. enumerable: !1,
  19897. configurable: !0
  19898. }), Object.defineProperty(t.prototype, "empty", {
  19899. /** True if there are no documents in the `QuerySnapshot`. */ get: function() {
  19900. return 0 === this.size;
  19901. },
  19902. enumerable: !1,
  19903. configurable: !0
  19904. }),
  19905. /**
  19906. * Enumerates all of the documents in the `QuerySnapshot`.
  19907. *
  19908. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  19909. * each document in the snapshot.
  19910. * @param thisArg - The `this` binding for the callback.
  19911. */
  19912. t.prototype.forEach = function(t, e) {
  19913. var n = this;
  19914. this._snapshot.docs.forEach((function(r) {
  19915. t.call(e, new Kh(n._firestore, n._userDataWriter, r.key, r, new Gh(n._snapshot.mutatedKeys.has(r.key), n._snapshot.fromCache), n.query.converter));
  19916. }));
  19917. },
  19918. /**
  19919. * Returns an array of the documents changes since the last snapshot. If this
  19920. * is the first snapshot, all documents will be in the list as 'added'
  19921. * changes.
  19922. *
  19923. * @param options - `SnapshotListenOptions` that control whether metadata-only
  19924. * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
  19925. * snapshot events.
  19926. */
  19927. t.prototype.docChanges = function(t) {
  19928. void 0 === t && (t = {});
  19929. var e = !!t.includeMetadataChanges;
  19930. if (e && this._snapshot.excludesMetadataChanges) throw new Q(K.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
  19931. return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges =
  19932. /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */
  19933. function(t, e) {
  19934. if (t._snapshot.oldDocs.isEmpty()) {
  19935. var n = 0;
  19936. return t._snapshot.docChanges.map((function(e) {
  19937. var r = new Kh(t._firestore, t._userDataWriter, e.doc.key, e.doc, new Gh(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);
  19938. return e.doc, {
  19939. type: "added",
  19940. doc: r,
  19941. oldIndex: -1,
  19942. newIndex: n++
  19943. };
  19944. }));
  19945. }
  19946. // A `DocumentSet` that is updated incrementally as changes are applied to use
  19947. // to lookup the index of a document.
  19948. var r = t._snapshot.oldDocs;
  19949. return t._snapshot.docChanges.filter((function(t) {
  19950. return e || 3 /* ChangeType.Metadata */ !== t.type;
  19951. })).map((function(e) {
  19952. var n = new Kh(t._firestore, t._userDataWriter, e.doc.key, e.doc, new Gh(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter), i = -1, o = -1;
  19953. return 0 /* ChangeType.Added */ !== e.type && (i = r.indexOf(e.doc.key), r = r.delete(e.doc.key)),
  19954. 1 /* ChangeType.Removed */ !== e.type && (o = (r = r.add(e.doc)).indexOf(e.doc.key)),
  19955. {
  19956. type: Wh(e.type),
  19957. doc: n,
  19958. oldIndex: i,
  19959. newIndex: o
  19960. };
  19961. }));
  19962. }(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;
  19963. }, t;
  19964. }();
  19965. /**
  19966. * A `DocumentSnapshot` contains data read from a document in your Firestore
  19967. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  19968. * get a specific field.
  19969. *
  19970. * For a `DocumentSnapshot` that points to a non-existing document, any data
  19971. * access will return 'undefined'. You can use the `exists()` method to
  19972. * explicitly verify a document's existence.
  19973. */ function Wh(t) {
  19974. switch (t) {
  19975. case 0 /* ChangeType.Added */ :
  19976. return "added";
  19977. case 2 /* ChangeType.Modified */ :
  19978. case 3 /* ChangeType.Metadata */ :
  19979. return "modified";
  19980. case 1 /* ChangeType.Removed */ :
  19981. return "removed";
  19982. default:
  19983. return U();
  19984. }
  19985. }
  19986. // TODO(firestoreexp): Add tests for snapshotEqual with different snapshot
  19987. // metadata
  19988. /**
  19989. * Returns true if the provided snapshots are equal.
  19990. *
  19991. * @param left - A snapshot to compare.
  19992. * @param right - A snapshot to compare.
  19993. * @returns true if the snapshots are equal.
  19994. */ function Hh(t, e) {
  19995. return t instanceof jh && e instanceof jh ? 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 Qh && e instanceof Qh && t._firestore === e._firestore && ul(t.query, e.query) && t.metadata.isEqual(e.metadata) && t._snapshot.isEqual(e._snapshot);
  19996. }
  19997. /**
  19998. * @license
  19999. * Copyright 2020 Google LLC
  20000. *
  20001. * Licensed under the Apache License, Version 2.0 (the "License");
  20002. * you may not use this file except in compliance with the License.
  20003. * You may obtain a copy of the License at
  20004. *
  20005. * http://www.apache.org/licenses/LICENSE-2.0
  20006. *
  20007. * Unless required by applicable law or agreed to in writing, software
  20008. * distributed under the License is distributed on an "AS IS" BASIS,
  20009. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20010. * See the License for the specific language governing permissions and
  20011. * limitations under the License.
  20012. */
  20013. /**
  20014. * Reads the document referred to by this `DocumentReference`.
  20015. *
  20016. * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting
  20017. * for data from the server, but it may return cached data or fail if you are
  20018. * offline and the server cannot be reached. To specify this behavior, invoke
  20019. * {@link getDocFromCache} or {@link getDocFromServer}.
  20020. *
  20021. * @param reference - The reference of the document to fetch.
  20022. * @returns A Promise resolved with a `DocumentSnapshot` containing the
  20023. * current document contents.
  20024. */ function Yh(t) {
  20025. t = Hc(t, $c);
  20026. var e = Hc(t.firestore, hl);
  20027. return qc(pl(e), t._key).then((function(n) {
  20028. return lf(e, t, n);
  20029. }));
  20030. }
  20031. var Xh = /** @class */ function(e) {
  20032. function n(t) {
  20033. var n = this;
  20034. return (n = e.call(this) || this).firestore = t, n;
  20035. }
  20036. return t(n, e), n.prototype.convertBytes = function(t) {
  20037. return new Nl(t);
  20038. }, n.prototype.convertReference = function(t) {
  20039. var e = this.convertDocumentKey(t, this.firestore._databaseId);
  20040. return new $c(this.firestore, /* converter= */ null, e);
  20041. }, n;
  20042. }(Rh);
  20043. /**
  20044. * Reads the document referred to by this `DocumentReference` from cache.
  20045. * Returns an error if the document is not currently cached.
  20046. *
  20047. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  20048. * current document contents.
  20049. */ function Jh(t) {
  20050. t = Hc(t, $c);
  20051. var r = Hc(t.firestore, hl), i = pl(r), o = new Xh(r);
  20052. return function(t, r) {
  20053. var i = this, o = new W;
  20054. return t.asyncQueue.enqueueAndForget((function() {
  20055. return e(i, void 0, void 0, (function() {
  20056. var i;
  20057. return n(this, (function(u) {
  20058. switch (u.label) {
  20059. case 0:
  20060. return i = function(t, r, i) {
  20061. return e(this, void 0, void 0, (function() {
  20062. var e, o, u;
  20063. return n(this, (function(n) {
  20064. switch (n.label) {
  20065. case 0:
  20066. return n.trys.push([ 0, 2, , 3 ]), [ 4 /*yield*/ , function(t, e) {
  20067. var n = j(t);
  20068. return n.persistence.runTransaction("read document", "readonly", (function(t) {
  20069. return n.localDocuments.getDocument(t, e);
  20070. }));
  20071. }(t, r) ];
  20072. case 1:
  20073. return (e = n.sent()).isFoundDocument() ? i.resolve(e) : e.isNoDocument() ? i.resolve(null) : i.reject(new Q(K.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.)")),
  20074. [ 3 /*break*/ , 3 ];
  20075. case 2:
  20076. return o = n.sent(), u = ys(o, "Failed to get document '".concat(r, " from cache")),
  20077. i.reject(u), [ 3 /*break*/ , 3 ];
  20078. case 3:
  20079. return [ 2 /*return*/ ];
  20080. }
  20081. }));
  20082. }));
  20083. }, [ 4 /*yield*/ , Pc(t) ];
  20084. case 1:
  20085. return [ 2 /*return*/ , i.apply(void 0, [ u.sent(), r, o ]) ];
  20086. }
  20087. }));
  20088. }));
  20089. })), o.promise;
  20090. }(i, t._key).then((function(e) {
  20091. return new jh(r, o, t._key, e, new Gh(null !== e && e.hasLocalMutations,
  20092. /* fromCache= */ !0), t.converter);
  20093. }));
  20094. }
  20095. /**
  20096. * Reads the document referred to by this `DocumentReference` from the server.
  20097. * Returns an error if the network is not available.
  20098. *
  20099. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  20100. * current document contents.
  20101. */ function Zh(t) {
  20102. t = Hc(t, $c);
  20103. var e = Hc(t.firestore, hl);
  20104. return qc(pl(e), t._key, {
  20105. source: "server"
  20106. }).then((function(n) {
  20107. return lf(e, t, n);
  20108. }));
  20109. }
  20110. /**
  20111. * Executes the query and returns the results as a `QuerySnapshot`.
  20112. *
  20113. * Note: `getDocs()` attempts to provide up-to-date data when possible by
  20114. * waiting for data from the server, but it may return cached data or fail if
  20115. * you are offline and the server cannot be reached. To specify this behavior,
  20116. * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
  20117. *
  20118. * @returns A `Promise` that will be resolved with the results of the query.
  20119. */ function $h(t) {
  20120. t = Hc(t, tl);
  20121. var e = Hc(t.firestore, hl), n = pl(e), r = new Xh(e);
  20122. return ch(t._query), Bc(n, t._query).then((function(n) {
  20123. return new Qh(e, r, t, n);
  20124. }))
  20125. /**
  20126. * Executes the query and returns the results as a `QuerySnapshot` from cache.
  20127. * Returns an empty result set if no documents matching the query are currently
  20128. * cached.
  20129. *
  20130. * @returns A `Promise` that will be resolved with the results of the query.
  20131. */;
  20132. }
  20133. function tf(t) {
  20134. t = Hc(t, tl);
  20135. var r = Hc(t.firestore, hl), i = pl(r), o = new Xh(r);
  20136. return function(t, r) {
  20137. var i = this, o = new W;
  20138. return t.asyncQueue.enqueueAndForget((function() {
  20139. return e(i, void 0, void 0, (function() {
  20140. var i;
  20141. return n(this, (function(u) {
  20142. switch (u.label) {
  20143. case 0:
  20144. return i = function(t, r, i) {
  20145. return e(this, void 0, void 0, (function() {
  20146. var e, o, u, a, s, c;
  20147. return n(this, (function(n) {
  20148. switch (n.label) {
  20149. case 0:
  20150. return n.trys.push([ 0, 2, , 3 ]), [ 4 /*yield*/ , la(t, r,
  20151. /* usePreviousResults= */ !0) ];
  20152. case 1:
  20153. return e = n.sent(), o = new Rs(r, e.ir), u = o.sc(e.documents), a = o.applyChanges(u,
  20154. /* updateLimboDocuments= */ !1), i.resolve(a.snapshot), [ 3 /*break*/ , 3 ];
  20155. case 2:
  20156. return s = n.sent(), c = ys(s, "Failed to execute query '".concat(r, " against cache")),
  20157. i.reject(c), [ 3 /*break*/ , 3 ];
  20158. case 3:
  20159. return [ 2 /*return*/ ];
  20160. }
  20161. }));
  20162. }));
  20163. }, [ 4 /*yield*/ , Pc(t) ];
  20164. case 1:
  20165. return [ 2 /*return*/ , i.apply(void 0, [ u.sent(), r, o ]) ];
  20166. }
  20167. }));
  20168. }));
  20169. })), o.promise;
  20170. }(i, t._query).then((function(e) {
  20171. return new Qh(r, o, t, e);
  20172. }));
  20173. }
  20174. /**
  20175. * Executes the query and returns the results as a `QuerySnapshot` from the
  20176. * server. Returns an error if the network is not available.
  20177. *
  20178. * @returns A `Promise` that will be resolved with the results of the query.
  20179. */ function ef(t) {
  20180. t = Hc(t, tl);
  20181. var e = Hc(t.firestore, hl), n = pl(e), r = new Xh(e);
  20182. return Bc(n, t._query, {
  20183. source: "server"
  20184. }).then((function(n) {
  20185. return new Qh(e, r, t, n);
  20186. }));
  20187. }
  20188. function nf(t, e, n) {
  20189. t = Hc(t, $c);
  20190. var r = Hc(t.firestore, hl), i = Vh(t.converter, e, n);
  20191. return cf(r, [ Ul(Bl(r), "setDoc", t._key, i, null !== t.converter, n).toMutation(t._key, Ur.none()) ]);
  20192. }
  20193. function rf(t, e, n) {
  20194. for (var r = [], i = 3; i < arguments.length; i++) r[i - 3] = arguments[i];
  20195. t = Hc(t, $c);
  20196. var o = Hc(t.firestore, hl), u = Bl(o);
  20197. return cf(o, [ ("string" == typeof (
  20198. // For Compat types, we have to "extract" the underlying types before
  20199. // performing validation.
  20200. e = v(e)) || e instanceof Al ? Yl(u, "updateDoc", t._key, e, n, r) : Hl(u, "updateDoc", t._key, e)).toMutation(t._key, Ur.exists(!0)) ]);
  20201. }
  20202. /**
  20203. * Deletes the document referred to by the specified `DocumentReference`.
  20204. *
  20205. * @param reference - A reference to the document to delete.
  20206. * @returns A Promise resolved once the document has been successfully
  20207. * deleted from the backend (note that it won't resolve while you're offline).
  20208. */ function of(t) {
  20209. return cf(Hc(t.firestore, hl), [ new ni(t._key, Ur.none()) ]);
  20210. }
  20211. /**
  20212. * Add a new document to specified `CollectionReference` with the given data,
  20213. * assigning it a document ID automatically.
  20214. *
  20215. * @param reference - A reference to the collection to add this document to.
  20216. * @param data - An Object containing the data for the new document.
  20217. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  20218. * newly created document after it has been written to the backend (Note that it
  20219. * won't resolve while you're offline).
  20220. */ function uf(t, e) {
  20221. var n = Hc(t.firestore, hl), r = il(t), i = Vh(t.converter, e);
  20222. return cf(n, [ Ul(Bl(t.firestore), "addDoc", r._key, i, null !== t.converter, {}).toMutation(r._key, Ur.exists(!1)) ]).then((function() {
  20223. return r;
  20224. }));
  20225. }
  20226. function af(t) {
  20227. for (var r, i, o, u = [], a = 1; a < arguments.length; a++) u[a - 1] = arguments[a];
  20228. t = v(t);
  20229. var s = {
  20230. includeMetadataChanges: !1
  20231. }, c = 0;
  20232. "object" != typeof u[c] || sl(u[c]) || (s = u[c], c++);
  20233. var l, h, f, d = {
  20234. includeMetadataChanges: s.includeMetadataChanges
  20235. };
  20236. if (sl(u[c])) {
  20237. var p = u[c];
  20238. u[c] = null === (r = p.next) || void 0 === r ? void 0 : r.bind(p), u[c + 1] = null === (i = p.error) || void 0 === i ? void 0 : i.bind(p),
  20239. u[c + 2] = null === (o = p.complete) || void 0 === o ? void 0 : o.bind(p);
  20240. }
  20241. if (t instanceof $c) h = Hc(t.firestore, hl), f = Hn(t._key.path), l = {
  20242. next: function(e) {
  20243. u[c] && u[c](lf(h, t, e));
  20244. },
  20245. error: u[c + 1],
  20246. complete: u[c + 2]
  20247. }; else {
  20248. var m = Hc(t, tl);
  20249. h = Hc(m.firestore, hl), f = m._query;
  20250. var y = new Xh(h);
  20251. l = {
  20252. next: function(t) {
  20253. u[c] && u[c](new Qh(h, y, m, t));
  20254. },
  20255. error: u[c + 1],
  20256. complete: u[c + 2]
  20257. }, ch(t._query);
  20258. }
  20259. return function(t, r, i, o) {
  20260. var u = this, a = new Tc(o), s = new xs(r, a, i);
  20261. return t.asyncQueue.enqueueAndForget((function() {
  20262. return e(u, void 0, void 0, (function() {
  20263. var e;
  20264. return n(this, (function(n) {
  20265. switch (n.label) {
  20266. case 0:
  20267. return e = Ts, [ 4 /*yield*/ , Lc(t) ];
  20268. case 1:
  20269. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), s ]) ];
  20270. }
  20271. }));
  20272. }));
  20273. })), function() {
  20274. a.Dc(), t.asyncQueue.enqueueAndForget((function() {
  20275. return e(u, void 0, void 0, (function() {
  20276. var e;
  20277. return n(this, (function(n) {
  20278. switch (n.label) {
  20279. case 0:
  20280. return e = Ss, [ 4 /*yield*/ , Lc(t) ];
  20281. case 1:
  20282. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), s ]) ];
  20283. }
  20284. }));
  20285. }));
  20286. }));
  20287. };
  20288. }(pl(h), f, d, l);
  20289. }
  20290. function sf(t, r) {
  20291. return function(t, r) {
  20292. var i = this, o = new Tc(r);
  20293. return t.asyncQueue.enqueueAndForget((function() {
  20294. return e(i, void 0, void 0, (function() {
  20295. var e;
  20296. return n(this, (function(n) {
  20297. switch (n.label) {
  20298. case 0:
  20299. return e = function(t, e) {
  20300. j(t).ku.add(e),
  20301. // Immediately fire an initial event, indicating all existing listeners
  20302. // are in-sync.
  20303. e.next();
  20304. }, [ 4 /*yield*/ , Lc(t) ];
  20305. case 1:
  20306. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), o ]) ];
  20307. }
  20308. }));
  20309. }));
  20310. })), function() {
  20311. o.Dc(), t.asyncQueue.enqueueAndForget((function() {
  20312. return e(i, void 0, void 0, (function() {
  20313. var e;
  20314. return n(this, (function(n) {
  20315. switch (n.label) {
  20316. case 0:
  20317. return e = function(t, e) {
  20318. j(t).ku.delete(e);
  20319. }, [ 4 /*yield*/ , Lc(t) ];
  20320. case 1:
  20321. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), o ]) ];
  20322. }
  20323. }));
  20324. }));
  20325. }));
  20326. };
  20327. }(pl(t = Hc(t, hl)), sl(r) ? r : {
  20328. next: r
  20329. });
  20330. }
  20331. /**
  20332. * Locally writes `mutations` on the async queue.
  20333. * @internal
  20334. */ function cf(t, r) {
  20335. return function(t, r) {
  20336. var i = this, o = new W;
  20337. return t.asyncQueue.enqueueAndForget((function() {
  20338. return e(i, void 0, void 0, (function() {
  20339. var e;
  20340. return n(this, (function(n) {
  20341. switch (n.label) {
  20342. case 0:
  20343. return e = zs, [ 4 /*yield*/ , Vc(t) ];
  20344. case 1:
  20345. return [ 2 /*return*/ , e.apply(void 0, [ n.sent(), r, o ]) ];
  20346. }
  20347. }));
  20348. }));
  20349. })), o.promise;
  20350. }(pl(t), r);
  20351. }
  20352. /**
  20353. * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`
  20354. * to a {@link DocumentSnapshot}.
  20355. */ function lf(t, e, n) {
  20356. var r = n.docs.get(e._key), i = new Xh(t);
  20357. return new jh(t, i, e._key, r, new Gh(n.hasPendingWrites, n.fromCache), e.converter);
  20358. }
  20359. /**
  20360. * @license
  20361. * Copyright 2022 Google LLC
  20362. *
  20363. * Licensed under the Apache License, Version 2.0 (the "License");
  20364. * you may not use this file except in compliance with the License.
  20365. * You may obtain a copy of the License at
  20366. *
  20367. * http://www.apache.org/licenses/LICENSE-2.0
  20368. *
  20369. * Unless required by applicable law or agreed to in writing, software
  20370. * distributed under the License is distributed on an "AS IS" BASIS,
  20371. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20372. * See the License for the specific language governing permissions and
  20373. * limitations under the License.
  20374. */
  20375. /**
  20376. * Calculates the number of documents in the result set of the given query,
  20377. * without actually downloading the documents.
  20378. *
  20379. * Using this function to count the documents is efficient because only the
  20380. * final count, not the documents' data, is downloaded. This function can even
  20381. * count the documents if the result set would be prohibitively large to
  20382. * download entirely (e.g. thousands of documents).
  20383. *
  20384. * The result received from the server is presented, unaltered, without
  20385. * considering any local state. That is, documents in the local cache are not
  20386. * taken into consideration, neither are local modifications not yet
  20387. * synchronized with the server. Previously-downloaded results, if any, are not
  20388. * used: every request using this source necessarily involves a round trip to
  20389. * the server.
  20390. *
  20391. * @param query - The query whose result set size to calculate.
  20392. * @returns A Promise that will be resolved with the count; the count can be
  20393. * retrieved from `snapshot.data().count`, where `snapshot` is the
  20394. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  20395. */ function hf(t) {
  20396. return ff(t, {
  20397. count: Bh()
  20398. });
  20399. }
  20400. /**
  20401. * Calculates the specified aggregations over the documents in the result
  20402. * set of the given query, without actually downloading the documents.
  20403. *
  20404. * Using this function to perform aggregations is efficient because only the
  20405. * final aggregation values, not the documents' data, is downloaded. This
  20406. * function can even perform aggregations of the documents if the result set
  20407. * would be prohibitively large to download entirely (e.g. thousands of documents).
  20408. *
  20409. * The result received from the server is presented, unaltered, without
  20410. * considering any local state. That is, documents in the local cache are not
  20411. * taken into consideration, neither are local modifications not yet
  20412. * synchronized with the server. Previously-downloaded results, if any, are not
  20413. * used: every request using this source necessarily involves a round trip to
  20414. * the server.
  20415. *
  20416. * @param query The query whose result set to aggregate over.
  20417. * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates
  20418. * to perform over the result set. The AggregateSpec specifies aliases for each
  20419. * aggregate, which can be used to retrieve the aggregate result.
  20420. * @example
  20421. * ```typescript
  20422. * const aggregateSnapshot = await getAggregateFromServer(query, {
  20423. * countOfDocs: count(),
  20424. * totalHours: sum('hours'),
  20425. * averageScore: average('score')
  20426. * });
  20427. *
  20428. * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;
  20429. * const totalHours: number = aggregateSnapshot.data().totalHours;
  20430. * const averageScore: number | null = aggregateSnapshot.data().averageScore;
  20431. * ```
  20432. * @internal TODO (sum/avg) remove when public
  20433. */ function ff(t, r) {
  20434. var i = Hc(t.firestore, hl), o = pl(i), u = function(t, e) {
  20435. var n = [];
  20436. for (var r in t) Object.prototype.hasOwnProperty.call(t, r) && n.push(e(t[r], r));
  20437. return n;
  20438. }(r, (function(t, e) {
  20439. return new ai(e, t._aggregateType, t._internalFieldPath);
  20440. }));
  20441. // Run the aggregation and convert the results
  20442. return function(t, r, i) {
  20443. var o = this, u = new W;
  20444. return t.asyncQueue.enqueueAndForget((function() {
  20445. return e(o, void 0, void 0, (function() {
  20446. var o, a;
  20447. return n(this, (function(s) {
  20448. switch (s.label) {
  20449. case 0:
  20450. return s.trys.push([ 0, 2, , 3 ]), [ 4 /*yield*/ , Mc(t) ];
  20451. case 1:
  20452. return o = s.sent(), u.resolve(
  20453. // TODO(firestorexp): Make sure there is only one Datastore instance per
  20454. // firestore-exp client.
  20455. function(t, r, i) {
  20456. return e(this, void 0, void 0, (function() {
  20457. var e, o, u, a, s, c, l, h;
  20458. return n(this, (function(n) {
  20459. switch (n.label) {
  20460. case 0:
  20461. return o = j(t), u = function(t, e, n) {
  20462. var r = Xi(t, e), i = {}, o = [], u = 0;
  20463. return n.forEach((function(t) {
  20464. // Map all client-side aliases to a unique short-form
  20465. // alias. This avoids issues with client-side aliases that
  20466. // exceed the 1500-byte string size limit.
  20467. var e = "aggregate_" + u++;
  20468. i[e] = t.alias, "count" === t.yt ? o.push({
  20469. alias: e,
  20470. count: {}
  20471. }) : "avg" === t.yt ? o.push({
  20472. alias: e,
  20473. avg: {
  20474. field: no(t.fieldPath)
  20475. }
  20476. }) : "sum" === t.yt && o.push({
  20477. alias: e,
  20478. sum: {
  20479. field: no(t.fieldPath)
  20480. }
  20481. });
  20482. })), {
  20483. request: {
  20484. structuredAggregationQuery: {
  20485. aggregations: o,
  20486. structuredQuery: r.structuredQuery
  20487. },
  20488. parent: r.parent
  20489. },
  20490. du: i
  20491. };
  20492. }(o.serializer, tr(r), i), a = u.request, s = u.du, c = a.parent, o.connection.po || delete a.parent,
  20493. [ 4 /*yield*/ , o.vo("RunAggregationQuery", c, a, /*expectedResponseCount=*/ 1) ];
  20494. case 1:
  20495. return l = n.sent().filter((function(t) {
  20496. return !!t.result;
  20497. })),
  20498. // Omit RunAggregationQueryResponse that only contain readTimes.
  20499. z(1 === l.length), h = null === (e = l[0].result) || void 0 === e ? void 0 : e.aggregateFields,
  20500. [ 2 /*return*/ , Object.keys(h).reduce((function(t, e) {
  20501. return t[s[e]] = h[e], t;
  20502. }), {}) ];
  20503. }
  20504. }));
  20505. }));
  20506. }(o, r, i)), [ 3 /*break*/ , 3 ];
  20507. case 2:
  20508. return a = s.sent(), u.reject(a), [ 3 /*break*/ , 3 ];
  20509. case 3:
  20510. return [ 2 /*return*/ ];
  20511. }
  20512. }));
  20513. }));
  20514. })), u.promise;
  20515. }(o, t._query, u).then((function(e) {
  20516. /**
  20517. * Converts the core aggregration result to an `AggregateQuerySnapshot`
  20518. * that can be returned to the consumer.
  20519. * @param query
  20520. * @param aggregateResult Core aggregation result
  20521. * @internal
  20522. */
  20523. return function(t, e, n) {
  20524. var r = new Xh(t);
  20525. return new xl(e, r, n);
  20526. }(i, t, e);
  20527. }));
  20528. }
  20529. var df = /** @class */ function() {
  20530. function t(t) {
  20531. this.kind = "memory", this._onlineComponentProvider = new Ic, (null == t ? void 0 : t.garbageCollector) ? this._offlineComponentProvider = t.garbageCollector._offlineComponentProvider : this._offlineComponentProvider = new yc;
  20532. }
  20533. return t.prototype.toJSON = function() {
  20534. return {
  20535. kind: this.kind
  20536. };
  20537. }, t;
  20538. }(), pf = /** @class */ function() {
  20539. function t(t) {
  20540. var e;
  20541. this.kind = "persistent", (null == t ? void 0 : t.tabManager) ? (t.tabManager._initialize(t),
  20542. e = t.tabManager) : (e = Tf(void 0))._initialize(t), this._onlineComponentProvider = e._onlineComponentProvider,
  20543. this._offlineComponentProvider = e._offlineComponentProvider;
  20544. }
  20545. return t.prototype.toJSON = function() {
  20546. return {
  20547. kind: this.kind
  20548. };
  20549. }, t;
  20550. }(), vf = /** @class */ function() {
  20551. function t() {
  20552. this.kind = "memoryEager", this._offlineComponentProvider = new yc;
  20553. }
  20554. return t.prototype.toJSON = function() {
  20555. return {
  20556. kind: this.kind
  20557. };
  20558. }, t;
  20559. }(), mf = /** @class */ function() {
  20560. function t(t) {
  20561. this.kind = "memoryLru", this._offlineComponentProvider = new gc(t);
  20562. }
  20563. return t.prototype.toJSON = function() {
  20564. return {
  20565. kind: this.kind
  20566. };
  20567. }, t;
  20568. }();
  20569. /**
  20570. * Creates an instance of `MemoryEagerGarbageCollector`. This is also the
  20571. * default garbage collector unless it is explicitly specified otherwise.
  20572. */
  20573. function yf() {
  20574. return new vf;
  20575. }
  20576. /**
  20577. * Creates an instance of `MemoryLruGarbageCollector`.
  20578. *
  20579. * A target size can be specified as part of the setting parameter. The
  20580. * collector will start deleting documents once the cache size exceeds
  20581. * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).
  20582. */ function gf(t) {
  20583. return new mf(null == t ? void 0 : t.cacheSizeBytes);
  20584. }
  20585. /**
  20586. * Creates an instance of `MemoryLocalCache`. The instance can be set to
  20587. * `FirestoreSettings.cache` to tell the SDK which cache layer to use.
  20588. */ function wf(t) {
  20589. return new df(t);
  20590. }
  20591. /**
  20592. * Creates an instance of `PersistentLocalCache`. The instance can be set to
  20593. * `FirestoreSettings.cache` to tell the SDK which cache layer to use.
  20594. *
  20595. * Persistent cache cannot be used in a Node.js environment.
  20596. */ function bf(t) {
  20597. return new pf(t);
  20598. }
  20599. var If = /** @class */ function() {
  20600. function t(t) {
  20601. this.forceOwnership = t, this.kind = "persistentSingleTab";
  20602. }
  20603. return t.prototype.toJSON = function() {
  20604. return {
  20605. kind: this.kind
  20606. };
  20607. },
  20608. /**
  20609. * @internal
  20610. */
  20611. t.prototype._initialize = function(t) {
  20612. this._onlineComponentProvider = new Ic, this._offlineComponentProvider = new wc(this._onlineComponentProvider, null == t ? void 0 : t.cacheSizeBytes, this.forceOwnership);
  20613. }, t;
  20614. }(), Ef = /** @class */ function() {
  20615. function t() {
  20616. this.kind = "PersistentMultipleTab";
  20617. }
  20618. return t.prototype.toJSON = function() {
  20619. return {
  20620. kind: this.kind
  20621. };
  20622. },
  20623. /**
  20624. * @internal
  20625. */
  20626. t.prototype._initialize = function(t) {
  20627. this._onlineComponentProvider = new Ic, this._offlineComponentProvider = new bc(this._onlineComponentProvider, null == t ? void 0 : t.cacheSizeBytes);
  20628. }, t;
  20629. }();
  20630. /**
  20631. * Creates an instance of `PersistentSingleTabManager`.
  20632. *
  20633. * @param settings Configures the created tab manager.
  20634. */
  20635. function Tf(t) {
  20636. return new If(null == t ? void 0 : t.forceOwnership);
  20637. }
  20638. /**
  20639. * Creates an instance of `PersistentMultipleTabManager`.
  20640. */ function Sf() {
  20641. return new Ef;
  20642. }
  20643. /**
  20644. * @license
  20645. * Copyright 2022 Google LLC
  20646. *
  20647. * Licensed under the Apache License, Version 2.0 (the "License");
  20648. * you may not use this file except in compliance with the License.
  20649. * You may obtain a copy of the License at
  20650. *
  20651. * http://www.apache.org/licenses/LICENSE-2.0
  20652. *
  20653. * Unless required by applicable law or agreed to in writing, software
  20654. * distributed under the License is distributed on an "AS IS" BASIS,
  20655. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20656. * See the License for the specific language governing permissions and
  20657. * limitations under the License.
  20658. */ var _f = {
  20659. maxAttempts: 5
  20660. }, Df = /** @class */ function() {
  20661. /** @hideconstructor */
  20662. function t(t, e) {
  20663. this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1,
  20664. this._dataReader = Bl(t);
  20665. }
  20666. return t.prototype.set = function(t, e, n) {
  20667. this._verifyNotCommitted();
  20668. var r = Cf(t, this._firestore), i = Vh(r.converter, e, n), o = Ul(this._dataReader, "WriteBatch.set", r._key, i, null !== r.converter, n);
  20669. return this._mutations.push(o.toMutation(r._key, Ur.none())), this;
  20670. }, t.prototype.update = function(t, e, n) {
  20671. for (var r = [], i = 3; i < arguments.length; i++) r[i - 3] = arguments[i];
  20672. this._verifyNotCommitted();
  20673. var o, u = Cf(t, this._firestore);
  20674. // For Compat types, we have to "extract" the underlying types before
  20675. // performing validation.
  20676. return o = "string" == typeof (e = v(e)) || e instanceof Al ? Yl(this._dataReader, "WriteBatch.update", u._key, e, n, r) : Hl(this._dataReader, "WriteBatch.update", u._key, e),
  20677. this._mutations.push(o.toMutation(u._key, Ur.exists(!0))), this;
  20678. },
  20679. /**
  20680. * Deletes the document referred to by the provided {@link DocumentReference}.
  20681. *
  20682. * @param documentRef - A reference to the document to be deleted.
  20683. * @returns This `WriteBatch` instance. Used for chaining method calls.
  20684. */
  20685. t.prototype.delete = function(t) {
  20686. this._verifyNotCommitted();
  20687. var e = Cf(t, this._firestore);
  20688. return this._mutations = this._mutations.concat(new ni(e._key, Ur.none())), this;
  20689. },
  20690. /**
  20691. * Commits all of the writes in this write batch as a single atomic unit.
  20692. *
  20693. * The result of these writes will only be reflected in document reads that
  20694. * occur after the returned promise resolves. If the client is offline, the
  20695. * write fails. If you would like to see local modifications or buffer writes
  20696. * until the client is online, use the full Firestore SDK.
  20697. *
  20698. * @returns A `Promise` resolved once all of the writes in the batch have been
  20699. * successfully written to the backend as an atomic unit (note that it won't
  20700. * resolve while you're offline).
  20701. */
  20702. t.prototype.commit = function() {
  20703. return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();
  20704. }, t.prototype._verifyNotCommitted = function() {
  20705. if (this._committed) throw new Q(K.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
  20706. }, t;
  20707. }();
  20708. /**
  20709. * @license
  20710. * Copyright 2020 Google LLC
  20711. *
  20712. * Licensed under the Apache License, Version 2.0 (the "License");
  20713. * you may not use this file except in compliance with the License.
  20714. * You may obtain a copy of the License at
  20715. *
  20716. * http://www.apache.org/licenses/LICENSE-2.0
  20717. *
  20718. * Unless required by applicable law or agreed to in writing, software
  20719. * distributed under the License is distributed on an "AS IS" BASIS,
  20720. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20721. * See the License for the specific language governing permissions and
  20722. * limitations under the License.
  20723. */
  20724. /**
  20725. * A write batch, used to perform multiple writes as a single atomic unit.
  20726. *
  20727. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  20728. * provides methods for adding writes to the write batch. None of the writes
  20729. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  20730. * called.
  20731. */ function Cf(t, e) {
  20732. if ((t = v(t)).firestore !== e) throw new Q(K.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
  20733. return t;
  20734. }
  20735. /**
  20736. * @license
  20737. * Copyright 2020 Google LLC
  20738. *
  20739. * Licensed under the Apache License, Version 2.0 (the "License");
  20740. * you may not use this file except in compliance with the License.
  20741. * You may obtain a copy of the License at
  20742. *
  20743. * http://www.apache.org/licenses/LICENSE-2.0
  20744. *
  20745. * Unless required by applicable law or agreed to in writing, software
  20746. * distributed under the License is distributed on an "AS IS" BASIS,
  20747. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20748. * See the License for the specific language governing permissions and
  20749. * limitations under the License.
  20750. */
  20751. // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
  20752. // legacy SDK.
  20753. /**
  20754. * A reference to a transaction.
  20755. *
  20756. * The `Transaction` object passed to a transaction's `updateFunction` provides
  20757. * the methods to read and write data within the transaction context. See
  20758. * {@link runTransaction}.
  20759. */
  20760. /**
  20761. * @license
  20762. * Copyright 2020 Google LLC
  20763. *
  20764. * Licensed under the Apache License, Version 2.0 (the "License");
  20765. * you may not use this file except in compliance with the License.
  20766. * You may obtain a copy of the License at
  20767. *
  20768. * http://www.apache.org/licenses/LICENSE-2.0
  20769. *
  20770. * Unless required by applicable law or agreed to in writing, software
  20771. * distributed under the License is distributed on an "AS IS" BASIS,
  20772. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20773. * See the License for the specific language governing permissions and
  20774. * limitations under the License.
  20775. */
  20776. /**
  20777. * A reference to a transaction.
  20778. *
  20779. * The `Transaction` object passed to a transaction's `updateFunction` provides
  20780. * the methods to read and write data within the transaction context. See
  20781. * {@link runTransaction}.
  20782. */ var xf, Nf = /** @class */ function(e) {
  20783. // This class implements the same logic as the Transaction API in the Lite SDK
  20784. // but is subclassed in order to return its own DocumentSnapshot types.
  20785. /** @hideconstructor */
  20786. function n(t, n) {
  20787. var r = this;
  20788. return (r = e.call(this, t, n) || this)._firestore = t, r;
  20789. }
  20790. /**
  20791. * Reads the document referenced by the provided {@link DocumentReference}.
  20792. *
  20793. * @param documentRef - A reference to the document to be read.
  20794. * @returns A `DocumentSnapshot` with the read data.
  20795. */ return t(n, e), n.prototype.get = function(t) {
  20796. var n = this, r = Cf(t, this._firestore), i = new Xh(this._firestore);
  20797. return e.prototype.get.call(this, t).then((function(t) {
  20798. return new jh(n._firestore, i, r._key, t._document, new Gh(
  20799. /* hasPendingWrites= */ !1,
  20800. /* fromCache= */ !1), r.converter);
  20801. }));
  20802. }, n;
  20803. }(/** @class */ function() {
  20804. /** @hideconstructor */
  20805. function t(t, e) {
  20806. this._firestore = t, this._transaction = e, this._dataReader = Bl(t)
  20807. /**
  20808. * Reads the document referenced by the provided {@link DocumentReference}.
  20809. *
  20810. * @param documentRef - A reference to the document to be read.
  20811. * @returns A `DocumentSnapshot` with the read data.
  20812. */;
  20813. }
  20814. return t.prototype.get = function(t) {
  20815. var e = this, n = Cf(t, this._firestore), r = new Mh(this._firestore);
  20816. return this._transaction.lookup([ n._key ]).then((function(t) {
  20817. if (!t || 1 !== t.length) return U();
  20818. var i = t[0];
  20819. if (i.isFoundDocument()) return new uh(e._firestore, r, i.key, i, n.converter);
  20820. if (i.isNoDocument()) return new uh(e._firestore, r, n._key, null, n.converter);
  20821. throw U();
  20822. }));
  20823. }, t.prototype.set = function(t, e, n) {
  20824. var r = Cf(t, this._firestore), i = Vh(r.converter, e, n), o = Ul(this._dataReader, "Transaction.set", r._key, i, null !== r.converter, n);
  20825. return this._transaction.set(r._key, o), this;
  20826. }, t.prototype.update = function(t, e, n) {
  20827. for (var r = [], i = 3; i < arguments.length; i++) r[i - 3] = arguments[i];
  20828. var o, u = Cf(t, this._firestore);
  20829. // For Compat types, we have to "extract" the underlying types before
  20830. // performing validation.
  20831. return o = "string" == typeof (e = v(e)) || e instanceof Al ? Yl(this._dataReader, "Transaction.update", u._key, e, n, r) : Hl(this._dataReader, "Transaction.update", u._key, e),
  20832. this._transaction.update(u._key, o), this;
  20833. },
  20834. /**
  20835. * Deletes the document referred to by the provided {@link DocumentReference}.
  20836. *
  20837. * @param documentRef - A reference to the document to be deleted.
  20838. * @returns This `Transaction` instance. Used for chaining method calls.
  20839. */
  20840. t.prototype.delete = function(t) {
  20841. var e = Cf(t, this._firestore);
  20842. return this._transaction.delete(e._key), this;
  20843. }, t;
  20844. }());
  20845. /**
  20846. * Executes the given `updateFunction` and then attempts to commit the changes
  20847. * applied within the transaction. If any document read within the transaction
  20848. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  20849. * commit after 5 attempts, the transaction fails.
  20850. *
  20851. * The maximum number of writes allowed in a single transaction is 500.
  20852. *
  20853. * @param firestore - A reference to the Firestore database to run this
  20854. * transaction against.
  20855. * @param updateFunction - The function to execute within the transaction
  20856. * context.
  20857. * @param options - An options object to configure maximum number of attempts to
  20858. * commit.
  20859. * @returns If the transaction completed successfully or was explicitly aborted
  20860. * (the `updateFunction` returned a failed promise), the promise returned by the
  20861. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  20862. * rejected promise with the corresponding failure error is returned.
  20863. */ function Af(t, r, i) {
  20864. t = Hc(t, hl);
  20865. var o = Object.assign(Object.assign({}, _f), i);
  20866. return function(t) {
  20867. if (t.maxAttempts < 1) throw new Q(K.INVALID_ARGUMENT, "Max attempts must be at least 1");
  20868. }(o), function(t, r, i) {
  20869. var o = this, u = new W;
  20870. return t.asyncQueue.enqueueAndForget((function() {
  20871. return e(o, void 0, void 0, (function() {
  20872. var e;
  20873. return n(this, (function(n) {
  20874. switch (n.label) {
  20875. case 0:
  20876. return [ 4 /*yield*/ , Mc(t) ];
  20877. case 1:
  20878. return e = n.sent(), new Dc(t.asyncQueue, e, i, r, u).run(), [ 2 /*return*/ ];
  20879. }
  20880. }));
  20881. }));
  20882. })), u.promise;
  20883. }(pl(t), (function(e) {
  20884. return r(new Nf(t, e));
  20885. }), o);
  20886. }
  20887. /**
  20888. * @license
  20889. * Copyright 2020 Google LLC
  20890. *
  20891. * Licensed under the Apache License, Version 2.0 (the "License");
  20892. * you may not use this file except in compliance with the License.
  20893. * You may obtain a copy of the License at
  20894. *
  20895. * http://www.apache.org/licenses/LICENSE-2.0
  20896. *
  20897. * Unless required by applicable law or agreed to in writing, software
  20898. * distributed under the License is distributed on an "AS IS" BASIS,
  20899. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20900. * See the License for the specific language governing permissions and
  20901. * limitations under the License.
  20902. */
  20903. /**
  20904. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  20905. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  20906. */ function kf() {
  20907. return new zl("deleteField");
  20908. }
  20909. /**
  20910. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  20911. * include a server-generated timestamp in the written data.
  20912. */ function Of() {
  20913. return new jl("serverTimestamp");
  20914. }
  20915. /**
  20916. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  20917. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  20918. * value that already exists on the server. Each specified element that doesn't
  20919. * already exist in the array will be added to the end. If the field being
  20920. * modified is not already an array it will be overwritten with an array
  20921. * containing exactly the specified elements.
  20922. *
  20923. * @param elements - The elements to union into the array.
  20924. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20925. * `updateDoc()`.
  20926. */ function Ff() {
  20927. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  20928. // NOTE: We don't actually parse the data until it's used in set() or
  20929. // update() since we'd need the Firestore instance to do this.
  20930. return new Kl("arrayUnion", t);
  20931. }
  20932. /**
  20933. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  20934. * updateDoc:1} that tells the server to remove the given elements from any
  20935. * array value that already exists on the server. All instances of each element
  20936. * specified will be removed from the array. If the field being modified is not
  20937. * already an array it will be overwritten with an empty array.
  20938. *
  20939. * @param elements - The elements to remove from the array.
  20940. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20941. * `updateDoc()`
  20942. */ function Pf() {
  20943. for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
  20944. // NOTE: We don't actually parse the data until it's used in set() or
  20945. // update() since we'd need the Firestore instance to do this.
  20946. return new Ql("arrayRemove", t);
  20947. }
  20948. /**
  20949. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  20950. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  20951. * the given value.
  20952. *
  20953. * If either the operand or the current field value uses floating point
  20954. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  20955. * integers, values outside of JavaScript's safe number range
  20956. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  20957. * precision loss. Furthermore, once processed by the Firestore backend, all
  20958. * integer operations are capped between -2^63 and 2^63-1.
  20959. *
  20960. * If the current field value is not of type `number`, or if the field does not
  20961. * yet exist, the transformation sets the field to the given value.
  20962. *
  20963. * @param n - The value to increment by.
  20964. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20965. * `updateDoc()`
  20966. */ function Rf(t) {
  20967. return new Wl("increment", t);
  20968. }
  20969. /**
  20970. * @license
  20971. * Copyright 2020 Google LLC
  20972. *
  20973. * Licensed under the Apache License, Version 2.0 (the "License");
  20974. * you may not use this file except in compliance with the License.
  20975. * You may obtain a copy of the License at
  20976. *
  20977. * http://www.apache.org/licenses/LICENSE-2.0
  20978. *
  20979. * Unless required by applicable law or agreed to in writing, software
  20980. * distributed under the License is distributed on an "AS IS" BASIS,
  20981. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20982. * See the License for the specific language governing permissions and
  20983. * limitations under the License.
  20984. */
  20985. /**
  20986. * Creates a write batch, used for performing multiple writes as a single
  20987. * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}
  20988. * is 500.
  20989. *
  20990. * Unlike transactions, write batches are persisted offline and therefore are
  20991. * preferable when you don't need to condition your writes on read data.
  20992. *
  20993. * @returns A {@link WriteBatch} that can be used to atomically execute multiple
  20994. * writes.
  20995. */ function Vf(t) {
  20996. return pl(t = Hc(t, hl)), new Df(t, (function(e) {
  20997. return cf(t, e);
  20998. }))
  20999. /**
  21000. * @license
  21001. * Copyright 2021 Google LLC
  21002. *
  21003. * Licensed under the Apache License, Version 2.0 (the "License");
  21004. * you may not use this file except in compliance with the License.
  21005. * You may obtain a copy of the License at
  21006. *
  21007. * http://www.apache.org/licenses/LICENSE-2.0
  21008. *
  21009. * Unless required by applicable law or agreed to in writing, software
  21010. * distributed under the License is distributed on an "AS IS" BASIS,
  21011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21012. * See the License for the specific language governing permissions and
  21013. * limitations under the License.
  21014. */;
  21015. }
  21016. function Mf(t, i) {
  21017. var o, u = pl(t = Hc(t, hl));
  21018. if (!u._uninitializedComponentsProvider || "memory" === (null === (o = u._uninitializedComponentsProvider) || void 0 === o ? void 0 : o._offlineKind))
  21019. // PORTING NOTE: We don't return an error if the user has not enabled
  21020. // persistence since `enableIndexeddbPersistence()` can fail on the Web.
  21021. return q("Cannot enable indexes when persistence is disabled"), Promise.resolve();
  21022. var a = function(t) {
  21023. var e = "string" == typeof t ? function(t) {
  21024. try {
  21025. return JSON.parse(t);
  21026. } catch (t) {
  21027. throw new Q(K.INVALID_ARGUMENT, "Failed to parse JSON: " + (null == t ? void 0 : t.message));
  21028. }
  21029. }(t) : t, n = [];
  21030. if (Array.isArray(e.indexes)) for (var r = 0, i = e.indexes; r < i.length; r++) {
  21031. var o = i[r], u = Lf(o, "collectionGroup"), a = [];
  21032. if (Array.isArray(o.fields)) for (var s = 0, c = o.fields; s < c.length; s++) {
  21033. var l = c[s], h = rh("setIndexConfiguration", Lf(l, "fieldPath"));
  21034. "CONTAINS" === l.arrayConfig ? a.push(new wt(h, 2 /* IndexKind.CONTAINS */)) : "ASCENDING" === l.order ? a.push(new wt(h, 0 /* IndexKind.ASCENDING */)) : "DESCENDING" === l.order && a.push(new wt(h, 1 /* IndexKind.DESCENDING */));
  21035. }
  21036. n.push(new vt(vt.UNKNOWN_ID, u, a, It.empty()));
  21037. }
  21038. return n;
  21039. }(i);
  21040. return function(t, i) {
  21041. var o = this;
  21042. return t.asyncQueue.enqueue((function() {
  21043. return e(o, void 0, void 0, (function() {
  21044. var o;
  21045. return n(this, (function(u) {
  21046. switch (u.label) {
  21047. case 0:
  21048. return o = function(t, i) {
  21049. return e(this, void 0, void 0, (function() {
  21050. var e, o, u;
  21051. return n(this, (function(n) {
  21052. return e = j(t), o = e.indexManager, u = [], [ 2 /*return*/ , e.persistence.runTransaction("Configure indexes", "readwrite", (function(t) {
  21053. return o.getFieldIndexes(t).next((function(e) {
  21054. /**
  21055. * @license
  21056. * Copyright 2017 Google LLC
  21057. *
  21058. * Licensed under the Apache License, Version 2.0 (the "License");
  21059. * you may not use this file except in compliance with the License.
  21060. * You may obtain a copy of the License at
  21061. *
  21062. * http://www.apache.org/licenses/LICENSE-2.0
  21063. *
  21064. * Unless required by applicable law or agreed to in writing, software
  21065. * distributed under the License is distributed on an "AS IS" BASIS,
  21066. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21067. * See the License for the specific language governing permissions and
  21068. * limitations under the License.
  21069. */
  21070. /**
  21071. * Compares two array for equality using comparator. The method computes the
  21072. * intersection and invokes `onAdd` for every element that is in `after` but not
  21073. * `before`. `onRemove` is invoked for every element in `before` but missing
  21074. * from `after`.
  21075. *
  21076. * The method creates a copy of both `before` and `after` and runs in O(n log
  21077. * n), where n is the size of the two lists.
  21078. *
  21079. * @param before - The elements that exist in the original array.
  21080. * @param after - The elements to diff against the original array.
  21081. * @param comparator - The comparator for the elements in before and after.
  21082. * @param onAdd - A function to invoke for every element that is part of `
  21083. * after` but not `before`.
  21084. * @param onRemove - A function to invoke for every element that is part of
  21085. * `before` but not `after`.
  21086. */
  21087. return function(t, e, n, i, o) {
  21088. t = r([], t, !0), e = r([], e, !0), t.sort(n), e.sort(n);
  21089. for (var u = t.length, a = e.length, s = 0, c = 0; s < a && c < u; ) {
  21090. var l = n(t[c], e[s]);
  21091. l < 0 ?
  21092. // The element was removed if the next element in our ordered
  21093. // walkthrough is only in `before`.
  21094. o(t[c++]) : l > 0 ?
  21095. // The element was added if the next element in our ordered walkthrough
  21096. // is only in `after`.
  21097. i(e[s++]) : (s++, c++);
  21098. }
  21099. for (;s < a; ) i(e[s++]);
  21100. for (;c < u; ) o(t[c++]);
  21101. }(e, i, gt, (function(e) {
  21102. u.push(o.addFieldIndex(t, e));
  21103. }), (function(e) {
  21104. u.push(o.deleteFieldIndex(t, e));
  21105. }));
  21106. })).next((function() {
  21107. return Nt.waitFor(u);
  21108. }));
  21109. })) ];
  21110. }));
  21111. }));
  21112. }, [ 4 /*yield*/ , Pc(t) ];
  21113. case 1:
  21114. return [ 2 /*return*/ , o.apply(void 0, [ u.sent(), i ]) ];
  21115. }
  21116. }));
  21117. }));
  21118. }));
  21119. }(u, a);
  21120. }
  21121. function Lf(t, e) {
  21122. if ("string" != typeof t[e]) throw new Q(K.INVALID_ARGUMENT, "Missing string value for: " + e);
  21123. return t[e];
  21124. }
  21125. /**
  21126. * Cloud Firestore
  21127. *
  21128. * @packageDocumentation
  21129. */ void 0 === xf && (xf = !0), F = i, o(new c("firestore", (function(t, e) {
  21130. var n = e.instanceIdentifier, r = e.options, i = t.getProvider("app").getImmediate(), o = new hl(new J(t.getProvider("auth-internal")), new et(t.getProvider("app-check-internal")), function(t, e) {
  21131. if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new Q(K.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
  21132. return new Ue(t.options.projectId, e);
  21133. }(i, n), i);
  21134. return r = Object.assign({
  21135. useFetchStreams: xf
  21136. }, r), o._setSettings(r), o;
  21137. }), "PUBLIC").setMultipleInstances(!0)), u(k, "3.13.0", void 0),
  21138. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  21139. u(k, "3.13.0", "esm5");
  21140. export { Rh as AbstractUserDataWriter, Cl as AggregateField, xl as AggregateQuerySnapshot, Nl as Bytes, ll as CACHE_SIZE_UNLIMITED, el as CollectionReference, $c as DocumentReference, jh as DocumentSnapshot, Al as FieldPath, Ol as FieldValue, hl as Firestore, Q as FirestoreError, Fl as GeoPoint, cl as LoadBundleTask, tl as Query, vh as QueryCompositeFilterConstraint, hh as QueryConstraint, Kh as QueryDocumentSnapshot, Dh as QueryEndAtConstraint, dh as QueryFieldFilterConstraint, bh as QueryLimitConstraint, gh as QueryOrderByConstraint, Qh as QuerySnapshot, Th as QueryStartAtConstraint, Gh as SnapshotMetadata, st as Timestamp, Nf as Transaction, Df as WriteBatch, Ue as _DatabaseId, pt as _DocumentKey, nt as _EmptyAppCheckTokenProvider, Y as _EmptyAuthCredentialsProvider, dt as _FieldPath, hi as _TestingHooks, Hc as _cast, G as _debugAssert, ke as _isBase64Available, q as _logWarn, jc as _validateIsNotUsedTogether, uf as addDoc, Uh as aggregateFieldEqual, zh as aggregateQuerySnapshotEqual, yh as and, Pf as arrayRemove, Ff as arrayUnion, qh as average, wl as clearIndexedDbPersistence, nl as collection, rl as collectionGroup, Zc as connectFirestoreEmulator, Bh as count, of as deleteDoc, kf as deleteField, El as disableNetwork, il as doc, kl as documentId, ml as enableIndexedDbPersistence, yl as enableMultiTabIndexedDbPersistence, Il as enableNetwork, xh as endAt, Ch as endBefore, pl as ensureFirestoreConfigured, cf as executeWrite, ff as getAggregateFromServer, hf as getCountFromServer, Yh as getDoc, Jh as getDocFromCache, Zh as getDocFromServer, $h as getDocs, tf as getDocsFromCache, ef as getDocsFromServer, dl as getFirestore, Rf as increment, fl as initializeFirestore, Ih as limit, Eh as limitToLast, Sl as loadBundle, yf as memoryEagerGarbageCollector, wf as memoryLocalCache, gf as memoryLruGarbageCollector, _l as namedQuery, af as onSnapshot, sf as onSnapshotsInSync, mh as or, wh as orderBy, bf as persistentLocalCache, Sf as persistentMultipleTabManager, Tf as persistentSingleTabManager, fh as query, ul as queryEqual, ol as refEqual, Af as runTransaction, Of as serverTimestamp, nf as setDoc, Mf as setIndexConfiguration, V as setLogLevel, Hh as snapshotEqual, _h as startAfter, Sh as startAt, Lh as sum, Tl as terminate, rf as updateDoc, bl as waitForPendingWrites, ph as where, Vf as writeBatch };
  21141. //# sourceMappingURL=index.esm5.js.map