index.rn.js 828 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410
  1. import { _getProvider, getApp as t, _removeServiceInstance as e, _registerComponent as n, registerVersion as s, SDK_VERSION as i } from "@firebase/app";
  2. import { Component as r } from "@firebase/component";
  3. import { Logger as o, LogLevel as u } from "@firebase/logger";
  4. import { FirebaseError as c, getUA as a, isIndexedDBAvailable as h, base64 as l, DecodeBase64StringError as f, isSafari as d, createMockUserToken as w, getModularInstance as _, deepEqual as m, getDefaultEmulatorHostnameAndPort as g } from "@firebase/util";
  5. import { Integer as y, Md5 as p, XhrIo as I, EventType as T, ErrorCode as E, createWebChannelTransport as A, getStatEventTarget as v, FetchXmlHttpFactory as R, WebChannel as P, Event as b, Stat as V } from "@firebase/webchannel-wrapper";
  6. const S = "@firebase/firestore";
  7. /**
  8. * @license
  9. * Copyright 2017 Google LLC
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. /**
  24. * Simple wrapper around a nullable UID. Mostly exists to make code more
  25. * readable.
  26. */
  27. class D {
  28. constructor(t) {
  29. this.uid = t;
  30. }
  31. isAuthenticated() {
  32. return null != this.uid;
  33. }
  34. /**
  35. * Returns a key representing this user, suitable for inclusion in a
  36. * dictionary.
  37. */ toKey() {
  38. return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
  39. }
  40. isEqual(t) {
  41. return t.uid === this.uid;
  42. }
  43. }
  44. /** A user with a null UID. */ D.UNAUTHENTICATED = new D(null),
  45. // TODO(mikelehen): Look into getting a proper uid-equivalent for
  46. // non-FirebaseAuth providers.
  47. D.GOOGLE_CREDENTIALS = new D("google-credentials-uid"), D.FIRST_PARTY = new D("first-party-uid"),
  48. D.MOCK_USER = new D("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. let C = "9.23.0";
  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. const x = new o("@firebase/firestore");
  83. // Helper methods are needed because variables can't be exported as read/write
  84. function N() {
  85. return x.logLevel;
  86. }
  87. /**
  88. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  89. *
  90. * @param logLevel - The verbosity you set for activity and error logging. Can
  91. * be any of the following values:
  92. *
  93. * <ul>
  94. * <li>`debug` for the most verbose logging level, primarily for
  95. * debugging.</li>
  96. * <li>`error` to log errors only.</li>
  97. * <li><code>`silent` to turn off logging.</li>
  98. * </ul>
  99. */ function k(t) {
  100. x.setLogLevel(t);
  101. }
  102. function $(t, ...e) {
  103. if (x.logLevel <= u.DEBUG) {
  104. const n = e.map(F);
  105. x.debug(`Firestore (${C}): ${t}`, ...n);
  106. }
  107. }
  108. function M(t, ...e) {
  109. if (x.logLevel <= u.ERROR) {
  110. const n = e.map(F);
  111. x.error(`Firestore (${C}): ${t}`, ...n);
  112. }
  113. }
  114. /**
  115. * @internal
  116. */ function O(t, ...e) {
  117. if (x.logLevel <= u.WARN) {
  118. const n = e.map(F);
  119. x.warn(`Firestore (${C}): ${t}`, ...n);
  120. }
  121. }
  122. /**
  123. * Converts an additional log parameter to a string representation.
  124. */ function F(t) {
  125. if ("string" == typeof t) return t;
  126. try {
  127. return e = t, JSON.stringify(e);
  128. } catch (e) {
  129. // Converting to JSON failed, just log the object directly
  130. return t;
  131. }
  132. /**
  133. * @license
  134. * Copyright 2020 Google LLC
  135. *
  136. * Licensed under the Apache License, Version 2.0 (the "License");
  137. * you may not use this file except in compliance with the License.
  138. * You may obtain a copy of the License at
  139. *
  140. * http://www.apache.org/licenses/LICENSE-2.0
  141. *
  142. * Unless required by applicable law or agreed to in writing, software
  143. * distributed under the License is distributed on an "AS IS" BASIS,
  144. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  145. * See the License for the specific language governing permissions and
  146. * limitations under the License.
  147. */
  148. /** Formats an object as a JSON string, suitable for logging. */
  149. var e;
  150. }
  151. /**
  152. * @license
  153. * Copyright 2017 Google LLC
  154. *
  155. * Licensed under the Apache License, Version 2.0 (the "License");
  156. * you may not use this file except in compliance with the License.
  157. * You may obtain a copy of the License at
  158. *
  159. * http://www.apache.org/licenses/LICENSE-2.0
  160. *
  161. * Unless required by applicable law or agreed to in writing, software
  162. * distributed under the License is distributed on an "AS IS" BASIS,
  163. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  164. * See the License for the specific language governing permissions and
  165. * limitations under the License.
  166. */
  167. /**
  168. * Unconditionally fails, throwing an Error with the given message.
  169. * Messages are stripped in production builds.
  170. *
  171. * Returns `never` and can be used in expressions:
  172. * @example
  173. * let futureVar = fail('not implemented yet');
  174. */ function B(t = "Unexpected state") {
  175. // Log the failure in addition to throw an exception, just in case the
  176. // exception is swallowed.
  177. const e = `FIRESTORE (${C}) INTERNAL ASSERTION FAILED: ` + t;
  178. // NOTE: We don't use FirestoreError here because these are internal failures
  179. // that cannot be handled by the user. (Also it would create a circular
  180. // dependency between the error and assert modules which doesn't work.)
  181. throw M(e), new Error(e);
  182. }
  183. /**
  184. * Fails if the given assertion condition is false, throwing an Error with the
  185. * given message if it did.
  186. *
  187. * Messages are stripped in production builds.
  188. */ function L(t, e) {
  189. t || B();
  190. }
  191. /**
  192. * Fails if the given assertion condition is false, throwing an Error with the
  193. * given message if it did.
  194. *
  195. * The code of callsites invoking this function are stripped out in production
  196. * builds. Any side-effects of code within the debugAssert() invocation will not
  197. * happen in this case.
  198. *
  199. * @internal
  200. */ function q(t, e) {
  201. t || B();
  202. }
  203. /**
  204. * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
  205. * instance of `T` before casting.
  206. */ function U(t,
  207. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  208. e) {
  209. return t;
  210. }
  211. /**
  212. * @license
  213. * Copyright 2017 Google LLC
  214. *
  215. * Licensed under the Apache License, Version 2.0 (the "License");
  216. * you may not use this file except in compliance with the License.
  217. * You may obtain a copy of the License at
  218. *
  219. * http://www.apache.org/licenses/LICENSE-2.0
  220. *
  221. * Unless required by applicable law or agreed to in writing, software
  222. * distributed under the License is distributed on an "AS IS" BASIS,
  223. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  224. * See the License for the specific language governing permissions and
  225. * limitations under the License.
  226. */ const K = {
  227. // Causes are copied from:
  228. // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  229. /** Not an error; returned on success. */
  230. OK: "ok",
  231. /** The operation was cancelled (typically by the caller). */
  232. CANCELLED: "cancelled",
  233. /** Unknown error or an error from a different error domain. */
  234. UNKNOWN: "unknown",
  235. /**
  236. * Client specified an invalid argument. Note that this differs from
  237. * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
  238. * problematic regardless of the state of the system (e.g., a malformed file
  239. * name).
  240. */
  241. INVALID_ARGUMENT: "invalid-argument",
  242. /**
  243. * Deadline expired before operation could complete. For operations that
  244. * change the state of the system, this error may be returned even if the
  245. * operation has completed successfully. For example, a successful response
  246. * from a server could have been delayed long enough for the deadline to
  247. * expire.
  248. */
  249. DEADLINE_EXCEEDED: "deadline-exceeded",
  250. /** Some requested entity (e.g., file or directory) was not found. */
  251. NOT_FOUND: "not-found",
  252. /**
  253. * Some entity that we attempted to create (e.g., file or directory) already
  254. * exists.
  255. */
  256. ALREADY_EXISTS: "already-exists",
  257. /**
  258. * The caller does not have permission to execute the specified operation.
  259. * PERMISSION_DENIED must not be used for rejections caused by exhausting
  260. * some resource (use RESOURCE_EXHAUSTED instead for those errors).
  261. * PERMISSION_DENIED must not be used if the caller can not be identified
  262. * (use UNAUTHENTICATED instead for those errors).
  263. */
  264. PERMISSION_DENIED: "permission-denied",
  265. /**
  266. * The request does not have valid authentication credentials for the
  267. * operation.
  268. */
  269. UNAUTHENTICATED: "unauthenticated",
  270. /**
  271. * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  272. * entire file system is out of space.
  273. */
  274. RESOURCE_EXHAUSTED: "resource-exhausted",
  275. /**
  276. * Operation was rejected because the system is not in a state required for
  277. * the operation's execution. For example, directory to be deleted may be
  278. * non-empty, an rmdir operation is applied to a non-directory, etc.
  279. *
  280. * A litmus test that may help a service implementor in deciding
  281. * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  282. * (a) Use UNAVAILABLE if the client can retry just the failing call.
  283. * (b) Use ABORTED if the client should retry at a higher-level
  284. * (e.g., restarting a read-modify-write sequence).
  285. * (c) Use FAILED_PRECONDITION if the client should not retry until
  286. * the system state has been explicitly fixed. E.g., if an "rmdir"
  287. * fails because the directory is non-empty, FAILED_PRECONDITION
  288. * should be returned since the client should not retry unless
  289. * they have first fixed up the directory by deleting files from it.
  290. * (d) Use FAILED_PRECONDITION if the client performs conditional
  291. * REST Get/Update/Delete on a resource and the resource on the
  292. * server does not match the condition. E.g., conflicting
  293. * read-modify-write on the same resource.
  294. */
  295. FAILED_PRECONDITION: "failed-precondition",
  296. /**
  297. * The operation was aborted, typically due to a concurrency issue like
  298. * sequencer check failures, transaction aborts, etc.
  299. *
  300. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  301. * and UNAVAILABLE.
  302. */
  303. ABORTED: "aborted",
  304. /**
  305. * Operation was attempted past the valid range. E.g., seeking or reading
  306. * past end of file.
  307. *
  308. * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
  309. * if the system state changes. For example, a 32-bit file system will
  310. * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
  311. * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  312. * an offset past the current file size.
  313. *
  314. * There is a fair bit of overlap between FAILED_PRECONDITION and
  315. * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  316. * when it applies so that callers who are iterating through a space can
  317. * easily look for an OUT_OF_RANGE error to detect when they are done.
  318. */
  319. OUT_OF_RANGE: "out-of-range",
  320. /** Operation is not implemented or not supported/enabled in this service. */
  321. UNIMPLEMENTED: "unimplemented",
  322. /**
  323. * Internal errors. Means some invariants expected by underlying System has
  324. * been broken. If you see one of these errors, Something is very broken.
  325. */
  326. INTERNAL: "internal",
  327. /**
  328. * The service is currently unavailable. This is a most likely a transient
  329. * condition and may be corrected by retrying with a backoff.
  330. *
  331. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  332. * and UNAVAILABLE.
  333. */
  334. UNAVAILABLE: "unavailable",
  335. /** Unrecoverable data loss or corruption. */
  336. DATA_LOSS: "data-loss"
  337. };
  338. /** An error returned by a Firestore operation. */ class G extends c {
  339. /** @hideconstructor */
  340. constructor(
  341. /**
  342. * The backend error code associated with this error.
  343. */
  344. t,
  345. /**
  346. * A custom error description.
  347. */
  348. e) {
  349. super(t, e), this.code = t, this.message = e,
  350. // HACK: We write a toString property directly because Error is not a real
  351. // class and so inheritance does not work correctly. We could alternatively
  352. // do the same "back-door inheritance" trick that FirebaseError does.
  353. this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
  354. }
  355. }
  356. /**
  357. * @license
  358. * Copyright 2017 Google LLC
  359. *
  360. * Licensed under the Apache License, Version 2.0 (the "License");
  361. * you may not use this file except in compliance with the License.
  362. * You may obtain a copy of the License at
  363. *
  364. * http://www.apache.org/licenses/LICENSE-2.0
  365. *
  366. * Unless required by applicable law or agreed to in writing, software
  367. * distributed under the License is distributed on an "AS IS" BASIS,
  368. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  369. * See the License for the specific language governing permissions and
  370. * limitations under the License.
  371. */ class Q {
  372. constructor() {
  373. this.promise = new Promise(((t, e) => {
  374. this.resolve = t, this.reject = e;
  375. }));
  376. }
  377. }
  378. /**
  379. * @license
  380. * Copyright 2017 Google LLC
  381. *
  382. * Licensed under the Apache License, Version 2.0 (the "License");
  383. * you may not use this file except in compliance with the License.
  384. * You may obtain a copy of the License at
  385. *
  386. * http://www.apache.org/licenses/LICENSE-2.0
  387. *
  388. * Unless required by applicable law or agreed to in writing, software
  389. * distributed under the License is distributed on an "AS IS" BASIS,
  390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  391. * See the License for the specific language governing permissions and
  392. * limitations under the License.
  393. */ class j {
  394. constructor(t, e) {
  395. this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`);
  396. }
  397. }
  398. /**
  399. * A CredentialsProvider that always yields an empty token.
  400. * @internal
  401. */ class z {
  402. getToken() {
  403. return Promise.resolve(null);
  404. }
  405. invalidateToken() {}
  406. start(t, e) {
  407. // Fire with initial user.
  408. t.enqueueRetryable((() => e(D.UNAUTHENTICATED)));
  409. }
  410. shutdown() {}
  411. }
  412. /**
  413. * A CredentialsProvider that always returns a constant token. Used for
  414. * emulator token mocking.
  415. */ class W {
  416. constructor(t) {
  417. this.token = t,
  418. /**
  419. * Stores the listener registered with setChangeListener()
  420. * This isn't actually necessary since the UID never changes, but we use this
  421. * to verify the listen contract is adhered to in tests.
  422. */
  423. this.changeListener = null;
  424. }
  425. getToken() {
  426. return Promise.resolve(this.token);
  427. }
  428. invalidateToken() {}
  429. start(t, e) {
  430. this.changeListener = e,
  431. // Fire with initial user.
  432. t.enqueueRetryable((() => e(this.token.user)));
  433. }
  434. shutdown() {
  435. this.changeListener = null;
  436. }
  437. }
  438. class H {
  439. constructor(t) {
  440. this.t = t,
  441. /** Tracks the current User. */
  442. this.currentUser = D.UNAUTHENTICATED,
  443. /**
  444. * Counter used to detect if the token changed while a getToken request was
  445. * outstanding.
  446. */
  447. this.i = 0, this.forceRefresh = !1, this.auth = null;
  448. }
  449. start(t, e) {
  450. let n = this.i;
  451. // A change listener that prevents double-firing for the same token change.
  452. const s = t => this.i !== n ? (n = this.i, e(t)) : Promise.resolve();
  453. // A promise that can be waited on to block on the next token change.
  454. // This promise is re-created after each change.
  455. let i = new Q;
  456. this.o = () => {
  457. this.i++, this.currentUser = this.u(), i.resolve(), i = new Q, t.enqueueRetryable((() => s(this.currentUser)));
  458. };
  459. const r = () => {
  460. const e = i;
  461. t.enqueueRetryable((async () => {
  462. await e.promise, await s(this.currentUser);
  463. }));
  464. }, o = t => {
  465. $("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = t, this.auth.addAuthTokenListener(this.o),
  466. r();
  467. };
  468. this.t.onInit((t => o(t))),
  469. // Our users can initialize Auth right after Firestore, so we give it
  470. // a chance to register itself with the component framework before we
  471. // determine whether to start up in unauthenticated mode.
  472. setTimeout((() => {
  473. if (!this.auth) {
  474. const t = this.t.getImmediate({
  475. optional: !0
  476. });
  477. t ? o(t) : (
  478. // If auth is still not available, proceed with `null` user
  479. $("FirebaseAuthCredentialsProvider", "Auth not yet detected"), i.resolve(), i = new Q);
  480. }
  481. }), 0), r();
  482. }
  483. getToken() {
  484. // Take note of the current value of the tokenCounter so that this method
  485. // can fail (with an ABORTED error) if there is a token change while the
  486. // request is outstanding.
  487. const t = this.i, e = this.forceRefresh;
  488. return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e =>
  489. // Cancel the request since the token changed while the request was
  490. // outstanding so the response is potentially for a previous user (which
  491. // user, we can't be sure).
  492. this.i !== t ? ($("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."),
  493. this.getToken()) : e ? (L("string" == typeof e.accessToken), new j(e.accessToken, this.currentUser)) : null)) : Promise.resolve(null);
  494. }
  495. invalidateToken() {
  496. this.forceRefresh = !0;
  497. }
  498. shutdown() {
  499. this.auth && this.auth.removeAuthTokenListener(this.o);
  500. }
  501. // Auth.getUid() can return null even with a user logged in. It is because
  502. // getUid() is synchronous, but the auth code populating Uid is asynchronous.
  503. // This method should only be called in the AuthTokenListener callback
  504. // to guarantee to get the actual user.
  505. u() {
  506. const t = this.auth && this.auth.getUid();
  507. return L(null === t || "string" == typeof t), new D(t);
  508. }
  509. }
  510. /*
  511. * FirstPartyToken provides a fresh token each time its value
  512. * is requested, because if the token is too old, requests will be rejected.
  513. * Technically this may no longer be necessary since the SDK should gracefully
  514. * recover from unauthenticated errors (see b/33147818 for context), but it's
  515. * safer to keep the implementation as-is.
  516. */ class J {
  517. constructor(t, e, n) {
  518. this.h = t, this.l = e, this.m = n, this.type = "FirstParty", this.user = D.FIRST_PARTY,
  519. this.g = new Map;
  520. }
  521. /**
  522. * Gets an authorization token, using a provided factory function, or return
  523. * null.
  524. */ p() {
  525. return this.m ? this.m() : null;
  526. }
  527. get headers() {
  528. this.g.set("X-Goog-AuthUser", this.h);
  529. // Use array notation to prevent minification
  530. const t = this.p();
  531. return t && this.g.set("Authorization", t), this.l && this.g.set("X-Goog-Iam-Authorization-Token", this.l),
  532. this.g;
  533. }
  534. }
  535. /*
  536. * Provides user credentials required for the Firestore JavaScript SDK
  537. * to authenticate the user, using technique that is only available
  538. * to applications hosted by Google.
  539. */ class Y {
  540. constructor(t, e, n) {
  541. this.h = t, this.l = e, this.m = n;
  542. }
  543. getToken() {
  544. return Promise.resolve(new J(this.h, this.l, this.m));
  545. }
  546. start(t, e) {
  547. // Fire with initial uid.
  548. t.enqueueRetryable((() => e(D.FIRST_PARTY)));
  549. }
  550. shutdown() {}
  551. invalidateToken() {}
  552. }
  553. class X {
  554. constructor(t) {
  555. this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
  556. }
  557. }
  558. class Z {
  559. constructor(t) {
  560. this.I = t, this.forceRefresh = !1, this.appCheck = null, this.T = null;
  561. }
  562. start(t, e) {
  563. const n = t => {
  564. null != t.error && $("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${t.error.message}`);
  565. const n = t.token !== this.T;
  566. return this.T = t.token, $("FirebaseAppCheckTokenProvider", `Received ${n ? "new" : "existing"} token.`),
  567. n ? e(t.token) : Promise.resolve();
  568. };
  569. this.o = e => {
  570. t.enqueueRetryable((() => n(e)));
  571. };
  572. const s = t => {
  573. $("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = t, this.appCheck.addTokenListener(this.o);
  574. };
  575. this.I.onInit((t => s(t))),
  576. // Our users can initialize AppCheck after Firestore, so we give it
  577. // a chance to register itself with the component framework.
  578. setTimeout((() => {
  579. if (!this.appCheck) {
  580. const t = this.I.getImmediate({
  581. optional: !0
  582. });
  583. t ? s(t) :
  584. // If AppCheck is still not available, proceed without it.
  585. $("FirebaseAppCheckTokenProvider", "AppCheck not yet detected");
  586. }
  587. }), 0);
  588. }
  589. getToken() {
  590. const t = this.forceRefresh;
  591. return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(t).then((t => t ? (L("string" == typeof t.token),
  592. this.T = t.token, new X(t.token)) : null)) : Promise.resolve(null);
  593. }
  594. invalidateToken() {
  595. this.forceRefresh = !0;
  596. }
  597. shutdown() {
  598. this.appCheck && this.appCheck.removeTokenListener(this.o);
  599. }
  600. }
  601. /**
  602. * An AppCheck token provider that always yields an empty token.
  603. * @internal
  604. */ class tt {
  605. getToken() {
  606. return Promise.resolve(new X(""));
  607. }
  608. invalidateToken() {}
  609. start(t, e) {}
  610. shutdown() {}
  611. }
  612. /**
  613. * Builds a CredentialsProvider depending on the type of
  614. * the credentials passed in.
  615. */
  616. /**
  617. * @license
  618. * Copyright 2020 Google LLC
  619. *
  620. * Licensed under the Apache License, Version 2.0 (the "License");
  621. * you may not use this file except in compliance with the License.
  622. * You may obtain a copy of the License at
  623. *
  624. * http://www.apache.org/licenses/LICENSE-2.0
  625. *
  626. * Unless required by applicable law or agreed to in writing, software
  627. * distributed under the License is distributed on an "AS IS" BASIS,
  628. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  629. * See the License for the specific language governing permissions and
  630. * limitations under the License.
  631. */
  632. /**
  633. * Generates `nBytes` of random bytes.
  634. *
  635. * If `nBytes < 0` , an error will be thrown.
  636. */
  637. function et(t) {
  638. // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
  639. const e =
  640. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  641. "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);
  642. if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else
  643. // Falls back to Math.random
  644. for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());
  645. return n;
  646. }
  647. /**
  648. * @license
  649. * Copyright 2017 Google LLC
  650. *
  651. * Licensed under the Apache License, Version 2.0 (the "License");
  652. * you may not use this file except in compliance with the License.
  653. * You may obtain a copy of the License at
  654. *
  655. * http://www.apache.org/licenses/LICENSE-2.0
  656. *
  657. * Unless required by applicable law or agreed to in writing, software
  658. * distributed under the License is distributed on an "AS IS" BASIS,
  659. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  660. * See the License for the specific language governing permissions and
  661. * limitations under the License.
  662. */ class nt {
  663. static A() {
  664. // Alphanumeric characters
  665. const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length;
  666. // The largest byte value that is a multiple of `char.length`.
  667. let n = "";
  668. for (;n.length < 20; ) {
  669. const s = et(40);
  670. for (let i = 0; i < s.length; ++i)
  671. // Only accept values that are [0, maxMultiple), this ensures they can
  672. // be evenly mapped to indices of `chars` via a modulo operation.
  673. n.length < 20 && s[i] < e && (n += t.charAt(s[i] % t.length));
  674. }
  675. return n;
  676. }
  677. }
  678. function st(t, e) {
  679. return t < e ? -1 : t > e ? 1 : 0;
  680. }
  681. /** Helper to compare arrays using isEqual(). */ function it(t, e, n) {
  682. return t.length === e.length && t.every(((t, s) => n(t, e[s])));
  683. }
  684. /**
  685. * Returns the immediate lexicographically-following string. This is useful to
  686. * construct an inclusive range for indexeddb iterators.
  687. */ function rt(t) {
  688. // Return the input string, with an additional NUL byte appended.
  689. return t + "\0";
  690. }
  691. /**
  692. * @license
  693. * Copyright 2017 Google LLC
  694. *
  695. * Licensed under the Apache License, Version 2.0 (the "License");
  696. * you may not use this file except in compliance with the License.
  697. * You may obtain a copy of the License at
  698. *
  699. * http://www.apache.org/licenses/LICENSE-2.0
  700. *
  701. * Unless required by applicable law or agreed to in writing, software
  702. * distributed under the License is distributed on an "AS IS" BASIS,
  703. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  704. * See the License for the specific language governing permissions and
  705. * limitations under the License.
  706. */
  707. // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
  708. /**
  709. * A `Timestamp` represents a point in time independent of any time zone or
  710. * calendar, represented as seconds and fractions of seconds at nanosecond
  711. * resolution in UTC Epoch time.
  712. *
  713. * It is encoded using the Proleptic Gregorian Calendar which extends the
  714. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  715. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  716. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  717. * 9999-12-31T23:59:59.999999999Z.
  718. *
  719. * For examples and further specifications, refer to the
  720. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  721. */
  722. class ot {
  723. /**
  724. * Creates a new timestamp.
  725. *
  726. * @param seconds - The number of seconds of UTC time since Unix epoch
  727. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  728. * 9999-12-31T23:59:59Z inclusive.
  729. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  730. * resolution. Negative second values with fractions must still have
  731. * non-negative nanoseconds values that count forward in time. Must be
  732. * from 0 to 999,999,999 inclusive.
  733. */
  734. constructor(
  735. /**
  736. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  737. */
  738. t,
  739. /**
  740. * The fractions of a second at nanosecond resolution.*
  741. */
  742. e) {
  743. if (this.seconds = t, this.nanoseconds = e, e < 0) throw new G(K.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  744. if (e >= 1e9) throw new G(K.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  745. if (t < -62135596800) throw new G(K.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  746. // This will break in the year 10,000.
  747. if (t >= 253402300800) throw new G(K.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  748. }
  749. /**
  750. * Creates a new timestamp with the current date, with millisecond precision.
  751. *
  752. * @returns a new timestamp representing the current date.
  753. */ static now() {
  754. return ot.fromMillis(Date.now());
  755. }
  756. /**
  757. * Creates a new timestamp from the given date.
  758. *
  759. * @param date - The date to initialize the `Timestamp` from.
  760. * @returns A new `Timestamp` representing the same point in time as the given
  761. * date.
  762. */ static fromDate(t) {
  763. return ot.fromMillis(t.getTime());
  764. }
  765. /**
  766. * Creates a new timestamp from the given number of milliseconds.
  767. *
  768. * @param milliseconds - Number of milliseconds since Unix epoch
  769. * 1970-01-01T00:00:00Z.
  770. * @returns A new `Timestamp` representing the same point in time as the given
  771. * number of milliseconds.
  772. */ static fromMillis(t) {
  773. const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));
  774. return new ot(e, n);
  775. }
  776. /**
  777. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  778. * causes a loss of precision since `Date` objects only support millisecond
  779. * precision.
  780. *
  781. * @returns JavaScript `Date` object representing the same point in time as
  782. * this `Timestamp`, with millisecond precision.
  783. */ toDate() {
  784. return new Date(this.toMillis());
  785. }
  786. /**
  787. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  788. * epoch). This operation causes a loss of precision.
  789. *
  790. * @returns The point in time corresponding to this timestamp, represented as
  791. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  792. */ toMillis() {
  793. return 1e3 * this.seconds + this.nanoseconds / 1e6;
  794. }
  795. _compareTo(t) {
  796. return this.seconds === t.seconds ? st(this.nanoseconds, t.nanoseconds) : st(this.seconds, t.seconds);
  797. }
  798. /**
  799. * Returns true if this `Timestamp` is equal to the provided one.
  800. *
  801. * @param other - The `Timestamp` to compare against.
  802. * @returns true if this `Timestamp` is equal to the provided one.
  803. */ isEqual(t) {
  804. return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
  805. }
  806. /** Returns a textual representation of this `Timestamp`. */ toString() {
  807. return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
  808. }
  809. /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {
  810. return {
  811. seconds: this.seconds,
  812. nanoseconds: this.nanoseconds
  813. };
  814. }
  815. /**
  816. * Converts this object to a primitive string, which allows `Timestamp` objects
  817. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  818. */ valueOf() {
  819. // This method returns a string of the form <seconds>.<nanoseconds> where
  820. // <seconds> is translated to have a non-negative value and both <seconds>
  821. // and <nanoseconds> are left-padded with zeroes to be a consistent length.
  822. // Strings with this format then have a lexiographical ordering that matches
  823. // the expected ordering. The <seconds> translation is done to avoid having
  824. // a leading negative sign (i.e. a leading '-' character) in its string
  825. // representation, which would affect its lexiographical ordering.
  826. const t = this.seconds - -62135596800;
  827. // Note: Up to 12 decimal digits are required to represent all valid
  828. // 'seconds' values.
  829. return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
  830. }
  831. }
  832. /**
  833. * @license
  834. * Copyright 2017 Google LLC
  835. *
  836. * Licensed under the Apache License, Version 2.0 (the "License");
  837. * you may not use this file except in compliance with the License.
  838. * You may obtain a copy of the License at
  839. *
  840. * http://www.apache.org/licenses/LICENSE-2.0
  841. *
  842. * Unless required by applicable law or agreed to in writing, software
  843. * distributed under the License is distributed on an "AS IS" BASIS,
  844. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  845. * See the License for the specific language governing permissions and
  846. * limitations under the License.
  847. */
  848. /**
  849. * A version of a document in Firestore. This corresponds to the version
  850. * timestamp, such as update_time or read_time.
  851. */ class ut {
  852. constructor(t) {
  853. this.timestamp = t;
  854. }
  855. static fromTimestamp(t) {
  856. return new ut(t);
  857. }
  858. static min() {
  859. return new ut(new ot(0, 0));
  860. }
  861. static max() {
  862. return new ut(new ot(253402300799, 999999999));
  863. }
  864. compareTo(t) {
  865. return this.timestamp._compareTo(t.timestamp);
  866. }
  867. isEqual(t) {
  868. return this.timestamp.isEqual(t.timestamp);
  869. }
  870. /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {
  871. // Convert to microseconds.
  872. return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
  873. }
  874. toString() {
  875. return "SnapshotVersion(" + this.timestamp.toString() + ")";
  876. }
  877. toTimestamp() {
  878. return this.timestamp;
  879. }
  880. }
  881. /**
  882. * @license
  883. * Copyright 2017 Google LLC
  884. *
  885. * Licensed under the Apache License, Version 2.0 (the "License");
  886. * you may not use this file except in compliance with the License.
  887. * You may obtain a copy of the License at
  888. *
  889. * http://www.apache.org/licenses/LICENSE-2.0
  890. *
  891. * Unless required by applicable law or agreed to in writing, software
  892. * distributed under the License is distributed on an "AS IS" BASIS,
  893. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  894. * See the License for the specific language governing permissions and
  895. * limitations under the License.
  896. */
  897. /**
  898. * Path represents an ordered sequence of string segments.
  899. */
  900. class ct {
  901. constructor(t, e, n) {
  902. void 0 === e ? e = 0 : e > t.length && B(), void 0 === n ? n = t.length - e : n > t.length - e && B(),
  903. this.segments = t, this.offset = e, this.len = n;
  904. }
  905. get length() {
  906. return this.len;
  907. }
  908. isEqual(t) {
  909. return 0 === ct.comparator(this, t);
  910. }
  911. child(t) {
  912. const e = this.segments.slice(this.offset, this.limit());
  913. return t instanceof ct ? t.forEach((t => {
  914. e.push(t);
  915. })) : e.push(t), this.construct(e);
  916. }
  917. /** The index of one past the last segment of the path. */ limit() {
  918. return this.offset + this.length;
  919. }
  920. popFirst(t) {
  921. return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);
  922. }
  923. popLast() {
  924. return this.construct(this.segments, this.offset, this.length - 1);
  925. }
  926. firstSegment() {
  927. return this.segments[this.offset];
  928. }
  929. lastSegment() {
  930. return this.get(this.length - 1);
  931. }
  932. get(t) {
  933. return this.segments[this.offset + t];
  934. }
  935. isEmpty() {
  936. return 0 === this.length;
  937. }
  938. isPrefixOf(t) {
  939. if (t.length < this.length) return !1;
  940. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  941. return !0;
  942. }
  943. isImmediateParentOf(t) {
  944. if (this.length + 1 !== t.length) return !1;
  945. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  946. return !0;
  947. }
  948. forEach(t) {
  949. for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);
  950. }
  951. toArray() {
  952. return this.segments.slice(this.offset, this.limit());
  953. }
  954. static comparator(t, e) {
  955. const n = Math.min(t.length, e.length);
  956. for (let s = 0; s < n; s++) {
  957. const n = t.get(s), i = e.get(s);
  958. if (n < i) return -1;
  959. if (n > i) return 1;
  960. }
  961. return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
  962. }
  963. }
  964. /**
  965. * A slash-separated path for navigating resources (documents and collections)
  966. * within Firestore.
  967. *
  968. * @internal
  969. */ class at extends ct {
  970. construct(t, e, n) {
  971. return new at(t, e, n);
  972. }
  973. canonicalString() {
  974. // NOTE: The client is ignorant of any path segments containing escape
  975. // sequences (e.g. __id123__) and just passes them through raw (they exist
  976. // for legacy reasons and should not be used frequently).
  977. return this.toArray().join("/");
  978. }
  979. toString() {
  980. return this.canonicalString();
  981. }
  982. /**
  983. * Creates a resource path from the given slash-delimited string. If multiple
  984. * arguments are provided, all components are combined. Leading and trailing
  985. * slashes from all components are ignored.
  986. */ static fromString(...t) {
  987. // NOTE: The client is ignorant of any path segments containing escape
  988. // sequences (e.g. __id123__) and just passes them through raw (they exist
  989. // for legacy reasons and should not be used frequently).
  990. const e = [];
  991. for (const n of t) {
  992. if (n.indexOf("//") >= 0) throw new G(K.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);
  993. // Strip leading and traling slashed.
  994. e.push(...n.split("/").filter((t => t.length > 0)));
  995. }
  996. return new at(e);
  997. }
  998. static emptyPath() {
  999. return new at([]);
  1000. }
  1001. }
  1002. const ht = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
  1003. /**
  1004. * A dot-separated path for navigating sub-objects within a document.
  1005. * @internal
  1006. */ class lt extends ct {
  1007. construct(t, e, n) {
  1008. return new lt(t, e, n);
  1009. }
  1010. /**
  1011. * Returns true if the string could be used as a segment in a field path
  1012. * without escaping.
  1013. */ static isValidIdentifier(t) {
  1014. return ht.test(t);
  1015. }
  1016. canonicalString() {
  1017. return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"),
  1018. lt.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join(".");
  1019. }
  1020. toString() {
  1021. return this.canonicalString();
  1022. }
  1023. /**
  1024. * Returns true if this field references the key of a document.
  1025. */ isKeyField() {
  1026. return 1 === this.length && "__name__" === this.get(0);
  1027. }
  1028. /**
  1029. * The field designating the key of a document.
  1030. */ static keyField() {
  1031. return new lt([ "__name__" ]);
  1032. }
  1033. /**
  1034. * Parses a field string from the given server-formatted string.
  1035. *
  1036. * - Splitting the empty string is not allowed (for now at least).
  1037. * - Empty segments within the string (e.g. if there are two consecutive
  1038. * separators) are not allowed.
  1039. *
  1040. * TODO(b/37244157): we should make this more strict. Right now, it allows
  1041. * non-identifier path components, even if they aren't escaped.
  1042. */ static fromServerFormat(t) {
  1043. const e = [];
  1044. let n = "", s = 0;
  1045. const i = () => {
  1046. if (0 === n.length) throw new G(K.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
  1047. e.push(n), n = "";
  1048. };
  1049. let r = !1;
  1050. for (;s < t.length; ) {
  1051. const e = t[s];
  1052. if ("\\" === e) {
  1053. if (s + 1 === t.length) throw new G(K.INVALID_ARGUMENT, "Path has trailing escape character: " + t);
  1054. const e = t[s + 1];
  1055. if ("\\" !== e && "." !== e && "`" !== e) throw new G(K.INVALID_ARGUMENT, "Path has invalid escape sequence: " + t);
  1056. n += e, s += 2;
  1057. } else "`" === e ? (r = !r, s++) : "." !== e || r ? (n += e, s++) : (i(), s++);
  1058. }
  1059. if (i(), r) throw new G(K.INVALID_ARGUMENT, "Unterminated ` in path: " + t);
  1060. return new lt(e);
  1061. }
  1062. static emptyPath() {
  1063. return new lt([]);
  1064. }
  1065. }
  1066. /**
  1067. * @license
  1068. * Copyright 2017 Google LLC
  1069. *
  1070. * Licensed under the Apache License, Version 2.0 (the "License");
  1071. * you may not use this file except in compliance with the License.
  1072. * You may obtain a copy of the License at
  1073. *
  1074. * http://www.apache.org/licenses/LICENSE-2.0
  1075. *
  1076. * Unless required by applicable law or agreed to in writing, software
  1077. * distributed under the License is distributed on an "AS IS" BASIS,
  1078. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1079. * See the License for the specific language governing permissions and
  1080. * limitations under the License.
  1081. */
  1082. /**
  1083. * @internal
  1084. */ class ft {
  1085. constructor(t) {
  1086. this.path = t;
  1087. }
  1088. static fromPath(t) {
  1089. return new ft(at.fromString(t));
  1090. }
  1091. static fromName(t) {
  1092. return new ft(at.fromString(t).popFirst(5));
  1093. }
  1094. static empty() {
  1095. return new ft(at.emptyPath());
  1096. }
  1097. get collectionGroup() {
  1098. return this.path.popLast().lastSegment();
  1099. }
  1100. /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {
  1101. return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
  1102. }
  1103. /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {
  1104. return this.path.get(this.path.length - 2);
  1105. }
  1106. /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {
  1107. return this.path.popLast();
  1108. }
  1109. isEqual(t) {
  1110. return null !== t && 0 === at.comparator(this.path, t.path);
  1111. }
  1112. toString() {
  1113. return this.path.toString();
  1114. }
  1115. static comparator(t, e) {
  1116. return at.comparator(t.path, e.path);
  1117. }
  1118. static isDocumentKey(t) {
  1119. return t.length % 2 == 0;
  1120. }
  1121. /**
  1122. * Creates and returns a new document key with the given segments.
  1123. *
  1124. * @param segments - The segments of the path to the document
  1125. * @returns A new instance of DocumentKey
  1126. */ static fromSegments(t) {
  1127. return new ft(new at(t.slice()));
  1128. }
  1129. }
  1130. /**
  1131. * @license
  1132. * Copyright 2021 Google LLC
  1133. *
  1134. * Licensed under the Apache License, Version 2.0 (the "License");
  1135. * you may not use this file except in compliance with the License.
  1136. * You may obtain a copy of the License at
  1137. *
  1138. * http://www.apache.org/licenses/LICENSE-2.0
  1139. *
  1140. * Unless required by applicable law or agreed to in writing, software
  1141. * distributed under the License is distributed on an "AS IS" BASIS,
  1142. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1143. * See the License for the specific language governing permissions and
  1144. * limitations under the License.
  1145. */
  1146. /**
  1147. * The initial mutation batch id for each index. Gets updated during index
  1148. * backfill.
  1149. */
  1150. /**
  1151. * An index definition for field indexes in Firestore.
  1152. *
  1153. * Every index is associated with a collection. The definition contains a list
  1154. * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or
  1155. * `CONTAINS` for ArrayContains/ArrayContainsAny queries).
  1156. *
  1157. * Unlike the backend, the SDK does not differentiate between collection or
  1158. * collection group-scoped indices. Every index can be used for both single
  1159. * collection and collection group queries.
  1160. */
  1161. class dt {
  1162. constructor(
  1163. /**
  1164. * The index ID. Returns -1 if the index ID is not available (e.g. the index
  1165. * has not yet been persisted).
  1166. */
  1167. t,
  1168. /** The collection ID this index applies to. */
  1169. e,
  1170. /** The field segments for this index. */
  1171. n,
  1172. /** Shows how up-to-date the index is for the current user. */
  1173. s) {
  1174. this.indexId = t, this.collectionGroup = e, this.fields = n, this.indexState = s;
  1175. }
  1176. }
  1177. /** An ID for an index that has not yet been added to persistence. */
  1178. /** Returns the ArrayContains/ArrayContainsAny segment for this index. */
  1179. function wt(t) {
  1180. return t.fields.find((t => 2 /* IndexKind.CONTAINS */ === t.kind));
  1181. }
  1182. /** Returns all directional (ascending/descending) segments for this index. */ function _t(t) {
  1183. return t.fields.filter((t => 2 /* IndexKind.CONTAINS */ !== t.kind));
  1184. }
  1185. /**
  1186. * Returns the order of the document key component for the given index.
  1187. *
  1188. * PORTING NOTE: This is only used in the Web IndexedDb implementation.
  1189. */
  1190. /**
  1191. * Compares indexes by collection group and segments. Ignores update time and
  1192. * index ID.
  1193. */
  1194. function mt(t, e) {
  1195. let n = st(t.collectionGroup, e.collectionGroup);
  1196. if (0 !== n) return n;
  1197. for (let s = 0; s < Math.min(t.fields.length, e.fields.length); ++s) if (n = yt(t.fields[s], e.fields[s]),
  1198. 0 !== n) return n;
  1199. return st(t.fields.length, e.fields.length);
  1200. }
  1201. /** Returns a debug representation of the field index */ dt.UNKNOWN_ID = -1;
  1202. /** An index component consisting of field path and index type. */
  1203. class gt {
  1204. constructor(
  1205. /** The field path of the component. */
  1206. t,
  1207. /** The fields sorting order. */
  1208. e) {
  1209. this.fieldPath = t, this.kind = e;
  1210. }
  1211. }
  1212. function yt(t, e) {
  1213. const n = lt.comparator(t.fieldPath, e.fieldPath);
  1214. return 0 !== n ? n : st(t.kind, e.kind);
  1215. }
  1216. /**
  1217. * Stores the "high water mark" that indicates how updated the Index is for the
  1218. * current user.
  1219. */ class pt {
  1220. constructor(
  1221. /**
  1222. * Indicates when the index was last updated (relative to other indexes).
  1223. */
  1224. t,
  1225. /** The the latest indexed read time, document and batch id. */
  1226. e) {
  1227. this.sequenceNumber = t, this.offset = e;
  1228. }
  1229. /** The state of an index that has not yet been backfilled. */ static empty() {
  1230. return new pt(0, Et.min());
  1231. }
  1232. }
  1233. /**
  1234. * Creates an offset that matches all documents with a read time higher than
  1235. * `readTime`.
  1236. */ function It(t, e) {
  1237. // We want to create an offset that matches all documents with a read time
  1238. // greater than the provided read time. To do so, we technically need to
  1239. // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use
  1240. // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use
  1241. // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches
  1242. // all valid document IDs.
  1243. const n = t.toTimestamp().seconds, s = t.toTimestamp().nanoseconds + 1, i = ut.fromTimestamp(1e9 === s ? new ot(n + 1, 0) : new ot(n, s));
  1244. return new Et(i, ft.empty(), e);
  1245. }
  1246. /** Creates a new offset based on the provided document. */ function Tt(t) {
  1247. return new Et(t.readTime, t.key, -1);
  1248. }
  1249. /**
  1250. * Stores the latest read time, document and batch ID that were processed for an
  1251. * index.
  1252. */ class Et {
  1253. constructor(
  1254. /**
  1255. * The latest read time version that has been indexed by Firestore for this
  1256. * field index.
  1257. */
  1258. t,
  1259. /**
  1260. * The key of the last document that was indexed for this query. Use
  1261. * `DocumentKey.empty()` if no document has been indexed.
  1262. */
  1263. e,
  1264. /*
  1265. * The largest mutation batch id that's been processed by Firestore.
  1266. */
  1267. n) {
  1268. this.readTime = t, this.documentKey = e, this.largestBatchId = n;
  1269. }
  1270. /** Returns an offset that sorts before all regular offsets. */ static min() {
  1271. return new Et(ut.min(), ft.empty(), -1);
  1272. }
  1273. /** Returns an offset that sorts after all regular offsets. */ static max() {
  1274. return new Et(ut.max(), ft.empty(), -1);
  1275. }
  1276. }
  1277. function At(t, e) {
  1278. let n = t.readTime.compareTo(e.readTime);
  1279. return 0 !== n ? n : (n = ft.comparator(t.documentKey, e.documentKey), 0 !== n ? n : st(t.largestBatchId, e.largestBatchId));
  1280. }
  1281. /**
  1282. * @license
  1283. * Copyright 2020 Google LLC
  1284. *
  1285. * Licensed under the Apache License, Version 2.0 (the "License");
  1286. * you may not use this file except in compliance with the License.
  1287. * You may obtain a copy of the License at
  1288. *
  1289. * http://www.apache.org/licenses/LICENSE-2.0
  1290. *
  1291. * Unless required by applicable law or agreed to in writing, software
  1292. * distributed under the License is distributed on an "AS IS" BASIS,
  1293. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1294. * See the License for the specific language governing permissions and
  1295. * limitations under the License.
  1296. */ const vt = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";
  1297. /**
  1298. * A base class representing a persistence transaction, encapsulating both the
  1299. * transaction's sequence numbers as well as a list of onCommitted listeners.
  1300. *
  1301. * When you call Persistence.runTransaction(), it will create a transaction and
  1302. * pass it to your callback. You then pass it to any method that operates
  1303. * on persistence.
  1304. */ class Rt {
  1305. constructor() {
  1306. this.onCommittedListeners = [];
  1307. }
  1308. addOnCommittedListener(t) {
  1309. this.onCommittedListeners.push(t);
  1310. }
  1311. raiseOnCommittedEvent() {
  1312. this.onCommittedListeners.forEach((t => t()));
  1313. }
  1314. }
  1315. /**
  1316. * @license
  1317. * Copyright 2017 Google LLC
  1318. *
  1319. * Licensed under the Apache License, Version 2.0 (the "License");
  1320. * you may not use this file except in compliance with the License.
  1321. * You may obtain a copy of the License at
  1322. *
  1323. * http://www.apache.org/licenses/LICENSE-2.0
  1324. *
  1325. * Unless required by applicable law or agreed to in writing, software
  1326. * distributed under the License is distributed on an "AS IS" BASIS,
  1327. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1328. * See the License for the specific language governing permissions and
  1329. * limitations under the License.
  1330. */
  1331. /**
  1332. * Verifies the error thrown by a LocalStore operation. If a LocalStore
  1333. * operation fails because the primary lease has been taken by another client,
  1334. * we ignore the error (the persistence layer will immediately call
  1335. * `applyPrimaryLease` to propagate the primary state change). All other errors
  1336. * are re-thrown.
  1337. *
  1338. * @param err - An error returned by a LocalStore operation.
  1339. * @returns A Promise that resolves after we recovered, or the original error.
  1340. */ async function Pt(t) {
  1341. if (t.code !== K.FAILED_PRECONDITION || t.message !== vt) throw t;
  1342. $("LocalStore", "Unexpectedly lost primary lease");
  1343. }
  1344. /**
  1345. * @license
  1346. * Copyright 2017 Google LLC
  1347. *
  1348. * Licensed under the Apache License, Version 2.0 (the "License");
  1349. * you may not use this file except in compliance with the License.
  1350. * You may obtain a copy of the License at
  1351. *
  1352. * http://www.apache.org/licenses/LICENSE-2.0
  1353. *
  1354. * Unless required by applicable law or agreed to in writing, software
  1355. * distributed under the License is distributed on an "AS IS" BASIS,
  1356. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1357. * See the License for the specific language governing permissions and
  1358. * limitations under the License.
  1359. */
  1360. /**
  1361. * PersistencePromise is essentially a re-implementation of Promise except
  1362. * it has a .next() method instead of .then() and .next() and .catch() callbacks
  1363. * are executed synchronously when a PersistencePromise resolves rather than
  1364. * asynchronously (Promise implementations use setImmediate() or similar).
  1365. *
  1366. * This is necessary to interoperate with IndexedDB which will automatically
  1367. * commit transactions if control is returned to the event loop without
  1368. * synchronously initiating another operation on the transaction.
  1369. *
  1370. * NOTE: .then() and .catch() only allow a single consumer, unlike normal
  1371. * Promises.
  1372. */ class bt {
  1373. constructor(t) {
  1374. // NOTE: next/catchCallback will always point to our own wrapper functions,
  1375. // not the user's raw next() or catch() callbacks.
  1376. this.nextCallback = null, this.catchCallback = null,
  1377. // When the operation resolves, we'll set result or error and mark isDone.
  1378. this.result = void 0, this.error = void 0, this.isDone = !1,
  1379. // Set to true when .then() or .catch() are called and prevents additional
  1380. // chaining.
  1381. this.callbackAttached = !1, t((t => {
  1382. this.isDone = !0, this.result = t, this.nextCallback &&
  1383. // value should be defined unless T is Void, but we can't express
  1384. // that in the type system.
  1385. this.nextCallback(t);
  1386. }), (t => {
  1387. this.isDone = !0, this.error = t, this.catchCallback && this.catchCallback(t);
  1388. }));
  1389. }
  1390. catch(t) {
  1391. return this.next(void 0, t);
  1392. }
  1393. next(t, e) {
  1394. return this.callbackAttached && B(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(e, this.error) : this.wrapSuccess(t, this.result) : new bt(((n, s) => {
  1395. this.nextCallback = e => {
  1396. this.wrapSuccess(t, e).next(n, s);
  1397. }, this.catchCallback = t => {
  1398. this.wrapFailure(e, t).next(n, s);
  1399. };
  1400. }));
  1401. }
  1402. toPromise() {
  1403. return new Promise(((t, e) => {
  1404. this.next(t, e);
  1405. }));
  1406. }
  1407. wrapUserFunction(t) {
  1408. try {
  1409. const e = t();
  1410. return e instanceof bt ? e : bt.resolve(e);
  1411. } catch (t) {
  1412. return bt.reject(t);
  1413. }
  1414. }
  1415. wrapSuccess(t, e) {
  1416. return t ? this.wrapUserFunction((() => t(e))) : bt.resolve(e);
  1417. }
  1418. wrapFailure(t, e) {
  1419. return t ? this.wrapUserFunction((() => t(e))) : bt.reject(e);
  1420. }
  1421. static resolve(t) {
  1422. return new bt(((e, n) => {
  1423. e(t);
  1424. }));
  1425. }
  1426. static reject(t) {
  1427. return new bt(((e, n) => {
  1428. n(t);
  1429. }));
  1430. }
  1431. static waitFor(
  1432. // Accept all Promise types in waitFor().
  1433. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1434. t) {
  1435. return new bt(((e, n) => {
  1436. let s = 0, i = 0, r = !1;
  1437. t.forEach((t => {
  1438. ++s, t.next((() => {
  1439. ++i, r && i === s && e();
  1440. }), (t => n(t)));
  1441. })), r = !0, i === s && e();
  1442. }));
  1443. }
  1444. /**
  1445. * Given an array of predicate functions that asynchronously evaluate to a
  1446. * boolean, implements a short-circuiting `or` between the results. Predicates
  1447. * will be evaluated until one of them returns `true`, then stop. The final
  1448. * result will be whether any of them returned `true`.
  1449. */ static or(t) {
  1450. let e = bt.resolve(!1);
  1451. for (const n of t) e = e.next((t => t ? bt.resolve(t) : n()));
  1452. return e;
  1453. }
  1454. static forEach(t, e) {
  1455. const n = [];
  1456. return t.forEach(((t, s) => {
  1457. n.push(e.call(this, t, s));
  1458. })), this.waitFor(n);
  1459. }
  1460. /**
  1461. * Concurrently map all array elements through asynchronous function.
  1462. */ static mapArray(t, e) {
  1463. return new bt(((n, s) => {
  1464. const i = t.length, r = new Array(i);
  1465. let o = 0;
  1466. for (let u = 0; u < i; u++) {
  1467. const c = u;
  1468. e(t[c]).next((t => {
  1469. r[c] = t, ++o, o === i && n(r);
  1470. }), (t => s(t)));
  1471. }
  1472. }));
  1473. }
  1474. /**
  1475. * An alternative to recursive PersistencePromise calls, that avoids
  1476. * potential memory problems from unbounded chains of promises.
  1477. *
  1478. * The `action` will be called repeatedly while `condition` is true.
  1479. */ static doWhile(t, e) {
  1480. return new bt(((n, s) => {
  1481. const i = () => {
  1482. !0 === t() ? e().next((() => {
  1483. i();
  1484. }), s) : n();
  1485. };
  1486. i();
  1487. }));
  1488. }
  1489. }
  1490. /**
  1491. * @license
  1492. * Copyright 2017 Google LLC
  1493. *
  1494. * Licensed under the Apache License, Version 2.0 (the "License");
  1495. * you may not use this file except in compliance with the License.
  1496. * You may obtain a copy of the License at
  1497. *
  1498. * http://www.apache.org/licenses/LICENSE-2.0
  1499. *
  1500. * Unless required by applicable law or agreed to in writing, software
  1501. * distributed under the License is distributed on an "AS IS" BASIS,
  1502. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1503. * See the License for the specific language governing permissions and
  1504. * limitations under the License.
  1505. */
  1506. // References to `window` are guarded by SimpleDb.isAvailable()
  1507. /* eslint-disable no-restricted-globals */
  1508. /**
  1509. * Wraps an IDBTransaction and exposes a store() method to get a handle to a
  1510. * specific object store.
  1511. */
  1512. class Vt {
  1513. constructor(t, e) {
  1514. this.action = t, this.transaction = e, this.aborted = !1,
  1515. /**
  1516. * A `Promise` that resolves with the result of the IndexedDb transaction.
  1517. */
  1518. this.v = new Q, this.transaction.oncomplete = () => {
  1519. this.v.resolve();
  1520. }, this.transaction.onabort = () => {
  1521. e.error ? this.v.reject(new Ct(t, e.error)) : this.v.resolve();
  1522. }, this.transaction.onerror = e => {
  1523. const n = Mt(e.target.error);
  1524. this.v.reject(new Ct(t, n));
  1525. };
  1526. }
  1527. static open(t, e, n, s) {
  1528. try {
  1529. return new Vt(e, t.transaction(s, n));
  1530. } catch (t) {
  1531. throw new Ct(e, t);
  1532. }
  1533. }
  1534. get R() {
  1535. return this.v.promise;
  1536. }
  1537. abort(t) {
  1538. t && this.v.reject(t), this.aborted || ($("SimpleDb", "Aborting transaction:", t ? t.message : "Client-initiated abort"),
  1539. this.aborted = !0, this.transaction.abort());
  1540. }
  1541. P() {
  1542. // If the browser supports V3 IndexedDB, we invoke commit() explicitly to
  1543. // speed up index DB processing if the event loop remains blocks.
  1544. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1545. const t = this.transaction;
  1546. this.aborted || "function" != typeof t.commit || t.commit();
  1547. }
  1548. /**
  1549. * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
  1550. * operations performed on the SimpleDbStore happen within the context of this
  1551. * transaction and it cannot be used anymore once the transaction is
  1552. * completed.
  1553. *
  1554. * Note that we can't actually enforce that the KeyType and ValueType are
  1555. * correct, but they allow type safety through the rest of the consuming code.
  1556. */ store(t) {
  1557. const e = this.transaction.objectStore(t);
  1558. return new Nt(e);
  1559. }
  1560. }
  1561. /**
  1562. * Provides a wrapper around IndexedDb with a simplified interface that uses
  1563. * Promise-like return values to chain operations. Real promises cannot be used
  1564. * since .then() continuations are executed asynchronously (e.g. via
  1565. * .setImmediate), which would cause IndexedDB to end the transaction.
  1566. * See PersistencePromise for more details.
  1567. */ class St {
  1568. /*
  1569. * Creates a new SimpleDb wrapper for IndexedDb database `name`.
  1570. *
  1571. * Note that `version` must not be a downgrade. IndexedDB does not support
  1572. * downgrading the schema version. We currently do not support any way to do
  1573. * versioning outside of IndexedDB's versioning mechanism, as only
  1574. * version-upgrade transactions are allowed to do things like create
  1575. * objectstores.
  1576. */
  1577. constructor(t, e, n) {
  1578. this.name = t, this.version = e, this.V = n;
  1579. // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the
  1580. // bug we're checking for should exist in iOS >= 12.2 and < 13, but for
  1581. // whatever reason it's much harder to hit after 12.2 so we only proactively
  1582. // log on 12.2.
  1583. 12.2 === St.S(a()) && M("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.");
  1584. }
  1585. /** Deletes the specified database. */ static delete(t) {
  1586. return $("SimpleDb", "Removing database:", t), kt(window.indexedDB.deleteDatabase(t)).toPromise();
  1587. }
  1588. /** Returns true if IndexedDB is available in the current environment. */ static D() {
  1589. if (!h()) return !1;
  1590. if (St.C()) return !0;
  1591. // We extensively use indexed array values and compound keys,
  1592. // which IE and Edge do not support. However, they still have indexedDB
  1593. // defined on the window, so we need to check for them here and make sure
  1594. // to return that persistence is not enabled for those browsers.
  1595. // For tracking support of this feature, see here:
  1596. // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/
  1597. // Check the UA string to find out the browser.
  1598. const t = a(), e = St.S(t), n = 0 < e && e < 10, s = St.N(t), i = 0 < s && s < 4.5;
  1599. // IE 10
  1600. // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
  1601. // IE 11
  1602. // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
  1603. // Edge
  1604. // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,
  1605. // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
  1606. // iOS Safari: Disable for users running iOS version < 10.
  1607. return !(t.indexOf("MSIE ") > 0 || t.indexOf("Trident/") > 0 || t.indexOf("Edge/") > 0 || n || i);
  1608. }
  1609. /**
  1610. * Returns true if the backing IndexedDB store is the Node IndexedDBShim
  1611. * (see https://github.com/axemclion/IndexedDBShim).
  1612. */ static C() {
  1613. var t;
  1614. return "undefined" != typeof process && "YES" === (null === (t = process.env) || void 0 === t ? void 0 : t.k);
  1615. }
  1616. /** Helper to get a typed SimpleDbStore from a transaction. */ static $(t, e) {
  1617. return t.store(e);
  1618. }
  1619. // visible for testing
  1620. /** Parse User Agent to determine iOS version. Returns -1 if not found. */
  1621. static S(t) {
  1622. const e = t.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = e ? e[1].split("_").slice(0, 2).join(".") : "-1";
  1623. return Number(n);
  1624. }
  1625. // visible for testing
  1626. /** Parse User Agent to determine Android version. Returns -1 if not found. */
  1627. static N(t) {
  1628. const e = t.match(/Android ([\d.]+)/i), n = e ? e[1].split(".").slice(0, 2).join(".") : "-1";
  1629. return Number(n);
  1630. }
  1631. /**
  1632. * Opens the specified database, creating or upgrading it if necessary.
  1633. */ async M(t) {
  1634. return this.db || ($("SimpleDb", "Opening database:", this.name), this.db = await new Promise(((e, n) => {
  1635. // TODO(mikelehen): Investigate browser compatibility.
  1636. // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
  1637. // suggests IE9 and older WebKit browsers handle upgrade
  1638. // differently. They expect setVersion, as described here:
  1639. // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion
  1640. const s = indexedDB.open(this.name, this.version);
  1641. s.onsuccess = t => {
  1642. const n = t.target.result;
  1643. e(n);
  1644. }, s.onblocked = () => {
  1645. n(new Ct(t, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."));
  1646. }, s.onerror = e => {
  1647. const s = e.target.error;
  1648. "VersionError" === s.name ? n(new G(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" === s.name ? n(new G(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: " + s)) : n(new Ct(t, s));
  1649. }, s.onupgradeneeded = t => {
  1650. $("SimpleDb", 'Database "' + this.name + '" requires upgrade from version:', t.oldVersion);
  1651. const e = t.target.result;
  1652. this.V.O(e, s.transaction, t.oldVersion, this.version).next((() => {
  1653. $("SimpleDb", "Database upgrade to version " + this.version + " complete");
  1654. }));
  1655. };
  1656. }))), this.F && (this.db.onversionchange = t => this.F(t)), this.db;
  1657. }
  1658. B(t) {
  1659. this.F = t, this.db && (this.db.onversionchange = e => t(e));
  1660. }
  1661. async runTransaction(t, e, n, s) {
  1662. const i = "readonly" === e;
  1663. let r = 0;
  1664. for (;;) {
  1665. ++r;
  1666. try {
  1667. this.db = await this.M(t);
  1668. const e = Vt.open(this.db, t, i ? "readonly" : "readwrite", n), r = s(e).next((t => (e.P(),
  1669. t))).catch((t => (
  1670. // Abort the transaction if there was an error.
  1671. e.abort(t), bt.reject(t)))).toPromise();
  1672. // As noted above, errors are propagated by aborting the transaction. So
  1673. // we swallow any error here to avoid the browser logging it as unhandled.
  1674. return r.catch((() => {})),
  1675. // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
  1676. // fire), but still return the original transactionFnResult back to the
  1677. // caller.
  1678. await e.R, r;
  1679. } catch (t) {
  1680. const e = t, n = "FirebaseError" !== e.name && r < 3;
  1681. // TODO(schmidt-sebastian): We could probably be smarter about this and
  1682. // not retry exceptions that are likely unrecoverable (such as quota
  1683. // exceeded errors).
  1684. // Note: We cannot use an instanceof check for FirestoreException, since the
  1685. // exception is wrapped in a generic error by our async/await handling.
  1686. if ($("SimpleDb", "Transaction failed with error:", e.message, "Retrying:", n),
  1687. this.close(), !n) return Promise.reject(e);
  1688. }
  1689. }
  1690. }
  1691. close() {
  1692. this.db && this.db.close(), this.db = void 0;
  1693. }
  1694. }
  1695. /**
  1696. * A controller for iterating over a key range or index. It allows an iterate
  1697. * callback to delete the currently-referenced object, or jump to a new key
  1698. * within the key range or index.
  1699. */ class Dt {
  1700. constructor(t) {
  1701. this.L = t, this.q = !1, this.U = null;
  1702. }
  1703. get isDone() {
  1704. return this.q;
  1705. }
  1706. get K() {
  1707. return this.U;
  1708. }
  1709. set cursor(t) {
  1710. this.L = t;
  1711. }
  1712. /**
  1713. * This function can be called to stop iteration at any point.
  1714. */ done() {
  1715. this.q = !0;
  1716. }
  1717. /**
  1718. * This function can be called to skip to that next key, which could be
  1719. * an index or a primary key.
  1720. */ G(t) {
  1721. this.U = t;
  1722. }
  1723. /**
  1724. * Delete the current cursor value from the object store.
  1725. *
  1726. * NOTE: You CANNOT do this with a keysOnly query.
  1727. */ delete() {
  1728. return kt(this.L.delete());
  1729. }
  1730. }
  1731. /** An error that wraps exceptions that thrown during IndexedDB execution. */ class Ct extends G {
  1732. constructor(t, e) {
  1733. super(K.UNAVAILABLE, `IndexedDB transaction '${t}' failed: ${e}`), this.name = "IndexedDbTransactionError";
  1734. }
  1735. }
  1736. /** Verifies whether `e` is an IndexedDbTransactionError. */ function xt(t) {
  1737. // Use name equality, as instanceof checks on errors don't work with errors
  1738. // that wrap other errors.
  1739. return "IndexedDbTransactionError" === t.name;
  1740. }
  1741. /**
  1742. * A wrapper around an IDBObjectStore providing an API that:
  1743. *
  1744. * 1) Has generic KeyType / ValueType parameters to provide strongly-typed
  1745. * methods for acting against the object store.
  1746. * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every
  1747. * method return a PersistencePromise instead.
  1748. * 3) Provides a higher-level API to avoid needing to do excessive wrapping of
  1749. * intermediate IndexedDB types (IDBCursorWithValue, etc.)
  1750. */ class Nt {
  1751. constructor(t) {
  1752. this.store = t;
  1753. }
  1754. put(t, e) {
  1755. let n;
  1756. return void 0 !== e ? ($("SimpleDb", "PUT", this.store.name, t, e), n = this.store.put(e, t)) : ($("SimpleDb", "PUT", this.store.name, "<auto-key>", t),
  1757. n = this.store.put(t)), kt(n);
  1758. }
  1759. /**
  1760. * Adds a new value into an Object Store and returns the new key. Similar to
  1761. * IndexedDb's `add()`, this method will fail on primary key collisions.
  1762. *
  1763. * @param value - The object to write.
  1764. * @returns The key of the value to add.
  1765. */ add(t) {
  1766. $("SimpleDb", "ADD", this.store.name, t, t);
  1767. return kt(this.store.add(t));
  1768. }
  1769. /**
  1770. * Gets the object with the specified key from the specified store, or null
  1771. * if no object exists with the specified key.
  1772. *
  1773. * @key The key of the object to get.
  1774. * @returns The object with the specified key or null if no object exists.
  1775. */ get(t) {
  1776. // We're doing an unsafe cast to ValueType.
  1777. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1778. return kt(this.store.get(t)).next((e => (
  1779. // Normalize nonexistence to null.
  1780. void 0 === e && (e = null), $("SimpleDb", "GET", this.store.name, t, e), e)));
  1781. }
  1782. delete(t) {
  1783. $("SimpleDb", "DELETE", this.store.name, t);
  1784. return kt(this.store.delete(t));
  1785. }
  1786. /**
  1787. * If we ever need more of the count variants, we can add overloads. For now,
  1788. * all we need is to count everything in a store.
  1789. *
  1790. * Returns the number of rows in the store.
  1791. */ count() {
  1792. $("SimpleDb", "COUNT", this.store.name);
  1793. return kt(this.store.count());
  1794. }
  1795. j(t, e) {
  1796. const n = this.options(t, e);
  1797. // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly
  1798. // 20% faster. Unfortunately, getAll() does not support custom indices.
  1799. if (n.index || "function" != typeof this.store.getAll) {
  1800. const t = this.cursor(n), e = [];
  1801. return this.W(t, ((t, n) => {
  1802. e.push(n);
  1803. })).next((() => e));
  1804. }
  1805. {
  1806. const t = this.store.getAll(n.range);
  1807. return new bt(((e, n) => {
  1808. t.onerror = t => {
  1809. n(t.target.error);
  1810. }, t.onsuccess = t => {
  1811. e(t.target.result);
  1812. };
  1813. }));
  1814. }
  1815. }
  1816. /**
  1817. * Loads the first `count` elements from the provided index range. Loads all
  1818. * elements if no limit is provided.
  1819. */ H(t, e) {
  1820. const n = this.store.getAll(t, null === e ? void 0 : e);
  1821. return new bt(((t, e) => {
  1822. n.onerror = t => {
  1823. e(t.target.error);
  1824. }, n.onsuccess = e => {
  1825. t(e.target.result);
  1826. };
  1827. }));
  1828. }
  1829. J(t, e) {
  1830. $("SimpleDb", "DELETE ALL", this.store.name);
  1831. const n = this.options(t, e);
  1832. n.Y = !1;
  1833. const s = this.cursor(n);
  1834. return this.W(s, ((t, e, n) => n.delete()));
  1835. }
  1836. X(t, e) {
  1837. let n;
  1838. e ? n = t : (n = {}, e = t);
  1839. const s = this.cursor(n);
  1840. return this.W(s, e);
  1841. }
  1842. /**
  1843. * Iterates over a store, but waits for the given callback to complete for
  1844. * each entry before iterating the next entry. This allows the callback to do
  1845. * asynchronous work to determine if this iteration should continue.
  1846. *
  1847. * The provided callback should return `true` to continue iteration, and
  1848. * `false` otherwise.
  1849. */ Z(t) {
  1850. const e = this.cursor({});
  1851. return new bt(((n, s) => {
  1852. e.onerror = t => {
  1853. const e = Mt(t.target.error);
  1854. s(e);
  1855. }, e.onsuccess = e => {
  1856. const s = e.target.result;
  1857. s ? t(s.primaryKey, s.value).next((t => {
  1858. t ? s.continue() : n();
  1859. })) : n();
  1860. };
  1861. }));
  1862. }
  1863. W(t, e) {
  1864. const n = [];
  1865. return new bt(((s, i) => {
  1866. t.onerror = t => {
  1867. i(t.target.error);
  1868. }, t.onsuccess = t => {
  1869. const i = t.target.result;
  1870. if (!i) return void s();
  1871. const r = new Dt(i), o = e(i.primaryKey, i.value, r);
  1872. if (o instanceof bt) {
  1873. const t = o.catch((t => (r.done(), bt.reject(t))));
  1874. n.push(t);
  1875. }
  1876. r.isDone ? s() : null === r.K ? i.continue() : i.continue(r.K);
  1877. };
  1878. })).next((() => bt.waitFor(n)));
  1879. }
  1880. options(t, e) {
  1881. let n;
  1882. return void 0 !== t && ("string" == typeof t ? n = t : e = t), {
  1883. index: n,
  1884. range: e
  1885. };
  1886. }
  1887. cursor(t) {
  1888. let e = "next";
  1889. if (t.reverse && (e = "prev"), t.index) {
  1890. const n = this.store.index(t.index);
  1891. return t.Y ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);
  1892. }
  1893. return this.store.openCursor(t.range, e);
  1894. }
  1895. }
  1896. /**
  1897. * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror
  1898. * handlers to resolve / reject the PersistencePromise as appropriate.
  1899. */ function kt(t) {
  1900. return new bt(((e, n) => {
  1901. t.onsuccess = t => {
  1902. const n = t.target.result;
  1903. e(n);
  1904. }, t.onerror = t => {
  1905. const e = Mt(t.target.error);
  1906. n(e);
  1907. };
  1908. }));
  1909. }
  1910. // Guard so we only report the error once.
  1911. let $t = !1;
  1912. function Mt(t) {
  1913. const e = St.S(a());
  1914. if (e >= 12.2 && e < 13) {
  1915. const e = "An internal error was encountered in the Indexed Database server";
  1916. if (t.message.indexOf(e) >= 0) {
  1917. // Wrap error in a more descriptive one.
  1918. const t = new G("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);
  1919. return $t || ($t = !0,
  1920. // Throw a global exception outside of this promise chain, for the user to
  1921. // potentially catch.
  1922. setTimeout((() => {
  1923. throw t;
  1924. }), 0)), t;
  1925. }
  1926. }
  1927. return t;
  1928. }
  1929. /** This class is responsible for the scheduling of Index Backfiller. */
  1930. class Ot {
  1931. constructor(t, e) {
  1932. this.asyncQueue = t, this.tt = e, this.task = null;
  1933. }
  1934. start() {
  1935. this.et(15e3);
  1936. }
  1937. stop() {
  1938. this.task && (this.task.cancel(), this.task = null);
  1939. }
  1940. get started() {
  1941. return null !== this.task;
  1942. }
  1943. et(t) {
  1944. $("IndexBackiller", `Scheduled in ${t}ms`), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */ , t, (async () => {
  1945. this.task = null;
  1946. try {
  1947. $("IndexBackiller", `Documents written: ${await this.tt.nt()}`);
  1948. } catch (t) {
  1949. xt(t) ? $("IndexBackiller", "Ignoring IndexedDB error during index backfill: ", t) : await Pt(t);
  1950. }
  1951. await this.et(6e4);
  1952. }));
  1953. }
  1954. }
  1955. /** Implements the steps for backfilling indexes. */ class Ft {
  1956. constructor(
  1957. /**
  1958. * LocalStore provides access to IndexManager and LocalDocumentView.
  1959. * These properties will update when the user changes. Consequently,
  1960. * making a local copy of IndexManager and LocalDocumentView will require
  1961. * updates over time. The simpler solution is to rely on LocalStore to have
  1962. * an up-to-date references to IndexManager and LocalDocumentStore.
  1963. */
  1964. t, e) {
  1965. this.localStore = t, this.persistence = e;
  1966. }
  1967. async nt(t = 50) {
  1968. return this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (e => this.st(e, t)));
  1969. }
  1970. /** Writes index entries until the cap is reached. Returns the number of documents processed. */ st(t, e) {
  1971. const n = new Set;
  1972. let s = e, i = !0;
  1973. return bt.doWhile((() => !0 === i && s > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(t).next((e => {
  1974. if (null !== e && !n.has(e)) return $("IndexBackiller", `Processing collection: ${e}`),
  1975. this.it(t, e, s).next((t => {
  1976. s -= t, n.add(e);
  1977. }));
  1978. i = !1;
  1979. })))).next((() => e - s));
  1980. }
  1981. /**
  1982. * Writes entries for the provided collection group. Returns the number of documents processed.
  1983. */ it(t, e, n) {
  1984. // Use the earliest offset of all field indexes to query the local cache.
  1985. return this.localStore.indexManager.getMinOffsetFromCollectionGroup(t, e).next((s => this.localStore.localDocuments.getNextDocuments(t, e, s, n).next((n => {
  1986. const i = n.changes;
  1987. return this.localStore.indexManager.updateIndexEntries(t, i).next((() => this.rt(s, n))).next((n => ($("IndexBackiller", `Updating offset: ${n}`),
  1988. this.localStore.indexManager.updateCollectionGroup(t, e, n)))).next((() => i.size));
  1989. }))));
  1990. }
  1991. /** Returns the next offset based on the provided documents. */ rt(t, e) {
  1992. let n = t;
  1993. return e.changes.forEach(((t, e) => {
  1994. const s = Tt(e);
  1995. At(s, n) > 0 && (n = s);
  1996. })), new Et(n.readTime, n.documentKey, Math.max(e.batchId, t.largestBatchId));
  1997. }
  1998. }
  1999. /**
  2000. * @license
  2001. * Copyright 2018 Google LLC
  2002. *
  2003. * Licensed under the Apache License, Version 2.0 (the "License");
  2004. * you may not use this file except in compliance with the License.
  2005. * You may obtain a copy of the License at
  2006. *
  2007. * http://www.apache.org/licenses/LICENSE-2.0
  2008. *
  2009. * Unless required by applicable law or agreed to in writing, software
  2010. * distributed under the License is distributed on an "AS IS" BASIS,
  2011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2012. * See the License for the specific language governing permissions and
  2013. * limitations under the License.
  2014. */
  2015. /**
  2016. * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to
  2017. * exceed. All subsequent calls to next will return increasing values. If provided with a
  2018. * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as
  2019. * well as write out sequence numbers that it produces via `next()`.
  2020. */ class Bt {
  2021. constructor(t, e) {
  2022. this.previousValue = t, e && (e.sequenceNumberHandler = t => this.ot(t), this.ut = t => e.writeSequenceNumber(t));
  2023. }
  2024. ot(t) {
  2025. return this.previousValue = Math.max(t, this.previousValue), this.previousValue;
  2026. }
  2027. next() {
  2028. const t = ++this.previousValue;
  2029. return this.ut && this.ut(t), t;
  2030. }
  2031. }
  2032. Bt.ct = -1;
  2033. /**
  2034. * Returns whether a variable is either undefined or null.
  2035. */
  2036. function Lt(t) {
  2037. return null == t;
  2038. }
  2039. /** Returns whether the value represents -0. */ function qt(t) {
  2040. // Detect if the value is -0.0. Based on polyfill from
  2041. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  2042. return 0 === t && 1 / t == -1 / 0;
  2043. }
  2044. /**
  2045. * Returns whether a value is an integer and in the safe integer range
  2046. * @param value - The value to test for being an integer and in the safe range
  2047. */ function Ut(t) {
  2048. return "number" == typeof t && Number.isInteger(t) && !qt(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;
  2049. }
  2050. /**
  2051. * @license
  2052. * Copyright 2017 Google LLC
  2053. *
  2054. * Licensed under the Apache License, Version 2.0 (the "License");
  2055. * you may not use this file except in compliance with the License.
  2056. * You may obtain a copy of the License at
  2057. *
  2058. * http://www.apache.org/licenses/LICENSE-2.0
  2059. *
  2060. * Unless required by applicable law or agreed to in writing, software
  2061. * distributed under the License is distributed on an "AS IS" BASIS,
  2062. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2063. * See the License for the specific language governing permissions and
  2064. * limitations under the License.
  2065. */
  2066. /**
  2067. * Encodes a resource path into a IndexedDb-compatible string form.
  2068. */
  2069. function Kt(t) {
  2070. let e = "";
  2071. for (let n = 0; n < t.length; n++) e.length > 0 && (e = Qt(e)), e = Gt(t.get(n), e);
  2072. return Qt(e);
  2073. }
  2074. /** Encodes a single segment of a resource path into the given result */ function Gt(t, e) {
  2075. let n = e;
  2076. const s = t.length;
  2077. for (let e = 0; e < s; e++) {
  2078. const s = t.charAt(e);
  2079. switch (s) {
  2080. case "\0":
  2081. n += "";
  2082. break;
  2083. case "":
  2084. n += "";
  2085. break;
  2086. default:
  2087. n += s;
  2088. }
  2089. }
  2090. return n;
  2091. }
  2092. /** Encodes a path separator into the given result */ function Qt(t) {
  2093. return t + "";
  2094. }
  2095. /**
  2096. * Decodes the given IndexedDb-compatible string form of a resource path into
  2097. * a ResourcePath instance. Note that this method is not suitable for use with
  2098. * decoding resource names from the server; those are One Platform format
  2099. * strings.
  2100. */ function jt(t) {
  2101. // Event the empty path must encode as a path of at least length 2. A path
  2102. // with exactly 2 must be the empty path.
  2103. const e = t.length;
  2104. if (L(e >= 2), 2 === e) return L("" === t.charAt(0) && "" === t.charAt(1)), at.emptyPath();
  2105. // Escape characters cannot exist past the second-to-last position in the
  2106. // source value.
  2107. const __PRIVATE_lastReasonableEscapeIndex = e - 2, n = [];
  2108. let s = "";
  2109. for (let i = 0; i < e; ) {
  2110. // The last two characters of a valid encoded path must be a separator, so
  2111. // there must be an end to this segment.
  2112. const e = t.indexOf("", i);
  2113. (e < 0 || e > __PRIVATE_lastReasonableEscapeIndex) && B();
  2114. switch (t.charAt(e + 1)) {
  2115. case "":
  2116. const r = t.substring(i, e);
  2117. let o;
  2118. 0 === s.length ?
  2119. // Avoid copying for the common case of a segment that excludes \0
  2120. // and \001
  2121. o = r : (s += r, o = s, s = ""), n.push(o);
  2122. break;
  2123. case "":
  2124. s += t.substring(i, e), s += "\0";
  2125. break;
  2126. case "":
  2127. // The escape character can be used in the output to encode itself.
  2128. s += t.substring(i, e + 1);
  2129. break;
  2130. default:
  2131. B();
  2132. }
  2133. i = e + 2;
  2134. }
  2135. return new at(n);
  2136. }
  2137. /**
  2138. * @license
  2139. * Copyright 2022 Google LLC
  2140. *
  2141. * Licensed under the Apache License, Version 2.0 (the "License");
  2142. * you may not use this file except in compliance with the License.
  2143. * You may obtain a copy of the License at
  2144. *
  2145. * http://www.apache.org/licenses/LICENSE-2.0
  2146. *
  2147. * Unless required by applicable law or agreed to in writing, software
  2148. * distributed under the License is distributed on an "AS IS" BASIS,
  2149. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2150. * See the License for the specific language governing permissions and
  2151. * limitations under the License.
  2152. */ const zt = [ "userId", "batchId" ];
  2153. /**
  2154. * @license
  2155. * Copyright 2022 Google LLC
  2156. *
  2157. * Licensed under the Apache License, Version 2.0 (the "License");
  2158. * you may not use this file except in compliance with the License.
  2159. * You may obtain a copy of the License at
  2160. *
  2161. * http://www.apache.org/licenses/LICENSE-2.0
  2162. *
  2163. * Unless required by applicable law or agreed to in writing, software
  2164. * distributed under the License is distributed on an "AS IS" BASIS,
  2165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2166. * See the License for the specific language governing permissions and
  2167. * limitations under the License.
  2168. */
  2169. /**
  2170. * Name of the IndexedDb object store.
  2171. *
  2172. * Note that the name 'owner' is chosen to ensure backwards compatibility with
  2173. * older clients that only supported single locked access to the persistence
  2174. * layer.
  2175. */
  2176. /**
  2177. * Creates a [userId, encodedPath] key for use in the DbDocumentMutations
  2178. * index to iterate over all at document mutations for a given path or lower.
  2179. */
  2180. function Wt(t, e) {
  2181. return [ t, Kt(e) ];
  2182. }
  2183. /**
  2184. * Creates a full index key of [userId, encodedPath, batchId] for inserting
  2185. * and deleting into the DbDocumentMutations index.
  2186. */ function Ht(t, e, n) {
  2187. return [ t, Kt(e), n ];
  2188. }
  2189. /**
  2190. * Because we store all the useful information for this store in the key,
  2191. * there is no useful information to store as the value. The raw (unencoded)
  2192. * path cannot be stored because IndexedDb doesn't store prototype
  2193. * information.
  2194. */ const Jt = {}, Yt = [ "prefixPath", "collectionGroup", "readTime", "documentId" ], Xt = [ "prefixPath", "collectionGroup", "documentId" ], Zt = [ "collectionGroup", "readTime", "prefixPath", "documentId" ], te = [ "canonicalId", "targetId" ], ee = [ "targetId", "path" ], ne = [ "path", "targetId" ], se = [ "collectionId", "parent" ], ie = [ "indexId", "uid" ], re = [ "uid", "sequenceNumber" ], oe = [ "indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey" ], ue = [ "indexId", "uid", "orderedDocumentKey" ], ce = [ "userId", "collectionPath", "documentId" ], ae = [ "userId", "collectionPath", "largestBatchId" ], he = [ "userId", "collectionGroup", "largestBatchId" ], le = [ ...[ ...[ ...[ ...[ "mutationQueues", "mutations", "documentMutations", "remoteDocuments", "targets", "owner", "targetGlobal", "targetDocuments" ], "clientMetadata" ], "remoteDocumentGlobal" ], "collectionParents" ], "bundles", "namedQueries" ], fe = [ ...le, "documentOverlays" ], de = [ "mutationQueues", "mutations", "documentMutations", "remoteDocumentsV14", "targets", "owner", "targetGlobal", "targetDocuments", "clientMetadata", "remoteDocumentGlobal", "collectionParents", "bundles", "namedQueries", "documentOverlays" ], we = de, _e = [ ...we, "indexConfiguration", "indexState", "indexEntries" ];
  2195. /**
  2196. * @license
  2197. * Copyright 2020 Google LLC
  2198. *
  2199. * Licensed under the Apache License, Version 2.0 (the "License");
  2200. * you may not use this file except in compliance with the License.
  2201. * You may obtain a copy of the License at
  2202. *
  2203. * http://www.apache.org/licenses/LICENSE-2.0
  2204. *
  2205. * Unless required by applicable law or agreed to in writing, software
  2206. * distributed under the License is distributed on an "AS IS" BASIS,
  2207. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2208. * See the License for the specific language governing permissions and
  2209. * limitations under the License.
  2210. */
  2211. class me extends Rt {
  2212. constructor(t, e) {
  2213. super(), this.ht = t, this.currentSequenceNumber = e;
  2214. }
  2215. }
  2216. function ge(t, e) {
  2217. const n = U(t);
  2218. return St.$(n.ht, e);
  2219. }
  2220. /**
  2221. * @license
  2222. * Copyright 2017 Google LLC
  2223. *
  2224. * Licensed under the Apache License, Version 2.0 (the "License");
  2225. * you may not use this file except in compliance with the License.
  2226. * You may obtain a copy of the License at
  2227. *
  2228. * http://www.apache.org/licenses/LICENSE-2.0
  2229. *
  2230. * Unless required by applicable law or agreed to in writing, software
  2231. * distributed under the License is distributed on an "AS IS" BASIS,
  2232. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2233. * See the License for the specific language governing permissions and
  2234. * limitations under the License.
  2235. */ function ye(t) {
  2236. let e = 0;
  2237. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;
  2238. return e;
  2239. }
  2240. function pe(t, e) {
  2241. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);
  2242. }
  2243. function Ie(t) {
  2244. for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
  2245. return !0;
  2246. }
  2247. /**
  2248. * @license
  2249. * Copyright 2017 Google LLC
  2250. *
  2251. * Licensed under the Apache License, Version 2.0 (the "License");
  2252. * you may not use this file except in compliance with the License.
  2253. * You may obtain a copy of the License at
  2254. *
  2255. * http://www.apache.org/licenses/LICENSE-2.0
  2256. *
  2257. * Unless required by applicable law or agreed to in writing, software
  2258. * distributed under the License is distributed on an "AS IS" BASIS,
  2259. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2260. * See the License for the specific language governing permissions and
  2261. * limitations under the License.
  2262. */
  2263. // An immutable sorted map implementation, based on a Left-leaning Red-Black
  2264. // tree.
  2265. class Te {
  2266. constructor(t, e) {
  2267. this.comparator = t, this.root = e || Ae.EMPTY;
  2268. }
  2269. // Returns a copy of the map, with the specified key/value added or replaced.
  2270. insert(t, e) {
  2271. return new Te(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, Ae.BLACK, null, null));
  2272. }
  2273. // Returns a copy of the map, with the specified key removed.
  2274. remove(t) {
  2275. return new Te(this.comparator, this.root.remove(t, this.comparator).copy(null, null, Ae.BLACK, null, null));
  2276. }
  2277. // Returns the value of the node with the given key, or null.
  2278. get(t) {
  2279. let e = this.root;
  2280. for (;!e.isEmpty(); ) {
  2281. const n = this.comparator(t, e.key);
  2282. if (0 === n) return e.value;
  2283. n < 0 ? e = e.left : n > 0 && (e = e.right);
  2284. }
  2285. return null;
  2286. }
  2287. // Returns the index of the element in this sorted map, or -1 if it doesn't
  2288. // exist.
  2289. indexOf(t) {
  2290. // Number of nodes that were pruned when descending right
  2291. let e = 0, n = this.root;
  2292. for (;!n.isEmpty(); ) {
  2293. const s = this.comparator(t, n.key);
  2294. if (0 === s) return e + n.left.size;
  2295. s < 0 ? n = n.left : (
  2296. // Count all nodes left of the node plus the node itself
  2297. e += n.left.size + 1, n = n.right);
  2298. }
  2299. // Node not found
  2300. return -1;
  2301. }
  2302. isEmpty() {
  2303. return this.root.isEmpty();
  2304. }
  2305. // Returns the total number of nodes in the map.
  2306. get size() {
  2307. return this.root.size;
  2308. }
  2309. // Returns the minimum key in the map.
  2310. minKey() {
  2311. return this.root.minKey();
  2312. }
  2313. // Returns the maximum key in the map.
  2314. maxKey() {
  2315. return this.root.maxKey();
  2316. }
  2317. // Traverses the map in key order and calls the specified action function
  2318. // for each key/value pair. If action returns true, traversal is aborted.
  2319. // Returns the first truthy value returned by action, or the last falsey
  2320. // value returned by action.
  2321. inorderTraversal(t) {
  2322. return this.root.inorderTraversal(t);
  2323. }
  2324. forEach(t) {
  2325. this.inorderTraversal(((e, n) => (t(e, n), !1)));
  2326. }
  2327. toString() {
  2328. const t = [];
  2329. return this.inorderTraversal(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(", ")}}`;
  2330. }
  2331. // Traverses the map in reverse key order and calls the specified action
  2332. // function for each key/value pair. If action returns true, traversal is
  2333. // aborted.
  2334. // Returns the first truthy value returned by action, or the last falsey
  2335. // value returned by action.
  2336. reverseTraversal(t) {
  2337. return this.root.reverseTraversal(t);
  2338. }
  2339. // Returns an iterator over the SortedMap.
  2340. getIterator() {
  2341. return new Ee(this.root, null, this.comparator, !1);
  2342. }
  2343. getIteratorFrom(t) {
  2344. return new Ee(this.root, t, this.comparator, !1);
  2345. }
  2346. getReverseIterator() {
  2347. return new Ee(this.root, null, this.comparator, !0);
  2348. }
  2349. getReverseIteratorFrom(t) {
  2350. return new Ee(this.root, t, this.comparator, !0);
  2351. }
  2352. }
  2353. // end SortedMap
  2354. // An iterator over an LLRBNode.
  2355. class Ee {
  2356. constructor(t, e, n, s) {
  2357. this.isReverse = s, this.nodeStack = [];
  2358. let i = 1;
  2359. for (;!t.isEmpty(); ) if (i = e ? n(t.key, e) : 1,
  2360. // flip the comparison if we're going in reverse
  2361. e && s && (i *= -1), i < 0)
  2362. // This node is less than our start key. ignore it
  2363. t = this.isReverse ? t.left : t.right; else {
  2364. if (0 === i) {
  2365. // This node is exactly equal to our start key. Push it on the stack,
  2366. // but stop iterating;
  2367. this.nodeStack.push(t);
  2368. break;
  2369. }
  2370. // This node is greater than our start key, add it to the stack and move
  2371. // to the next one
  2372. this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;
  2373. }
  2374. }
  2375. getNext() {
  2376. let t = this.nodeStack.pop();
  2377. const e = {
  2378. key: t.key,
  2379. value: t.value
  2380. };
  2381. 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),
  2382. t = t.left;
  2383. return e;
  2384. }
  2385. hasNext() {
  2386. return this.nodeStack.length > 0;
  2387. }
  2388. peek() {
  2389. if (0 === this.nodeStack.length) return null;
  2390. const t = this.nodeStack[this.nodeStack.length - 1];
  2391. return {
  2392. key: t.key,
  2393. value: t.value
  2394. };
  2395. }
  2396. }
  2397. // end SortedMapIterator
  2398. // Represents a node in a Left-leaning Red-Black tree.
  2399. class Ae {
  2400. constructor(t, e, n, s, i) {
  2401. this.key = t, this.value = e, this.color = null != n ? n : Ae.RED, this.left = null != s ? s : Ae.EMPTY,
  2402. this.right = null != i ? i : Ae.EMPTY, this.size = this.left.size + 1 + this.right.size;
  2403. }
  2404. // Returns a copy of the current node, optionally replacing pieces of it.
  2405. copy(t, e, n, s, i) {
  2406. return new Ae(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != s ? s : this.left, null != i ? i : this.right);
  2407. }
  2408. isEmpty() {
  2409. return !1;
  2410. }
  2411. // Traverses the tree in key order and calls the specified action function
  2412. // for each node. If action returns true, traversal is aborted.
  2413. // Returns the first truthy value returned by action, or the last falsey
  2414. // value returned by action.
  2415. inorderTraversal(t) {
  2416. return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);
  2417. }
  2418. // Traverses the tree in reverse key order and calls the specified action
  2419. // function for each node. If action returns true, traversal is aborted.
  2420. // Returns the first truthy value returned by action, or the last falsey
  2421. // value returned by action.
  2422. reverseTraversal(t) {
  2423. return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);
  2424. }
  2425. // Returns the minimum node in the tree.
  2426. min() {
  2427. return this.left.isEmpty() ? this : this.left.min();
  2428. }
  2429. // Returns the maximum key in the tree.
  2430. minKey() {
  2431. return this.min().key;
  2432. }
  2433. // Returns the maximum key in the tree.
  2434. maxKey() {
  2435. return this.right.isEmpty() ? this.key : this.right.maxKey();
  2436. }
  2437. // Returns new tree, with the key/value added.
  2438. insert(t, e, n) {
  2439. let s = this;
  2440. const i = n(t, s.key);
  2441. return s = i < 0 ? s.copy(null, null, null, s.left.insert(t, e, n), null) : 0 === i ? s.copy(null, e, null, null, null) : s.copy(null, null, null, null, s.right.insert(t, e, n)),
  2442. s.fixUp();
  2443. }
  2444. removeMin() {
  2445. if (this.left.isEmpty()) return Ae.EMPTY;
  2446. let t = this;
  2447. return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null),
  2448. t.fixUp();
  2449. }
  2450. // Returns new tree, with the specified item removed.
  2451. remove(t, e) {
  2452. let n, s = this;
  2453. if (e(t, s.key) < 0) s.left.isEmpty() || s.left.isRed() || s.left.left.isRed() || (s = s.moveRedLeft()),
  2454. s = s.copy(null, null, null, s.left.remove(t, e), null); else {
  2455. if (s.left.isRed() && (s = s.rotateRight()), s.right.isEmpty() || s.right.isRed() || s.right.left.isRed() || (s = s.moveRedRight()),
  2456. 0 === e(t, s.key)) {
  2457. if (s.right.isEmpty()) return Ae.EMPTY;
  2458. n = s.right.min(), s = s.copy(n.key, n.value, null, null, s.right.removeMin());
  2459. }
  2460. s = s.copy(null, null, null, null, s.right.remove(t, e));
  2461. }
  2462. return s.fixUp();
  2463. }
  2464. isRed() {
  2465. return this.color;
  2466. }
  2467. // Returns new tree after performing any needed rotations.
  2468. fixUp() {
  2469. let t = this;
  2470. return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()),
  2471. t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;
  2472. }
  2473. moveRedLeft() {
  2474. let t = this.colorFlip();
  2475. return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()),
  2476. t = t.rotateLeft(), t = t.colorFlip()), t;
  2477. }
  2478. moveRedRight() {
  2479. let t = this.colorFlip();
  2480. return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t;
  2481. }
  2482. rotateLeft() {
  2483. const t = this.copy(null, null, Ae.RED, null, this.right.left);
  2484. return this.right.copy(null, null, this.color, t, null);
  2485. }
  2486. rotateRight() {
  2487. const t = this.copy(null, null, Ae.RED, this.left.right, null);
  2488. return this.left.copy(null, null, this.color, null, t);
  2489. }
  2490. colorFlip() {
  2491. const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);
  2492. return this.copy(null, null, !this.color, t, e);
  2493. }
  2494. // For testing.
  2495. checkMaxDepth() {
  2496. const t = this.check();
  2497. return Math.pow(2, t) <= this.size + 1;
  2498. }
  2499. // In a balanced RB tree, the black-depth (number of black nodes) from root to
  2500. // leaves is equal on both sides. This function verifies that or asserts.
  2501. check() {
  2502. if (this.isRed() && this.left.isRed()) throw B();
  2503. if (this.right.isRed()) throw B();
  2504. const t = this.left.check();
  2505. if (t !== this.right.check()) throw B();
  2506. return t + (this.isRed() ? 0 : 1);
  2507. }
  2508. }
  2509. // end LLRBNode
  2510. // Empty node is shared between all LLRB trees.
  2511. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2512. Ae.EMPTY = null, Ae.RED = !0, Ae.BLACK = !1;
  2513. // end LLRBEmptyNode
  2514. Ae.EMPTY = new
  2515. // Represents an empty node (a leaf node in the Red-Black Tree).
  2516. class {
  2517. constructor() {
  2518. this.size = 0;
  2519. }
  2520. get key() {
  2521. throw B();
  2522. }
  2523. get value() {
  2524. throw B();
  2525. }
  2526. get color() {
  2527. throw B();
  2528. }
  2529. get left() {
  2530. throw B();
  2531. }
  2532. get right() {
  2533. throw B();
  2534. }
  2535. // Returns a copy of the current node.
  2536. copy(t, e, n, s, i) {
  2537. return this;
  2538. }
  2539. // Returns a copy of the tree, with the specified key/value added.
  2540. insert(t, e, n) {
  2541. return new Ae(t, e);
  2542. }
  2543. // Returns a copy of the tree, with the specified key removed.
  2544. remove(t, e) {
  2545. return this;
  2546. }
  2547. isEmpty() {
  2548. return !0;
  2549. }
  2550. inorderTraversal(t) {
  2551. return !1;
  2552. }
  2553. reverseTraversal(t) {
  2554. return !1;
  2555. }
  2556. minKey() {
  2557. return null;
  2558. }
  2559. maxKey() {
  2560. return null;
  2561. }
  2562. isRed() {
  2563. return !1;
  2564. }
  2565. // For testing.
  2566. checkMaxDepth() {
  2567. return !0;
  2568. }
  2569. check() {
  2570. return 0;
  2571. }
  2572. };
  2573. /**
  2574. * @license
  2575. * Copyright 2017 Google LLC
  2576. *
  2577. * Licensed under the Apache License, Version 2.0 (the "License");
  2578. * you may not use this file except in compliance with the License.
  2579. * You may obtain a copy of the License at
  2580. *
  2581. * http://www.apache.org/licenses/LICENSE-2.0
  2582. *
  2583. * Unless required by applicable law or agreed to in writing, software
  2584. * distributed under the License is distributed on an "AS IS" BASIS,
  2585. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2586. * See the License for the specific language governing permissions and
  2587. * limitations under the License.
  2588. */
  2589. /**
  2590. * SortedSet is an immutable (copy-on-write) collection that holds elements
  2591. * in order specified by the provided comparator.
  2592. *
  2593. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  2594. * be equal!
  2595. */
  2596. class ve {
  2597. constructor(t) {
  2598. this.comparator = t, this.data = new Te(this.comparator);
  2599. }
  2600. has(t) {
  2601. return null !== this.data.get(t);
  2602. }
  2603. first() {
  2604. return this.data.minKey();
  2605. }
  2606. last() {
  2607. return this.data.maxKey();
  2608. }
  2609. get size() {
  2610. return this.data.size;
  2611. }
  2612. indexOf(t) {
  2613. return this.data.indexOf(t);
  2614. }
  2615. /** Iterates elements in order defined by "comparator" */ forEach(t) {
  2616. this.data.inorderTraversal(((e, n) => (t(e), !1)));
  2617. }
  2618. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */ forEachInRange(t, e) {
  2619. const n = this.data.getIteratorFrom(t[0]);
  2620. for (;n.hasNext(); ) {
  2621. const s = n.getNext();
  2622. if (this.comparator(s.key, t[1]) >= 0) return;
  2623. e(s.key);
  2624. }
  2625. }
  2626. /**
  2627. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  2628. */ forEachWhile(t, e) {
  2629. let n;
  2630. for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) {
  2631. if (!t(n.getNext().key)) return;
  2632. }
  2633. }
  2634. /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {
  2635. const e = this.data.getIteratorFrom(t);
  2636. return e.hasNext() ? e.getNext().key : null;
  2637. }
  2638. getIterator() {
  2639. return new Re(this.data.getIterator());
  2640. }
  2641. getIteratorFrom(t) {
  2642. return new Re(this.data.getIteratorFrom(t));
  2643. }
  2644. /** Inserts or updates an element */ add(t) {
  2645. return this.copy(this.data.remove(t).insert(t, !0));
  2646. }
  2647. /** Deletes an element */ delete(t) {
  2648. return this.has(t) ? this.copy(this.data.remove(t)) : this;
  2649. }
  2650. isEmpty() {
  2651. return this.data.isEmpty();
  2652. }
  2653. unionWith(t) {
  2654. let e = this;
  2655. // Make sure `result` always refers to the larger one of the two sets.
  2656. return e.size < t.size && (e = t, t = this), t.forEach((t => {
  2657. e = e.add(t);
  2658. })), e;
  2659. }
  2660. isEqual(t) {
  2661. if (!(t instanceof ve)) return !1;
  2662. if (this.size !== t.size) return !1;
  2663. const e = this.data.getIterator(), n = t.data.getIterator();
  2664. for (;e.hasNext(); ) {
  2665. const t = e.getNext().key, s = n.getNext().key;
  2666. if (0 !== this.comparator(t, s)) return !1;
  2667. }
  2668. return !0;
  2669. }
  2670. toArray() {
  2671. const t = [];
  2672. return this.forEach((e => {
  2673. t.push(e);
  2674. })), t;
  2675. }
  2676. toString() {
  2677. const t = [];
  2678. return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")";
  2679. }
  2680. copy(t) {
  2681. const e = new ve(this.comparator);
  2682. return e.data = t, e;
  2683. }
  2684. }
  2685. class Re {
  2686. constructor(t) {
  2687. this.iter = t;
  2688. }
  2689. getNext() {
  2690. return this.iter.getNext().key;
  2691. }
  2692. hasNext() {
  2693. return this.iter.hasNext();
  2694. }
  2695. }
  2696. /**
  2697. * Compares two sorted sets for equality using their natural ordering. The
  2698. * method computes the intersection and invokes `onAdd` for every element that
  2699. * is in `after` but not `before`. `onRemove` is invoked for every element in
  2700. * `before` but missing from `after`.
  2701. *
  2702. * The method creates a copy of both `before` and `after` and runs in O(n log
  2703. * n), where n is the size of the two lists.
  2704. *
  2705. * @param before - The elements that exist in the original set.
  2706. * @param after - The elements to diff against the original set.
  2707. * @param comparator - The comparator for the elements in before and after.
  2708. * @param onAdd - A function to invoke for every element that is part of `
  2709. * after` but not `before`.
  2710. * @param onRemove - A function to invoke for every element that is part of
  2711. * `before` but not `after`.
  2712. */
  2713. /**
  2714. * Returns the next element from the iterator or `undefined` if none available.
  2715. */
  2716. function Pe(t) {
  2717. return t.hasNext() ? t.getNext() : void 0;
  2718. }
  2719. /**
  2720. * @license
  2721. * Copyright 2020 Google LLC
  2722. *
  2723. * Licensed under the Apache License, Version 2.0 (the "License");
  2724. * you may not use this file except in compliance with the License.
  2725. * You may obtain a copy of the License at
  2726. *
  2727. * http://www.apache.org/licenses/LICENSE-2.0
  2728. *
  2729. * Unless required by applicable law or agreed to in writing, software
  2730. * distributed under the License is distributed on an "AS IS" BASIS,
  2731. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2732. * See the License for the specific language governing permissions and
  2733. * limitations under the License.
  2734. */
  2735. /**
  2736. * Provides a set of fields that can be used to partially patch a document.
  2737. * FieldMask is used in conjunction with ObjectValue.
  2738. * Examples:
  2739. * foo - Overwrites foo entirely with the provided value. If foo is not
  2740. * present in the companion ObjectValue, the field is deleted.
  2741. * foo.bar - Overwrites only the field bar of the object foo.
  2742. * If foo is not an object, foo is replaced with an object
  2743. * containing foo
  2744. */ class be {
  2745. constructor(t) {
  2746. this.fields = t,
  2747. // TODO(dimond): validation of FieldMask
  2748. // Sort the field mask to support `FieldMask.isEqual()` and assert below.
  2749. t.sort(lt.comparator);
  2750. }
  2751. static empty() {
  2752. return new be([]);
  2753. }
  2754. /**
  2755. * Returns a new FieldMask object that is the result of adding all the given
  2756. * fields paths to this field mask.
  2757. */ unionWith(t) {
  2758. let e = new ve(lt.comparator);
  2759. for (const t of this.fields) e = e.add(t);
  2760. for (const n of t) e = e.add(n);
  2761. return new be(e.toArray());
  2762. }
  2763. /**
  2764. * Verifies that `fieldPath` is included by at least one field in this field
  2765. * mask.
  2766. *
  2767. * This is an O(n) operation, where `n` is the size of the field mask.
  2768. */ covers(t) {
  2769. for (const e of this.fields) if (e.isPrefixOf(t)) return !0;
  2770. return !1;
  2771. }
  2772. isEqual(t) {
  2773. return it(this.fields, t.fields, ((t, e) => t.isEqual(e)));
  2774. }
  2775. }
  2776. /**
  2777. * @license
  2778. * Copyright 2023 Google LLC
  2779. *
  2780. * Licensed under the Apache License, Version 2.0 (the "License");
  2781. * you may not use this file except in compliance with the License.
  2782. * You may obtain a copy of the License at
  2783. *
  2784. * http://www.apache.org/licenses/LICENSE-2.0
  2785. *
  2786. * Unless required by applicable law or agreed to in writing, software
  2787. * distributed under the License is distributed on an "AS IS" BASIS,
  2788. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2789. * See the License for the specific language governing permissions and
  2790. * limitations under the License.
  2791. */
  2792. /**
  2793. * An error encountered while decoding base64 string.
  2794. */ class Ve extends Error {
  2795. constructor() {
  2796. super(...arguments), this.name = "Base64DecodeError";
  2797. }
  2798. }
  2799. /**
  2800. * @license
  2801. * Copyright 2020 Google LLC
  2802. *
  2803. * Licensed under the Apache License, Version 2.0 (the "License");
  2804. * you may not use this file except in compliance with the License.
  2805. * You may obtain a copy of the License at
  2806. *
  2807. * http://www.apache.org/licenses/LICENSE-2.0
  2808. *
  2809. * Unless required by applicable law or agreed to in writing, software
  2810. * distributed under the License is distributed on an "AS IS" BASIS,
  2811. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2812. * See the License for the specific language governing permissions and
  2813. * limitations under the License.
  2814. */
  2815. // WebSafe uses a different URL-encoding safe alphabet that doesn't match
  2816. // the encoding used on the backend.
  2817. /** Converts a Base64 encoded string to a binary string. */
  2818. function Se(t) {
  2819. try {
  2820. return String.fromCharCode.apply(null,
  2821. // We use `decodeStringToByteArray()` instead of `decodeString()` since
  2822. // `decodeString()` returns Unicode strings, which doesn't match the values
  2823. // returned by `atob()`'s Latin1 representation.
  2824. l.decodeStringToByteArray(t, false));
  2825. } catch (t) {
  2826. throw t instanceof f ? new Ve("Invalid base64 string: " + t) : t;
  2827. }
  2828. }
  2829. /** Converts a binary string to a Base64 encoded string. */
  2830. /** True if and only if the Base64 conversion functions are available. */
  2831. function De() {
  2832. return !0;
  2833. }
  2834. /**
  2835. * @license
  2836. * Copyright 2020 Google LLC
  2837. *
  2838. * Licensed under the Apache License, Version 2.0 (the "License");
  2839. * you may not use this file except in compliance with the License.
  2840. * You may obtain a copy of the License at
  2841. *
  2842. * http://www.apache.org/licenses/LICENSE-2.0
  2843. *
  2844. * Unless required by applicable law or agreed to in writing, software
  2845. * distributed under the License is distributed on an "AS IS" BASIS,
  2846. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2847. * See the License for the specific language governing permissions and
  2848. * limitations under the License.
  2849. */
  2850. /**
  2851. * Immutable class that represents a "proto" byte string.
  2852. *
  2853. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  2854. * sent on the wire. This class abstracts away this differentiation by holding
  2855. * the proto byte string in a common class that must be converted into a string
  2856. * before being sent as a proto.
  2857. * @internal
  2858. */ class Ce {
  2859. constructor(t) {
  2860. this.binaryString = t;
  2861. }
  2862. static fromBase64String(t) {
  2863. const e = Se(t);
  2864. return new Ce(e);
  2865. }
  2866. static fromUint8Array(t) {
  2867. // TODO(indexing); Remove the copy of the byte string here as this method
  2868. // is frequently called during indexing.
  2869. const e =
  2870. /**
  2871. * Helper function to convert an Uint8array to a binary string.
  2872. */
  2873. function(t) {
  2874. let e = "";
  2875. for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);
  2876. return e;
  2877. }
  2878. /**
  2879. * Helper function to convert a binary string to an Uint8Array.
  2880. */ (t);
  2881. return new Ce(e);
  2882. }
  2883. [Symbol.iterator]() {
  2884. let t = 0;
  2885. return {
  2886. next: () => t < this.binaryString.length ? {
  2887. value: this.binaryString.charCodeAt(t++),
  2888. done: !1
  2889. } : {
  2890. value: void 0,
  2891. done: !0
  2892. }
  2893. };
  2894. }
  2895. toBase64() {
  2896. return function(t) {
  2897. const e = [];
  2898. for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  2899. return l.encodeByteArray(e, !1);
  2900. }(this.binaryString);
  2901. }
  2902. toUint8Array() {
  2903. return function(t) {
  2904. const e = new Uint8Array(t.length);
  2905. for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  2906. return e;
  2907. }
  2908. /**
  2909. * @license
  2910. * Copyright 2020 Google LLC
  2911. *
  2912. * Licensed under the Apache License, Version 2.0 (the "License");
  2913. * you may not use this file except in compliance with the License.
  2914. * You may obtain a copy of the License at
  2915. *
  2916. * http://www.apache.org/licenses/LICENSE-2.0
  2917. *
  2918. * Unless required by applicable law or agreed to in writing, software
  2919. * distributed under the License is distributed on an "AS IS" BASIS,
  2920. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2921. * See the License for the specific language governing permissions and
  2922. * limitations under the License.
  2923. */
  2924. // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
  2925. (this.binaryString);
  2926. }
  2927. approximateByteSize() {
  2928. return 2 * this.binaryString.length;
  2929. }
  2930. compareTo(t) {
  2931. return st(this.binaryString, t.binaryString);
  2932. }
  2933. isEqual(t) {
  2934. return this.binaryString === t.binaryString;
  2935. }
  2936. }
  2937. Ce.EMPTY_BYTE_STRING = new Ce("");
  2938. const xe = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  2939. /**
  2940. * Converts the possible Proto values for a timestamp value into a "seconds and
  2941. * nanos" representation.
  2942. */ function Ne(t) {
  2943. // The json interface (for the browser) will return an iso timestamp string,
  2944. // while the proto js library (for node) will return a
  2945. // google.protobuf.Timestamp instance.
  2946. if (L(!!t), "string" == typeof t) {
  2947. // The date string can have higher precision (nanos) than the Date class
  2948. // (millis), so we do some custom parsing here.
  2949. // Parse the nanos right out of the string.
  2950. let e = 0;
  2951. const n = xe.exec(t);
  2952. if (L(!!n), n[1]) {
  2953. // Pad the fraction out to 9 digits (nanos).
  2954. let t = n[1];
  2955. t = (t + "000000000").substr(0, 9), e = Number(t);
  2956. }
  2957. // Parse the date to get the seconds.
  2958. const s = new Date(t);
  2959. return {
  2960. seconds: Math.floor(s.getTime() / 1e3),
  2961. nanos: e
  2962. };
  2963. }
  2964. return {
  2965. seconds: ke(t.seconds),
  2966. nanos: ke(t.nanos)
  2967. };
  2968. }
  2969. /**
  2970. * Converts the possible Proto types for numbers into a JavaScript number.
  2971. * Returns 0 if the value is not numeric.
  2972. */ function ke(t) {
  2973. // TODO(bjornick): Handle int64 greater than 53 bits.
  2974. return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0;
  2975. }
  2976. /** Converts the possible Proto types for Blobs into a ByteString. */ function $e(t) {
  2977. return "string" == typeof t ? Ce.fromBase64String(t) : Ce.fromUint8Array(t);
  2978. }
  2979. /**
  2980. * @license
  2981. * Copyright 2020 Google LLC
  2982. *
  2983. * Licensed under the Apache License, Version 2.0 (the "License");
  2984. * you may not use this file except in compliance with the License.
  2985. * You may obtain a copy of the License at
  2986. *
  2987. * http://www.apache.org/licenses/LICENSE-2.0
  2988. *
  2989. * Unless required by applicable law or agreed to in writing, software
  2990. * distributed under the License is distributed on an "AS IS" BASIS,
  2991. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2992. * See the License for the specific language governing permissions and
  2993. * limitations under the License.
  2994. */
  2995. /**
  2996. * Represents a locally-applied ServerTimestamp.
  2997. *
  2998. * Server Timestamps are backed by MapValues that contain an internal field
  2999. * `__type__` with a value of `server_timestamp`. The previous value and local
  3000. * write time are stored in its `__previous_value__` and `__local_write_time__`
  3001. * fields respectively.
  3002. *
  3003. * Notes:
  3004. * - ServerTimestampValue instances are created as the result of applying a
  3005. * transform. They can only exist in the local view of a document. Therefore
  3006. * they do not need to be parsed or serialized.
  3007. * - When evaluated locally (e.g. for snapshot.data()), they by default
  3008. * evaluate to `null`. This behavior can be configured by passing custom
  3009. * FieldValueOptions to value().
  3010. * - With respect to other ServerTimestampValues, they sort by their
  3011. * localWriteTime.
  3012. */ function Me(t) {
  3013. var e, n;
  3014. 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);
  3015. }
  3016. /**
  3017. * Creates a new ServerTimestamp proto value (using the internal format).
  3018. */
  3019. /**
  3020. * Returns the value of the field before this ServerTimestamp was set.
  3021. *
  3022. * Preserving the previous values allows the user to display the last resoled
  3023. * value until the backend responds with the timestamp.
  3024. */
  3025. function Oe(t) {
  3026. const e = t.mapValue.fields.__previous_value__;
  3027. return Me(e) ? Oe(e) : e;
  3028. }
  3029. /**
  3030. * Returns the local time at which this timestamp was first set.
  3031. */ function Fe(t) {
  3032. const e = Ne(t.mapValue.fields.__local_write_time__.timestampValue);
  3033. return new ot(e.seconds, e.nanos);
  3034. }
  3035. /**
  3036. * @license
  3037. * Copyright 2017 Google LLC
  3038. *
  3039. * Licensed under the Apache License, Version 2.0 (the "License");
  3040. * you may not use this file except in compliance with the License.
  3041. * You may obtain a copy of the License at
  3042. *
  3043. * http://www.apache.org/licenses/LICENSE-2.0
  3044. *
  3045. * Unless required by applicable law or agreed to in writing, software
  3046. * distributed under the License is distributed on an "AS IS" BASIS,
  3047. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3048. * See the License for the specific language governing permissions and
  3049. * limitations under the License.
  3050. */ class Be {
  3051. /**
  3052. * Constructs a DatabaseInfo using the provided host, databaseId and
  3053. * persistenceKey.
  3054. *
  3055. * @param databaseId - The database to use.
  3056. * @param appId - The Firebase App Id.
  3057. * @param persistenceKey - A unique identifier for this Firestore's local
  3058. * storage (used in conjunction with the databaseId).
  3059. * @param host - The Firestore backend host to connect to.
  3060. * @param ssl - Whether to use SSL when connecting.
  3061. * @param forceLongPolling - Whether to use the forceLongPolling option
  3062. * when using WebChannel as the network transport.
  3063. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  3064. * option when using WebChannel as the network transport.
  3065. * @param longPollingOptions Options that configure long-polling.
  3066. * @param useFetchStreams Whether to use the Fetch API instead of
  3067. * XMLHTTPRequest
  3068. */
  3069. constructor(t, e, n, s, i, r, o, u, c) {
  3070. this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = s, this.ssl = i,
  3071. this.forceLongPolling = r, this.autoDetectLongPolling = o, this.longPollingOptions = u,
  3072. this.useFetchStreams = c;
  3073. }
  3074. }
  3075. /** The default database name for a project. */
  3076. /**
  3077. * Represents the database ID a Firestore client is associated with.
  3078. * @internal
  3079. */
  3080. class Le {
  3081. constructor(t, e) {
  3082. this.projectId = t, this.database = e || "(default)";
  3083. }
  3084. static empty() {
  3085. return new Le("", "");
  3086. }
  3087. get isDefaultDatabase() {
  3088. return "(default)" === this.database;
  3089. }
  3090. isEqual(t) {
  3091. return t instanceof Le && t.projectId === this.projectId && t.database === this.database;
  3092. }
  3093. }
  3094. /**
  3095. * @license
  3096. * Copyright 2020 Google LLC
  3097. *
  3098. * Licensed under the Apache License, Version 2.0 (the "License");
  3099. * you may not use this file except in compliance with the License.
  3100. * You may obtain a copy of the License at
  3101. *
  3102. * http://www.apache.org/licenses/LICENSE-2.0
  3103. *
  3104. * Unless required by applicable law or agreed to in writing, software
  3105. * distributed under the License is distributed on an "AS IS" BASIS,
  3106. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3107. * See the License for the specific language governing permissions and
  3108. * limitations under the License.
  3109. */
  3110. const qe = {
  3111. mapValue: {
  3112. fields: {
  3113. __type__: {
  3114. stringValue: "__max__"
  3115. }
  3116. }
  3117. }
  3118. }, Ue = {
  3119. nullValue: "NULL_VALUE"
  3120. };
  3121. /** Extracts the backend's type order for the provided value. */
  3122. function Ke(t) {
  3123. 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 */ : rn(t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : B();
  3124. }
  3125. /** Tests `left` and `right` for equality based on the backend semantics. */ function Ge(t, e) {
  3126. if (t === e) return !0;
  3127. const n = Ke(t);
  3128. if (n !== Ke(e)) return !1;
  3129. switch (n) {
  3130. case 0 /* TypeOrder.NullValue */ :
  3131. case 9007199254740991 /* TypeOrder.MaxValue */ :
  3132. return !0;
  3133. case 1 /* TypeOrder.BooleanValue */ :
  3134. return t.booleanValue === e.booleanValue;
  3135. case 4 /* TypeOrder.ServerTimestampValue */ :
  3136. return Fe(t).isEqual(Fe(e));
  3137. case 3 /* TypeOrder.TimestampValue */ :
  3138. return function(t, e) {
  3139. if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length)
  3140. // Use string equality for ISO 8601 timestamps
  3141. return t.timestampValue === e.timestampValue;
  3142. const n = Ne(t.timestampValue), s = Ne(e.timestampValue);
  3143. return n.seconds === s.seconds && n.nanos === s.nanos;
  3144. }(t, e);
  3145. case 5 /* TypeOrder.StringValue */ :
  3146. return t.stringValue === e.stringValue;
  3147. case 6 /* TypeOrder.BlobValue */ :
  3148. return function(t, e) {
  3149. return $e(t.bytesValue).isEqual($e(e.bytesValue));
  3150. }(t, e);
  3151. case 7 /* TypeOrder.RefValue */ :
  3152. return t.referenceValue === e.referenceValue;
  3153. case 8 /* TypeOrder.GeoPointValue */ :
  3154. return function(t, e) {
  3155. return ke(t.geoPointValue.latitude) === ke(e.geoPointValue.latitude) && ke(t.geoPointValue.longitude) === ke(e.geoPointValue.longitude);
  3156. }(t, e);
  3157. case 2 /* TypeOrder.NumberValue */ :
  3158. return function(t, e) {
  3159. if ("integerValue" in t && "integerValue" in e) return ke(t.integerValue) === ke(e.integerValue);
  3160. if ("doubleValue" in t && "doubleValue" in e) {
  3161. const n = ke(t.doubleValue), s = ke(e.doubleValue);
  3162. return n === s ? qt(n) === qt(s) : isNaN(n) && isNaN(s);
  3163. }
  3164. return !1;
  3165. }(t, e);
  3166. case 9 /* TypeOrder.ArrayValue */ :
  3167. return it(t.arrayValue.values || [], e.arrayValue.values || [], Ge);
  3168. case 10 /* TypeOrder.ObjectValue */ :
  3169. return function(t, e) {
  3170. const n = t.mapValue.fields || {}, s = e.mapValue.fields || {};
  3171. if (ye(n) !== ye(s)) return !1;
  3172. for (const t in n) if (n.hasOwnProperty(t) && (void 0 === s[t] || !Ge(n[t], s[t]))) return !1;
  3173. return !0;
  3174. }
  3175. /** Returns true if the ArrayValue contains the specified element. */ (t, e);
  3176. default:
  3177. return B();
  3178. }
  3179. }
  3180. function Qe(t, e) {
  3181. return void 0 !== (t.values || []).find((t => Ge(t, e)));
  3182. }
  3183. function je(t, e) {
  3184. if (t === e) return 0;
  3185. const n = Ke(t), s = Ke(e);
  3186. if (n !== s) return st(n, s);
  3187. switch (n) {
  3188. case 0 /* TypeOrder.NullValue */ :
  3189. case 9007199254740991 /* TypeOrder.MaxValue */ :
  3190. return 0;
  3191. case 1 /* TypeOrder.BooleanValue */ :
  3192. return st(t.booleanValue, e.booleanValue);
  3193. case 2 /* TypeOrder.NumberValue */ :
  3194. return function(t, e) {
  3195. const n = ke(t.integerValue || t.doubleValue), s = ke(e.integerValue || e.doubleValue);
  3196. return n < s ? -1 : n > s ? 1 : n === s ? 0 :
  3197. // one or both are NaN.
  3198. isNaN(n) ? isNaN(s) ? 0 : -1 : 1;
  3199. }(t, e);
  3200. case 3 /* TypeOrder.TimestampValue */ :
  3201. return ze(t.timestampValue, e.timestampValue);
  3202. case 4 /* TypeOrder.ServerTimestampValue */ :
  3203. return ze(Fe(t), Fe(e));
  3204. case 5 /* TypeOrder.StringValue */ :
  3205. return st(t.stringValue, e.stringValue);
  3206. case 6 /* TypeOrder.BlobValue */ :
  3207. return function(t, e) {
  3208. const n = $e(t), s = $e(e);
  3209. return n.compareTo(s);
  3210. }(t.bytesValue, e.bytesValue);
  3211. case 7 /* TypeOrder.RefValue */ :
  3212. return function(t, e) {
  3213. const n = t.split("/"), s = e.split("/");
  3214. for (let t = 0; t < n.length && t < s.length; t++) {
  3215. const e = st(n[t], s[t]);
  3216. if (0 !== e) return e;
  3217. }
  3218. return st(n.length, s.length);
  3219. }(t.referenceValue, e.referenceValue);
  3220. case 8 /* TypeOrder.GeoPointValue */ :
  3221. return function(t, e) {
  3222. const n = st(ke(t.latitude), ke(e.latitude));
  3223. if (0 !== n) return n;
  3224. return st(ke(t.longitude), ke(e.longitude));
  3225. }(t.geoPointValue, e.geoPointValue);
  3226. case 9 /* TypeOrder.ArrayValue */ :
  3227. return function(t, e) {
  3228. const n = t.values || [], s = e.values || [];
  3229. for (let t = 0; t < n.length && t < s.length; ++t) {
  3230. const e = je(n[t], s[t]);
  3231. if (e) return e;
  3232. }
  3233. return st(n.length, s.length);
  3234. }(t.arrayValue, e.arrayValue);
  3235. case 10 /* TypeOrder.ObjectValue */ :
  3236. return function(t, e) {
  3237. if (t === qe.mapValue && e === qe.mapValue) return 0;
  3238. if (t === qe.mapValue) return 1;
  3239. if (e === qe.mapValue) return -1;
  3240. const n = t.fields || {}, s = Object.keys(n), i = e.fields || {}, r = Object.keys(i);
  3241. // Even though MapValues are likely sorted correctly based on their insertion
  3242. // order (e.g. when received from the backend), local modifications can bring
  3243. // elements out of order. We need to re-sort the elements to ensure that
  3244. // canonical IDs are independent of insertion order.
  3245. s.sort(), r.sort();
  3246. for (let t = 0; t < s.length && t < r.length; ++t) {
  3247. const e = st(s[t], r[t]);
  3248. if (0 !== e) return e;
  3249. const o = je(n[s[t]], i[r[t]]);
  3250. if (0 !== o) return o;
  3251. }
  3252. return st(s.length, r.length);
  3253. }
  3254. /**
  3255. * Generates the canonical ID for the provided field value (as used in Target
  3256. * serialization).
  3257. */ (t.mapValue, e.mapValue);
  3258. default:
  3259. throw B();
  3260. }
  3261. }
  3262. function ze(t, e) {
  3263. if ("string" == typeof t && "string" == typeof e && t.length === e.length) return st(t, e);
  3264. const n = Ne(t), s = Ne(e), i = st(n.seconds, s.seconds);
  3265. return 0 !== i ? i : st(n.nanos, s.nanos);
  3266. }
  3267. function We(t) {
  3268. return He(t);
  3269. }
  3270. function He(t) {
  3271. 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) {
  3272. const e = Ne(t);
  3273. return `time(${e.seconds},${e.nanos})`;
  3274. }(t.timestampValue) : "stringValue" in t ? t.stringValue : "bytesValue" in t ? $e(t.bytesValue).toBase64() : "referenceValue" in t ? (n = t.referenceValue,
  3275. ft.fromName(n).toString()) : "geoPointValue" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : "arrayValue" in t ? function(t) {
  3276. let e = "[", n = !0;
  3277. for (const s of t.values || []) n ? n = !1 : e += ",", e += He(s);
  3278. return e + "]";
  3279. }
  3280. /**
  3281. * Returns an approximate (and wildly inaccurate) in-memory size for the field
  3282. * value.
  3283. *
  3284. * The memory size takes into account only the actual user data as it resides
  3285. * in memory and ignores object overhead.
  3286. */ (t.arrayValue) : "mapValue" in t ? function(t) {
  3287. // Iteration order in JavaScript is not guaranteed. To ensure that we generate
  3288. // matching canonical IDs for identical maps, we need to sort the keys.
  3289. const e = Object.keys(t.fields || {}).sort();
  3290. let n = "{", s = !0;
  3291. for (const i of e) s ? s = !1 : n += ",", n += `${i}:${He(t.fields[i])}`;
  3292. return n + "}";
  3293. }(t.mapValue) : B();
  3294. var e, n;
  3295. }
  3296. function Je(t) {
  3297. switch (Ke(t)) {
  3298. case 0 /* TypeOrder.NullValue */ :
  3299. case 1 /* TypeOrder.BooleanValue */ :
  3300. return 4;
  3301. case 2 /* TypeOrder.NumberValue */ :
  3302. return 8;
  3303. case 3 /* TypeOrder.TimestampValue */ :
  3304. case 8 /* TypeOrder.GeoPointValue */ :
  3305. // GeoPoints are made up of two distinct numbers (latitude + longitude)
  3306. return 16;
  3307. case 4 /* TypeOrder.ServerTimestampValue */ :
  3308. const e = Oe(t);
  3309. return e ? 16 + Je(e) : 16;
  3310. case 5 /* TypeOrder.StringValue */ :
  3311. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:
  3312. // "JavaScript's String type is [...] a set of elements of 16-bit unsigned
  3313. // integer values"
  3314. return 2 * t.stringValue.length;
  3315. case 6 /* TypeOrder.BlobValue */ :
  3316. return $e(t.bytesValue).approximateByteSize();
  3317. case 7 /* TypeOrder.RefValue */ :
  3318. return t.referenceValue.length;
  3319. case 9 /* TypeOrder.ArrayValue */ :
  3320. return (t.arrayValue.values || []).reduce(((t, e) => t + Je(e)), 0);
  3321. case 10 /* TypeOrder.ObjectValue */ :
  3322. return function(t) {
  3323. let e = 0;
  3324. return pe(t.fields, ((t, n) => {
  3325. e += t.length + Je(n);
  3326. })), e;
  3327. }(t.mapValue);
  3328. default:
  3329. throw B();
  3330. }
  3331. }
  3332. /** Returns a reference value for the provided database and key. */
  3333. function Ye(t, e) {
  3334. return {
  3335. referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`
  3336. };
  3337. }
  3338. /** Returns true if `value` is an IntegerValue . */ function Xe(t) {
  3339. return !!t && "integerValue" in t;
  3340. }
  3341. /** Returns true if `value` is a DoubleValue. */
  3342. /** Returns true if `value` is an ArrayValue. */
  3343. function Ze(t) {
  3344. return !!t && "arrayValue" in t;
  3345. }
  3346. /** Returns true if `value` is a NullValue. */ function tn(t) {
  3347. return !!t && "nullValue" in t;
  3348. }
  3349. /** Returns true if `value` is NaN. */ function en(t) {
  3350. return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
  3351. }
  3352. /** Returns true if `value` is a MapValue. */ function nn(t) {
  3353. return !!t && "mapValue" in t;
  3354. }
  3355. /** Creates a deep copy of `source`. */ function sn(t) {
  3356. if (t.geoPointValue) return {
  3357. geoPointValue: Object.assign({}, t.geoPointValue)
  3358. };
  3359. if (t.timestampValue && "object" == typeof t.timestampValue) return {
  3360. timestampValue: Object.assign({}, t.timestampValue)
  3361. };
  3362. if (t.mapValue) {
  3363. const e = {
  3364. mapValue: {
  3365. fields: {}
  3366. }
  3367. };
  3368. return pe(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = sn(n))), e;
  3369. }
  3370. if (t.arrayValue) {
  3371. const e = {
  3372. arrayValue: {
  3373. values: []
  3374. }
  3375. };
  3376. for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = sn(t.arrayValue.values[n]);
  3377. return e;
  3378. }
  3379. return Object.assign({}, t);
  3380. }
  3381. /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function rn(t) {
  3382. return "__max__" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;
  3383. }
  3384. /** Returns the lowest value for the given value type (inclusive). */ function on(t) {
  3385. return "nullValue" in t ? Ue : "booleanValue" in t ? {
  3386. booleanValue: !1
  3387. } : "integerValue" in t || "doubleValue" in t ? {
  3388. doubleValue: NaN
  3389. } : "timestampValue" in t ? {
  3390. timestampValue: {
  3391. seconds: Number.MIN_SAFE_INTEGER
  3392. }
  3393. } : "stringValue" in t ? {
  3394. stringValue: ""
  3395. } : "bytesValue" in t ? {
  3396. bytesValue: ""
  3397. } : "referenceValue" in t ? Ye(Le.empty(), ft.empty()) : "geoPointValue" in t ? {
  3398. geoPointValue: {
  3399. latitude: -90,
  3400. longitude: -180
  3401. }
  3402. } : "arrayValue" in t ? {
  3403. arrayValue: {}
  3404. } : "mapValue" in t ? {
  3405. mapValue: {}
  3406. } : B();
  3407. }
  3408. /** Returns the largest value for the given value type (exclusive). */ function un(t) {
  3409. return "nullValue" in t ? {
  3410. booleanValue: !1
  3411. } : "booleanValue" in t ? {
  3412. doubleValue: NaN
  3413. } : "integerValue" in t || "doubleValue" in t ? {
  3414. timestampValue: {
  3415. seconds: Number.MIN_SAFE_INTEGER
  3416. }
  3417. } : "timestampValue" in t ? {
  3418. stringValue: ""
  3419. } : "stringValue" in t ? {
  3420. bytesValue: ""
  3421. } : "bytesValue" in t ? Ye(Le.empty(), ft.empty()) : "referenceValue" in t ? {
  3422. geoPointValue: {
  3423. latitude: -90,
  3424. longitude: -180
  3425. }
  3426. } : "geoPointValue" in t ? {
  3427. arrayValue: {}
  3428. } : "arrayValue" in t ? {
  3429. mapValue: {}
  3430. } : "mapValue" in t ? qe : B();
  3431. }
  3432. function cn(t, e) {
  3433. const n = je(t.value, e.value);
  3434. return 0 !== n ? n : t.inclusive && !e.inclusive ? -1 : !t.inclusive && e.inclusive ? 1 : 0;
  3435. }
  3436. function an(t, e) {
  3437. const n = je(t.value, e.value);
  3438. return 0 !== n ? n : t.inclusive && !e.inclusive ? 1 : !t.inclusive && e.inclusive ? -1 : 0;
  3439. }
  3440. /**
  3441. * @license
  3442. * Copyright 2017 Google LLC
  3443. *
  3444. * Licensed under the Apache License, Version 2.0 (the "License");
  3445. * you may not use this file except in compliance with the License.
  3446. * You may obtain a copy of the License at
  3447. *
  3448. * http://www.apache.org/licenses/LICENSE-2.0
  3449. *
  3450. * Unless required by applicable law or agreed to in writing, software
  3451. * distributed under the License is distributed on an "AS IS" BASIS,
  3452. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3453. * See the License for the specific language governing permissions and
  3454. * limitations under the License.
  3455. */
  3456. /**
  3457. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  3458. * ability to add and remove fields (via the ObjectValueBuilder).
  3459. */ class hn {
  3460. constructor(t) {
  3461. this.value = t;
  3462. }
  3463. static empty() {
  3464. return new hn({
  3465. mapValue: {}
  3466. });
  3467. }
  3468. /**
  3469. * Returns the value at the given path or null.
  3470. *
  3471. * @param path - the path to search
  3472. * @returns The value at the path or null if the path is not set.
  3473. */ field(t) {
  3474. if (t.isEmpty()) return this.value;
  3475. {
  3476. let e = this.value;
  3477. for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)],
  3478. !nn(e)) return null;
  3479. return e = (e.mapValue.fields || {})[t.lastSegment()], e || null;
  3480. }
  3481. }
  3482. /**
  3483. * Sets the field to the provided value.
  3484. *
  3485. * @param path - The field path to set.
  3486. * @param value - The value to set.
  3487. */ set(t, e) {
  3488. this.getFieldsMap(t.popLast())[t.lastSegment()] = sn(e);
  3489. }
  3490. /**
  3491. * Sets the provided fields to the provided values.
  3492. *
  3493. * @param data - A map of fields to values (or null for deletes).
  3494. */ setAll(t) {
  3495. let e = lt.emptyPath(), n = {}, s = [];
  3496. t.forEach(((t, i) => {
  3497. if (!e.isImmediateParentOf(i)) {
  3498. // Insert the accumulated changes at this parent location
  3499. const t = this.getFieldsMap(e);
  3500. this.applyChanges(t, n, s), n = {}, s = [], e = i.popLast();
  3501. }
  3502. t ? n[i.lastSegment()] = sn(t) : s.push(i.lastSegment());
  3503. }));
  3504. const i = this.getFieldsMap(e);
  3505. this.applyChanges(i, n, s);
  3506. }
  3507. /**
  3508. * Removes the field at the specified path. If there is no field at the
  3509. * specified path, nothing is changed.
  3510. *
  3511. * @param path - The field path to remove.
  3512. */ delete(t) {
  3513. const e = this.field(t.popLast());
  3514. nn(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];
  3515. }
  3516. isEqual(t) {
  3517. return Ge(this.value, t.value);
  3518. }
  3519. /**
  3520. * Returns the map that contains the leaf element of `path`. If the parent
  3521. * entry does not yet exist, or if it is not a map, a new map will be created.
  3522. */ getFieldsMap(t) {
  3523. let e = this.value;
  3524. e.mapValue.fields || (e.mapValue = {
  3525. fields: {}
  3526. });
  3527. for (let n = 0; n < t.length; ++n) {
  3528. let s = e.mapValue.fields[t.get(n)];
  3529. nn(s) && s.mapValue.fields || (s = {
  3530. mapValue: {
  3531. fields: {}
  3532. }
  3533. }, e.mapValue.fields[t.get(n)] = s), e = s;
  3534. }
  3535. return e.mapValue.fields;
  3536. }
  3537. /**
  3538. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  3539. * entries.
  3540. */ applyChanges(t, e, n) {
  3541. pe(e, ((e, n) => t[e] = n));
  3542. for (const e of n) delete t[e];
  3543. }
  3544. clone() {
  3545. return new hn(sn(this.value));
  3546. }
  3547. }
  3548. /**
  3549. * Returns a FieldMask built from all fields in a MapValue.
  3550. */ function ln(t) {
  3551. const e = [];
  3552. return pe(t.fields, ((t, n) => {
  3553. const s = new lt([ t ]);
  3554. if (nn(n)) {
  3555. const t = ln(n.mapValue).fields;
  3556. if (0 === t.length)
  3557. // Preserve the empty map by adding it to the FieldMask.
  3558. e.push(s); else
  3559. // For nested and non-empty ObjectValues, add the FieldPath of the
  3560. // leaf nodes.
  3561. for (const n of t) e.push(s.child(n));
  3562. } else
  3563. // For nested and non-empty ObjectValues, add the FieldPath of the leaf
  3564. // nodes.
  3565. e.push(s);
  3566. })), new be(e);
  3567. }
  3568. /**
  3569. * @license
  3570. * Copyright 2017 Google LLC
  3571. *
  3572. * Licensed under the Apache License, Version 2.0 (the "License");
  3573. * you may not use this file except in compliance with the License.
  3574. * You may obtain a copy of the License at
  3575. *
  3576. * http://www.apache.org/licenses/LICENSE-2.0
  3577. *
  3578. * Unless required by applicable law or agreed to in writing, software
  3579. * distributed under the License is distributed on an "AS IS" BASIS,
  3580. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3581. * See the License for the specific language governing permissions and
  3582. * limitations under the License.
  3583. */
  3584. /**
  3585. * Represents a document in Firestore with a key, version, data and whether it
  3586. * has local mutations applied to it.
  3587. *
  3588. * Documents can transition between states via `convertToFoundDocument()`,
  3589. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  3590. * not transition to one of these states even after all mutations have been
  3591. * applied, `isValidDocument()` returns false and the document should be removed
  3592. * from all views.
  3593. */ class fn {
  3594. constructor(t, e, n, s, i, r, o) {
  3595. this.key = t, this.documentType = e, this.version = n, this.readTime = s, this.createTime = i,
  3596. this.data = r, this.documentState = o;
  3597. }
  3598. /**
  3599. * Creates a document with no known version or data, but which can serve as
  3600. * base document for mutations.
  3601. */ static newInvalidDocument(t) {
  3602. return new fn(t, 0 /* DocumentType.INVALID */ ,
  3603. /* version */ ut.min(),
  3604. /* readTime */ ut.min(),
  3605. /* createTime */ ut.min(), hn.empty(), 0 /* DocumentState.SYNCED */);
  3606. }
  3607. /**
  3608. * Creates a new document that is known to exist with the given data at the
  3609. * given version.
  3610. */ static newFoundDocument(t, e, n, s) {
  3611. return new fn(t, 1 /* DocumentType.FOUND_DOCUMENT */ ,
  3612. /* version */ e,
  3613. /* readTime */ ut.min(),
  3614. /* createTime */ n, s, 0 /* DocumentState.SYNCED */);
  3615. }
  3616. /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {
  3617. return new fn(t, 2 /* DocumentType.NO_DOCUMENT */ ,
  3618. /* version */ e,
  3619. /* readTime */ ut.min(),
  3620. /* createTime */ ut.min(), hn.empty(), 0 /* DocumentState.SYNCED */);
  3621. }
  3622. /**
  3623. * Creates a new document that is known to exist at the given version but
  3624. * whose data is not known (e.g. a document that was updated without a known
  3625. * base document).
  3626. */ static newUnknownDocument(t, e) {
  3627. return new fn(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3628. /* version */ e,
  3629. /* readTime */ ut.min(),
  3630. /* createTime */ ut.min(), hn.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
  3631. }
  3632. /**
  3633. * Changes the document type to indicate that it exists and that its version
  3634. * and data are known.
  3635. */ convertToFoundDocument(t, e) {
  3636. // If a document is switching state from being an invalid or deleted
  3637. // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
  3638. // update from Watch or due to applying a local set mutation on top
  3639. // of a deleted document, our best guess about its createTime would be the
  3640. // version at which the document transitioned to a FOUND_DOCUMENT.
  3641. return !this.createTime.isEqual(ut.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t),
  3642. this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e,
  3643. this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3644. }
  3645. /**
  3646. * Changes the document type to indicate that it doesn't exist at the given
  3647. * version.
  3648. */ convertToNoDocument(t) {
  3649. return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ ,
  3650. this.data = hn.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3651. }
  3652. /**
  3653. * Changes the document type to indicate that it exists at a given version but
  3654. * that its data is not known (e.g. a document that was updated without a known
  3655. * base document).
  3656. */ convertToUnknownDocument(t) {
  3657. return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3658. this.data = hn.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ ,
  3659. this;
  3660. }
  3661. setHasCommittedMutations() {
  3662. return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;
  3663. }
  3664. setHasLocalMutations() {
  3665. return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = ut.min(),
  3666. this;
  3667. }
  3668. setReadTime(t) {
  3669. return this.readTime = t, this;
  3670. }
  3671. get hasLocalMutations() {
  3672. return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;
  3673. }
  3674. get hasCommittedMutations() {
  3675. return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;
  3676. }
  3677. get hasPendingWrites() {
  3678. return this.hasLocalMutations || this.hasCommittedMutations;
  3679. }
  3680. isValidDocument() {
  3681. return 0 /* DocumentType.INVALID */ !== this.documentType;
  3682. }
  3683. isFoundDocument() {
  3684. return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;
  3685. }
  3686. isNoDocument() {
  3687. return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;
  3688. }
  3689. isUnknownDocument() {
  3690. return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;
  3691. }
  3692. isEqual(t) {
  3693. return t instanceof fn && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);
  3694. }
  3695. mutableCopy() {
  3696. return new fn(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  3697. }
  3698. toString() {
  3699. return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;
  3700. }
  3701. }
  3702. /**
  3703. * Compares the value for field `field` in the provided documents. Throws if
  3704. * the field does not exist in both documents.
  3705. */
  3706. /**
  3707. * @license
  3708. * Copyright 2022 Google LLC
  3709. *
  3710. * Licensed under the Apache License, Version 2.0 (the "License");
  3711. * you may not use this file except in compliance with the License.
  3712. * You may obtain a copy of the License at
  3713. *
  3714. * http://www.apache.org/licenses/LICENSE-2.0
  3715. *
  3716. * Unless required by applicable law or agreed to in writing, software
  3717. * distributed under the License is distributed on an "AS IS" BASIS,
  3718. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3719. * See the License for the specific language governing permissions and
  3720. * limitations under the License.
  3721. */
  3722. /**
  3723. * Represents a bound of a query.
  3724. *
  3725. * The bound is specified with the given components representing a position and
  3726. * whether it's just before or just after the position (relative to whatever the
  3727. * query order is).
  3728. *
  3729. * The position represents a logical index position for a query. It's a prefix
  3730. * of values for the (potentially implicit) order by clauses of a query.
  3731. *
  3732. * Bound provides a function to determine whether a document comes before or
  3733. * after a bound. This is influenced by whether the position is just before or
  3734. * just after the provided values.
  3735. */
  3736. class dn {
  3737. constructor(t, e) {
  3738. this.position = t, this.inclusive = e;
  3739. }
  3740. }
  3741. function wn(t, e, n) {
  3742. let s = 0;
  3743. for (let i = 0; i < t.position.length; i++) {
  3744. const r = e[i], o = t.position[i];
  3745. if (r.field.isKeyField()) s = ft.comparator(ft.fromName(o.referenceValue), n.key); else {
  3746. s = je(o, n.data.field(r.field));
  3747. }
  3748. if ("desc" /* Direction.DESCENDING */ === r.dir && (s *= -1), 0 !== s) break;
  3749. }
  3750. return s;
  3751. }
  3752. /**
  3753. * Returns true if a document sorts after a bound using the provided sort
  3754. * order.
  3755. */ function _n(t, e) {
  3756. if (null === t) return null === e;
  3757. if (null === e) return !1;
  3758. if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;
  3759. for (let n = 0; n < t.position.length; n++) {
  3760. if (!Ge(t.position[n], e.position[n])) return !1;
  3761. }
  3762. return !0;
  3763. }
  3764. /**
  3765. * @license
  3766. * Copyright 2022 Google LLC
  3767. *
  3768. * Licensed under the Apache License, Version 2.0 (the "License");
  3769. * you may not use this file except in compliance with the License.
  3770. * You may obtain a copy of the License at
  3771. *
  3772. * http://www.apache.org/licenses/LICENSE-2.0
  3773. *
  3774. * Unless required by applicable law or agreed to in writing, software
  3775. * distributed under the License is distributed on an "AS IS" BASIS,
  3776. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3777. * See the License for the specific language governing permissions and
  3778. * limitations under the License.
  3779. */
  3780. /**
  3781. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  3782. */ class mn {
  3783. constructor(t, e = "asc" /* Direction.ASCENDING */) {
  3784. this.field = t, this.dir = e;
  3785. }
  3786. }
  3787. function gn(t, e) {
  3788. return t.dir === e.dir && t.field.isEqual(e.field);
  3789. }
  3790. /**
  3791. * @license
  3792. * Copyright 2022 Google LLC
  3793. *
  3794. * Licensed under the Apache License, Version 2.0 (the "License");
  3795. * you may not use this file except in compliance with the License.
  3796. * You may obtain a copy of the License at
  3797. *
  3798. * http://www.apache.org/licenses/LICENSE-2.0
  3799. *
  3800. * Unless required by applicable law or agreed to in writing, software
  3801. * distributed under the License is distributed on an "AS IS" BASIS,
  3802. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3803. * See the License for the specific language governing permissions and
  3804. * limitations under the License.
  3805. */ class yn {}
  3806. class pn extends yn {
  3807. constructor(t, e, n) {
  3808. super(), this.field = t, this.op = e, this.value = n;
  3809. }
  3810. /**
  3811. * Creates a filter based on the provided arguments.
  3812. */ static create(t, e, n) {
  3813. return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, n) : new Sn(t, e, n) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new Nn(t, n) : "in" /* Operator.IN */ === e ? new kn(t, n) : "not-in" /* Operator.NOT_IN */ === e ? new $n(t, n) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new Mn(t, n) : new pn(t, e, n);
  3814. }
  3815. static createKeyFieldInFilter(t, e, n) {
  3816. return "in" /* Operator.IN */ === e ? new Dn(t, n) : new Cn(t, n);
  3817. }
  3818. matches(t) {
  3819. const e = t.data.field(this.field);
  3820. // Types do not have to match in NOT_EQUAL filters.
  3821. return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(je(e, this.value)) : null !== e && Ke(this.value) === Ke(e) && this.matchesComparison(je(e, this.value));
  3822. // Only compare types with matching backend order (such as double and int).
  3823. }
  3824. matchesComparison(t) {
  3825. switch (this.op) {
  3826. case "<" /* Operator.LESS_THAN */ :
  3827. return t < 0;
  3828. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  3829. return t <= 0;
  3830. case "==" /* Operator.EQUAL */ :
  3831. return 0 === t;
  3832. case "!=" /* Operator.NOT_EQUAL */ :
  3833. return 0 !== t;
  3834. case ">" /* Operator.GREATER_THAN */ :
  3835. return t > 0;
  3836. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  3837. return t >= 0;
  3838. default:
  3839. return B();
  3840. }
  3841. }
  3842. isInequality() {
  3843. 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;
  3844. }
  3845. getFlattenedFilters() {
  3846. return [ this ];
  3847. }
  3848. getFilters() {
  3849. return [ this ];
  3850. }
  3851. getFirstInequalityField() {
  3852. return this.isInequality() ? this.field : null;
  3853. }
  3854. }
  3855. class In extends yn {
  3856. constructor(t, e) {
  3857. super(), this.filters = t, this.op = e, this.lt = null;
  3858. }
  3859. /**
  3860. * Creates a filter based on the provided arguments.
  3861. */ static create(t, e) {
  3862. return new In(t, e);
  3863. }
  3864. matches(t) {
  3865. return Tn(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t)));
  3866. }
  3867. getFlattenedFilters() {
  3868. return null !== this.lt || (this.lt = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])),
  3869. this.lt;
  3870. }
  3871. // Returns a mutable copy of `this.filters`
  3872. getFilters() {
  3873. return Object.assign([], this.filters);
  3874. }
  3875. getFirstInequalityField() {
  3876. const t = this.ft((t => t.isInequality()));
  3877. return null !== t ? t.field : null;
  3878. }
  3879. // Performs a depth-first search to find and return the first FieldFilter in the composite filter
  3880. // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
  3881. // predicate.
  3882. ft(t) {
  3883. for (const e of this.getFlattenedFilters()) if (t(e)) return e;
  3884. return null;
  3885. }
  3886. }
  3887. function Tn(t) {
  3888. return "and" /* CompositeOperator.AND */ === t.op;
  3889. }
  3890. function En(t) {
  3891. return "or" /* CompositeOperator.OR */ === t.op;
  3892. }
  3893. /**
  3894. * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.
  3895. */ function An(t) {
  3896. return vn(t) && Tn(t);
  3897. }
  3898. /**
  3899. * Returns true if this filter does not contain any composite filters. Returns false otherwise.
  3900. */ function vn(t) {
  3901. for (const e of t.filters) if (e instanceof In) return !1;
  3902. return !0;
  3903. }
  3904. function Rn(t) {
  3905. if (t instanceof pn)
  3906. // TODO(b/29183165): Technically, this won't be unique if two values have
  3907. // the same description, such as the int 3 and the string "3". So we should
  3908. // add the types in here somehow, too.
  3909. return t.field.canonicalString() + t.op.toString() + We(t.value);
  3910. if (An(t))
  3911. // Older SDK versions use an implicit AND operation between their filters.
  3912. // In the new SDK versions, the developer may use an explicit AND filter.
  3913. // To stay consistent with the old usages, we add a special case to ensure
  3914. // the canonical ID for these two are the same. For example:
  3915. // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same
  3916. // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`.
  3917. return t.filters.map((t => Rn(t))).join(",");
  3918. {
  3919. // filter instanceof CompositeFilter
  3920. const e = t.filters.map((t => Rn(t))).join(",");
  3921. return `${t.op}(${e})`;
  3922. }
  3923. }
  3924. function Pn(t, e) {
  3925. return t instanceof pn ? function(t, e) {
  3926. return e instanceof pn && t.op === e.op && t.field.isEqual(e.field) && Ge(t.value, e.value);
  3927. }(t, e) : t instanceof In ? function(t, e) {
  3928. if (e instanceof In && t.op === e.op && t.filters.length === e.filters.length) {
  3929. return t.filters.reduce(((t, n, s) => t && Pn(n, e.filters[s])), !0);
  3930. }
  3931. return !1;
  3932. }
  3933. /**
  3934. * Returns a new composite filter that contains all filter from
  3935. * `compositeFilter` plus all the given filters in `otherFilters`.
  3936. */ (t, e) : void B();
  3937. }
  3938. function bn(t, e) {
  3939. const n = t.filters.concat(e);
  3940. return In.create(n, t.op);
  3941. }
  3942. /** Returns a debug description for `filter`. */ function Vn(t) {
  3943. return t instanceof pn ? function(t) {
  3944. return `${t.field.canonicalString()} ${t.op} ${We(t.value)}`;
  3945. }
  3946. /** Filter that matches on key fields (i.e. '__name__'). */ (t) : t instanceof In ? function(t) {
  3947. return t.op.toString() + " {" + t.getFilters().map(Vn).join(" ,") + "}";
  3948. }(t) : "Filter";
  3949. }
  3950. class Sn extends pn {
  3951. constructor(t, e, n) {
  3952. super(t, e, n), this.key = ft.fromName(n.referenceValue);
  3953. }
  3954. matches(t) {
  3955. const e = ft.comparator(t.key, this.key);
  3956. return this.matchesComparison(e);
  3957. }
  3958. }
  3959. /** Filter that matches on key fields within an array. */ class Dn extends pn {
  3960. constructor(t, e) {
  3961. super(t, "in" /* Operator.IN */ , e), this.keys = xn("in" /* Operator.IN */ , e);
  3962. }
  3963. matches(t) {
  3964. return this.keys.some((e => e.isEqual(t.key)));
  3965. }
  3966. }
  3967. /** Filter that matches on key fields not present within an array. */ class Cn extends pn {
  3968. constructor(t, e) {
  3969. super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = xn("not-in" /* Operator.NOT_IN */ , e);
  3970. }
  3971. matches(t) {
  3972. return !this.keys.some((e => e.isEqual(t.key)));
  3973. }
  3974. }
  3975. function xn(t, e) {
  3976. var n;
  3977. return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => ft.fromName(t.referenceValue)));
  3978. }
  3979. /** A Filter that implements the array-contains operator. */ class Nn extends pn {
  3980. constructor(t, e) {
  3981. super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e);
  3982. }
  3983. matches(t) {
  3984. const e = t.data.field(this.field);
  3985. return Ze(e) && Qe(e.arrayValue, this.value);
  3986. }
  3987. }
  3988. /** A Filter that implements the IN operator. */ class kn extends pn {
  3989. constructor(t, e) {
  3990. super(t, "in" /* Operator.IN */ , e);
  3991. }
  3992. matches(t) {
  3993. const e = t.data.field(this.field);
  3994. return null !== e && Qe(this.value.arrayValue, e);
  3995. }
  3996. }
  3997. /** A Filter that implements the not-in operator. */ class $n extends pn {
  3998. constructor(t, e) {
  3999. super(t, "not-in" /* Operator.NOT_IN */ , e);
  4000. }
  4001. matches(t) {
  4002. if (Qe(this.value.arrayValue, {
  4003. nullValue: "NULL_VALUE"
  4004. })) return !1;
  4005. const e = t.data.field(this.field);
  4006. return null !== e && !Qe(this.value.arrayValue, e);
  4007. }
  4008. }
  4009. /** A Filter that implements the array-contains-any operator. */ class Mn extends pn {
  4010. constructor(t, e) {
  4011. super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e);
  4012. }
  4013. matches(t) {
  4014. const e = t.data.field(this.field);
  4015. return !(!Ze(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => Qe(this.value.arrayValue, t)));
  4016. }
  4017. }
  4018. /**
  4019. * @license
  4020. * Copyright 2019 Google LLC
  4021. *
  4022. * Licensed under the Apache License, Version 2.0 (the "License");
  4023. * you may not use this file except in compliance with the License.
  4024. * You may obtain a copy of the License at
  4025. *
  4026. * http://www.apache.org/licenses/LICENSE-2.0
  4027. *
  4028. * Unless required by applicable law or agreed to in writing, software
  4029. * distributed under the License is distributed on an "AS IS" BASIS,
  4030. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4031. * See the License for the specific language governing permissions and
  4032. * limitations under the License.
  4033. */
  4034. // Visible for testing
  4035. class On {
  4036. constructor(t, e = null, n = [], s = [], i = null, r = null, o = null) {
  4037. this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = s, this.limit = i,
  4038. this.startAt = r, this.endAt = o, this.dt = null;
  4039. }
  4040. }
  4041. /**
  4042. * Initializes a Target with a path and optional additional query constraints.
  4043. * Path must currently be empty if this is a collection group query.
  4044. *
  4045. * NOTE: you should always construct `Target` from `Query.toTarget` instead of
  4046. * using this factory method, because `Query` provides an implicit `orderBy`
  4047. * property.
  4048. */ function Fn(t, e = null, n = [], s = [], i = null, r = null, o = null) {
  4049. return new On(t, e, n, s, i, r, o);
  4050. }
  4051. function Bn(t) {
  4052. const e = U(t);
  4053. if (null === e.dt) {
  4054. let t = e.path.canonicalString();
  4055. null !== e.collectionGroup && (t += "|cg:" + e.collectionGroup), t += "|f:", t += e.filters.map((t => Rn(t))).join(","),
  4056. t += "|ob:", t += e.orderBy.map((t => function(t) {
  4057. // TODO(b/29183165): Make this collision robust.
  4058. return t.field.canonicalString() + t.dir;
  4059. }(t))).join(","), Lt(e.limit) || (t += "|l:", t += e.limit), e.startAt && (t += "|lb:",
  4060. t += e.startAt.inclusive ? "b:" : "a:", t += e.startAt.position.map((t => We(t))).join(",")),
  4061. e.endAt && (t += "|ub:", t += e.endAt.inclusive ? "a:" : "b:", t += e.endAt.position.map((t => We(t))).join(",")),
  4062. e.dt = t;
  4063. }
  4064. return e.dt;
  4065. }
  4066. function Ln(t, e) {
  4067. if (t.limit !== e.limit) return !1;
  4068. if (t.orderBy.length !== e.orderBy.length) return !1;
  4069. for (let n = 0; n < t.orderBy.length; n++) if (!gn(t.orderBy[n], e.orderBy[n])) return !1;
  4070. if (t.filters.length !== e.filters.length) return !1;
  4071. for (let n = 0; n < t.filters.length; n++) if (!Pn(t.filters[n], e.filters[n])) return !1;
  4072. return t.collectionGroup === e.collectionGroup && (!!t.path.isEqual(e.path) && (!!_n(t.startAt, e.startAt) && _n(t.endAt, e.endAt)));
  4073. }
  4074. function qn(t) {
  4075. return ft.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  4076. }
  4077. /** Returns the field filters that target the given field path. */ function Un(t, e) {
  4078. return t.filters.filter((t => t instanceof pn && t.field.isEqual(e)));
  4079. }
  4080. /**
  4081. * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
  4082. * filters. Returns `null` if there are no such filters.
  4083. */
  4084. /**
  4085. * Returns the value to use as the lower bound for ascending index segment at
  4086. * the provided `fieldPath` (or the upper bound for an descending segment).
  4087. */
  4088. function Kn(t, e, n) {
  4089. let s = Ue, i = !0;
  4090. // Process all filters to find a value for the current field segment
  4091. for (const n of Un(t, e)) {
  4092. let t = Ue, e = !0;
  4093. switch (n.op) {
  4094. case "<" /* Operator.LESS_THAN */ :
  4095. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  4096. t = on(n.value);
  4097. break;
  4098. case "==" /* Operator.EQUAL */ :
  4099. case "in" /* Operator.IN */ :
  4100. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  4101. t = n.value;
  4102. break;
  4103. case ">" /* Operator.GREATER_THAN */ :
  4104. t = n.value, e = !1;
  4105. break;
  4106. case "!=" /* Operator.NOT_EQUAL */ :
  4107. case "not-in" /* Operator.NOT_IN */ :
  4108. t = Ue;
  4109. // Remaining filters cannot be used as lower bounds.
  4110. }
  4111. cn({
  4112. value: s,
  4113. inclusive: i
  4114. }, {
  4115. value: t,
  4116. inclusive: e
  4117. }) < 0 && (s = t, i = e);
  4118. }
  4119. // If there is an additional bound, compare the values against the existing
  4120. // range to see if we can narrow the scope.
  4121. if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {
  4122. if (t.orderBy[r].field.isEqual(e)) {
  4123. const t = n.position[r];
  4124. cn({
  4125. value: s,
  4126. inclusive: i
  4127. }, {
  4128. value: t,
  4129. inclusive: n.inclusive
  4130. }) < 0 && (s = t, i = n.inclusive);
  4131. break;
  4132. }
  4133. }
  4134. return {
  4135. value: s,
  4136. inclusive: i
  4137. };
  4138. }
  4139. /**
  4140. * Returns the value to use as the upper bound for ascending index segment at
  4141. * the provided `fieldPath` (or the lower bound for a descending segment).
  4142. */ function Gn(t, e, n) {
  4143. let s = qe, i = !0;
  4144. // Process all filters to find a value for the current field segment
  4145. for (const n of Un(t, e)) {
  4146. let t = qe, e = !0;
  4147. switch (n.op) {
  4148. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  4149. case ">" /* Operator.GREATER_THAN */ :
  4150. t = un(n.value), e = !1;
  4151. break;
  4152. case "==" /* Operator.EQUAL */ :
  4153. case "in" /* Operator.IN */ :
  4154. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  4155. t = n.value;
  4156. break;
  4157. case "<" /* Operator.LESS_THAN */ :
  4158. t = n.value, e = !1;
  4159. break;
  4160. case "!=" /* Operator.NOT_EQUAL */ :
  4161. case "not-in" /* Operator.NOT_IN */ :
  4162. t = qe;
  4163. // Remaining filters cannot be used as upper bounds.
  4164. }
  4165. an({
  4166. value: s,
  4167. inclusive: i
  4168. }, {
  4169. value: t,
  4170. inclusive: e
  4171. }) > 0 && (s = t, i = e);
  4172. }
  4173. // If there is an additional bound, compare the values against the existing
  4174. // range to see if we can narrow the scope.
  4175. if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {
  4176. if (t.orderBy[r].field.isEqual(e)) {
  4177. const t = n.position[r];
  4178. an({
  4179. value: s,
  4180. inclusive: i
  4181. }, {
  4182. value: t,
  4183. inclusive: n.inclusive
  4184. }) > 0 && (s = t, i = n.inclusive);
  4185. break;
  4186. }
  4187. }
  4188. return {
  4189. value: s,
  4190. inclusive: i
  4191. };
  4192. }
  4193. /** Returns the number of segments of a perfect index for this target. */
  4194. /**
  4195. * @license
  4196. * Copyright 2017 Google LLC
  4197. *
  4198. * Licensed under the Apache License, Version 2.0 (the "License");
  4199. * you may not use this file except in compliance with the License.
  4200. * You may obtain a copy of the License at
  4201. *
  4202. * http://www.apache.org/licenses/LICENSE-2.0
  4203. *
  4204. * Unless required by applicable law or agreed to in writing, software
  4205. * distributed under the License is distributed on an "AS IS" BASIS,
  4206. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4207. * See the License for the specific language governing permissions and
  4208. * limitations under the License.
  4209. */
  4210. /**
  4211. * Query encapsulates all the query attributes we support in the SDK. It can
  4212. * be run against the LocalStore, as well as be converted to a `Target` to
  4213. * query the RemoteStore results.
  4214. *
  4215. * Visible for testing.
  4216. */
  4217. class Qn {
  4218. /**
  4219. * Initializes a Query with a path and optional additional query constraints.
  4220. * Path must currently be empty if this is a collection group query.
  4221. */
  4222. constructor(t, e = null, n = [], s = [], i = null, r = "F" /* LimitType.First */ , o = null, u = null) {
  4223. this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = s,
  4224. this.limit = i, this.limitType = r, this.startAt = o, this.endAt = u, this.wt = null,
  4225. // The corresponding `Target` of this `Query` instance.
  4226. this._t = null, this.startAt, this.endAt;
  4227. }
  4228. }
  4229. /** Creates a new Query instance with the options provided. */ function jn(t, e, n, s, i, r, o, u) {
  4230. return new Qn(t, e, n, s, i, r, o, u);
  4231. }
  4232. /** Creates a new Query for a query that matches all documents at `path` */ function zn(t) {
  4233. return new Qn(t);
  4234. }
  4235. /**
  4236. * Helper to convert a collection group query into a collection query at a
  4237. * specific path. This is used when executing collection group queries, since
  4238. * we have to split the query into a set of collection queries at multiple
  4239. * paths.
  4240. */
  4241. /**
  4242. * Returns true if this query does not specify any query constraints that
  4243. * could remove results.
  4244. */
  4245. function Wn(t) {
  4246. 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());
  4247. }
  4248. function Hn(t) {
  4249. return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;
  4250. }
  4251. function Jn(t) {
  4252. for (const e of t.filters) {
  4253. const t = e.getFirstInequalityField();
  4254. if (null !== t) return t;
  4255. }
  4256. return null;
  4257. }
  4258. /**
  4259. * Creates a new Query for a collection group query that matches all documents
  4260. * within the provided collection group.
  4261. */
  4262. /**
  4263. * Returns whether the query matches a collection group rather than a specific
  4264. * collection.
  4265. */
  4266. function Yn(t) {
  4267. return null !== t.collectionGroup;
  4268. }
  4269. /**
  4270. * Returns the implicit order by constraint that is used to execute the Query,
  4271. * which can be different from the order by constraints the user provided (e.g.
  4272. * the SDK and backend always orders by `__name__`).
  4273. */ function Xn(t) {
  4274. const e = U(t);
  4275. if (null === e.wt) {
  4276. e.wt = [];
  4277. const t = Jn(e), n = Hn(e);
  4278. if (null !== t && null === n)
  4279. // In order to implicitly add key ordering, we must also add the
  4280. // inequality filter field for it to be a valid query.
  4281. // Note that the default inequality field and key ordering is ascending.
  4282. t.isKeyField() || e.wt.push(new mn(t)), e.wt.push(new mn(lt.keyField(), "asc" /* Direction.ASCENDING */)); else {
  4283. let t = !1;
  4284. for (const n of e.explicitOrderBy) e.wt.push(n), n.field.isKeyField() && (t = !0);
  4285. if (!t) {
  4286. // The order of the implicit key ordering always matches the last
  4287. // explicit order by
  4288. const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */;
  4289. e.wt.push(new mn(lt.keyField(), t));
  4290. }
  4291. }
  4292. }
  4293. return e.wt;
  4294. }
  4295. /**
  4296. * Converts this `Query` instance to it's corresponding `Target` representation.
  4297. */ function Zn(t) {
  4298. const e = U(t);
  4299. if (!e._t) if ("F" /* LimitType.First */ === e.limitType) e._t = Fn(e.path, e.collectionGroup, Xn(e), e.filters, e.limit, e.startAt, e.endAt); else {
  4300. // Flip the orderBy directions since we want the last results
  4301. const t = [];
  4302. for (const n of Xn(e)) {
  4303. const e = "desc" /* Direction.DESCENDING */ === n.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */;
  4304. t.push(new mn(n.field, e));
  4305. }
  4306. // We need to swap the cursors to match the now-flipped query ordering.
  4307. const n = e.endAt ? new dn(e.endAt.position, e.endAt.inclusive) : null, s = e.startAt ? new dn(e.startAt.position, e.startAt.inclusive) : null;
  4308. // Now return as a LimitType.First query.
  4309. e._t = Fn(e.path, e.collectionGroup, t, e.filters, e.limit, n, s);
  4310. }
  4311. return e._t;
  4312. }
  4313. function ts(t, e) {
  4314. e.getFirstInequalityField(), Jn(t);
  4315. const n = t.filters.concat([ e ]);
  4316. return new Qn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);
  4317. }
  4318. function es(t, e, n) {
  4319. return new Qn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);
  4320. }
  4321. function ns(t, e) {
  4322. return Ln(Zn(t), Zn(e)) && t.limitType === e.limitType;
  4323. }
  4324. // TODO(b/29183165): This is used to get a unique string from a query to, for
  4325. // example, use as a dictionary key, but the implementation is subject to
  4326. // collisions. Make it collision-free.
  4327. function ss(t) {
  4328. return `${Bn(Zn(t))}|lt:${t.limitType}`;
  4329. }
  4330. function is(t) {
  4331. return `Query(target=${function(t) {
  4332. let e = t.path.canonicalString();
  4333. return null !== t.collectionGroup && (e += " collectionGroup=" + t.collectionGroup),
  4334. t.filters.length > 0 && (e += `, filters: [${t.filters.map((t => Vn(t))).join(", ")}]`),
  4335. Lt(t.limit) || (e += ", limit: " + t.limit), t.orderBy.length > 0 && (e += `, orderBy: [${t.orderBy.map((t => function(t) {
  4336. return `${t.field.canonicalString()} (${t.dir})`;
  4337. }(t))).join(", ")}]`), t.startAt && (e += ", startAt: ", e += t.startAt.inclusive ? "b:" : "a:",
  4338. e += t.startAt.position.map((t => We(t))).join(",")), t.endAt && (e += ", endAt: ",
  4339. e += t.endAt.inclusive ? "a:" : "b:", e += t.endAt.position.map((t => We(t))).join(",")),
  4340. `Target(${e})`;
  4341. }(Zn(t))}; limitType=${t.limitType})`;
  4342. }
  4343. /** Returns whether `doc` matches the constraints of `query`. */ function rs(t, e) {
  4344. return e.isFoundDocument() && function(t, e) {
  4345. const n = e.key.path;
  4346. return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : ft.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);
  4347. }
  4348. /**
  4349. * A document must have a value for every ordering clause in order to show up
  4350. * in the results.
  4351. */ (t, e) && function(t, e) {
  4352. // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).
  4353. // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must
  4354. // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due
  4355. // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a".
  4356. // A document with content of {b:1} matches the filters, but does not match the orderBy because
  4357. // it's missing the field 'a'.
  4358. for (const n of Xn(t))
  4359. // order by key always matches
  4360. if (!n.field.isKeyField() && null === e.data.field(n.field)) return !1;
  4361. return !0;
  4362. }(t, e) && function(t, e) {
  4363. for (const n of t.filters) if (!n.matches(e)) return !1;
  4364. return !0;
  4365. }
  4366. /** Makes sure a document is within the bounds, if provided. */ (t, e) && function(t, e) {
  4367. if (t.startAt && !
  4368. /**
  4369. * Returns true if a document sorts before a bound using the provided sort
  4370. * order.
  4371. */
  4372. function(t, e, n) {
  4373. const s = wn(t, e, n);
  4374. return t.inclusive ? s <= 0 : s < 0;
  4375. }(t.startAt, Xn(t), e)) return !1;
  4376. if (t.endAt && !function(t, e, n) {
  4377. const s = wn(t, e, n);
  4378. return t.inclusive ? s >= 0 : s > 0;
  4379. }(t.endAt, Xn(t), e)) return !1;
  4380. return !0;
  4381. }
  4382. /**
  4383. * Returns the collection group that this query targets.
  4384. *
  4385. * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
  4386. * synchronization for query results.
  4387. */ (t, e);
  4388. }
  4389. function os(t) {
  4390. return t.collectionGroup || (t.path.length % 2 == 1 ? t.path.lastSegment() : t.path.get(t.path.length - 2));
  4391. }
  4392. /**
  4393. * Returns a new comparator function that can be used to compare two documents
  4394. * based on the Query's ordering constraint.
  4395. */ function us(t) {
  4396. return (e, n) => {
  4397. let s = !1;
  4398. for (const i of Xn(t)) {
  4399. const t = cs(i, e, n);
  4400. if (0 !== t) return t;
  4401. s = s || i.field.isKeyField();
  4402. }
  4403. return 0;
  4404. };
  4405. }
  4406. function cs(t, e, n) {
  4407. const s = t.field.isKeyField() ? ft.comparator(e.key, n.key) : function(t, e, n) {
  4408. const s = e.data.field(t), i = n.data.field(t);
  4409. return null !== s && null !== i ? je(s, i) : B();
  4410. }(t.field, e, n);
  4411. switch (t.dir) {
  4412. case "asc" /* Direction.ASCENDING */ :
  4413. return s;
  4414. case "desc" /* Direction.DESCENDING */ :
  4415. return -1 * s;
  4416. default:
  4417. return B();
  4418. }
  4419. }
  4420. /**
  4421. * @license
  4422. * Copyright 2017 Google LLC
  4423. *
  4424. * Licensed under the Apache License, Version 2.0 (the "License");
  4425. * you may not use this file except in compliance with the License.
  4426. * You may obtain a copy of the License at
  4427. *
  4428. * http://www.apache.org/licenses/LICENSE-2.0
  4429. *
  4430. * Unless required by applicable law or agreed to in writing, software
  4431. * distributed under the License is distributed on an "AS IS" BASIS,
  4432. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4433. * See the License for the specific language governing permissions and
  4434. * limitations under the License.
  4435. */
  4436. /**
  4437. * A map implementation that uses objects as keys. Objects must have an
  4438. * associated equals function and must be immutable. Entries in the map are
  4439. * stored together with the key being produced from the mapKeyFn. This map
  4440. * automatically handles collisions of keys.
  4441. */ class as {
  4442. constructor(t, e) {
  4443. this.mapKeyFn = t, this.equalsFn = e,
  4444. /**
  4445. * The inner map for a key/value pair. Due to the possibility of collisions we
  4446. * keep a list of entries that we do a linear search through to find an actual
  4447. * match. Note that collisions should be rare, so we still expect near
  4448. * constant time lookups in practice.
  4449. */
  4450. this.inner = {},
  4451. /** The number of entries stored in the map */
  4452. this.innerSize = 0;
  4453. }
  4454. /** Get a value for this key, or undefined if it does not exist. */ get(t) {
  4455. const e = this.mapKeyFn(t), n = this.inner[e];
  4456. if (void 0 !== n) for (const [e, s] of n) if (this.equalsFn(e, t)) return s;
  4457. }
  4458. has(t) {
  4459. return void 0 !== this.get(t);
  4460. }
  4461. /** Put this key and value in the map. */ set(t, e) {
  4462. const n = this.mapKeyFn(t), s = this.inner[n];
  4463. if (void 0 === s) return this.inner[n] = [ [ t, e ] ], void this.innerSize++;
  4464. for (let n = 0; n < s.length; n++) if (this.equalsFn(s[n][0], t))
  4465. // This is updating an existing entry and does not increase `innerSize`.
  4466. return void (s[n] = [ t, e ]);
  4467. s.push([ t, e ]), this.innerSize++;
  4468. }
  4469. /**
  4470. * Remove this key from the map. Returns a boolean if anything was deleted.
  4471. */ delete(t) {
  4472. const e = this.mapKeyFn(t), n = this.inner[e];
  4473. if (void 0 === n) return !1;
  4474. for (let s = 0; s < n.length; s++) if (this.equalsFn(n[s][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(s, 1),
  4475. this.innerSize--, !0;
  4476. return !1;
  4477. }
  4478. forEach(t) {
  4479. pe(this.inner, ((e, n) => {
  4480. for (const [e, s] of n) t(e, s);
  4481. }));
  4482. }
  4483. isEmpty() {
  4484. return Ie(this.inner);
  4485. }
  4486. size() {
  4487. return this.innerSize;
  4488. }
  4489. }
  4490. /**
  4491. * @license
  4492. * Copyright 2017 Google LLC
  4493. *
  4494. * Licensed under the Apache License, Version 2.0 (the "License");
  4495. * you may not use this file except in compliance with the License.
  4496. * You may obtain a copy of the License at
  4497. *
  4498. * http://www.apache.org/licenses/LICENSE-2.0
  4499. *
  4500. * Unless required by applicable law or agreed to in writing, software
  4501. * distributed under the License is distributed on an "AS IS" BASIS,
  4502. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4503. * See the License for the specific language governing permissions and
  4504. * limitations under the License.
  4505. */ const hs = new Te(ft.comparator);
  4506. function ls() {
  4507. return hs;
  4508. }
  4509. const fs = new Te(ft.comparator);
  4510. function ds(...t) {
  4511. let e = fs;
  4512. for (const n of t) e = e.insert(n.key, n);
  4513. return e;
  4514. }
  4515. function ws(t) {
  4516. let e = fs;
  4517. return t.forEach(((t, n) => e = e.insert(t, n.overlayedDocument))), e;
  4518. }
  4519. function _s() {
  4520. return gs();
  4521. }
  4522. function ms() {
  4523. return gs();
  4524. }
  4525. function gs() {
  4526. return new as((t => t.toString()), ((t, e) => t.isEqual(e)));
  4527. }
  4528. const ys = new Te(ft.comparator);
  4529. const ps = new ve(ft.comparator);
  4530. function Is(...t) {
  4531. let e = ps;
  4532. for (const n of t) e = e.add(n);
  4533. return e;
  4534. }
  4535. const Ts = new ve(st);
  4536. function Es() {
  4537. return Ts;
  4538. }
  4539. /**
  4540. * @license
  4541. * Copyright 2020 Google LLC
  4542. *
  4543. * Licensed under the Apache License, Version 2.0 (the "License");
  4544. * you may not use this file except in compliance with the License.
  4545. * You may obtain a copy of the License at
  4546. *
  4547. * http://www.apache.org/licenses/LICENSE-2.0
  4548. *
  4549. * Unless required by applicable law or agreed to in writing, software
  4550. * distributed under the License is distributed on an "AS IS" BASIS,
  4551. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4552. * See the License for the specific language governing permissions and
  4553. * limitations under the License.
  4554. */
  4555. /**
  4556. * Returns an DoubleValue for `value` that is encoded based the serializer's
  4557. * `useProto3Json` setting.
  4558. */ function As(t, e) {
  4559. if (t.useProto3Json) {
  4560. if (isNaN(e)) return {
  4561. doubleValue: "NaN"
  4562. };
  4563. if (e === 1 / 0) return {
  4564. doubleValue: "Infinity"
  4565. };
  4566. if (e === -1 / 0) return {
  4567. doubleValue: "-Infinity"
  4568. };
  4569. }
  4570. return {
  4571. doubleValue: qt(e) ? "-0" : e
  4572. };
  4573. }
  4574. /**
  4575. * Returns an IntegerValue for `value`.
  4576. */ function vs(t) {
  4577. return {
  4578. integerValue: "" + t
  4579. };
  4580. }
  4581. /**
  4582. * Returns a value for a number that's appropriate to put into a proto.
  4583. * The return value is an IntegerValue if it can safely represent the value,
  4584. * otherwise a DoubleValue is returned.
  4585. */ function Rs(t, e) {
  4586. return Ut(e) ? vs(e) : As(t, e);
  4587. }
  4588. /**
  4589. * @license
  4590. * Copyright 2018 Google LLC
  4591. *
  4592. * Licensed under the Apache License, Version 2.0 (the "License");
  4593. * you may not use this file except in compliance with the License.
  4594. * You may obtain a copy of the License at
  4595. *
  4596. * http://www.apache.org/licenses/LICENSE-2.0
  4597. *
  4598. * Unless required by applicable law or agreed to in writing, software
  4599. * distributed under the License is distributed on an "AS IS" BASIS,
  4600. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4601. * See the License for the specific language governing permissions and
  4602. * limitations under the License.
  4603. */
  4604. /** Used to represent a field transform on a mutation. */ class Ps {
  4605. constructor() {
  4606. // Make sure that the structural type of `TransformOperation` is unique.
  4607. // See https://github.com/microsoft/TypeScript/issues/5451
  4608. this._ = void 0;
  4609. }
  4610. }
  4611. /**
  4612. * Computes the local transform result against the provided `previousValue`,
  4613. * optionally using the provided localWriteTime.
  4614. */ function bs(t, e, n) {
  4615. return t instanceof Ds ? function(t, e) {
  4616. const n = {
  4617. fields: {
  4618. __type__: {
  4619. stringValue: "server_timestamp"
  4620. },
  4621. __local_write_time__: {
  4622. timestampValue: {
  4623. seconds: t.seconds,
  4624. nanos: t.nanoseconds
  4625. }
  4626. }
  4627. }
  4628. };
  4629. // We should avoid storing deeply nested server timestamp map values
  4630. // because we never use the intermediate "previous values".
  4631. // For example:
  4632. // previous: 42L, add: t1, result: t1 -> 42L
  4633. // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)
  4634. // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)
  4635. // `getPreviousValue` recursively traverses server timestamps to find the
  4636. // least recent Value.
  4637. return e && Me(e) && (e = Oe(e)), e && (n.fields.__previous_value__ = e),
  4638. {
  4639. mapValue: n
  4640. };
  4641. }(n, e) : t instanceof Cs ? xs(t, e) : t instanceof Ns ? ks(t, e) : function(t, e) {
  4642. // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit
  4643. // precision and resolves overflows by reducing precision, we do not
  4644. // manually cap overflows at 2^63.
  4645. const n = Ss(t, e), s = Ms(n) + Ms(t.gt);
  4646. return Xe(n) && Xe(t.gt) ? vs(s) : As(t.serializer, s);
  4647. }(t, e);
  4648. }
  4649. /**
  4650. * Computes a final transform result after the transform has been acknowledged
  4651. * by the server, potentially using the server-provided transformResult.
  4652. */ function Vs(t, e, n) {
  4653. // The server just sends null as the transform result for array operations,
  4654. // so we have to calculate a result the same as we do for local
  4655. // applications.
  4656. return t instanceof Cs ? xs(t, e) : t instanceof Ns ? ks(t, e) : n;
  4657. }
  4658. /**
  4659. * If this transform operation is not idempotent, returns the base value to
  4660. * persist for this transform. If a base value is returned, the transform
  4661. * operation is always applied to this base value, even if document has
  4662. * already been updated.
  4663. *
  4664. * Base values provide consistent behavior for non-idempotent transforms and
  4665. * allow us to return the same latency-compensated value even if the backend
  4666. * has already applied the transform operation. The base value is null for
  4667. * idempotent transforms, as they can be re-played even if the backend has
  4668. * already applied them.
  4669. *
  4670. * @returns a base value to store along with the mutation, or null for
  4671. * idempotent transforms.
  4672. */ function Ss(t, e) {
  4673. return t instanceof $s ? Xe(n = e) || function(t) {
  4674. return !!t && "doubleValue" in t;
  4675. }
  4676. /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (n) ? e : {
  4677. integerValue: 0
  4678. } : null;
  4679. var n;
  4680. }
  4681. /** Transforms a value into a server-generated timestamp. */
  4682. class Ds extends Ps {}
  4683. /** Transforms an array value via a union operation. */ class Cs extends Ps {
  4684. constructor(t) {
  4685. super(), this.elements = t;
  4686. }
  4687. }
  4688. function xs(t, e) {
  4689. const n = Os(e);
  4690. for (const e of t.elements) n.some((t => Ge(t, e))) || n.push(e);
  4691. return {
  4692. arrayValue: {
  4693. values: n
  4694. }
  4695. };
  4696. }
  4697. /** Transforms an array value via a remove operation. */ class Ns extends Ps {
  4698. constructor(t) {
  4699. super(), this.elements = t;
  4700. }
  4701. }
  4702. function ks(t, e) {
  4703. let n = Os(e);
  4704. for (const e of t.elements) n = n.filter((t => !Ge(t, e)));
  4705. return {
  4706. arrayValue: {
  4707. values: n
  4708. }
  4709. };
  4710. }
  4711. /**
  4712. * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
  4713. * transforms. Converts all field values to integers or doubles, but unlike the
  4714. * backend does not cap integer values at 2^63. Instead, JavaScript number
  4715. * arithmetic is used and precision loss can occur for values greater than 2^53.
  4716. */ class $s extends Ps {
  4717. constructor(t, e) {
  4718. super(), this.serializer = t, this.gt = e;
  4719. }
  4720. }
  4721. function Ms(t) {
  4722. return ke(t.integerValue || t.doubleValue);
  4723. }
  4724. function Os(t) {
  4725. return Ze(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];
  4726. }
  4727. /**
  4728. * @license
  4729. * Copyright 2017 Google LLC
  4730. *
  4731. * Licensed under the Apache License, Version 2.0 (the "License");
  4732. * you may not use this file except in compliance with the License.
  4733. * You may obtain a copy of the License at
  4734. *
  4735. * http://www.apache.org/licenses/LICENSE-2.0
  4736. *
  4737. * Unless required by applicable law or agreed to in writing, software
  4738. * distributed under the License is distributed on an "AS IS" BASIS,
  4739. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4740. * See the License for the specific language governing permissions and
  4741. * limitations under the License.
  4742. */
  4743. /** A field path and the TransformOperation to perform upon it. */ class Fs {
  4744. constructor(t, e) {
  4745. this.field = t, this.transform = e;
  4746. }
  4747. }
  4748. function Bs(t, e) {
  4749. return t.field.isEqual(e.field) && function(t, e) {
  4750. return t instanceof Cs && e instanceof Cs || t instanceof Ns && e instanceof Ns ? it(t.elements, e.elements, Ge) : t instanceof $s && e instanceof $s ? Ge(t.gt, e.gt) : t instanceof Ds && e instanceof Ds;
  4751. }(t.transform, e.transform);
  4752. }
  4753. /** The result of successfully applying a mutation to the backend. */
  4754. class Ls {
  4755. constructor(
  4756. /**
  4757. * The version at which the mutation was committed:
  4758. *
  4759. * - For most operations, this is the updateTime in the WriteResult.
  4760. * - For deletes, the commitTime of the WriteResponse (because deletes are
  4761. * not stored and have no updateTime).
  4762. *
  4763. * Note that these versions can be different: No-op writes will not change
  4764. * the updateTime even though the commitTime advances.
  4765. */
  4766. t,
  4767. /**
  4768. * The resulting fields returned from the backend after a mutation
  4769. * containing field transforms has been committed. Contains one FieldValue
  4770. * for each FieldTransform that was in the mutation.
  4771. *
  4772. * Will be empty if the mutation did not contain any field transforms.
  4773. */
  4774. e) {
  4775. this.version = t, this.transformResults = e;
  4776. }
  4777. }
  4778. /**
  4779. * Encodes a precondition for a mutation. This follows the model that the
  4780. * backend accepts with the special case of an explicit "empty" precondition
  4781. * (meaning no precondition).
  4782. */ class qs {
  4783. constructor(t, e) {
  4784. this.updateTime = t, this.exists = e;
  4785. }
  4786. /** Creates a new empty Precondition. */ static none() {
  4787. return new qs;
  4788. }
  4789. /** Creates a new Precondition with an exists flag. */ static exists(t) {
  4790. return new qs(void 0, t);
  4791. }
  4792. /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) {
  4793. return new qs(t);
  4794. }
  4795. /** Returns whether this Precondition is empty. */ get isNone() {
  4796. return void 0 === this.updateTime && void 0 === this.exists;
  4797. }
  4798. isEqual(t) {
  4799. return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
  4800. }
  4801. }
  4802. /** Returns true if the preconditions is valid for the given document. */ function Us(t, e) {
  4803. return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();
  4804. }
  4805. /**
  4806. * A mutation describes a self-contained change to a document. Mutations can
  4807. * create, replace, delete, and update subsets of documents.
  4808. *
  4809. * Mutations not only act on the value of the document but also its version.
  4810. *
  4811. * For local mutations (mutations that haven't been committed yet), we preserve
  4812. * the existing version for Set and Patch mutations. For Delete mutations, we
  4813. * reset the version to 0.
  4814. *
  4815. * Here's the expected transition table.
  4816. *
  4817. * MUTATION APPLIED TO RESULTS IN
  4818. *
  4819. * SetMutation Document(v3) Document(v3)
  4820. * SetMutation NoDocument(v3) Document(v0)
  4821. * SetMutation InvalidDocument(v0) Document(v0)
  4822. * PatchMutation Document(v3) Document(v3)
  4823. * PatchMutation NoDocument(v3) NoDocument(v3)
  4824. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  4825. * DeleteMutation Document(v3) NoDocument(v0)
  4826. * DeleteMutation NoDocument(v3) NoDocument(v0)
  4827. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  4828. *
  4829. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  4830. * the resulting version for Set and Patch mutations. As deletes have no
  4831. * explicit update time, we use the commitTime of the WriteResponse for
  4832. * Delete mutations.
  4833. *
  4834. * If a mutation is acknowledged by the backend but fails the precondition check
  4835. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  4836. * the updated version.
  4837. *
  4838. * Field transforms are used only with Patch and Set Mutations. We use the
  4839. * `updateTransforms` message to store transforms, rather than the `transforms`s
  4840. * messages.
  4841. *
  4842. * ## Subclassing Notes
  4843. *
  4844. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  4845. * applyToLocalView() to implement the actual behavior of applying the mutation
  4846. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  4847. * example).
  4848. */ class Ks {}
  4849. /**
  4850. * A utility method to calculate a `Mutation` representing the overlay from the
  4851. * final state of the document, and a `FieldMask` representing the fields that
  4852. * are mutated by the local mutations.
  4853. */ function Gs(t, e) {
  4854. if (!t.hasLocalMutations || e && 0 === e.fields.length) return null;
  4855. // mask is null when sets or deletes are applied to the current document.
  4856. if (null === e) return t.isNoDocument() ? new ti(t.key, qs.none()) : new Hs(t.key, t.data, qs.none());
  4857. {
  4858. const n = t.data, s = hn.empty();
  4859. let i = new ve(lt.comparator);
  4860. for (let t of e.fields) if (!i.has(t)) {
  4861. let e = n.field(t);
  4862. // If we are deleting a nested field, we take the immediate parent as
  4863. // the mask used to construct the resulting mutation.
  4864. // Justification: Nested fields can create parent fields implicitly. If
  4865. // only a leaf entry is deleted in later mutations, the parent field
  4866. // should still remain, but we may have lost this information.
  4867. // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).
  4868. // This leaves the final result (foo, {}). Despite the fact that `doc`
  4869. // has the correct result, `foo` is not in `mask`, and the resulting
  4870. // mutation would miss `foo`.
  4871. null === e && t.length > 1 && (t = t.popLast(), e = n.field(t)), null === e ? s.delete(t) : s.set(t, e),
  4872. i = i.add(t);
  4873. }
  4874. return new Js(t.key, s, new be(i.toArray()), qs.none());
  4875. }
  4876. }
  4877. /**
  4878. * Applies this mutation to the given document for the purposes of computing a
  4879. * new remote document. If the input document doesn't match the expected state
  4880. * (e.g. it is invalid or outdated), the document type may transition to
  4881. * unknown.
  4882. *
  4883. * @param mutation - The mutation to apply.
  4884. * @param document - The document to mutate. The input document can be an
  4885. * invalid document if the client has no knowledge of the pre-mutation state
  4886. * of the document.
  4887. * @param mutationResult - The result of applying the mutation from the backend.
  4888. */ function Qs(t, e, n) {
  4889. t instanceof Hs ? function(t, e, n) {
  4890. // Unlike setMutationApplyToLocalView, if we're applying a mutation to a
  4891. // remote document the server has accepted the mutation so the precondition
  4892. // must have held.
  4893. const s = t.value.clone(), i = Xs(t.fieldTransforms, e, n.transformResults);
  4894. s.setAll(i), e.convertToFoundDocument(n.version, s).setHasCommittedMutations();
  4895. }(t, e, n) : t instanceof Js ? function(t, e, n) {
  4896. if (!Us(t.precondition, e))
  4897. // Since the mutation was not rejected, we know that the precondition
  4898. // matched on the backend. We therefore must not have the expected version
  4899. // of the document in our cache and convert to an UnknownDocument with a
  4900. // known updateTime.
  4901. return void e.convertToUnknownDocument(n.version);
  4902. const s = Xs(t.fieldTransforms, e, n.transformResults), i = e.data;
  4903. i.setAll(Ys(t)), i.setAll(s), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();
  4904. }(t, e, n) : function(t, e, n) {
  4905. // Unlike applyToLocalView, if we're applying a mutation to a remote
  4906. // document the server has accepted the mutation so the precondition must
  4907. // have held.
  4908. e.convertToNoDocument(n.version).setHasCommittedMutations();
  4909. }(0, e, n);
  4910. }
  4911. /**
  4912. * Applies this mutation to the given document for the purposes of computing
  4913. * the new local view of a document. If the input document doesn't match the
  4914. * expected state, the document is not modified.
  4915. *
  4916. * @param mutation - The mutation to apply.
  4917. * @param document - The document to mutate. The input document can be an
  4918. * invalid document if the client has no knowledge of the pre-mutation state
  4919. * of the document.
  4920. * @param previousMask - The fields that have been updated before applying this mutation.
  4921. * @param localWriteTime - A timestamp indicating the local write time of the
  4922. * batch this mutation is a part of.
  4923. * @returns A `FieldMask` representing the fields that are changed by applying this mutation.
  4924. */ function js(t, e, n, s) {
  4925. return t instanceof Hs ? function(t, e, n, s) {
  4926. if (!Us(t.precondition, e))
  4927. // The mutation failed to apply (e.g. a document ID created with add()
  4928. // caused a name collision).
  4929. return n;
  4930. const i = t.value.clone(), r = Zs(t.fieldTransforms, s, e);
  4931. return i.setAll(r), e.convertToFoundDocument(e.version, i).setHasLocalMutations(),
  4932. null;
  4933. // SetMutation overwrites all fields.
  4934. }
  4935. /**
  4936. * A mutation that modifies fields of the document at the given key with the
  4937. * given values. The values are applied through a field mask:
  4938. *
  4939. * * When a field is in both the mask and the values, the corresponding field
  4940. * is updated.
  4941. * * When a field is in neither the mask nor the values, the corresponding
  4942. * field is unmodified.
  4943. * * When a field is in the mask but not in the values, the corresponding field
  4944. * is deleted.
  4945. * * When a field is not in the mask but is in the values, the values map is
  4946. * ignored.
  4947. */ (t, e, n, s) : t instanceof Js ? function(t, e, n, s) {
  4948. if (!Us(t.precondition, e)) return n;
  4949. const i = Zs(t.fieldTransforms, s, e), r = e.data;
  4950. if (r.setAll(Ys(t)), r.setAll(i), e.convertToFoundDocument(e.version, r).setHasLocalMutations(),
  4951. null === n) return null;
  4952. return n.unionWith(t.fieldMask.fields).unionWith(t.fieldTransforms.map((t => t.field)));
  4953. }
  4954. /**
  4955. * Returns a FieldPath/Value map with the content of the PatchMutation.
  4956. */ (t, e, n, s) : function(t, e, n) {
  4957. if (Us(t.precondition, e)) return e.convertToNoDocument(e.version).setHasLocalMutations(),
  4958. null;
  4959. return n;
  4960. }
  4961. /**
  4962. * A mutation that verifies the existence of the document at the given key with
  4963. * the provided precondition.
  4964. *
  4965. * The `verify` operation is only used in Transactions, and this class serves
  4966. * primarily to facilitate serialization into protos.
  4967. */ (t, e, n);
  4968. }
  4969. /**
  4970. * If this mutation is not idempotent, returns the base value to persist with
  4971. * this mutation. If a base value is returned, the mutation is always applied
  4972. * to this base value, even if document has already been updated.
  4973. *
  4974. * The base value is a sparse object that consists of only the document
  4975. * fields for which this mutation contains a non-idempotent transformation
  4976. * (e.g. a numeric increment). The provided value guarantees consistent
  4977. * behavior for non-idempotent transforms and allow us to return the same
  4978. * latency-compensated value even if the backend has already applied the
  4979. * mutation. The base value is null for idempotent mutations, as they can be
  4980. * re-played even if the backend has already applied them.
  4981. *
  4982. * @returns a base value to store along with the mutation, or null for
  4983. * idempotent mutations.
  4984. */ function zs(t, e) {
  4985. let n = null;
  4986. for (const s of t.fieldTransforms) {
  4987. const t = e.data.field(s.field), i = Ss(s.transform, t || null);
  4988. null != i && (null === n && (n = hn.empty()), n.set(s.field, i));
  4989. }
  4990. return n || null;
  4991. }
  4992. function Ws(t, e) {
  4993. return t.type === e.type && (!!t.key.isEqual(e.key) && (!!t.precondition.isEqual(e.precondition) && (!!function(t, e) {
  4994. return void 0 === t && void 0 === e || !(!t || !e) && it(t, e, ((t, e) => Bs(t, e)));
  4995. }(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)))));
  4996. }
  4997. /**
  4998. * A mutation that creates or replaces the document at the given key with the
  4999. * object value contents.
  5000. */ class Hs extends Ks {
  5001. constructor(t, e, n, s = []) {
  5002. super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = s,
  5003. this.type = 0 /* MutationType.Set */;
  5004. }
  5005. getFieldMask() {
  5006. return null;
  5007. }
  5008. }
  5009. class Js extends Ks {
  5010. constructor(t, e, n, s, i = []) {
  5011. super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = s,
  5012. this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;
  5013. }
  5014. getFieldMask() {
  5015. return this.fieldMask;
  5016. }
  5017. }
  5018. function Ys(t) {
  5019. const e = new Map;
  5020. return t.fieldMask.fields.forEach((n => {
  5021. if (!n.isEmpty()) {
  5022. const s = t.data.field(n);
  5023. e.set(n, s);
  5024. }
  5025. })), e;
  5026. }
  5027. /**
  5028. * Creates a list of "transform results" (a transform result is a field value
  5029. * representing the result of applying a transform) for use after a mutation
  5030. * containing transforms has been acknowledged by the server.
  5031. *
  5032. * @param fieldTransforms - The field transforms to apply the result to.
  5033. * @param mutableDocument - The current state of the document after applying all
  5034. * previous mutations.
  5035. * @param serverTransformResults - The transform results received by the server.
  5036. * @returns The transform results list.
  5037. */ function Xs(t, e, n) {
  5038. const s = new Map;
  5039. L(t.length === n.length);
  5040. for (let i = 0; i < n.length; i++) {
  5041. const r = t[i], o = r.transform, u = e.data.field(r.field);
  5042. s.set(r.field, Vs(o, u, n[i]));
  5043. }
  5044. return s;
  5045. }
  5046. /**
  5047. * Creates a list of "transform results" (a transform result is a field value
  5048. * representing the result of applying a transform) for use when applying a
  5049. * transform locally.
  5050. *
  5051. * @param fieldTransforms - The field transforms to apply the result to.
  5052. * @param localWriteTime - The local time of the mutation (used to
  5053. * generate ServerTimestampValues).
  5054. * @param mutableDocument - The document to apply transforms on.
  5055. * @returns The transform results list.
  5056. */ function Zs(t, e, n) {
  5057. const s = new Map;
  5058. for (const i of t) {
  5059. const t = i.transform, r = n.data.field(i.field);
  5060. s.set(i.field, bs(t, r, e));
  5061. }
  5062. return s;
  5063. }
  5064. /** A mutation that deletes the document at the given key. */ class ti extends Ks {
  5065. constructor(t, e) {
  5066. super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ ,
  5067. this.fieldTransforms = [];
  5068. }
  5069. getFieldMask() {
  5070. return null;
  5071. }
  5072. }
  5073. class ei extends Ks {
  5074. constructor(t, e) {
  5075. super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ ,
  5076. this.fieldTransforms = [];
  5077. }
  5078. getFieldMask() {
  5079. return null;
  5080. }
  5081. }
  5082. /**
  5083. * @license
  5084. * Copyright 2017 Google LLC
  5085. *
  5086. * Licensed under the Apache License, Version 2.0 (the "License");
  5087. * you may not use this file except in compliance with the License.
  5088. * You may obtain a copy of the License at
  5089. *
  5090. * http://www.apache.org/licenses/LICENSE-2.0
  5091. *
  5092. * Unless required by applicable law or agreed to in writing, software
  5093. * distributed under the License is distributed on an "AS IS" BASIS,
  5094. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5095. * See the License for the specific language governing permissions and
  5096. * limitations under the License.
  5097. */
  5098. /**
  5099. * A batch of mutations that will be sent as one unit to the backend.
  5100. */ class ni {
  5101. /**
  5102. * @param batchId - The unique ID of this mutation batch.
  5103. * @param localWriteTime - The original write time of this mutation.
  5104. * @param baseMutations - Mutations that are used to populate the base
  5105. * values when this mutation is applied locally. This can be used to locally
  5106. * overwrite values that are persisted in the remote document cache. Base
  5107. * mutations are never sent to the backend.
  5108. * @param mutations - The user-provided mutations in this mutation batch.
  5109. * User-provided mutations are applied both locally and remotely on the
  5110. * backend.
  5111. */
  5112. constructor(t, e, n, s) {
  5113. this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = s;
  5114. }
  5115. /**
  5116. * Applies all the mutations in this MutationBatch to the specified document
  5117. * to compute the state of the remote document
  5118. *
  5119. * @param document - The document to apply mutations to.
  5120. * @param batchResult - The result of applying the MutationBatch to the
  5121. * backend.
  5122. */ applyToRemoteDocument(t, e) {
  5123. const n = e.mutationResults;
  5124. for (let e = 0; e < this.mutations.length; e++) {
  5125. const s = this.mutations[e];
  5126. if (s.key.isEqual(t.key)) {
  5127. Qs(s, t, n[e]);
  5128. }
  5129. }
  5130. }
  5131. /**
  5132. * Computes the local view of a document given all the mutations in this
  5133. * batch.
  5134. *
  5135. * @param document - The document to apply mutations to.
  5136. * @param mutatedFields - Fields that have been updated before applying this mutation batch.
  5137. * @returns A `FieldMask` representing all the fields that are mutated.
  5138. */ applyToLocalView(t, e) {
  5139. // First, apply the base state. This allows us to apply non-idempotent
  5140. // transform against a consistent set of values.
  5141. for (const n of this.baseMutations) n.key.isEqual(t.key) && (e = js(n, t, e, this.localWriteTime));
  5142. // Second, apply all user-provided mutations.
  5143. for (const n of this.mutations) n.key.isEqual(t.key) && (e = js(n, t, e, this.localWriteTime));
  5144. return e;
  5145. }
  5146. /**
  5147. * Computes the local view for all provided documents given the mutations in
  5148. * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
  5149. * replace all the mutation applications.
  5150. */ applyToLocalDocumentSet(t, e) {
  5151. // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations
  5152. // directly (as done in `applyToLocalView()`), we can reduce the complexity
  5153. // to O(n).
  5154. const n = ms();
  5155. return this.mutations.forEach((s => {
  5156. const i = t.get(s.key), r = i.overlayedDocument;
  5157. // TODO(mutabledocuments): This method should take a MutableDocumentMap
  5158. // and we should remove this cast.
  5159. let o = this.applyToLocalView(r, i.mutatedFields);
  5160. // Set mutatedFields to null if the document is only from local mutations.
  5161. // This creates a Set or Delete mutation, instead of trying to create a
  5162. // patch mutation as the overlay.
  5163. o = e.has(s.key) ? null : o;
  5164. const u = Gs(r, o);
  5165. null !== u && n.set(s.key, u), r.isValidDocument() || r.convertToNoDocument(ut.min());
  5166. })), n;
  5167. }
  5168. keys() {
  5169. return this.mutations.reduce(((t, e) => t.add(e.key)), Is());
  5170. }
  5171. isEqual(t) {
  5172. return this.batchId === t.batchId && it(this.mutations, t.mutations, ((t, e) => Ws(t, e))) && it(this.baseMutations, t.baseMutations, ((t, e) => Ws(t, e)));
  5173. }
  5174. }
  5175. /** The result of applying a mutation batch to the backend. */ class si {
  5176. constructor(t, e, n,
  5177. /**
  5178. * A pre-computed mapping from each mutated document to the resulting
  5179. * version.
  5180. */
  5181. s) {
  5182. this.batch = t, this.commitVersion = e, this.mutationResults = n, this.docVersions = s;
  5183. }
  5184. /**
  5185. * Creates a new MutationBatchResult for the given batch and results. There
  5186. * must be one result for each mutation in the batch. This static factory
  5187. * caches a document=&gt;version mapping (docVersions).
  5188. */ static from(t, e, n) {
  5189. L(t.mutations.length === n.length);
  5190. let s = ys;
  5191. const i = t.mutations;
  5192. for (let t = 0; t < i.length; t++) s = s.insert(i[t].key, n[t].version);
  5193. return new si(t, e, n, s);
  5194. }
  5195. }
  5196. /**
  5197. * @license
  5198. * Copyright 2022 Google LLC
  5199. *
  5200. * Licensed under the Apache License, Version 2.0 (the "License");
  5201. * you may not use this file except in compliance with the License.
  5202. * You may obtain a copy of the License at
  5203. *
  5204. * http://www.apache.org/licenses/LICENSE-2.0
  5205. *
  5206. * Unless required by applicable law or agreed to in writing, software
  5207. * distributed under the License is distributed on an "AS IS" BASIS,
  5208. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5209. * See the License for the specific language governing permissions and
  5210. * limitations under the License.
  5211. */
  5212. /**
  5213. * Representation of an overlay computed by Firestore.
  5214. *
  5215. * Holds information about a mutation and the largest batch id in Firestore when
  5216. * the mutation was created.
  5217. */ class ii {
  5218. constructor(t, e) {
  5219. this.largestBatchId = t, this.mutation = e;
  5220. }
  5221. getKey() {
  5222. return this.mutation.key;
  5223. }
  5224. isEqual(t) {
  5225. return null !== t && this.mutation === t.mutation;
  5226. }
  5227. toString() {
  5228. return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`;
  5229. }
  5230. }
  5231. /**
  5232. * @license
  5233. * Copyright 2023 Google LLC
  5234. *
  5235. * Licensed under the Apache License, Version 2.0 (the "License");
  5236. * you may not use this file except in compliance with the License.
  5237. * You may obtain a copy of the License at
  5238. *
  5239. * http://www.apache.org/licenses/LICENSE-2.0
  5240. *
  5241. * Unless required by applicable law or agreed to in writing, software
  5242. * distributed under the License is distributed on an "AS IS" BASIS,
  5243. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5244. * See the License for the specific language governing permissions and
  5245. * limitations under the License.
  5246. */
  5247. /**
  5248. * Concrete implementation of the Aggregate type.
  5249. */ class ri {
  5250. constructor(t, e, n) {
  5251. this.alias = t, this.yt = e, this.fieldPath = n;
  5252. }
  5253. }
  5254. /**
  5255. * @license
  5256. * Copyright 2017 Google LLC
  5257. *
  5258. * Licensed under the Apache License, Version 2.0 (the "License");
  5259. * you may not use this file except in compliance with the License.
  5260. * You may obtain a copy of the License at
  5261. *
  5262. * http://www.apache.org/licenses/LICENSE-2.0
  5263. *
  5264. * Unless required by applicable law or agreed to in writing, software
  5265. * distributed under the License is distributed on an "AS IS" BASIS,
  5266. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5267. * See the License for the specific language governing permissions and
  5268. * limitations under the License.
  5269. */ class oi {
  5270. constructor(t, e) {
  5271. this.count = t, this.unchangedNames = e;
  5272. }
  5273. }
  5274. /**
  5275. * @license
  5276. * Copyright 2017 Google LLC
  5277. *
  5278. * Licensed under the Apache License, Version 2.0 (the "License");
  5279. * you may not use this file except in compliance with the License.
  5280. * You may obtain a copy of the License at
  5281. *
  5282. * http://www.apache.org/licenses/LICENSE-2.0
  5283. *
  5284. * Unless required by applicable law or agreed to in writing, software
  5285. * distributed under the License is distributed on an "AS IS" BASIS,
  5286. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5287. * See the License for the specific language governing permissions and
  5288. * limitations under the License.
  5289. */
  5290. /**
  5291. * Error Codes describing the different ways GRPC can fail. These are copied
  5292. * directly from GRPC's sources here:
  5293. *
  5294. * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  5295. *
  5296. * Important! The names of these identifiers matter because the string forms
  5297. * are used for reverse lookups from the webchannel stream. Do NOT change the
  5298. * names of these identifiers or change this into a const enum.
  5299. */ var ui, ci;
  5300. /**
  5301. * Determines whether an error code represents a permanent error when received
  5302. * in response to a non-write operation.
  5303. *
  5304. * See isPermanentWriteError for classifying write errors.
  5305. */
  5306. function ai(t) {
  5307. switch (t) {
  5308. default:
  5309. return B();
  5310. case K.CANCELLED:
  5311. case K.UNKNOWN:
  5312. case K.DEADLINE_EXCEEDED:
  5313. case K.RESOURCE_EXHAUSTED:
  5314. case K.INTERNAL:
  5315. case K.UNAVAILABLE:
  5316. // Unauthenticated means something went wrong with our token and we need
  5317. // to retry with new credentials which will happen automatically.
  5318. case K.UNAUTHENTICATED:
  5319. return !1;
  5320. case K.INVALID_ARGUMENT:
  5321. case K.NOT_FOUND:
  5322. case K.ALREADY_EXISTS:
  5323. case K.PERMISSION_DENIED:
  5324. case K.FAILED_PRECONDITION:
  5325. // Aborted might be retried in some scenarios, but that is dependant on
  5326. // the context and should handled individually by the calling code.
  5327. // See https://cloud.google.com/apis/design/errors.
  5328. case K.ABORTED:
  5329. case K.OUT_OF_RANGE:
  5330. case K.UNIMPLEMENTED:
  5331. case K.DATA_LOSS:
  5332. return !0;
  5333. }
  5334. }
  5335. /**
  5336. * Determines whether an error code represents a permanent error when received
  5337. * in response to a write operation.
  5338. *
  5339. * Write operations must be handled specially because as of b/119437764, ABORTED
  5340. * errors on the write stream should be retried too (even though ABORTED errors
  5341. * are not generally retryable).
  5342. *
  5343. * Note that during the initial handshake on the write stream an ABORTED error
  5344. * signals that we should discard our stream token (i.e. it is permanent). This
  5345. * means a handshake error should be classified with isPermanentError, above.
  5346. */
  5347. /**
  5348. * Maps an error Code from GRPC status code number, like 0, 1, or 14. These
  5349. * are not the same as HTTP status codes.
  5350. *
  5351. * @returns The Code equivalent to the given GRPC status code. Fails if there
  5352. * is no match.
  5353. */
  5354. function hi(t) {
  5355. if (void 0 === t)
  5356. // This shouldn't normally happen, but in certain error cases (like trying
  5357. // to send invalid proto messages) we may get an error with no GRPC code.
  5358. return M("GRPC error has no .code"), K.UNKNOWN;
  5359. switch (t) {
  5360. case ui.OK:
  5361. return K.OK;
  5362. case ui.CANCELLED:
  5363. return K.CANCELLED;
  5364. case ui.UNKNOWN:
  5365. return K.UNKNOWN;
  5366. case ui.DEADLINE_EXCEEDED:
  5367. return K.DEADLINE_EXCEEDED;
  5368. case ui.RESOURCE_EXHAUSTED:
  5369. return K.RESOURCE_EXHAUSTED;
  5370. case ui.INTERNAL:
  5371. return K.INTERNAL;
  5372. case ui.UNAVAILABLE:
  5373. return K.UNAVAILABLE;
  5374. case ui.UNAUTHENTICATED:
  5375. return K.UNAUTHENTICATED;
  5376. case ui.INVALID_ARGUMENT:
  5377. return K.INVALID_ARGUMENT;
  5378. case ui.NOT_FOUND:
  5379. return K.NOT_FOUND;
  5380. case ui.ALREADY_EXISTS:
  5381. return K.ALREADY_EXISTS;
  5382. case ui.PERMISSION_DENIED:
  5383. return K.PERMISSION_DENIED;
  5384. case ui.FAILED_PRECONDITION:
  5385. return K.FAILED_PRECONDITION;
  5386. case ui.ABORTED:
  5387. return K.ABORTED;
  5388. case ui.OUT_OF_RANGE:
  5389. return K.OUT_OF_RANGE;
  5390. case ui.UNIMPLEMENTED:
  5391. return K.UNIMPLEMENTED;
  5392. case ui.DATA_LOSS:
  5393. return K.DATA_LOSS;
  5394. default:
  5395. return B();
  5396. }
  5397. }
  5398. /**
  5399. * Converts an HTTP response's error status to the equivalent error code.
  5400. *
  5401. * @param status - An HTTP error response status ("FAILED_PRECONDITION",
  5402. * "UNKNOWN", etc.)
  5403. * @returns The equivalent Code. Non-matching responses are mapped to
  5404. * Code.UNKNOWN.
  5405. */ (ci = ui || (ui = {}))[ci.OK = 0] = "OK", ci[ci.CANCELLED = 1] = "CANCELLED",
  5406. ci[ci.UNKNOWN = 2] = "UNKNOWN", ci[ci.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT",
  5407. ci[ci.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", ci[ci.NOT_FOUND = 5] = "NOT_FOUND",
  5408. ci[ci.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", ci[ci.PERMISSION_DENIED = 7] = "PERMISSION_DENIED",
  5409. ci[ci.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", ci[ci.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED",
  5410. ci[ci.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", ci[ci.ABORTED = 10] = "ABORTED",
  5411. ci[ci.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", ci[ci.UNIMPLEMENTED = 12] = "UNIMPLEMENTED",
  5412. ci[ci.INTERNAL = 13] = "INTERNAL", ci[ci.UNAVAILABLE = 14] = "UNAVAILABLE", ci[ci.DATA_LOSS = 15] = "DATA_LOSS";
  5413. /**
  5414. * @license
  5415. * Copyright 2023 Google LLC
  5416. *
  5417. * Licensed under the Apache License, Version 2.0 (the "License");
  5418. * you may not use this file except in compliance with the License.
  5419. * You may obtain a copy of the License at
  5420. *
  5421. * http://www.apache.org/licenses/LICENSE-2.0
  5422. *
  5423. * Unless required by applicable law or agreed to in writing, software
  5424. * distributed under the License is distributed on an "AS IS" BASIS,
  5425. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5426. * See the License for the specific language governing permissions and
  5427. * limitations under the License.
  5428. */
  5429. /**
  5430. * Manages "testing hooks", hooks into the internals of the SDK to verify
  5431. * internal state and events during integration tests. Do not use this class
  5432. * except for testing purposes.
  5433. *
  5434. * There are two ways to retrieve the global singleton instance of this class:
  5435. * 1. The `instance` property, which returns null if the global singleton
  5436. * instance has not been created. Use this property if the caller should
  5437. * "do nothing" if there are no testing hooks registered, such as when
  5438. * delivering an event to notify registered callbacks.
  5439. * 2. The `getOrCreateInstance()` method, which creates the global singleton
  5440. * instance if it has not been created. Use this method if the instance is
  5441. * needed to, for example, register a callback.
  5442. *
  5443. * @internal
  5444. */
  5445. class li {
  5446. constructor() {
  5447. this.onExistenceFilterMismatchCallbacks = new Map;
  5448. }
  5449. /**
  5450. * Returns the singleton instance of this class, or null if it has not been
  5451. * initialized.
  5452. */ static get instance() {
  5453. return fi;
  5454. }
  5455. /**
  5456. * Returns the singleton instance of this class, creating it if is has never
  5457. * been created before.
  5458. */ static getOrCreateInstance() {
  5459. return null === fi && (fi = new li), fi;
  5460. }
  5461. /**
  5462. * Registers a callback to be notified when an existence filter mismatch
  5463. * occurs in the Watch listen stream.
  5464. *
  5465. * The relative order in which callbacks are notified is unspecified; do not
  5466. * rely on any particular ordering. If a given callback is registered multiple
  5467. * times then it will be notified multiple times, once per registration.
  5468. *
  5469. * @param callback the callback to invoke upon existence filter mismatch.
  5470. *
  5471. * @return a function that, when called, unregisters the given callback; only
  5472. * the first invocation of the returned function does anything; all subsequent
  5473. * invocations do nothing.
  5474. */ onExistenceFilterMismatch(t) {
  5475. const e = Symbol();
  5476. return this.onExistenceFilterMismatchCallbacks.set(e, t), () => this.onExistenceFilterMismatchCallbacks.delete(e);
  5477. }
  5478. /**
  5479. * Invokes all currently-registered `onExistenceFilterMismatch` callbacks.
  5480. * @param info Information about the existence filter mismatch.
  5481. */ notifyOnExistenceFilterMismatch(t) {
  5482. this.onExistenceFilterMismatchCallbacks.forEach((e => e(t)));
  5483. }
  5484. }
  5485. /** The global singleton instance of `TestingHooks`. */ let fi = null;
  5486. /**
  5487. * @license
  5488. * Copyright 2023 Google LLC
  5489. *
  5490. * Licensed under the Apache License, Version 2.0 (the "License");
  5491. * you may not use this file except in compliance with the License.
  5492. * You may obtain a copy of the License at
  5493. *
  5494. * http://www.apache.org/licenses/LICENSE-2.0
  5495. *
  5496. * Unless required by applicable law or agreed to in writing, software
  5497. * distributed under the License is distributed on an "AS IS" BASIS,
  5498. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5499. * See the License for the specific language governing permissions and
  5500. * limitations under the License.
  5501. */
  5502. /**
  5503. * An instance of the Platform's 'TextEncoder' implementation.
  5504. */ function di() {
  5505. return new TextEncoder;
  5506. }
  5507. /**
  5508. * An instance of the Platform's 'TextDecoder' implementation.
  5509. */
  5510. /**
  5511. * @license
  5512. * Copyright 2022 Google LLC
  5513. *
  5514. * Licensed under the Apache License, Version 2.0 (the "License");
  5515. * you may not use this file except in compliance with the License.
  5516. * You may obtain a copy of the License at
  5517. *
  5518. * http://www.apache.org/licenses/LICENSE-2.0
  5519. *
  5520. * Unless required by applicable law or agreed to in writing, software
  5521. * distributed under the License is distributed on an "AS IS" BASIS,
  5522. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5523. * See the License for the specific language governing permissions and
  5524. * limitations under the License.
  5525. */
  5526. const wi = new y([ 4294967295, 4294967295 ], 0);
  5527. // Hash a string using md5 hashing algorithm.
  5528. function _i(t) {
  5529. const e = di().encode(t), n = new p;
  5530. return n.update(e), new Uint8Array(n.digest());
  5531. }
  5532. // Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using
  5533. // 2’s complement using little endian.
  5534. function mi(t) {
  5535. const e = new DataView(t.buffer), n = e.getUint32(0, /* littleEndian= */ !0), s = e.getUint32(4, /* littleEndian= */ !0), i = e.getUint32(8, /* littleEndian= */ !0), r = e.getUint32(12, /* littleEndian= */ !0);
  5536. return [ new y([ n, s ], 0), new y([ i, r ], 0) ];
  5537. }
  5538. class gi {
  5539. constructor(t, e, n) {
  5540. if (this.bitmap = t, this.padding = e, this.hashCount = n, e < 0 || e >= 8) throw new yi(`Invalid padding: ${e}`);
  5541. if (n < 0) throw new yi(`Invalid hash count: ${n}`);
  5542. if (t.length > 0 && 0 === this.hashCount)
  5543. // Only empty bloom filter can have 0 hash count.
  5544. throw new yi(`Invalid hash count: ${n}`);
  5545. if (0 === t.length && 0 !== e)
  5546. // Empty bloom filter should have 0 padding.
  5547. throw new yi(`Invalid padding when bitmap length is 0: ${e}`);
  5548. this.It = 8 * t.length - e,
  5549. // Set the bit count in Integer to avoid repetition in mightContain().
  5550. this.Tt = y.fromNumber(this.It);
  5551. }
  5552. // Calculate the ith hash value based on the hashed 64bit integers,
  5553. // and calculate its corresponding bit index in the bitmap to be checked.
  5554. Et(t, e, n) {
  5555. // Calculate hashed value h(i) = h1 + (i * h2).
  5556. let s = t.add(e.multiply(y.fromNumber(n)));
  5557. // Wrap if hash value overflow 64bit.
  5558. return 1 === s.compare(wi) && (s = new y([ s.getBits(0), s.getBits(1) ], 0)),
  5559. s.modulo(this.Tt).toNumber();
  5560. }
  5561. // Return whether the bit on the given index in the bitmap is set to 1.
  5562. At(t) {
  5563. return 0 != (this.bitmap[Math.floor(t / 8)] & 1 << t % 8);
  5564. }
  5565. vt(t) {
  5566. // Empty bitmap should always return false on membership check.
  5567. if (0 === this.It) return !1;
  5568. const e = _i(t), [n, s] = mi(e);
  5569. for (let t = 0; t < this.hashCount; t++) {
  5570. const e = this.Et(n, s, t);
  5571. if (!this.At(e)) return !1;
  5572. }
  5573. return !0;
  5574. }
  5575. /** Create bloom filter for testing purposes only. */ static create(t, e, n) {
  5576. const s = t % 8 == 0 ? 0 : 8 - t % 8, i = new Uint8Array(Math.ceil(t / 8)), r = new gi(i, s, e);
  5577. return n.forEach((t => r.insert(t))), r;
  5578. }
  5579. insert(t) {
  5580. if (0 === this.It) return;
  5581. const e = _i(t), [n, s] = mi(e);
  5582. for (let t = 0; t < this.hashCount; t++) {
  5583. const e = this.Et(n, s, t);
  5584. this.Rt(e);
  5585. }
  5586. }
  5587. Rt(t) {
  5588. const e = Math.floor(t / 8), n = t % 8;
  5589. this.bitmap[e] |= 1 << n;
  5590. }
  5591. }
  5592. class yi extends Error {
  5593. constructor() {
  5594. super(...arguments), this.name = "BloomFilterError";
  5595. }
  5596. }
  5597. /**
  5598. * @license
  5599. * Copyright 2017 Google LLC
  5600. *
  5601. * Licensed under the Apache License, Version 2.0 (the "License");
  5602. * you may not use this file except in compliance with the License.
  5603. * You may obtain a copy of the License at
  5604. *
  5605. * http://www.apache.org/licenses/LICENSE-2.0
  5606. *
  5607. * Unless required by applicable law or agreed to in writing, software
  5608. * distributed under the License is distributed on an "AS IS" BASIS,
  5609. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5610. * See the License for the specific language governing permissions and
  5611. * limitations under the License.
  5612. */
  5613. /**
  5614. * An event from the RemoteStore. It is split into targetChanges (changes to the
  5615. * state or the set of documents in our watched targets) and documentUpdates
  5616. * (changes to the actual documents).
  5617. */ class pi {
  5618. constructor(
  5619. /**
  5620. * The snapshot version this event brings us up to, or MIN if not set.
  5621. */
  5622. t,
  5623. /**
  5624. * A map from target to changes to the target. See TargetChange.
  5625. */
  5626. e,
  5627. /**
  5628. * A map of targets that is known to be inconsistent, and the purpose for
  5629. * re-listening. Listens for these targets should be re-established without
  5630. * resume tokens.
  5631. */
  5632. n,
  5633. /**
  5634. * A set of which documents have changed or been deleted, along with the
  5635. * doc's new values (if not deleted).
  5636. */
  5637. s,
  5638. /**
  5639. * A set of which document updates are due only to limbo resolution targets.
  5640. */
  5641. i) {
  5642. this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = s,
  5643. this.resolvedLimboDocuments = i;
  5644. }
  5645. /**
  5646. * HACK: Views require RemoteEvents in order to determine whether the view is
  5647. * CURRENT, but secondary tabs don't receive remote events. So this method is
  5648. * used to create a synthesized RemoteEvent that can be used to apply a
  5649. * CURRENT status change to a View, for queries executed in a different tab.
  5650. */
  5651. // PORTING NOTE: Multi-tab only
  5652. static createSynthesizedRemoteEventForCurrentChange(t, e, n) {
  5653. const s = new Map;
  5654. return s.set(t, Ii.createSynthesizedTargetChangeForCurrentChange(t, e, n)), new pi(ut.min(), s, new Te(st), ls(), Is());
  5655. }
  5656. }
  5657. /**
  5658. * A TargetChange specifies the set of changes for a specific target as part of
  5659. * a RemoteEvent. These changes track which documents are added, modified or
  5660. * removed, as well as the target's resume token and whether the target is
  5661. * marked CURRENT.
  5662. * The actual changes *to* documents are not part of the TargetChange since
  5663. * documents may be part of multiple targets.
  5664. */ class Ii {
  5665. constructor(
  5666. /**
  5667. * An opaque, server-assigned token that allows watching a query to be resumed
  5668. * after disconnecting without retransmitting all the data that matches the
  5669. * query. The resume token essentially identifies a point in time from which
  5670. * the server should resume sending results.
  5671. */
  5672. t,
  5673. /**
  5674. * The "current" (synced) status of this target. Note that "current"
  5675. * has special meaning in the RPC protocol that implies that a target is
  5676. * both up-to-date and consistent with the rest of the watch stream.
  5677. */
  5678. e,
  5679. /**
  5680. * The set of documents that were newly assigned to this target as part of
  5681. * this remote event.
  5682. */
  5683. n,
  5684. /**
  5685. * The set of documents that were already assigned to this target but received
  5686. * an update during this remote event.
  5687. */
  5688. s,
  5689. /**
  5690. * The set of documents that were removed from this target as part of this
  5691. * remote event.
  5692. */
  5693. i) {
  5694. this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = s,
  5695. this.removedDocuments = i;
  5696. }
  5697. /**
  5698. * This method is used to create a synthesized TargetChanges that can be used to
  5699. * apply a CURRENT status change to a View (for queries executed in a different
  5700. * tab) or for new queries (to raise snapshots with correct CURRENT status).
  5701. */ static createSynthesizedTargetChangeForCurrentChange(t, e, n) {
  5702. return new Ii(n, e, Is(), Is(), Is());
  5703. }
  5704. }
  5705. /**
  5706. * @license
  5707. * Copyright 2017 Google LLC
  5708. *
  5709. * Licensed under the Apache License, Version 2.0 (the "License");
  5710. * you may not use this file except in compliance with the License.
  5711. * You may obtain a copy of the License at
  5712. *
  5713. * http://www.apache.org/licenses/LICENSE-2.0
  5714. *
  5715. * Unless required by applicable law or agreed to in writing, software
  5716. * distributed under the License is distributed on an "AS IS" BASIS,
  5717. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5718. * See the License for the specific language governing permissions and
  5719. * limitations under the License.
  5720. */
  5721. /**
  5722. * Represents a changed document and a list of target ids to which this change
  5723. * applies.
  5724. *
  5725. * If document has been deleted NoDocument will be provided.
  5726. */ class Ti {
  5727. constructor(
  5728. /** The new document applies to all of these targets. */
  5729. t,
  5730. /** The new document is removed from all of these targets. */
  5731. e,
  5732. /** The key of the document for this change. */
  5733. n,
  5734. /**
  5735. * The new document or NoDocument if it was deleted. Is null if the
  5736. * document went out of view without the server sending a new document.
  5737. */
  5738. s) {
  5739. this.Pt = t, this.removedTargetIds = e, this.key = n, this.bt = s;
  5740. }
  5741. }
  5742. class Ei {
  5743. constructor(t, e) {
  5744. this.targetId = t, this.Vt = e;
  5745. }
  5746. }
  5747. class Ai {
  5748. constructor(
  5749. /** What kind of change occurred to the watch target. */
  5750. t,
  5751. /** The target IDs that were added/removed/set. */
  5752. e,
  5753. /**
  5754. * An opaque, server-assigned token that allows watching a target to be
  5755. * resumed after disconnecting without retransmitting all the data that
  5756. * matches the target. The resume token essentially identifies a point in
  5757. * time from which the server should resume sending results.
  5758. */
  5759. n = Ce.EMPTY_BYTE_STRING
  5760. /** An RPC error indicating why the watch failed. */ , s = null) {
  5761. this.state = t, this.targetIds = e, this.resumeToken = n, this.cause = s;
  5762. }
  5763. }
  5764. /** Tracks the internal state of a Watch target. */ class vi {
  5765. constructor() {
  5766. /**
  5767. * The number of pending responses (adds or removes) that we are waiting on.
  5768. * We only consider targets active that have no pending responses.
  5769. */
  5770. this.St = 0,
  5771. /**
  5772. * Keeps track of the document changes since the last raised snapshot.
  5773. *
  5774. * These changes are continuously updated as we receive document updates and
  5775. * always reflect the current set of changes against the last issued snapshot.
  5776. */
  5777. this.Dt = bi(),
  5778. /** See public getters for explanations of these fields. */
  5779. this.Ct = Ce.EMPTY_BYTE_STRING, this.xt = !1,
  5780. /**
  5781. * Whether this target state should be included in the next snapshot. We
  5782. * initialize to true so that newly-added targets are included in the next
  5783. * RemoteEvent.
  5784. */
  5785. this.Nt = !0;
  5786. }
  5787. /**
  5788. * Whether this target has been marked 'current'.
  5789. *
  5790. * 'Current' has special meaning in the RPC protocol: It implies that the
  5791. * Watch backend has sent us all changes up to the point at which the target
  5792. * was added and that the target is consistent with the rest of the watch
  5793. * stream.
  5794. */ get current() {
  5795. return this.xt;
  5796. }
  5797. /** The last resume token sent to us for this target. */ get resumeToken() {
  5798. return this.Ct;
  5799. }
  5800. /** Whether this target has pending target adds or target removes. */ get kt() {
  5801. return 0 !== this.St;
  5802. }
  5803. /** Whether we have modified any state that should trigger a snapshot. */ get $t() {
  5804. return this.Nt;
  5805. }
  5806. /**
  5807. * Applies the resume token to the TargetChange, but only when it has a new
  5808. * value. Empty resumeTokens are discarded.
  5809. */ Mt(t) {
  5810. t.approximateByteSize() > 0 && (this.Nt = !0, this.Ct = t);
  5811. }
  5812. /**
  5813. * Creates a target change from the current set of changes.
  5814. *
  5815. * To reset the document changes after raising this snapshot, call
  5816. * `clearPendingChanges()`.
  5817. */ Ot() {
  5818. let t = Is(), e = Is(), n = Is();
  5819. return this.Dt.forEach(((s, i) => {
  5820. switch (i) {
  5821. case 0 /* ChangeType.Added */ :
  5822. t = t.add(s);
  5823. break;
  5824. case 2 /* ChangeType.Modified */ :
  5825. e = e.add(s);
  5826. break;
  5827. case 1 /* ChangeType.Removed */ :
  5828. n = n.add(s);
  5829. break;
  5830. default:
  5831. B();
  5832. }
  5833. })), new Ii(this.Ct, this.xt, t, e, n);
  5834. }
  5835. /**
  5836. * Resets the document changes and sets `hasPendingChanges` to false.
  5837. */ Ft() {
  5838. this.Nt = !1, this.Dt = bi();
  5839. }
  5840. Bt(t, e) {
  5841. this.Nt = !0, this.Dt = this.Dt.insert(t, e);
  5842. }
  5843. Lt(t) {
  5844. this.Nt = !0, this.Dt = this.Dt.remove(t);
  5845. }
  5846. qt() {
  5847. this.St += 1;
  5848. }
  5849. Ut() {
  5850. this.St -= 1;
  5851. }
  5852. Kt() {
  5853. this.Nt = !0, this.xt = !0;
  5854. }
  5855. }
  5856. /**
  5857. * A helper class to accumulate watch changes into a RemoteEvent.
  5858. */
  5859. class Ri {
  5860. constructor(t) {
  5861. this.Gt = t,
  5862. /** The internal state of all tracked targets. */
  5863. this.Qt = new Map,
  5864. /** Keeps track of the documents to update since the last raised snapshot. */
  5865. this.jt = ls(),
  5866. /** A mapping of document keys to their set of target IDs. */
  5867. this.zt = Pi(),
  5868. /**
  5869. * A map of targets with existence filter mismatches. These targets are
  5870. * known to be inconsistent and their listens needs to be re-established by
  5871. * RemoteStore.
  5872. */
  5873. this.Wt = new Te(st);
  5874. }
  5875. /**
  5876. * Processes and adds the DocumentWatchChange to the current set of changes.
  5877. */ Ht(t) {
  5878. for (const e of t.Pt) t.bt && t.bt.isFoundDocument() ? this.Jt(e, t.bt) : this.Yt(e, t.key, t.bt);
  5879. for (const e of t.removedTargetIds) this.Yt(e, t.key, t.bt);
  5880. }
  5881. /** Processes and adds the WatchTargetChange to the current set of changes. */ Xt(t) {
  5882. this.forEachTarget(t, (e => {
  5883. const n = this.Zt(e);
  5884. switch (t.state) {
  5885. case 0 /* WatchTargetChangeState.NoChange */ :
  5886. this.te(e) && n.Mt(t.resumeToken);
  5887. break;
  5888. case 1 /* WatchTargetChangeState.Added */ :
  5889. // We need to decrement the number of pending acks needed from watch
  5890. // for this targetId.
  5891. n.Ut(), n.kt ||
  5892. // We have a freshly added target, so we need to reset any state
  5893. // that we had previously. This can happen e.g. when remove and add
  5894. // back a target for existence filter mismatches.
  5895. n.Ft(), n.Mt(t.resumeToken);
  5896. break;
  5897. case 2 /* WatchTargetChangeState.Removed */ :
  5898. // We need to keep track of removed targets to we can post-filter and
  5899. // remove any target changes.
  5900. // We need to decrement the number of pending acks needed from watch
  5901. // for this targetId.
  5902. n.Ut(), n.kt || this.removeTarget(e);
  5903. break;
  5904. case 3 /* WatchTargetChangeState.Current */ :
  5905. this.te(e) && (n.Kt(), n.Mt(t.resumeToken));
  5906. break;
  5907. case 4 /* WatchTargetChangeState.Reset */ :
  5908. this.te(e) && (
  5909. // Reset the target and synthesizes removes for all existing
  5910. // documents. The backend will re-add any documents that still
  5911. // match the target before it sends the next global snapshot.
  5912. this.ee(e), n.Mt(t.resumeToken));
  5913. break;
  5914. default:
  5915. B();
  5916. }
  5917. }));
  5918. }
  5919. /**
  5920. * Iterates over all targetIds that the watch change applies to: either the
  5921. * targetIds explicitly listed in the change or the targetIds of all currently
  5922. * active targets.
  5923. */ forEachTarget(t, e) {
  5924. t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Qt.forEach(((t, n) => {
  5925. this.te(n) && e(n);
  5926. }));
  5927. }
  5928. /**
  5929. * Handles existence filters and synthesizes deletes for filter mismatches.
  5930. * Targets that are invalidated by filter mismatches are added to
  5931. * `pendingTargetResets`.
  5932. */ ne(t) {
  5933. var e;
  5934. const n = t.targetId, s = t.Vt.count, i = this.se(n);
  5935. if (i) {
  5936. const r = i.target;
  5937. if (qn(r)) if (0 === s) {
  5938. // The existence filter told us the document does not exist. We deduce
  5939. // that this document does not exist and apply a deleted document to
  5940. // our updates. Without applying this deleted document there might be
  5941. // another query that will raise this document as part of a snapshot
  5942. // until it is resolved, essentially exposing inconsistency between
  5943. // queries.
  5944. const t = new ft(r.path);
  5945. this.Yt(n, t, fn.newNoDocument(t, ut.min()));
  5946. } else L(1 === s); else {
  5947. const i = this.ie(n);
  5948. // Existence filter mismatch. Mark the documents as being in limbo, and
  5949. // raise a snapshot with `isFromCache:true`.
  5950. if (i !== s) {
  5951. // Apply bloom filter to identify and mark removed documents.
  5952. const s = this.re(t, i);
  5953. if (0 /* BloomFilterApplicationStatus.Success */ !== s) {
  5954. // If bloom filter application fails, we reset the mapping and
  5955. // trigger re-run of the query.
  5956. this.ee(n);
  5957. const t = 2 /* BloomFilterApplicationStatus.FalsePositive */ === s ? "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ : "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */;
  5958. this.Wt = this.Wt.insert(n, t);
  5959. }
  5960. null === (e = li.instance) || void 0 === e || e.notifyOnExistenceFilterMismatch(function(t, e, n) {
  5961. var s, i, r, o, u, c;
  5962. const a = {
  5963. localCacheCount: e,
  5964. existenceFilterCount: n.count
  5965. }, h = n.unchangedNames;
  5966. h && (a.bloomFilter = {
  5967. applied: 0 /* BloomFilterApplicationStatus.Success */ === t,
  5968. hashCount: null !== (s = null == h ? void 0 : h.hashCount) && void 0 !== s ? s : 0,
  5969. bitmapLength: null !== (o = null === (r = null === (i = null == h ? void 0 : h.bits) || void 0 === i ? void 0 : i.bitmap) || void 0 === r ? void 0 : r.length) && void 0 !== o ? o : 0,
  5970. padding: null !== (c = null === (u = null == h ? void 0 : h.bits) || void 0 === u ? void 0 : u.padding) && void 0 !== c ? c : 0
  5971. });
  5972. return a;
  5973. }
  5974. /**
  5975. * @license
  5976. * Copyright 2017 Google LLC
  5977. *
  5978. * Licensed under the Apache License, Version 2.0 (the "License");
  5979. * you may not use this file except in compliance with the License.
  5980. * You may obtain a copy of the License at
  5981. *
  5982. * http://www.apache.org/licenses/LICENSE-2.0
  5983. *
  5984. * Unless required by applicable law or agreed to in writing, software
  5985. * distributed under the License is distributed on an "AS IS" BASIS,
  5986. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5987. * See the License for the specific language governing permissions and
  5988. * limitations under the License.
  5989. */ (s, i, t.Vt));
  5990. }
  5991. }
  5992. }
  5993. }
  5994. /**
  5995. * Apply bloom filter to remove the deleted documents, and return the
  5996. * application status.
  5997. */ re(t, e) {
  5998. const {unchangedNames: n, count: s} = t.Vt;
  5999. if (!n || !n.bits) return 1 /* BloomFilterApplicationStatus.Skipped */;
  6000. const {bits: {bitmap: i = "", padding: r = 0}, hashCount: o = 0} = n;
  6001. let u, c;
  6002. try {
  6003. u = $e(i).toUint8Array();
  6004. } catch (t) {
  6005. if (t instanceof Ve) return O("Decoding the base64 bloom filter in existence filter failed (" + t.message + "); ignoring the bloom filter and falling back to full re-query."),
  6006. 1 /* BloomFilterApplicationStatus.Skipped */;
  6007. throw t;
  6008. }
  6009. try {
  6010. // BloomFilter throws error if the inputs are invalid.
  6011. c = new gi(u, r, o);
  6012. } catch (t) {
  6013. return O(t instanceof yi ? "BloomFilter error: " : "Applying bloom filter failed: ", t),
  6014. 1 /* BloomFilterApplicationStatus.Skipped */;
  6015. }
  6016. if (0 === c.It) return 1 /* BloomFilterApplicationStatus.Skipped */;
  6017. return s !== e - this.oe(t.targetId, c) ? 2 /* BloomFilterApplicationStatus.FalsePositive */ : 0 /* BloomFilterApplicationStatus.Success */;
  6018. }
  6019. /**
  6020. * Filter out removed documents based on bloom filter membership result and
  6021. * return number of documents removed.
  6022. */ oe(t, e) {
  6023. const n = this.Gt.getRemoteKeysForTarget(t);
  6024. let s = 0;
  6025. return n.forEach((n => {
  6026. const i = this.Gt.ue(), r = `projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;
  6027. e.vt(r) || (this.Yt(t, n, /*updatedDocument=*/ null), s++);
  6028. })), s;
  6029. }
  6030. /**
  6031. * Converts the currently accumulated state into a remote event at the
  6032. * provided snapshot version. Resets the accumulated changes before returning.
  6033. */ ce(t) {
  6034. const e = new Map;
  6035. this.Qt.forEach(((n, s) => {
  6036. const i = this.se(s);
  6037. if (i) {
  6038. if (n.current && qn(i.target)) {
  6039. // Document queries for document that don't exist can produce an empty
  6040. // result set. To update our local cache, we synthesize a document
  6041. // delete if we have not previously received the document. This
  6042. // resolves the limbo state of the document, removing it from
  6043. // limboDocumentRefs.
  6044. // TODO(dimond): Ideally we would have an explicit lookup target
  6045. // instead resulting in an explicit delete message and we could
  6046. // remove this special logic.
  6047. const e = new ft(i.target.path);
  6048. null !== this.jt.get(e) || this.ae(s, e) || this.Yt(s, e, fn.newNoDocument(e, t));
  6049. }
  6050. n.$t && (e.set(s, n.Ot()), n.Ft());
  6051. }
  6052. }));
  6053. let n = Is();
  6054. // We extract the set of limbo-only document updates as the GC logic
  6055. // special-cases documents that do not appear in the target cache.
  6056. // TODO(gsoltis): Expand on this comment once GC is available in the JS
  6057. // client.
  6058. this.zt.forEach(((t, e) => {
  6059. let s = !0;
  6060. e.forEachWhile((t => {
  6061. const e = this.se(t);
  6062. return !e || "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ === e.purpose || (s = !1,
  6063. !1);
  6064. })), s && (n = n.add(t));
  6065. })), this.jt.forEach(((e, n) => n.setReadTime(t)));
  6066. const s = new pi(t, e, this.Wt, this.jt, n);
  6067. return this.jt = ls(), this.zt = Pi(), this.Wt = new Te(st), s;
  6068. }
  6069. /**
  6070. * Adds the provided document to the internal list of document updates and
  6071. * its document key to the given target's mapping.
  6072. */
  6073. // Visible for testing.
  6074. Jt(t, e) {
  6075. if (!this.te(t)) return;
  6076. const n = this.ae(t, e.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;
  6077. 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));
  6078. }
  6079. /**
  6080. * Removes the provided document from the target mapping. If the
  6081. * document no longer matches the target, but the document's state is still
  6082. * known (e.g. we know that the document was deleted or we received the change
  6083. * that caused the filter mismatch), the new document can be provided
  6084. * to update the remote document cache.
  6085. */
  6086. // Visible for testing.
  6087. Yt(t, e, n) {
  6088. if (!this.te(t)) return;
  6089. const s = this.Zt(t);
  6090. this.ae(t, e) ? s.Bt(e, 1 /* ChangeType.Removed */) :
  6091. // The document may have entered and left the target before we raised a
  6092. // snapshot, so we can just ignore the change.
  6093. s.Lt(e), this.zt = this.zt.insert(e, this.he(e).delete(t)), n && (this.jt = this.jt.insert(e, n));
  6094. }
  6095. removeTarget(t) {
  6096. this.Qt.delete(t);
  6097. }
  6098. /**
  6099. * Returns the current count of documents in the target. This includes both
  6100. * the number of documents that the LocalStore considers to be part of the
  6101. * target as well as any accumulated changes.
  6102. */ ie(t) {
  6103. const e = this.Zt(t).Ot();
  6104. return this.Gt.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;
  6105. }
  6106. /**
  6107. * Increment the number of acks needed from watch before we can consider the
  6108. * server to be 'in-sync' with the client's active targets.
  6109. */ qt(t) {
  6110. this.Zt(t).qt();
  6111. }
  6112. Zt(t) {
  6113. let e = this.Qt.get(t);
  6114. return e || (e = new vi, this.Qt.set(t, e)), e;
  6115. }
  6116. he(t) {
  6117. let e = this.zt.get(t);
  6118. return e || (e = new ve(st), this.zt = this.zt.insert(t, e)), e;
  6119. }
  6120. /**
  6121. * Verifies that the user is still interested in this target (by calling
  6122. * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
  6123. * from watch.
  6124. */ te(t) {
  6125. const e = null !== this.se(t);
  6126. return e || $("WatchChangeAggregator", "Detected inactive target", t), e;
  6127. }
  6128. /**
  6129. * Returns the TargetData for an active target (i.e. a target that the user
  6130. * is still interested in that has no outstanding target change requests).
  6131. */ se(t) {
  6132. const e = this.Qt.get(t);
  6133. return e && e.kt ? null : this.Gt.le(t);
  6134. }
  6135. /**
  6136. * Resets the state of a Watch target to its initial state (e.g. sets
  6137. * 'current' to false, clears the resume token and removes its target mapping
  6138. * from all documents).
  6139. */ ee(t) {
  6140. this.Qt.set(t, new vi);
  6141. this.Gt.getRemoteKeysForTarget(t).forEach((e => {
  6142. this.Yt(t, e, /*updatedDocument=*/ null);
  6143. }));
  6144. }
  6145. /**
  6146. * Returns whether the LocalStore considers the document to be part of the
  6147. * specified target.
  6148. */ ae(t, e) {
  6149. return this.Gt.getRemoteKeysForTarget(t).has(e);
  6150. }
  6151. }
  6152. function Pi() {
  6153. return new Te(ft.comparator);
  6154. }
  6155. function bi() {
  6156. return new Te(ft.comparator);
  6157. }
  6158. const Vi = (() => {
  6159. const t = {
  6160. asc: "ASCENDING",
  6161. desc: "DESCENDING"
  6162. };
  6163. return t;
  6164. })(), Si = (() => {
  6165. const t = {
  6166. "<": "LESS_THAN",
  6167. "<=": "LESS_THAN_OR_EQUAL",
  6168. ">": "GREATER_THAN",
  6169. ">=": "GREATER_THAN_OR_EQUAL",
  6170. "==": "EQUAL",
  6171. "!=": "NOT_EQUAL",
  6172. "array-contains": "ARRAY_CONTAINS",
  6173. in: "IN",
  6174. "not-in": "NOT_IN",
  6175. "array-contains-any": "ARRAY_CONTAINS_ANY"
  6176. };
  6177. return t;
  6178. })(), Di = (() => {
  6179. const t = {
  6180. and: "AND",
  6181. or: "OR"
  6182. };
  6183. return t;
  6184. })();
  6185. /**
  6186. * This class generates JsonObject values for the Datastore API suitable for
  6187. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  6188. *
  6189. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  6190. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  6191. * format.
  6192. *
  6193. * For a description of the Proto3 JSON format check
  6194. * https://developers.google.com/protocol-buffers/docs/proto3#json
  6195. *
  6196. * TODO(klimt): We can remove the databaseId argument if we keep the full
  6197. * resource name in documents.
  6198. */
  6199. class Ci {
  6200. constructor(t, e) {
  6201. this.databaseId = t, this.useProto3Json = e;
  6202. }
  6203. }
  6204. /**
  6205. * Returns a value for a number (or null) that's appropriate to put into
  6206. * a google.protobuf.Int32Value proto.
  6207. * DO NOT USE THIS FOR ANYTHING ELSE.
  6208. * This method cheats. It's typed as returning "number" because that's what
  6209. * our generated proto interfaces say Int32Value must be. But GRPC actually
  6210. * expects a { value: <number> } struct.
  6211. */
  6212. function xi(t, e) {
  6213. return t.useProto3Json || Lt(e) ? e : {
  6214. value: e
  6215. };
  6216. }
  6217. /**
  6218. * Returns a number (or null) from a google.protobuf.Int32Value proto.
  6219. */
  6220. /**
  6221. * Returns a value for a Date that's appropriate to put into a proto.
  6222. */
  6223. function Ni(t, e) {
  6224. if (t.useProto3Json) {
  6225. return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`;
  6226. }
  6227. return {
  6228. seconds: "" + e.seconds,
  6229. nanos: e.nanoseconds
  6230. };
  6231. }
  6232. /**
  6233. * Returns a value for bytes that's appropriate to put in a proto.
  6234. *
  6235. * Visible for testing.
  6236. */
  6237. function ki(t, e) {
  6238. return t.useProto3Json ? e.toBase64() : e.toUint8Array();
  6239. }
  6240. /**
  6241. * Returns a ByteString based on the proto string value.
  6242. */ function $i(t, e) {
  6243. return Ni(t, e.toTimestamp());
  6244. }
  6245. function Mi(t) {
  6246. return L(!!t), ut.fromTimestamp(function(t) {
  6247. const e = Ne(t);
  6248. return new ot(e.seconds, e.nanos);
  6249. }(t));
  6250. }
  6251. function Oi(t, e) {
  6252. return function(t) {
  6253. return new at([ "projects", t.projectId, "databases", t.database ]);
  6254. }(t).child("documents").child(e).canonicalString();
  6255. }
  6256. function Fi(t) {
  6257. const e = at.fromString(t);
  6258. return L(hr(e)), e;
  6259. }
  6260. function Bi(t, e) {
  6261. return Oi(t.databaseId, e.path);
  6262. }
  6263. function Li(t, e) {
  6264. const n = Fi(e);
  6265. if (n.get(1) !== t.databaseId.projectId) throw new G(K.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.databaseId.projectId);
  6266. if (n.get(3) !== t.databaseId.database) throw new G(K.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.databaseId.database);
  6267. return new ft(Gi(n));
  6268. }
  6269. function qi(t, e) {
  6270. return Oi(t.databaseId, e);
  6271. }
  6272. function Ui(t) {
  6273. const e = Fi(t);
  6274. // In v1beta1 queries for collections at the root did not have a trailing
  6275. // "/documents". In v1 all resource paths contain "/documents". Preserve the
  6276. // ability to read the v1beta1 form for compatibility with queries persisted
  6277. // in the local target cache.
  6278. return 4 === e.length ? at.emptyPath() : Gi(e);
  6279. }
  6280. function Ki(t) {
  6281. return new at([ "projects", t.databaseId.projectId, "databases", t.databaseId.database ]).canonicalString();
  6282. }
  6283. function Gi(t) {
  6284. return L(t.length > 4 && "documents" === t.get(4)), t.popFirst(5);
  6285. }
  6286. /** Creates a Document proto from key and fields (but no create/update time) */ function Qi(t, e, n) {
  6287. return {
  6288. name: Bi(t, e),
  6289. fields: n.value.mapValue.fields
  6290. };
  6291. }
  6292. function ji(t, e, n) {
  6293. const s = Li(t, e.name), i = Mi(e.updateTime), r = e.createTime ? Mi(e.createTime) : ut.min(), o = new hn({
  6294. mapValue: {
  6295. fields: e.fields
  6296. }
  6297. }), u = fn.newFoundDocument(s, i, r, o);
  6298. return n && u.setHasCommittedMutations(), n ? u.setHasCommittedMutations() : u;
  6299. }
  6300. function zi(t, e) {
  6301. return "found" in e ? function(t, e) {
  6302. L(!!e.found), e.found.name, e.found.updateTime;
  6303. const n = Li(t, e.found.name), s = Mi(e.found.updateTime), i = e.found.createTime ? Mi(e.found.createTime) : ut.min(), r = new hn({
  6304. mapValue: {
  6305. fields: e.found.fields
  6306. }
  6307. });
  6308. return fn.newFoundDocument(n, s, i, r);
  6309. }(t, e) : "missing" in e ? function(t, e) {
  6310. L(!!e.missing), L(!!e.readTime);
  6311. const n = Li(t, e.missing), s = Mi(e.readTime);
  6312. return fn.newNoDocument(n, s);
  6313. }(t, e) : B();
  6314. }
  6315. function Wi(t, e) {
  6316. let n;
  6317. if ("targetChange" in e) {
  6318. e.targetChange;
  6319. // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
  6320. // if unset
  6321. const s = function(t) {
  6322. 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 */ : B();
  6323. }(e.targetChange.targetChangeType || "NO_CHANGE"), i = e.targetChange.targetIds || [], r = function(t, e) {
  6324. return t.useProto3Json ? (L(void 0 === e || "string" == typeof e), Ce.fromBase64String(e || "")) : (L(void 0 === e || e instanceof Uint8Array),
  6325. Ce.fromUint8Array(e || new Uint8Array));
  6326. }(t, e.targetChange.resumeToken), o = e.targetChange.cause, u = o && function(t) {
  6327. const e = void 0 === t.code ? K.UNKNOWN : hi(t.code);
  6328. return new G(e, t.message || "");
  6329. }(o);
  6330. n = new Ai(s, i, r, u || null);
  6331. } else if ("documentChange" in e) {
  6332. e.documentChange;
  6333. const s = e.documentChange;
  6334. s.document, s.document.name, s.document.updateTime;
  6335. const i = Li(t, s.document.name), r = Mi(s.document.updateTime), o = s.document.createTime ? Mi(s.document.createTime) : ut.min(), u = new hn({
  6336. mapValue: {
  6337. fields: s.document.fields
  6338. }
  6339. }), c = fn.newFoundDocument(i, r, o, u), a = s.targetIds || [], h = s.removedTargetIds || [];
  6340. n = new Ti(a, h, c.key, c);
  6341. } else if ("documentDelete" in e) {
  6342. e.documentDelete;
  6343. const s = e.documentDelete;
  6344. s.document;
  6345. const i = Li(t, s.document), r = s.readTime ? Mi(s.readTime) : ut.min(), o = fn.newNoDocument(i, r), u = s.removedTargetIds || [];
  6346. n = new Ti([], u, o.key, o);
  6347. } else if ("documentRemove" in e) {
  6348. e.documentRemove;
  6349. const s = e.documentRemove;
  6350. s.document;
  6351. const i = Li(t, s.document), r = s.removedTargetIds || [];
  6352. n = new Ti([], r, i, null);
  6353. } else {
  6354. if (!("filter" in e)) return B();
  6355. {
  6356. e.filter;
  6357. const t = e.filter;
  6358. t.targetId;
  6359. const {count: s = 0, unchangedNames: i} = t, r = new oi(s, i), o = t.targetId;
  6360. n = new Ei(o, r);
  6361. }
  6362. }
  6363. return n;
  6364. }
  6365. function Hi(t, e) {
  6366. let n;
  6367. if (e instanceof Hs) n = {
  6368. update: Qi(t, e.key, e.value)
  6369. }; else if (e instanceof ti) n = {
  6370. delete: Bi(t, e.key)
  6371. }; else if (e instanceof Js) n = {
  6372. update: Qi(t, e.key, e.data),
  6373. updateMask: ar(e.fieldMask)
  6374. }; else {
  6375. if (!(e instanceof ei)) return B();
  6376. n = {
  6377. verify: Bi(t, e.key)
  6378. };
  6379. }
  6380. return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {
  6381. const n = e.transform;
  6382. if (n instanceof Ds) return {
  6383. fieldPath: e.field.canonicalString(),
  6384. setToServerValue: "REQUEST_TIME"
  6385. };
  6386. if (n instanceof Cs) return {
  6387. fieldPath: e.field.canonicalString(),
  6388. appendMissingElements: {
  6389. values: n.elements
  6390. }
  6391. };
  6392. if (n instanceof Ns) return {
  6393. fieldPath: e.field.canonicalString(),
  6394. removeAllFromArray: {
  6395. values: n.elements
  6396. }
  6397. };
  6398. if (n instanceof $s) return {
  6399. fieldPath: e.field.canonicalString(),
  6400. increment: n.gt
  6401. };
  6402. throw B();
  6403. }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) {
  6404. return void 0 !== e.updateTime ? {
  6405. updateTime: $i(t, e.updateTime)
  6406. } : void 0 !== e.exists ? {
  6407. exists: e.exists
  6408. } : B();
  6409. }(t, e.precondition)), n;
  6410. }
  6411. function Ji(t, e) {
  6412. const n = e.currentDocument ? function(t) {
  6413. return void 0 !== t.updateTime ? qs.updateTime(Mi(t.updateTime)) : void 0 !== t.exists ? qs.exists(t.exists) : qs.none();
  6414. }(e.currentDocument) : qs.none(), s = e.updateTransforms ? e.updateTransforms.map((e => function(t, e) {
  6415. let n = null;
  6416. if ("setToServerValue" in e) L("REQUEST_TIME" === e.setToServerValue), n = new Ds; else if ("appendMissingElements" in e) {
  6417. const t = e.appendMissingElements.values || [];
  6418. n = new Cs(t);
  6419. } else if ("removeAllFromArray" in e) {
  6420. const t = e.removeAllFromArray.values || [];
  6421. n = new Ns(t);
  6422. } else "increment" in e ? n = new $s(t, e.increment) : B();
  6423. const s = lt.fromServerFormat(e.fieldPath);
  6424. return new Fs(s, n);
  6425. }(t, e))) : [];
  6426. if (e.update) {
  6427. e.update.name;
  6428. const i = Li(t, e.update.name), r = new hn({
  6429. mapValue: {
  6430. fields: e.update.fields
  6431. }
  6432. });
  6433. if (e.updateMask) {
  6434. const t = function(t) {
  6435. const e = t.fieldPaths || [];
  6436. return new be(e.map((t => lt.fromServerFormat(t))));
  6437. }(e.updateMask);
  6438. return new Js(i, r, t, n, s);
  6439. }
  6440. return new Hs(i, r, n, s);
  6441. }
  6442. if (e.delete) {
  6443. const s = Li(t, e.delete);
  6444. return new ti(s, n);
  6445. }
  6446. if (e.verify) {
  6447. const s = Li(t, e.verify);
  6448. return new ei(s, n);
  6449. }
  6450. return B();
  6451. }
  6452. function Yi(t, e) {
  6453. return t && t.length > 0 ? (L(void 0 !== e), t.map((t => function(t, e) {
  6454. // NOTE: Deletes don't have an updateTime.
  6455. let n = t.updateTime ? Mi(t.updateTime) : Mi(e);
  6456. return n.isEqual(ut.min()) && (
  6457. // The Firestore Emulator currently returns an update time of 0 for
  6458. // deletes of non-existing documents (rather than null). This breaks the
  6459. // test "get deleted doc while offline with source=cache" as NoDocuments
  6460. // with version 0 are filtered by IndexedDb's RemoteDocumentCache.
  6461. // TODO(#2149): Remove this when Emulator is fixed
  6462. n = Mi(e)), new Ls(n, t.transformResults || []);
  6463. }(t, e)))) : [];
  6464. }
  6465. function Xi(t, e) {
  6466. return {
  6467. documents: [ qi(t, e.path) ]
  6468. };
  6469. }
  6470. function Zi(t, e) {
  6471. // Dissect the path into parent, collectionId, and optional key filter.
  6472. const n = {
  6473. structuredQuery: {}
  6474. }, s = e.path;
  6475. null !== e.collectionGroup ? (n.parent = qi(t, s), n.structuredQuery.from = [ {
  6476. collectionId: e.collectionGroup,
  6477. allDescendants: !0
  6478. } ]) : (n.parent = qi(t, s.popLast()), n.structuredQuery.from = [ {
  6479. collectionId: s.lastSegment()
  6480. } ]);
  6481. const i = function(t) {
  6482. if (0 === t.length) return;
  6483. return cr(In.create(t, "and" /* CompositeOperator.AND */));
  6484. }(e.filters);
  6485. i && (n.structuredQuery.where = i);
  6486. const r = function(t) {
  6487. if (0 === t.length) return;
  6488. return t.map((t =>
  6489. // visible for testing
  6490. function(t) {
  6491. return {
  6492. field: or(t.field),
  6493. direction: sr(t.dir)
  6494. };
  6495. }(t)));
  6496. }(e.orderBy);
  6497. r && (n.structuredQuery.orderBy = r);
  6498. const o = xi(t, e.limit);
  6499. var u;
  6500. return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = {
  6501. before: (u = e.startAt).inclusive,
  6502. values: u.position
  6503. }), e.endAt && (n.structuredQuery.endAt = function(t) {
  6504. return {
  6505. before: !t.inclusive,
  6506. values: t.position
  6507. };
  6508. }(e.endAt)), n;
  6509. }
  6510. function tr(t) {
  6511. let e = Ui(t.parent);
  6512. const n = t.structuredQuery, s = n.from ? n.from.length : 0;
  6513. let i = null;
  6514. if (s > 0) {
  6515. L(1 === s);
  6516. const t = n.from[0];
  6517. t.allDescendants ? i = t.collectionId : e = e.child(t.collectionId);
  6518. }
  6519. let r = [];
  6520. n.where && (r = function(t) {
  6521. const e = nr(t);
  6522. if (e instanceof In && An(e)) return e.getFilters();
  6523. return [ e ];
  6524. }(n.where));
  6525. let o = [];
  6526. n.orderBy && (o = n.orderBy.map((t => function(t) {
  6527. return new mn(ur(t.field),
  6528. // visible for testing
  6529. function(t) {
  6530. switch (t) {
  6531. case "ASCENDING":
  6532. return "asc" /* Direction.ASCENDING */;
  6533. case "DESCENDING":
  6534. return "desc" /* Direction.DESCENDING */;
  6535. default:
  6536. return;
  6537. }
  6538. }
  6539. // visible for testing
  6540. (t.direction));
  6541. }
  6542. // visible for testing
  6543. (t))));
  6544. let u = null;
  6545. n.limit && (u = function(t) {
  6546. let e;
  6547. return e = "object" == typeof t ? t.value : t, Lt(e) ? null : e;
  6548. }(n.limit));
  6549. let c = null;
  6550. n.startAt && (c = function(t) {
  6551. const e = !!t.before, n = t.values || [];
  6552. return new dn(n, e);
  6553. }(n.startAt));
  6554. let a = null;
  6555. return n.endAt && (a = function(t) {
  6556. const e = !t.before, n = t.values || [];
  6557. return new dn(n, e);
  6558. }
  6559. // visible for testing
  6560. (n.endAt)), jn(e, i, o, r, u, "F" /* LimitType.First */ , c, a);
  6561. }
  6562. function er(t, e) {
  6563. const n = function(t) {
  6564. switch (t) {
  6565. case "TargetPurposeListen" /* TargetPurpose.Listen */ :
  6566. return null;
  6567. case "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */ :
  6568. return "existence-filter-mismatch";
  6569. case "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ :
  6570. return "existence-filter-mismatch-bloom";
  6571. case "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ :
  6572. return "limbo-document";
  6573. default:
  6574. return B();
  6575. }
  6576. }(e.purpose);
  6577. return null == n ? null : {
  6578. "goog-listen-tags": n
  6579. };
  6580. }
  6581. function nr(t) {
  6582. return void 0 !== t.unaryFilter ? function(t) {
  6583. switch (t.unaryFilter.op) {
  6584. case "IS_NAN":
  6585. const e = ur(t.unaryFilter.field);
  6586. return pn.create(e, "==" /* Operator.EQUAL */ , {
  6587. doubleValue: NaN
  6588. });
  6589. case "IS_NULL":
  6590. const n = ur(t.unaryFilter.field);
  6591. return pn.create(n, "==" /* Operator.EQUAL */ , {
  6592. nullValue: "NULL_VALUE"
  6593. });
  6594. case "IS_NOT_NAN":
  6595. const s = ur(t.unaryFilter.field);
  6596. return pn.create(s, "!=" /* Operator.NOT_EQUAL */ , {
  6597. doubleValue: NaN
  6598. });
  6599. case "IS_NOT_NULL":
  6600. const i = ur(t.unaryFilter.field);
  6601. return pn.create(i, "!=" /* Operator.NOT_EQUAL */ , {
  6602. nullValue: "NULL_VALUE"
  6603. });
  6604. default:
  6605. return B();
  6606. }
  6607. }(t) : void 0 !== t.fieldFilter ? function(t) {
  6608. return pn.create(ur(t.fieldFilter.field), function(t) {
  6609. switch (t) {
  6610. case "EQUAL":
  6611. return "==" /* Operator.EQUAL */;
  6612. case "NOT_EQUAL":
  6613. return "!=" /* Operator.NOT_EQUAL */;
  6614. case "GREATER_THAN":
  6615. return ">" /* Operator.GREATER_THAN */;
  6616. case "GREATER_THAN_OR_EQUAL":
  6617. return ">=" /* Operator.GREATER_THAN_OR_EQUAL */;
  6618. case "LESS_THAN":
  6619. return "<" /* Operator.LESS_THAN */;
  6620. case "LESS_THAN_OR_EQUAL":
  6621. return "<=" /* Operator.LESS_THAN_OR_EQUAL */;
  6622. case "ARRAY_CONTAINS":
  6623. return "array-contains" /* Operator.ARRAY_CONTAINS */;
  6624. case "IN":
  6625. return "in" /* Operator.IN */;
  6626. case "NOT_IN":
  6627. return "not-in" /* Operator.NOT_IN */;
  6628. case "ARRAY_CONTAINS_ANY":
  6629. return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */;
  6630. default:
  6631. return B();
  6632. }
  6633. }(t.fieldFilter.op), t.fieldFilter.value);
  6634. }(t) : void 0 !== t.compositeFilter ? function(t) {
  6635. return In.create(t.compositeFilter.filters.map((t => nr(t))), function(t) {
  6636. switch (t) {
  6637. case "AND":
  6638. return "and" /* CompositeOperator.AND */;
  6639. case "OR":
  6640. return "or" /* CompositeOperator.OR */;
  6641. default:
  6642. return B();
  6643. }
  6644. }(t.compositeFilter.op));
  6645. }(t) : B();
  6646. }
  6647. function sr(t) {
  6648. return Vi[t];
  6649. }
  6650. function ir(t) {
  6651. return Si[t];
  6652. }
  6653. function rr(t) {
  6654. return Di[t];
  6655. }
  6656. function or(t) {
  6657. return {
  6658. fieldPath: t.canonicalString()
  6659. };
  6660. }
  6661. function ur(t) {
  6662. return lt.fromServerFormat(t.fieldPath);
  6663. }
  6664. function cr(t) {
  6665. return t instanceof pn ? function(t) {
  6666. if ("==" /* Operator.EQUAL */ === t.op) {
  6667. if (en(t.value)) return {
  6668. unaryFilter: {
  6669. field: or(t.field),
  6670. op: "IS_NAN"
  6671. }
  6672. };
  6673. if (tn(t.value)) return {
  6674. unaryFilter: {
  6675. field: or(t.field),
  6676. op: "IS_NULL"
  6677. }
  6678. };
  6679. } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) {
  6680. if (en(t.value)) return {
  6681. unaryFilter: {
  6682. field: or(t.field),
  6683. op: "IS_NOT_NAN"
  6684. }
  6685. };
  6686. if (tn(t.value)) return {
  6687. unaryFilter: {
  6688. field: or(t.field),
  6689. op: "IS_NOT_NULL"
  6690. }
  6691. };
  6692. }
  6693. return {
  6694. fieldFilter: {
  6695. field: or(t.field),
  6696. op: ir(t.op),
  6697. value: t.value
  6698. }
  6699. };
  6700. }(t) : t instanceof In ? function(t) {
  6701. const e = t.getFilters().map((t => cr(t)));
  6702. if (1 === e.length) return e[0];
  6703. return {
  6704. compositeFilter: {
  6705. op: rr(t.op),
  6706. filters: e
  6707. }
  6708. };
  6709. }(t) : B();
  6710. }
  6711. function ar(t) {
  6712. const e = [];
  6713. return t.fields.forEach((t => e.push(t.canonicalString()))), {
  6714. fieldPaths: e
  6715. };
  6716. }
  6717. function hr(t) {
  6718. // Resource names have at least 4 components (project ID, database ID)
  6719. return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2);
  6720. }
  6721. /**
  6722. * @license
  6723. * Copyright 2017 Google LLC
  6724. *
  6725. * Licensed under the Apache License, Version 2.0 (the "License");
  6726. * you may not use this file except in compliance with the License.
  6727. * You may obtain a copy of the License at
  6728. *
  6729. * http://www.apache.org/licenses/LICENSE-2.0
  6730. *
  6731. * Unless required by applicable law or agreed to in writing, software
  6732. * distributed under the License is distributed on an "AS IS" BASIS,
  6733. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6734. * See the License for the specific language governing permissions and
  6735. * limitations under the License.
  6736. */
  6737. /**
  6738. * An immutable set of metadata that the local store tracks for each target.
  6739. */ class lr {
  6740. constructor(
  6741. /** The target being listened to. */
  6742. t,
  6743. /**
  6744. * The target ID to which the target corresponds; Assigned by the
  6745. * LocalStore for user listens and by the SyncEngine for limbo watches.
  6746. */
  6747. e,
  6748. /** The purpose of the target. */
  6749. n,
  6750. /**
  6751. * The sequence number of the last transaction during which this target data
  6752. * was modified.
  6753. */
  6754. s,
  6755. /** The latest snapshot version seen for this target. */
  6756. i = ut.min()
  6757. /**
  6758. * The maximum snapshot version at which the associated view
  6759. * contained no limbo documents.
  6760. */ , r = ut.min()
  6761. /**
  6762. * An opaque, server-assigned token that allows watching a target to be
  6763. * resumed after disconnecting without retransmitting all the data that
  6764. * matches the target. The resume token essentially identifies a point in
  6765. * time from which the server should resume sending results.
  6766. */ , o = Ce.EMPTY_BYTE_STRING
  6767. /**
  6768. * The number of documents that last matched the query at the resume token or
  6769. * read time. Documents are counted only when making a listen request with
  6770. * resume token or read time, otherwise, keep it null.
  6771. */ , u = null) {
  6772. this.target = t, this.targetId = e, this.purpose = n, this.sequenceNumber = s, this.snapshotVersion = i,
  6773. this.lastLimboFreeSnapshotVersion = r, this.resumeToken = o, this.expectedCount = u;
  6774. }
  6775. /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(t) {
  6776. return new lr(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount);
  6777. }
  6778. /**
  6779. * Creates a new target data instance with an updated resume token and
  6780. * snapshot version.
  6781. */ withResumeToken(t, e) {
  6782. return new lr(this.target, this.targetId, this.purpose, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t,
  6783. /* expectedCount= */ null);
  6784. }
  6785. /**
  6786. * Creates a new target data instance with an updated expected count.
  6787. */ withExpectedCount(t) {
  6788. return new lr(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, t);
  6789. }
  6790. /**
  6791. * Creates a new target data instance with an updated last limbo free
  6792. * snapshot version number.
  6793. */ withLastLimboFreeSnapshotVersion(t) {
  6794. return new lr(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, t, this.resumeToken, this.expectedCount);
  6795. }
  6796. }
  6797. /**
  6798. * @license
  6799. * Copyright 2017 Google LLC
  6800. *
  6801. * Licensed under the Apache License, Version 2.0 (the "License");
  6802. * you may not use this file except in compliance with the License.
  6803. * You may obtain a copy of the License at
  6804. *
  6805. * http://www.apache.org/licenses/LICENSE-2.0
  6806. *
  6807. * Unless required by applicable law or agreed to in writing, software
  6808. * distributed under the License is distributed on an "AS IS" BASIS,
  6809. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6810. * See the License for the specific language governing permissions and
  6811. * limitations under the License.
  6812. */
  6813. /** Serializer for values stored in the LocalStore. */ class fr {
  6814. constructor(t) {
  6815. this.fe = t;
  6816. }
  6817. }
  6818. /** Decodes a remote document from storage locally to a Document. */ function dr(t, e) {
  6819. let n;
  6820. if (e.document) n = ji(t.fe, e.document, !!e.hasCommittedMutations); else if (e.noDocument) {
  6821. const t = ft.fromSegments(e.noDocument.path), s = gr(e.noDocument.readTime);
  6822. n = fn.newNoDocument(t, s), e.hasCommittedMutations && n.setHasCommittedMutations();
  6823. } else {
  6824. if (!e.unknownDocument) return B();
  6825. {
  6826. const t = ft.fromSegments(e.unknownDocument.path), s = gr(e.unknownDocument.version);
  6827. n = fn.newUnknownDocument(t, s);
  6828. }
  6829. }
  6830. return e.readTime && n.setReadTime(function(t) {
  6831. const e = new ot(t[0], t[1]);
  6832. return ut.fromTimestamp(e);
  6833. }(e.readTime)), n;
  6834. }
  6835. /** Encodes a document for storage locally. */ function wr(t, e) {
  6836. const n = e.key, s = {
  6837. prefixPath: n.getCollectionPath().popLast().toArray(),
  6838. collectionGroup: n.collectionGroup,
  6839. documentId: n.path.lastSegment(),
  6840. readTime: _r(e.readTime),
  6841. hasCommittedMutations: e.hasCommittedMutations
  6842. };
  6843. if (e.isFoundDocument()) s.document = function(t, e) {
  6844. return {
  6845. name: Bi(t, e.key),
  6846. fields: e.data.value.mapValue.fields,
  6847. updateTime: Ni(t, e.version.toTimestamp()),
  6848. createTime: Ni(t, e.createTime.toTimestamp())
  6849. };
  6850. }(t.fe, e); else if (e.isNoDocument()) s.noDocument = {
  6851. path: n.path.toArray(),
  6852. readTime: mr(e.version)
  6853. }; else {
  6854. if (!e.isUnknownDocument()) return B();
  6855. s.unknownDocument = {
  6856. path: n.path.toArray(),
  6857. version: mr(e.version)
  6858. };
  6859. }
  6860. return s;
  6861. }
  6862. function _r(t) {
  6863. const e = t.toTimestamp();
  6864. return [ e.seconds, e.nanoseconds ];
  6865. }
  6866. function mr(t) {
  6867. const e = t.toTimestamp();
  6868. return {
  6869. seconds: e.seconds,
  6870. nanoseconds: e.nanoseconds
  6871. };
  6872. }
  6873. function gr(t) {
  6874. const e = new ot(t.seconds, t.nanoseconds);
  6875. return ut.fromTimestamp(e);
  6876. }
  6877. /** Encodes a batch of mutations into a DbMutationBatch for local storage. */
  6878. /** Decodes a DbMutationBatch into a MutationBatch */
  6879. function yr(t, e) {
  6880. const n = (e.baseMutations || []).map((e => Ji(t.fe, e)));
  6881. // Squash old transform mutations into existing patch or set mutations.
  6882. // The replacement of representing `transforms` with `update_transforms`
  6883. // on the SDK means that old `transform` mutations stored in IndexedDB need
  6884. // to be updated to `update_transforms`.
  6885. // TODO(b/174608374): Remove this code once we perform a schema migration.
  6886. for (let t = 0; t < e.mutations.length - 1; ++t) {
  6887. const n = e.mutations[t];
  6888. if (t + 1 < e.mutations.length && void 0 !== e.mutations[t + 1].transform) {
  6889. const s = e.mutations[t + 1];
  6890. n.updateTransforms = s.transform.fieldTransforms, e.mutations.splice(t + 1, 1),
  6891. ++t;
  6892. }
  6893. }
  6894. const s = e.mutations.map((e => Ji(t.fe, e))), i = ot.fromMillis(e.localWriteTimeMs);
  6895. return new ni(e.batchId, i, n, s);
  6896. }
  6897. /** Decodes a DbTarget into TargetData */ function pr(t) {
  6898. const e = gr(t.readTime), n = void 0 !== t.lastLimboFreeSnapshotVersion ? gr(t.lastLimboFreeSnapshotVersion) : ut.min();
  6899. let s;
  6900. var i;
  6901. return void 0 !== t.query.documents ? (L(1 === (i = t.query).documents.length),
  6902. s = Zn(zn(Ui(i.documents[0])))) : s = function(t) {
  6903. return Zn(tr(t));
  6904. }(t.query), new lr(s, t.targetId, "TargetPurposeListen" /* TargetPurpose.Listen */ , t.lastListenSequenceNumber, e, n, Ce.fromBase64String(t.resumeToken));
  6905. }
  6906. /** Encodes TargetData into a DbTarget for storage locally. */ function Ir(t, e) {
  6907. const n = mr(e.snapshotVersion), s = mr(e.lastLimboFreeSnapshotVersion);
  6908. let i;
  6909. i = qn(e.target) ? Xi(t.fe, e.target) : Zi(t.fe, e.target);
  6910. // We can't store the resumeToken as a ByteString in IndexedDb, so we
  6911. // convert it to a base64 string for storage.
  6912. const r = e.resumeToken.toBase64();
  6913. // lastListenSequenceNumber is always 0 until we do real GC.
  6914. return {
  6915. targetId: e.targetId,
  6916. canonicalId: Bn(e.target),
  6917. readTime: n,
  6918. resumeToken: r,
  6919. lastListenSequenceNumber: e.sequenceNumber,
  6920. lastLimboFreeSnapshotVersion: s,
  6921. query: i
  6922. };
  6923. }
  6924. /**
  6925. * A helper function for figuring out what kind of query has been stored.
  6926. */
  6927. /**
  6928. * Encodes a `BundledQuery` from bundle proto to a Query object.
  6929. *
  6930. * This reconstructs the original query used to build the bundle being loaded,
  6931. * including features exists only in SDKs (for example: limit-to-last).
  6932. */
  6933. function Tr(t) {
  6934. const e = tr({
  6935. parent: t.parent,
  6936. structuredQuery: t.structuredQuery
  6937. });
  6938. return "LAST" === t.limitType ? es(e, e.limit, "L" /* LimitType.Last */) : e;
  6939. }
  6940. /** Encodes a NamedQuery proto object to a NamedQuery model object. */
  6941. /** Encodes a DbDocumentOverlay object to an Overlay model object. */
  6942. function Er(t, e) {
  6943. return new ii(e.largestBatchId, Ji(t.fe, e.overlayMutation));
  6944. }
  6945. /** Decodes an Overlay model object into a DbDocumentOverlay object. */
  6946. /**
  6947. * Returns the DbDocumentOverlayKey corresponding to the given user and
  6948. * document key.
  6949. */
  6950. function Ar(t, e) {
  6951. const n = e.path.lastSegment();
  6952. return [ t, Kt(e.path.popLast()), n ];
  6953. }
  6954. function vr(t, e, n, s) {
  6955. return {
  6956. indexId: t,
  6957. uid: e.uid || "",
  6958. sequenceNumber: n,
  6959. readTime: mr(s.readTime),
  6960. documentKey: Kt(s.documentKey.path),
  6961. largestBatchId: s.largestBatchId
  6962. };
  6963. }
  6964. /**
  6965. * @license
  6966. * Copyright 2020 Google LLC
  6967. *
  6968. * Licensed under the Apache License, Version 2.0 (the "License");
  6969. * you may not use this file except in compliance with the License.
  6970. * You may obtain a copy of the License at
  6971. *
  6972. * http://www.apache.org/licenses/LICENSE-2.0
  6973. *
  6974. * Unless required by applicable law or agreed to in writing, software
  6975. * distributed under the License is distributed on an "AS IS" BASIS,
  6976. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6977. * See the License for the specific language governing permissions and
  6978. * limitations under the License.
  6979. */ class Rr {
  6980. getBundleMetadata(t, e) {
  6981. return Pr(t).get(e).next((t => {
  6982. if (t) return {
  6983. id: (e = t).bundleId,
  6984. createTime: gr(e.createTime),
  6985. version: e.version
  6986. };
  6987. /** Encodes a DbBundle to a BundleMetadata object. */
  6988. var e;
  6989. /** Encodes a BundleMetadata to a DbBundle. */ }));
  6990. }
  6991. saveBundleMetadata(t, e) {
  6992. return Pr(t).put({
  6993. bundleId: (n = e).id,
  6994. createTime: mr(Mi(n.createTime)),
  6995. version: n.version
  6996. });
  6997. var n;
  6998. /** Encodes a DbNamedQuery to a NamedQuery. */ }
  6999. getNamedQuery(t, e) {
  7000. return br(t).get(e).next((t => {
  7001. if (t) return {
  7002. name: (e = t).name,
  7003. query: Tr(e.bundledQuery),
  7004. readTime: gr(e.readTime)
  7005. };
  7006. var e;
  7007. /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ }));
  7008. }
  7009. saveNamedQuery(t, e) {
  7010. return br(t).put(function(t) {
  7011. return {
  7012. name: t.name,
  7013. readTime: mr(Mi(t.readTime)),
  7014. bundledQuery: t.bundledQuery
  7015. };
  7016. }(e));
  7017. }
  7018. }
  7019. /**
  7020. * Helper to get a typed SimpleDbStore for the bundles object store.
  7021. */ function Pr(t) {
  7022. return ge(t, "bundles");
  7023. }
  7024. /**
  7025. * Helper to get a typed SimpleDbStore for the namedQueries object store.
  7026. */ function br(t) {
  7027. return ge(t, "namedQueries");
  7028. }
  7029. /**
  7030. * @license
  7031. * Copyright 2022 Google LLC
  7032. *
  7033. * Licensed under the Apache License, Version 2.0 (the "License");
  7034. * you may not use this file except in compliance with the License.
  7035. * You may obtain a copy of the License at
  7036. *
  7037. * http://www.apache.org/licenses/LICENSE-2.0
  7038. *
  7039. * Unless required by applicable law or agreed to in writing, software
  7040. * distributed under the License is distributed on an "AS IS" BASIS,
  7041. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7042. * See the License for the specific language governing permissions and
  7043. * limitations under the License.
  7044. */
  7045. /**
  7046. * Implementation of DocumentOverlayCache using IndexedDb.
  7047. */ class Vr {
  7048. /**
  7049. * @param serializer - The document serializer.
  7050. * @param userId - The userId for which we are accessing overlays.
  7051. */
  7052. constructor(t, e) {
  7053. this.serializer = t, this.userId = e;
  7054. }
  7055. static de(t, e) {
  7056. const n = e.uid || "";
  7057. return new Vr(t, n);
  7058. }
  7059. getOverlay(t, e) {
  7060. return Sr(t).get(Ar(this.userId, e)).next((t => t ? Er(this.serializer, t) : null));
  7061. }
  7062. getOverlays(t, e) {
  7063. const n = _s();
  7064. return bt.forEach(e, (e => this.getOverlay(t, e).next((t => {
  7065. null !== t && n.set(e, t);
  7066. })))).next((() => n));
  7067. }
  7068. saveOverlays(t, e, n) {
  7069. const s = [];
  7070. return n.forEach(((n, i) => {
  7071. const r = new ii(e, i);
  7072. s.push(this.we(t, r));
  7073. })), bt.waitFor(s);
  7074. }
  7075. removeOverlaysForBatchId(t, e, n) {
  7076. const s = new Set;
  7077. // Get the set of unique collection paths.
  7078. e.forEach((t => s.add(Kt(t.getCollectionPath()))));
  7079. const i = [];
  7080. return s.forEach((e => {
  7081. const s = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, n + 1 ],
  7082. /*lowerOpen=*/ !1,
  7083. /*upperOpen=*/ !0);
  7084. i.push(Sr(t).J("collectionPathOverlayIndex", s));
  7085. })), bt.waitFor(i);
  7086. }
  7087. getOverlaysForCollection(t, e, n) {
  7088. const s = _s(), i = Kt(e), r = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ],
  7089. /*lowerOpen=*/ !0);
  7090. return Sr(t).j("collectionPathOverlayIndex", r).next((t => {
  7091. for (const e of t) {
  7092. const t = Er(this.serializer, e);
  7093. s.set(t.getKey(), t);
  7094. }
  7095. return s;
  7096. }));
  7097. }
  7098. getOverlaysForCollectionGroup(t, e, n, s) {
  7099. const i = _s();
  7100. let r;
  7101. // We want batch IDs larger than `sinceBatchId`, and so the lower bound
  7102. // is not inclusive.
  7103. const o = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, Number.POSITIVE_INFINITY ],
  7104. /*lowerOpen=*/ !0);
  7105. return Sr(t).X({
  7106. index: "collectionGroupOverlayIndex",
  7107. range: o
  7108. }, ((t, e, n) => {
  7109. // We do not want to return partial batch overlays, even if the size
  7110. // of the result set exceeds the given `count` argument. Therefore, we
  7111. // continue to aggregate results even after the result size exceeds
  7112. // `count` if there are more overlays from the `currentBatchId`.
  7113. const o = Er(this.serializer, e);
  7114. i.size() < s || o.largestBatchId === r ? (i.set(o.getKey(), o), r = o.largestBatchId) : n.done();
  7115. })).next((() => i));
  7116. }
  7117. we(t, e) {
  7118. return Sr(t).put(function(t, e, n) {
  7119. const [s, i, r] = Ar(e, n.mutation.key);
  7120. return {
  7121. userId: e,
  7122. collectionPath: i,
  7123. documentId: r,
  7124. collectionGroup: n.mutation.key.getCollectionGroup(),
  7125. largestBatchId: n.largestBatchId,
  7126. overlayMutation: Hi(t.fe, n.mutation)
  7127. };
  7128. }(this.serializer, this.userId, e));
  7129. }
  7130. }
  7131. /**
  7132. * Helper to get a typed SimpleDbStore for the document overlay object store.
  7133. */ function Sr(t) {
  7134. return ge(t, "documentOverlays");
  7135. }
  7136. /**
  7137. * @license
  7138. * Copyright 2021 Google LLC
  7139. *
  7140. * Licensed under the Apache License, Version 2.0 (the "License");
  7141. * you may not use this file except in compliance with the License.
  7142. * You may obtain a copy of the License at
  7143. *
  7144. * http://www.apache.org/licenses/LICENSE-2.0
  7145. *
  7146. * Unless required by applicable law or agreed to in writing, software
  7147. * distributed under the License is distributed on an "AS IS" BASIS,
  7148. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7149. * See the License for the specific language governing permissions and
  7150. * limitations under the License.
  7151. */
  7152. // Note: This code is copied from the backend. Code that is not used by
  7153. // Firestore was removed.
  7154. /** Firestore index value writer. */
  7155. class Dr {
  7156. constructor() {}
  7157. // The write methods below short-circuit writing terminators for values
  7158. // containing a (terminating) truncated value.
  7159. // As an example, consider the resulting encoding for:
  7160. // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM)
  7161. // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC)
  7162. // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC)
  7163. /** Writes an index value. */
  7164. _e(t, e) {
  7165. this.me(t, e),
  7166. // Write separator to split index values
  7167. // (see go/firestore-storage-format#encodings).
  7168. e.ge();
  7169. }
  7170. me(t, e) {
  7171. if ("nullValue" in t) this.ye(e, 5); else if ("booleanValue" in t) this.ye(e, 10),
  7172. e.pe(t.booleanValue ? 1 : 0); else if ("integerValue" in t) this.ye(e, 15), e.pe(ke(t.integerValue)); else if ("doubleValue" in t) {
  7173. const n = ke(t.doubleValue);
  7174. isNaN(n) ? this.ye(e, 13) : (this.ye(e, 15), qt(n) ?
  7175. // -0.0, 0 and 0.0 are all considered the same
  7176. e.pe(0) : e.pe(n));
  7177. } else if ("timestampValue" in t) {
  7178. const n = t.timestampValue;
  7179. this.ye(e, 20), "string" == typeof n ? e.Ie(n) : (e.Ie(`${n.seconds || ""}`), e.pe(n.nanos || 0));
  7180. } else if ("stringValue" in t) this.Te(t.stringValue, e), this.Ee(e); else if ("bytesValue" in t) this.ye(e, 30),
  7181. e.Ae($e(t.bytesValue)), this.Ee(e); else if ("referenceValue" in t) this.ve(t.referenceValue, e); else if ("geoPointValue" in t) {
  7182. const n = t.geoPointValue;
  7183. this.ye(e, 45), e.pe(n.latitude || 0), e.pe(n.longitude || 0);
  7184. } else "mapValue" in t ? rn(t) ? this.ye(e, Number.MAX_SAFE_INTEGER) : (this.Re(t.mapValue, e),
  7185. this.Ee(e)) : "arrayValue" in t ? (this.Pe(t.arrayValue, e), this.Ee(e)) : B();
  7186. }
  7187. Te(t, e) {
  7188. this.ye(e, 25), this.be(t, e);
  7189. }
  7190. be(t, e) {
  7191. e.Ie(t);
  7192. }
  7193. Re(t, e) {
  7194. const n = t.fields || {};
  7195. this.ye(e, 55);
  7196. for (const t of Object.keys(n)) this.Te(t, e), this.me(n[t], e);
  7197. }
  7198. Pe(t, e) {
  7199. const n = t.values || [];
  7200. this.ye(e, 50);
  7201. for (const t of n) this.me(t, e);
  7202. }
  7203. ve(t, e) {
  7204. this.ye(e, 37);
  7205. ft.fromName(t).path.forEach((t => {
  7206. this.ye(e, 60), this.be(t, e);
  7207. }));
  7208. }
  7209. ye(t, e) {
  7210. t.pe(e);
  7211. }
  7212. Ee(t) {
  7213. // While the SDK does not implement truncation, the truncation marker is
  7214. // used to terminate all variable length values (which are strings, bytes,
  7215. // references, arrays and maps).
  7216. t.pe(2);
  7217. }
  7218. }
  7219. Dr.Ve = new Dr;
  7220. /**
  7221. * Counts the number of zeros in a byte.
  7222. *
  7223. * Visible for testing.
  7224. */
  7225. function Cr(t) {
  7226. if (0 === t) return 8;
  7227. let e = 0;
  7228. return t >> 4 == 0 && (
  7229. // Test if the first four bits are zero.
  7230. e += 4, t <<= 4), t >> 6 == 0 && (
  7231. // Test if the first two (or next two) bits are zero.
  7232. e += 2, t <<= 2), t >> 7 == 0 && (
  7233. // Test if the remaining bit is zero.
  7234. e += 1), e;
  7235. }
  7236. /** Counts the number of leading zeros in the given byte array. */
  7237. /**
  7238. * Returns the number of bytes required to store "value". Leading zero bytes
  7239. * are skipped.
  7240. */
  7241. function xr(t) {
  7242. // This is just the number of bytes for the unsigned representation of the number.
  7243. const e = 64 - function(t) {
  7244. let e = 0;
  7245. for (let n = 0; n < 8; ++n) {
  7246. const s = Cr(255 & t[n]);
  7247. if (e += s, 8 !== s) break;
  7248. }
  7249. return e;
  7250. }(t);
  7251. return Math.ceil(e / 8);
  7252. }
  7253. /**
  7254. * OrderedCodeWriter is a minimal-allocation implementation of the writing
  7255. * behavior defined by the backend.
  7256. *
  7257. * The code is ported from its Java counterpart.
  7258. */ class Nr {
  7259. constructor() {
  7260. this.buffer = new Uint8Array(1024), this.position = 0;
  7261. }
  7262. Se(t) {
  7263. const e = t[Symbol.iterator]();
  7264. let n = e.next();
  7265. for (;!n.done; ) this.De(n.value), n = e.next();
  7266. this.Ce();
  7267. }
  7268. xe(t) {
  7269. const e = t[Symbol.iterator]();
  7270. let n = e.next();
  7271. for (;!n.done; ) this.Ne(n.value), n = e.next();
  7272. this.ke();
  7273. }
  7274. /** Writes utf8 bytes into this byte sequence, ascending. */ $e(t) {
  7275. for (const e of t) {
  7276. const t = e.charCodeAt(0);
  7277. if (t < 128) this.De(t); else if (t < 2048) this.De(960 | t >>> 6), this.De(128 | 63 & t); else if (e < "\ud800" || "\udbff" < e) this.De(480 | t >>> 12),
  7278. this.De(128 | 63 & t >>> 6), this.De(128 | 63 & t); else {
  7279. const t = e.codePointAt(0);
  7280. this.De(240 | t >>> 18), this.De(128 | 63 & t >>> 12), this.De(128 | 63 & t >>> 6),
  7281. this.De(128 | 63 & t);
  7282. }
  7283. }
  7284. this.Ce();
  7285. }
  7286. /** Writes utf8 bytes into this byte sequence, descending */ Me(t) {
  7287. for (const e of t) {
  7288. const t = e.charCodeAt(0);
  7289. if (t < 128) this.Ne(t); else if (t < 2048) this.Ne(960 | t >>> 6), this.Ne(128 | 63 & t); else if (e < "\ud800" || "\udbff" < e) this.Ne(480 | t >>> 12),
  7290. this.Ne(128 | 63 & t >>> 6), this.Ne(128 | 63 & t); else {
  7291. const t = e.codePointAt(0);
  7292. this.Ne(240 | t >>> 18), this.Ne(128 | 63 & t >>> 12), this.Ne(128 | 63 & t >>> 6),
  7293. this.Ne(128 | 63 & t);
  7294. }
  7295. }
  7296. this.ke();
  7297. }
  7298. Oe(t) {
  7299. // Values are encoded with a single byte length prefix, followed by the
  7300. // actual value in big-endian format with leading 0 bytes dropped.
  7301. const e = this.Fe(t), n = xr(e);
  7302. this.Be(1 + n), this.buffer[this.position++] = 255 & n;
  7303. // Write the length
  7304. for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = 255 & e[t];
  7305. }
  7306. Le(t) {
  7307. // Values are encoded with a single byte length prefix, followed by the
  7308. // inverted value in big-endian format with leading 0 bytes dropped.
  7309. const e = this.Fe(t), n = xr(e);
  7310. this.Be(1 + n), this.buffer[this.position++] = ~(255 & n);
  7311. // Write the length
  7312. for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = ~(255 & e[t]);
  7313. }
  7314. /**
  7315. * Writes the "infinity" byte sequence that sorts after all other byte
  7316. * sequences written in ascending order.
  7317. */ qe() {
  7318. this.Ue(255), this.Ue(255);
  7319. }
  7320. /**
  7321. * Writes the "infinity" byte sequence that sorts before all other byte
  7322. * sequences written in descending order.
  7323. */ Ke() {
  7324. this.Ge(255), this.Ge(255);
  7325. }
  7326. /**
  7327. * Resets the buffer such that it is the same as when it was newly
  7328. * constructed.
  7329. */ reset() {
  7330. this.position = 0;
  7331. }
  7332. seed(t) {
  7333. this.Be(t.length), this.buffer.set(t, this.position), this.position += t.length;
  7334. }
  7335. /** Makes a copy of the encoded bytes in this buffer. */ Qe() {
  7336. return this.buffer.slice(0, this.position);
  7337. }
  7338. /**
  7339. * Encodes `val` into an encoding so that the order matches the IEEE 754
  7340. * floating-point comparison results with the following exceptions:
  7341. * -0.0 < 0.0
  7342. * all non-NaN < NaN
  7343. * NaN = NaN
  7344. */ Fe(t) {
  7345. const e =
  7346. /** Converts a JavaScript number to a byte array (using big endian encoding). */
  7347. function(t) {
  7348. const e = new DataView(new ArrayBuffer(8));
  7349. return e.setFloat64(0, t, /* littleEndian= */ !1), new Uint8Array(e.buffer);
  7350. }(t), n = 0 != (128 & e[0]);
  7351. // Check if the first bit is set. We use a bit mask since value[0] is
  7352. // encoded as a number from 0 to 255.
  7353. // Revert the two complement to get natural ordering
  7354. e[0] ^= n ? 255 : 128;
  7355. for (let t = 1; t < e.length; ++t) e[t] ^= n ? 255 : 0;
  7356. return e;
  7357. }
  7358. /** Writes a single byte ascending to the buffer. */ De(t) {
  7359. const e = 255 & t;
  7360. 0 === e ? (this.Ue(0), this.Ue(255)) : 255 === e ? (this.Ue(255), this.Ue(0)) : this.Ue(e);
  7361. }
  7362. /** Writes a single byte descending to the buffer. */ Ne(t) {
  7363. const e = 255 & t;
  7364. 0 === e ? (this.Ge(0), this.Ge(255)) : 255 === e ? (this.Ge(255), this.Ge(0)) : this.Ge(t);
  7365. }
  7366. Ce() {
  7367. this.Ue(0), this.Ue(1);
  7368. }
  7369. ke() {
  7370. this.Ge(0), this.Ge(1);
  7371. }
  7372. Ue(t) {
  7373. this.Be(1), this.buffer[this.position++] = t;
  7374. }
  7375. Ge(t) {
  7376. this.Be(1), this.buffer[this.position++] = ~t;
  7377. }
  7378. Be(t) {
  7379. const e = t + this.position;
  7380. if (e <= this.buffer.length) return;
  7381. // Try doubling.
  7382. let n = 2 * this.buffer.length;
  7383. // Still not big enough? Just allocate the right size.
  7384. n < e && (n = e);
  7385. // Create the new buffer.
  7386. const s = new Uint8Array(n);
  7387. s.set(this.buffer), // copy old data
  7388. this.buffer = s;
  7389. }
  7390. }
  7391. class kr {
  7392. constructor(t) {
  7393. this.je = t;
  7394. }
  7395. Ae(t) {
  7396. this.je.Se(t);
  7397. }
  7398. Ie(t) {
  7399. this.je.$e(t);
  7400. }
  7401. pe(t) {
  7402. this.je.Oe(t);
  7403. }
  7404. ge() {
  7405. this.je.qe();
  7406. }
  7407. }
  7408. class $r {
  7409. constructor(t) {
  7410. this.je = t;
  7411. }
  7412. Ae(t) {
  7413. this.je.xe(t);
  7414. }
  7415. Ie(t) {
  7416. this.je.Me(t);
  7417. }
  7418. pe(t) {
  7419. this.je.Le(t);
  7420. }
  7421. ge() {
  7422. this.je.Ke();
  7423. }
  7424. }
  7425. /**
  7426. * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the
  7427. * actual encoding.
  7428. */ class Mr {
  7429. constructor() {
  7430. this.je = new Nr, this.ze = new kr(this.je), this.We = new $r(this.je);
  7431. }
  7432. seed(t) {
  7433. this.je.seed(t);
  7434. }
  7435. He(t) {
  7436. return 0 /* IndexKind.ASCENDING */ === t ? this.ze : this.We;
  7437. }
  7438. Qe() {
  7439. return this.je.Qe();
  7440. }
  7441. reset() {
  7442. this.je.reset();
  7443. }
  7444. }
  7445. /**
  7446. * @license
  7447. * Copyright 2022 Google LLC
  7448. *
  7449. * Licensed under the Apache License, Version 2.0 (the "License");
  7450. * you may not use this file except in compliance with the License.
  7451. * You may obtain a copy of the License at
  7452. *
  7453. * http://www.apache.org/licenses/LICENSE-2.0
  7454. *
  7455. * Unless required by applicable law or agreed to in writing, software
  7456. * distributed under the License is distributed on an "AS IS" BASIS,
  7457. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7458. * See the License for the specific language governing permissions and
  7459. * limitations under the License.
  7460. */
  7461. /** Represents an index entry saved by the SDK in persisted storage. */ class Or {
  7462. constructor(t, e, n, s) {
  7463. this.indexId = t, this.documentKey = e, this.arrayValue = n, this.directionalValue = s;
  7464. }
  7465. /**
  7466. * Returns an IndexEntry entry that sorts immediately after the current
  7467. * directional value.
  7468. */ Je() {
  7469. const t = this.directionalValue.length, e = 0 === t || 255 === this.directionalValue[t - 1] ? t + 1 : t, n = new Uint8Array(e);
  7470. return n.set(this.directionalValue, 0), e !== t ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1],
  7471. new Or(this.indexId, this.documentKey, this.arrayValue, n);
  7472. }
  7473. }
  7474. function Fr(t, e) {
  7475. let n = t.indexId - e.indexId;
  7476. return 0 !== n ? n : (n = Br(t.arrayValue, e.arrayValue), 0 !== n ? n : (n = Br(t.directionalValue, e.directionalValue),
  7477. 0 !== n ? n : ft.comparator(t.documentKey, e.documentKey)));
  7478. }
  7479. function Br(t, e) {
  7480. for (let n = 0; n < t.length && n < e.length; ++n) {
  7481. const s = t[n] - e[n];
  7482. if (0 !== s) return s;
  7483. }
  7484. return t.length - e.length;
  7485. }
  7486. /**
  7487. * @license
  7488. * Copyright 2022 Google LLC
  7489. *
  7490. * Licensed under the Apache License, Version 2.0 (the "License");
  7491. * you may not use this file except in compliance with the License.
  7492. * You may obtain a copy of the License at
  7493. *
  7494. * http://www.apache.org/licenses/LICENSE-2.0
  7495. *
  7496. * Unless required by applicable law or agreed to in writing, software
  7497. * distributed under the License is distributed on an "AS IS" BASIS,
  7498. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7499. * See the License for the specific language governing permissions and
  7500. * limitations under the License.
  7501. */
  7502. /**
  7503. * A light query planner for Firestore.
  7504. *
  7505. * This class matches a `FieldIndex` against a Firestore Query `Target`. It
  7506. * determines whether a given index can be used to serve the specified target.
  7507. *
  7508. * The following table showcases some possible index configurations:
  7509. *
  7510. * Query | Index
  7511. * -----------------------------------------------------------------------------
  7512. * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC
  7513. * where('a', '==', 'a').where('b', '==', 'b') | a ASC
  7514. * where('a', '==', 'a').where('b', '==', 'b') | b DESC
  7515. * where('a', '>=', 'a').orderBy('a') | a ASC
  7516. * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC
  7517. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC
  7518. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC
  7519. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING
  7520. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS
  7521. */ class Lr {
  7522. constructor(t) {
  7523. this.collectionId = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(),
  7524. this.Ye = t.orderBy, this.Xe = [];
  7525. for (const e of t.filters) {
  7526. const t = e;
  7527. t.isInequality() ? this.Ze = t : this.Xe.push(t);
  7528. }
  7529. }
  7530. /**
  7531. * Returns whether the index can be used to serve the TargetIndexMatcher's
  7532. * target.
  7533. *
  7534. * An index is considered capable of serving the target when:
  7535. * - The target uses all index segments for its filters and orderBy clauses.
  7536. * The target can have additional filter and orderBy clauses, but not
  7537. * fewer.
  7538. * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also
  7539. * have a corresponding `CONTAINS` segment.
  7540. * - All directional index segments can be mapped to the target as a series of
  7541. * equality filters, a single inequality filter and a series of orderBy
  7542. * clauses.
  7543. * - The segments that represent the equality filters may appear out of order.
  7544. * - The optional segment for the inequality filter must appear after all
  7545. * equality segments.
  7546. * - The segments that represent that orderBy clause of the target must appear
  7547. * in order after all equality and inequality segments. Single orderBy
  7548. * clauses cannot be skipped, but a continuous orderBy suffix may be
  7549. * omitted.
  7550. */ tn(t) {
  7551. L(t.collectionGroup === this.collectionId);
  7552. // If there is an array element, find a matching filter.
  7553. const e = wt(t);
  7554. if (void 0 !== e && !this.en(e)) return !1;
  7555. const n = _t(t);
  7556. let s = new Set, i = 0, r = 0;
  7557. // Process all equalities first. Equalities can appear out of order.
  7558. for (;i < n.length && this.en(n[i]); ++i) s = s.add(n[i].fieldPath.canonicalString());
  7559. // If we already have processed all segments, all segments are used to serve
  7560. // the equality filters and we do not need to map any segments to the
  7561. // target's inequality and orderBy clauses.
  7562. if (i === n.length) return !0;
  7563. if (void 0 !== this.Ze) {
  7564. // If there is an inequality filter and the field was not in one of the
  7565. // equality filters above, the next segment must match both the filter
  7566. // and the first orderBy clause.
  7567. if (!s.has(this.Ze.field.canonicalString())) {
  7568. const t = n[i];
  7569. if (!this.nn(this.Ze, t) || !this.sn(this.Ye[r++], t)) return !1;
  7570. }
  7571. ++i;
  7572. }
  7573. // All remaining segments need to represent the prefix of the target's
  7574. // orderBy.
  7575. for (;i < n.length; ++i) {
  7576. const t = n[i];
  7577. if (r >= this.Ye.length || !this.sn(this.Ye[r++], t)) return !1;
  7578. }
  7579. return !0;
  7580. }
  7581. en(t) {
  7582. for (const e of this.Xe) if (this.nn(e, t)) return !0;
  7583. return !1;
  7584. }
  7585. nn(t, e) {
  7586. if (void 0 === t || !t.field.isEqual(e.fieldPath)) return !1;
  7587. const n = "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op;
  7588. return 2 /* IndexKind.CONTAINS */ === e.kind === n;
  7589. }
  7590. sn(t, e) {
  7591. 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);
  7592. }
  7593. }
  7594. /**
  7595. * @license
  7596. * Copyright 2022 Google LLC
  7597. *
  7598. * Licensed under the Apache License, Version 2.0 (the "License");
  7599. * you may not use this file except in compliance with the License.
  7600. * You may obtain a copy of the License at
  7601. *
  7602. * http://www.apache.org/licenses/LICENSE-2.0
  7603. *
  7604. * Unless required by applicable law or agreed to in writing, software
  7605. * distributed under the License is distributed on an "AS IS" BASIS,
  7606. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7607. * See the License for the specific language governing permissions and
  7608. * limitations under the License.
  7609. */
  7610. /**
  7611. * Provides utility functions that help with boolean logic transformations needed for handling
  7612. * complex filters used in queries.
  7613. */
  7614. /**
  7615. * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in
  7616. * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given
  7617. * input into a disjunction of equality filters and returns the expanded filter.
  7618. */ function qr(t) {
  7619. var e, n;
  7620. if (L(t instanceof pn || t instanceof In), t instanceof pn) {
  7621. if (t instanceof kn) {
  7622. const s = (null === (n = null === (e = t.value.arrayValue) || void 0 === e ? void 0 : e.values) || void 0 === n ? void 0 : n.map((e => pn.create(t.field, "==" /* Operator.EQUAL */ , e)))) || [];
  7623. return In.create(s, "or" /* CompositeOperator.OR */);
  7624. }
  7625. // We have reached other kinds of field filters.
  7626. return t;
  7627. }
  7628. // We have a composite filter.
  7629. const s = t.filters.map((t => qr(t)));
  7630. return In.create(s, t.op);
  7631. }
  7632. /**
  7633. * Given a composite filter, returns the list of terms in its disjunctive normal form.
  7634. *
  7635. * <p>Each element in the return value is one term of the resulting DNF. For instance: For the
  7636. * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list
  7637. * with two elements: a composite filter that performs (A && C), and a composite filter that
  7638. * performs (B && C).
  7639. *
  7640. * @param filter the composite filter to calculate DNF transform for.
  7641. * @return the terms in the DNF transform.
  7642. */ function Ur(t) {
  7643. if (0 === t.getFilters().length) return [];
  7644. const e = jr(qr(t));
  7645. return L(Qr(e)), Kr(e) || Gr(e) ? [ e ] : e.getFilters();
  7646. }
  7647. /** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function Kr(t) {
  7648. return t instanceof pn;
  7649. }
  7650. /**
  7651. * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10
  7652. * && b == 20)
  7653. */ function Gr(t) {
  7654. return t instanceof In && An(t);
  7655. }
  7656. /**
  7657. * Returns whether or not the given filter is in disjunctive normal form (DNF).
  7658. *
  7659. * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical
  7660. * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.
  7661. *
  7662. * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form
  7663. */ function Qr(t) {
  7664. return Kr(t) || Gr(t) ||
  7665. /**
  7666. * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and
  7667. * field filters. e.g. (a == 10) || (b==20 && c==30)
  7668. */
  7669. function(t) {
  7670. if (t instanceof In && En(t)) {
  7671. for (const e of t.getFilters()) if (!Kr(e) && !Gr(e)) return !1;
  7672. return !0;
  7673. }
  7674. return !1;
  7675. }(t);
  7676. }
  7677. function jr(t) {
  7678. if (L(t instanceof pn || t instanceof In), t instanceof pn) return t;
  7679. if (1 === t.filters.length) return jr(t.filters[0]);
  7680. // Compute DNF for each of the subfilters first
  7681. const e = t.filters.map((t => jr(t)));
  7682. let n = In.create(e, t.op);
  7683. return n = Hr(n), Qr(n) ? n : (L(n instanceof In), L(Tn(n)), L(n.filters.length > 1),
  7684. n.filters.reduce(((t, e) => zr(t, e))));
  7685. }
  7686. function zr(t, e) {
  7687. let n;
  7688. return L(t instanceof pn || t instanceof In), L(e instanceof pn || e instanceof In),
  7689. // FieldFilter FieldFilter
  7690. n = t instanceof pn ? e instanceof pn ? function(t, e) {
  7691. // Conjunction distribution for two field filters is the conjunction of them.
  7692. return In.create([ t, e ], "and" /* CompositeOperator.AND */);
  7693. }(t, e) : Wr(t, e) : e instanceof pn ? Wr(e, t) : function(t, e) {
  7694. // There are four cases:
  7695. // (A & B) & (C & D) --> (A & B & C & D)
  7696. // (A & B) & (C | D) --> (A & B & C) | (A & B & D)
  7697. // (A | B) & (C & D) --> (C & D & A) | (C & D & B)
  7698. // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)
  7699. // Case 1 is a merge.
  7700. if (L(t.filters.length > 0 && e.filters.length > 0), Tn(t) && Tn(e)) return bn(t, e.getFilters());
  7701. // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases
  7702. // we should take each element of the disjunction and distribute it over the other side, and
  7703. // return the disjunction of the distribution results.
  7704. const n = En(t) ? t : e, s = En(t) ? e : t, i = n.filters.map((t => zr(t, s)));
  7705. return In.create(i, "or" /* CompositeOperator.OR */);
  7706. }(t, e), Hr(n);
  7707. }
  7708. function Wr(t, e) {
  7709. // There are two cases:
  7710. // A & (B & C) --> (A & B & C)
  7711. // A & (B | C) --> (A & B) | (A & C)
  7712. if (Tn(e))
  7713. // Case 1
  7714. return bn(e, t.getFilters());
  7715. {
  7716. // Case 2
  7717. const n = e.filters.map((e => zr(t, e)));
  7718. return In.create(n, "or" /* CompositeOperator.OR */);
  7719. }
  7720. }
  7721. /**
  7722. * Applies the associativity property to the given filter and returns the resulting filter.
  7723. *
  7724. * <ul>
  7725. * <li>A | (B | C) == (A | B) | C == (A | B | C)
  7726. * <li>A & (B & C) == (A & B) & C == (A & B & C)
  7727. * </ul>
  7728. *
  7729. * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic
  7730. */ function Hr(t) {
  7731. if (L(t instanceof pn || t instanceof In), t instanceof pn) return t;
  7732. const e = t.getFilters();
  7733. // If the composite filter only contains 1 filter, apply associativity to it.
  7734. if (1 === e.length) return Hr(e[0]);
  7735. // Associativity applied to a flat composite filter results is itself.
  7736. if (vn(t)) return t;
  7737. // First apply associativity to all subfilters. This will in turn recursively apply
  7738. // associativity to all nested composite filters and field filters.
  7739. const n = e.map((t => Hr(t))), s = [];
  7740. // For composite subfilters that perform the same kind of logical operation as `compositeFilter`
  7741. // take out their filters and add them to `compositeFilter`. For example:
  7742. // compositeFilter = (A | (B | C | D))
  7743. // compositeSubfilter = (B | C | D)
  7744. // Result: (A | B | C | D)
  7745. // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been
  7746. // added to the top-level "compositeFilter".
  7747. return n.forEach((e => {
  7748. e instanceof pn ? s.push(e) : e instanceof In && (e.op === t.op ?
  7749. // compositeFilter: (A | (B | C))
  7750. // compositeSubfilter: (B | C)
  7751. // Result: (A | B | C)
  7752. s.push(...e.filters) :
  7753. // compositeFilter: (A | (B & C))
  7754. // compositeSubfilter: (B & C)
  7755. // Result: (A | (B & C))
  7756. s.push(e));
  7757. })), 1 === s.length ? s[0] : In.create(s, t.op);
  7758. }
  7759. /**
  7760. * @license
  7761. * Copyright 2019 Google LLC
  7762. *
  7763. * Licensed under the Apache License, Version 2.0 (the "License");
  7764. * you may not use this file except in compliance with the License.
  7765. * You may obtain a copy of the License at
  7766. *
  7767. * http://www.apache.org/licenses/LICENSE-2.0
  7768. *
  7769. * Unless required by applicable law or agreed to in writing, software
  7770. * distributed under the License is distributed on an "AS IS" BASIS,
  7771. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7772. * See the License for the specific language governing permissions and
  7773. * limitations under the License.
  7774. */
  7775. /**
  7776. * An in-memory implementation of IndexManager.
  7777. */ class Jr {
  7778. constructor() {
  7779. this.rn = new Yr;
  7780. }
  7781. addToCollectionParentIndex(t, e) {
  7782. return this.rn.add(e), bt.resolve();
  7783. }
  7784. getCollectionParents(t, e) {
  7785. return bt.resolve(this.rn.getEntries(e));
  7786. }
  7787. addFieldIndex(t, e) {
  7788. // Field indices are not supported with memory persistence.
  7789. return bt.resolve();
  7790. }
  7791. deleteFieldIndex(t, e) {
  7792. // Field indices are not supported with memory persistence.
  7793. return bt.resolve();
  7794. }
  7795. getDocumentsMatchingTarget(t, e) {
  7796. // Field indices are not supported with memory persistence.
  7797. return bt.resolve(null);
  7798. }
  7799. getIndexType(t, e) {
  7800. // Field indices are not supported with memory persistence.
  7801. return bt.resolve(0 /* IndexType.NONE */);
  7802. }
  7803. getFieldIndexes(t, e) {
  7804. // Field indices are not supported with memory persistence.
  7805. return bt.resolve([]);
  7806. }
  7807. getNextCollectionGroupToUpdate(t) {
  7808. // Field indices are not supported with memory persistence.
  7809. return bt.resolve(null);
  7810. }
  7811. getMinOffset(t, e) {
  7812. return bt.resolve(Et.min());
  7813. }
  7814. getMinOffsetFromCollectionGroup(t, e) {
  7815. return bt.resolve(Et.min());
  7816. }
  7817. updateCollectionGroup(t, e, n) {
  7818. // Field indices are not supported with memory persistence.
  7819. return bt.resolve();
  7820. }
  7821. updateIndexEntries(t, e) {
  7822. // Field indices are not supported with memory persistence.
  7823. return bt.resolve();
  7824. }
  7825. }
  7826. /**
  7827. * Internal implementation of the collection-parent index exposed by MemoryIndexManager.
  7828. * Also used for in-memory caching by IndexedDbIndexManager and initial index population
  7829. * in indexeddb_schema.ts
  7830. */ class Yr {
  7831. constructor() {
  7832. this.index = {};
  7833. }
  7834. // Returns false if the entry already existed.
  7835. add(t) {
  7836. const e = t.lastSegment(), n = t.popLast(), s = this.index[e] || new ve(at.comparator), i = !s.has(n);
  7837. return this.index[e] = s.add(n), i;
  7838. }
  7839. has(t) {
  7840. const e = t.lastSegment(), n = t.popLast(), s = this.index[e];
  7841. return s && s.has(n);
  7842. }
  7843. getEntries(t) {
  7844. return (this.index[t] || new ve(at.comparator)).toArray();
  7845. }
  7846. }
  7847. /**
  7848. * @license
  7849. * Copyright 2019 Google LLC
  7850. *
  7851. * Licensed under the Apache License, Version 2.0 (the "License");
  7852. * you may not use this file except in compliance with the License.
  7853. * You may obtain a copy of the License at
  7854. *
  7855. * http://www.apache.org/licenses/LICENSE-2.0
  7856. *
  7857. * Unless required by applicable law or agreed to in writing, software
  7858. * distributed under the License is distributed on an "AS IS" BASIS,
  7859. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7860. * See the License for the specific language governing permissions and
  7861. * limitations under the License.
  7862. */ const Xr = new Uint8Array(0);
  7863. /**
  7864. * A persisted implementation of IndexManager.
  7865. *
  7866. * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index
  7867. * data as it supports multi-tab access.
  7868. */
  7869. class Zr {
  7870. constructor(t, e) {
  7871. this.user = t, this.databaseId = e,
  7872. /**
  7873. * An in-memory copy of the index entries we've already written since the SDK
  7874. * launched. Used to avoid re-writing the same entry repeatedly.
  7875. *
  7876. * This is *NOT* a complete cache of what's in persistence and so can never be
  7877. * used to satisfy reads.
  7878. */
  7879. this.on = new Yr,
  7880. /**
  7881. * Maps from a target to its equivalent list of sub-targets. Each sub-target
  7882. * contains only one term from the target's disjunctive normal form (DNF).
  7883. */
  7884. this.un = new as((t => Bn(t)), ((t, e) => Ln(t, e))), this.uid = t.uid || "";
  7885. }
  7886. /**
  7887. * Adds a new entry to the collection parent index.
  7888. *
  7889. * Repeated calls for the same collectionPath should be avoided within a
  7890. * transaction as IndexedDbIndexManager only caches writes once a transaction
  7891. * has been committed.
  7892. */ addToCollectionParentIndex(t, e) {
  7893. if (!this.on.has(e)) {
  7894. const n = e.lastSegment(), s = e.popLast();
  7895. t.addOnCommittedListener((() => {
  7896. // Add the collection to the in memory cache only if the transaction was
  7897. // successfully committed.
  7898. this.on.add(e);
  7899. }));
  7900. const i = {
  7901. collectionId: n,
  7902. parent: Kt(s)
  7903. };
  7904. return to(t).put(i);
  7905. }
  7906. return bt.resolve();
  7907. }
  7908. getCollectionParents(t, e) {
  7909. const n = [], s = IDBKeyRange.bound([ e, "" ], [ rt(e), "" ],
  7910. /*lowerOpen=*/ !1,
  7911. /*upperOpen=*/ !0);
  7912. return to(t).j(s).next((t => {
  7913. for (const s of t) {
  7914. // This collectionId guard shouldn't be necessary (and isn't as long
  7915. // as we're running in a real browser), but there's a bug in
  7916. // indexeddbshim that breaks our range in our tests running in node:
  7917. // https://github.com/axemclion/IndexedDBShim/issues/334
  7918. if (s.collectionId !== e) break;
  7919. n.push(jt(s.parent));
  7920. }
  7921. return n;
  7922. }));
  7923. }
  7924. addFieldIndex(t, e) {
  7925. // TODO(indexing): Verify that the auto-incrementing index ID works in
  7926. // Safari & Firefox.
  7927. const n = no(t), s = function(t) {
  7928. return {
  7929. indexId: t.indexId,
  7930. collectionGroup: t.collectionGroup,
  7931. fields: t.fields.map((t => [ t.fieldPath.canonicalString(), t.kind ]))
  7932. };
  7933. }(e);
  7934. delete s.indexId;
  7935. // `indexId` is auto-populated by IndexedDb
  7936. const i = n.add(s);
  7937. if (e.indexState) {
  7938. const n = so(t);
  7939. return i.next((t => {
  7940. n.put(vr(t, this.user, e.indexState.sequenceNumber, e.indexState.offset));
  7941. }));
  7942. }
  7943. return i.next();
  7944. }
  7945. deleteFieldIndex(t, e) {
  7946. const n = no(t), s = so(t), i = eo(t);
  7947. return n.delete(e.indexId).next((() => s.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7948. /*lowerOpen=*/ !1,
  7949. /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7950. /*lowerOpen=*/ !1,
  7951. /*upperOpen=*/ !0))));
  7952. }
  7953. getDocumentsMatchingTarget(t, e) {
  7954. const n = eo(t);
  7955. let s = !0;
  7956. const i = new Map;
  7957. return bt.forEach(this.cn(e), (e => this.an(t, e).next((t => {
  7958. s && (s = !!t), i.set(e, t);
  7959. })))).next((() => {
  7960. if (s) {
  7961. let t = Is();
  7962. const s = [];
  7963. return bt.forEach(i, ((i, r) => {
  7964. var o;
  7965. $("IndexedDbIndexManager", `Using index ${o = i, `id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map((t => `${t.fieldPath}:${t.kind}`)).join(",")}`} to execute ${Bn(e)}`);
  7966. const u = function(t, e) {
  7967. const n = wt(e);
  7968. if (void 0 === n) return null;
  7969. for (const e of Un(t, n.fieldPath)) switch (e.op) {
  7970. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  7971. return e.value.arrayValue.values || [];
  7972. case "array-contains" /* Operator.ARRAY_CONTAINS */ :
  7973. return [ e.value ];
  7974. // Remaining filters are not array filters.
  7975. }
  7976. return null;
  7977. }
  7978. /**
  7979. * Returns the list of values that are used in != or NOT_IN filters. Returns
  7980. * `null` if there are no such filters.
  7981. */ (r, i), c = function(t, e) {
  7982. const n = new Map;
  7983. for (const s of _t(e)) for (const e of Un(t, s.fieldPath)) switch (e.op) {
  7984. case "==" /* Operator.EQUAL */ :
  7985. case "in" /* Operator.IN */ :
  7986. // Encode equality prefix, which is encoded in the index value before
  7987. // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
  7988. // `value != 'ab'`).
  7989. n.set(s.fieldPath.canonicalString(), e.value);
  7990. break;
  7991. case "not-in" /* Operator.NOT_IN */ :
  7992. case "!=" /* Operator.NOT_EQUAL */ :
  7993. // NotIn/NotEqual is always a suffix. There cannot be any remaining
  7994. // segments and hence we can return early here.
  7995. return n.set(s.fieldPath.canonicalString(), e.value), Array.from(n.values());
  7996. // Remaining filters cannot be used as notIn bounds.
  7997. }
  7998. return null;
  7999. }
  8000. /**
  8001. * Returns a lower bound of field values that can be used as a starting point to
  8002. * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound
  8003. * exists.
  8004. */ (r, i), a = function(t, e) {
  8005. const n = [];
  8006. let s = !0;
  8007. // For each segment, retrieve a lower bound if there is a suitable filter or
  8008. // startAt.
  8009. for (const i of _t(e)) {
  8010. const e = 0 /* IndexKind.ASCENDING */ === i.kind ? Kn(t, i.fieldPath, t.startAt) : Gn(t, i.fieldPath, t.startAt);
  8011. n.push(e.value), s && (s = e.inclusive);
  8012. }
  8013. return new dn(n, s);
  8014. }
  8015. /**
  8016. * Returns an upper bound of field values that can be used as an ending point
  8017. * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no
  8018. * upper bound exists.
  8019. */ (r, i), h = function(t, e) {
  8020. const n = [];
  8021. let s = !0;
  8022. // For each segment, retrieve an upper bound if there is a suitable filter or
  8023. // endAt.
  8024. for (const i of _t(e)) {
  8025. const e = 0 /* IndexKind.ASCENDING */ === i.kind ? Gn(t, i.fieldPath, t.endAt) : Kn(t, i.fieldPath, t.endAt);
  8026. n.push(e.value), s && (s = e.inclusive);
  8027. }
  8028. return new dn(n, s);
  8029. }(r, i), l = this.hn(i, r, a), f = this.hn(i, r, h), d = this.ln(i, r, c), w = this.fn(i.indexId, u, l, a.inclusive, f, h.inclusive, d);
  8030. return bt.forEach(w, (i => n.H(i, e.limit).next((e => {
  8031. e.forEach((e => {
  8032. const n = ft.fromSegments(e.documentKey);
  8033. t.has(n) || (t = t.add(n), s.push(n));
  8034. }));
  8035. }))));
  8036. })).next((() => s));
  8037. }
  8038. return bt.resolve(null);
  8039. }));
  8040. }
  8041. cn(t) {
  8042. let e = this.un.get(t);
  8043. if (e) return e;
  8044. if (0 === t.filters.length) e = [ t ]; else {
  8045. e = Ur(In.create(t.filters, "and" /* CompositeOperator.AND */)).map((e => Fn(t.path, t.collectionGroup, t.orderBy, e.getFilters(), t.limit, t.startAt, t.endAt)));
  8046. }
  8047. return this.un.set(t, e), e;
  8048. }
  8049. /**
  8050. * Constructs a key range query on `DbIndexEntryStore` that unions all
  8051. * bounds.
  8052. */ fn(t, e, n, s, i, r, o) {
  8053. // The number of total index scans we union together. This is similar to a
  8054. // distributed normal form, but adapted for array values. We create a single
  8055. // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter
  8056. // combined with the values from the query bounds.
  8057. const u = (null != e ? e.length : 1) * Math.max(n.length, i.length), c = u / (null != e ? e.length : 1), a = [];
  8058. for (let h = 0; h < u; ++h) {
  8059. const u = e ? this.dn(e[h / c]) : Xr, l = this.wn(t, u, n[h % c], s), f = this._n(t, u, i[h % c], r), d = o.map((e => this.wn(t, u, e,
  8060. /* inclusive= */ !0)));
  8061. a.push(...this.createRange(l, f, d));
  8062. }
  8063. return a;
  8064. }
  8065. /** Generates the lower bound for `arrayValue` and `directionalValue`. */ wn(t, e, n, s) {
  8066. const i = new Or(t, ft.empty(), e, n);
  8067. return s ? i : i.Je();
  8068. }
  8069. /** Generates the upper bound for `arrayValue` and `directionalValue`. */ _n(t, e, n, s) {
  8070. const i = new Or(t, ft.empty(), e, n);
  8071. return s ? i.Je() : i;
  8072. }
  8073. an(t, e) {
  8074. const n = new Lr(e), s = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment();
  8075. return this.getFieldIndexes(t, s).next((t => {
  8076. // Return the index with the most number of segments.
  8077. let e = null;
  8078. for (const s of t) {
  8079. n.tn(s) && (!e || s.fields.length > e.fields.length) && (e = s);
  8080. }
  8081. return e;
  8082. }));
  8083. }
  8084. getIndexType(t, e) {
  8085. let n = 2 /* IndexType.FULL */;
  8086. const s = this.cn(e);
  8087. return bt.forEach(s, (e => this.an(t, e).next((t => {
  8088. t ? 0 /* IndexType.NONE */ !== n && t.fields.length < function(t) {
  8089. let e = new ve(lt.comparator), n = !1;
  8090. for (const s of t.filters) for (const t of s.getFlattenedFilters())
  8091. // __name__ is not an explicit segment of any index, so we don't need to
  8092. // count it.
  8093. t.field.isKeyField() || (
  8094. // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
  8095. // For instance, it is possible to have an index for "a ARRAY a ASC". Even
  8096. // though these are on the same field, they should be counted as two
  8097. // separate segments in an index.
  8098. "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op ? n = !0 : e = e.add(t.field));
  8099. for (const n of t.orderBy)
  8100. // __name__ is not an explicit segment of any index, so we don't need to
  8101. // count it.
  8102. n.field.isKeyField() || (e = e.add(n.field));
  8103. return e.size + (n ? 1 : 0);
  8104. }(e) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;
  8105. })))).next((() =>
  8106. // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider
  8107. // OR queries that have a `limit` to have a partial index. For such queries we perform sorting
  8108. // and apply the limit in memory as a post-processing step.
  8109. function(t) {
  8110. return null !== t.limit;
  8111. }(e) && s.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));
  8112. }
  8113. /**
  8114. * Returns the byte encoded form of the directional values in the field index.
  8115. * Returns `null` if the document does not have all fields specified in the
  8116. * index.
  8117. */ mn(t, e) {
  8118. const n = new Mr;
  8119. for (const s of _t(t)) {
  8120. const t = e.data.field(s.fieldPath);
  8121. if (null == t) return null;
  8122. const i = n.He(s.kind);
  8123. Dr.Ve._e(t, i);
  8124. }
  8125. return n.Qe();
  8126. }
  8127. /** Encodes a single value to the ascending index format. */ dn(t) {
  8128. const e = new Mr;
  8129. return Dr.Ve._e(t, e.He(0 /* IndexKind.ASCENDING */)), e.Qe();
  8130. }
  8131. /**
  8132. * Returns an encoded form of the document key that sorts based on the key
  8133. * ordering of the field index.
  8134. */ gn(t, e) {
  8135. const n = new Mr;
  8136. return Dr.Ve._e(Ye(this.databaseId, e), n.He(function(t) {
  8137. const e = _t(t);
  8138. return 0 === e.length ? 0 /* IndexKind.ASCENDING */ : e[e.length - 1].kind;
  8139. }(t))), n.Qe();
  8140. }
  8141. /**
  8142. * Encodes the given field values according to the specification in `target`.
  8143. * For IN queries, a list of possible values is returned.
  8144. */ ln(t, e, n) {
  8145. if (null === n) return [];
  8146. let s = [];
  8147. s.push(new Mr);
  8148. let i = 0;
  8149. for (const r of _t(t)) {
  8150. const t = n[i++];
  8151. for (const n of s) if (this.yn(e, r.fieldPath) && Ze(t)) s = this.pn(s, r, t); else {
  8152. const e = n.He(r.kind);
  8153. Dr.Ve._e(t, e);
  8154. }
  8155. }
  8156. return this.In(s);
  8157. }
  8158. /**
  8159. * Encodes the given bounds according to the specification in `target`. For IN
  8160. * queries, a list of possible values is returned.
  8161. */ hn(t, e, n) {
  8162. return this.ln(t, e, n.position);
  8163. }
  8164. /** Returns the byte representation for the provided encoders. */ In(t) {
  8165. const e = [];
  8166. for (let n = 0; n < t.length; ++n) e[n] = t[n].Qe();
  8167. return e;
  8168. }
  8169. /**
  8170. * Creates a separate encoder for each element of an array.
  8171. *
  8172. * The method appends each value to all existing encoders (e.g. filter("a",
  8173. * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A
  8174. * list of new encoders is returned.
  8175. */ pn(t, e, n) {
  8176. const s = [ ...t ], i = [];
  8177. for (const t of n.arrayValue.values || []) for (const n of s) {
  8178. const s = new Mr;
  8179. s.seed(n.Qe()), Dr.Ve._e(t, s.He(e.kind)), i.push(s);
  8180. }
  8181. return i;
  8182. }
  8183. yn(t, e) {
  8184. return !!t.filters.find((t => t instanceof pn && t.field.isEqual(e) && ("in" /* Operator.IN */ === t.op || "not-in" /* Operator.NOT_IN */ === t.op)));
  8185. }
  8186. getFieldIndexes(t, e) {
  8187. const n = no(t), s = so(t);
  8188. return (e ? n.j("collectionGroupIndex", IDBKeyRange.bound(e, e)) : n.j()).next((t => {
  8189. const e = [];
  8190. return bt.forEach(t, (t => s.get([ t.indexId, this.uid ]).next((n => {
  8191. e.push(function(t, e) {
  8192. const n = e ? new pt(e.sequenceNumber, new Et(gr(e.readTime), new ft(jt(e.documentKey)), e.largestBatchId)) : pt.empty(), s = t.fields.map((([t, e]) => new gt(lt.fromServerFormat(t), e)));
  8193. return new dt(t.indexId, t.collectionGroup, s, n);
  8194. }(t, n));
  8195. })))).next((() => e));
  8196. }));
  8197. }
  8198. getNextCollectionGroupToUpdate(t) {
  8199. return this.getFieldIndexes(t).next((t => 0 === t.length ? null : (t.sort(((t, e) => {
  8200. const n = t.indexState.sequenceNumber - e.indexState.sequenceNumber;
  8201. return 0 !== n ? n : st(t.collectionGroup, e.collectionGroup);
  8202. })), t[0].collectionGroup)));
  8203. }
  8204. updateCollectionGroup(t, e, n) {
  8205. const s = no(t), i = so(t);
  8206. return this.Tn(t).next((t => s.j("collectionGroupIndex", IDBKeyRange.bound(e, e)).next((e => bt.forEach(e, (e => i.put(vr(e.indexId, this.user, t, n))))))));
  8207. }
  8208. updateIndexEntries(t, e) {
  8209. // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as
  8210. // it could be used across different IndexedDB transactions. As any cached
  8211. // data might be invalidated by other multi-tab clients, we can only trust
  8212. // data within a single IndexedDB transaction. We therefore add a cache
  8213. // here.
  8214. const n = new Map;
  8215. return bt.forEach(e, ((e, s) => {
  8216. const i = n.get(e.collectionGroup);
  8217. return (i ? bt.resolve(i) : this.getFieldIndexes(t, e.collectionGroup)).next((i => (n.set(e.collectionGroup, i),
  8218. bt.forEach(i, (n => this.En(t, e, n).next((e => {
  8219. const i = this.An(s, n);
  8220. return e.isEqual(i) ? bt.resolve() : this.vn(t, s, n, e, i);
  8221. })))))));
  8222. }));
  8223. }
  8224. Rn(t, e, n, s) {
  8225. return eo(t).put({
  8226. indexId: s.indexId,
  8227. uid: this.uid,
  8228. arrayValue: s.arrayValue,
  8229. directionalValue: s.directionalValue,
  8230. orderedDocumentKey: this.gn(n, e.key),
  8231. documentKey: e.key.path.toArray()
  8232. });
  8233. }
  8234. Pn(t, e, n, s) {
  8235. return eo(t).delete([ s.indexId, this.uid, s.arrayValue, s.directionalValue, this.gn(n, e.key), e.key.path.toArray() ]);
  8236. }
  8237. En(t, e, n) {
  8238. const s = eo(t);
  8239. let i = new ve(Fr);
  8240. return s.X({
  8241. index: "documentKeyIndex",
  8242. range: IDBKeyRange.only([ n.indexId, this.uid, this.gn(n, e) ])
  8243. }, ((t, s) => {
  8244. i = i.add(new Or(n.indexId, e, s.arrayValue, s.directionalValue));
  8245. })).next((() => i));
  8246. }
  8247. /** Creates the index entries for the given document. */ An(t, e) {
  8248. let n = new ve(Fr);
  8249. const s = this.mn(e, t);
  8250. if (null == s) return n;
  8251. const i = wt(e);
  8252. if (null != i) {
  8253. const r = t.data.field(i.fieldPath);
  8254. if (Ze(r)) for (const i of r.arrayValue.values || []) n = n.add(new Or(e.indexId, t.key, this.dn(i), s));
  8255. } else n = n.add(new Or(e.indexId, t.key, Xr, s));
  8256. return n;
  8257. }
  8258. /**
  8259. * Updates the index entries for the provided document by deleting entries
  8260. * that are no longer referenced in `newEntries` and adding all newly added
  8261. * entries.
  8262. */ vn(t, e, n, s, i) {
  8263. $("IndexedDbIndexManager", "Updating index entries for document '%s'", e.key);
  8264. const r = [];
  8265. return function(t, e, n, s, i) {
  8266. const r = t.getIterator(), o = e.getIterator();
  8267. let u = Pe(r), c = Pe(o);
  8268. // Walk through the two sets at the same time, using the ordering defined by
  8269. // `comparator`.
  8270. for (;u || c; ) {
  8271. let t = !1, e = !1;
  8272. if (u && c) {
  8273. const s = n(u, c);
  8274. s < 0 ?
  8275. // The element was removed if the next element in our ordered
  8276. // walkthrough is only in `before`.
  8277. e = !0 : s > 0 && (
  8278. // The element was added if the next element in our ordered walkthrough
  8279. // is only in `after`.
  8280. t = !0);
  8281. } else null != u ? e = !0 : t = !0;
  8282. t ? (s(c), c = Pe(o)) : e ? (i(u), u = Pe(r)) : (u = Pe(r), c = Pe(o));
  8283. }
  8284. }(s, i, Fr, (
  8285. /* onAdd= */ s => {
  8286. r.push(this.Rn(t, e, n, s));
  8287. }), (
  8288. /* onRemove= */ s => {
  8289. r.push(this.Pn(t, e, n, s));
  8290. })), bt.waitFor(r);
  8291. }
  8292. Tn(t) {
  8293. let e = 1;
  8294. return so(t).X({
  8295. index: "sequenceNumberIndex",
  8296. reverse: !0,
  8297. range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])
  8298. }, ((t, n, s) => {
  8299. s.done(), e = n.sequenceNumber + 1;
  8300. })).next((() => e));
  8301. }
  8302. /**
  8303. * Returns a new set of IDB ranges that splits the existing range and excludes
  8304. * any values that match the `notInValue` from these ranges. As an example,
  8305. * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.
  8306. */ createRange(t, e, n) {
  8307. // The notIn values need to be sorted and unique so that we can return a
  8308. // sorted set of non-overlapping ranges.
  8309. n = n.sort(((t, e) => Fr(t, e))).filter(((t, e, n) => !e || 0 !== Fr(t, n[e - 1])));
  8310. const s = [];
  8311. s.push(t);
  8312. for (const i of n) {
  8313. const n = Fr(i, t), r = Fr(i, e);
  8314. if (0 === n)
  8315. // `notInValue` is the lower bound. We therefore need to raise the bound
  8316. // to the next value.
  8317. s[0] = t.Je(); else if (n > 0 && r < 0)
  8318. // `notInValue` is in the middle of the range
  8319. s.push(i), s.push(i.Je()); else if (r > 0)
  8320. // `notInValue` (and all following values) are out of the range
  8321. break;
  8322. }
  8323. s.push(e);
  8324. const i = [];
  8325. for (let t = 0; t < s.length; t += 2) {
  8326. // If we encounter two bounds that will create an unmatchable key range,
  8327. // then we return an empty set of key ranges.
  8328. if (this.bn(s[t], s[t + 1])) return [];
  8329. const e = [ s[t].indexId, this.uid, s[t].arrayValue, s[t].directionalValue, Xr, [] ], n = [ s[t + 1].indexId, this.uid, s[t + 1].arrayValue, s[t + 1].directionalValue, Xr, [] ];
  8330. i.push(IDBKeyRange.bound(e, n));
  8331. }
  8332. return i;
  8333. }
  8334. bn(t, e) {
  8335. // If lower bound is greater than the upper bound, then the key
  8336. // range can never be matched.
  8337. return Fr(t, e) > 0;
  8338. }
  8339. getMinOffsetFromCollectionGroup(t, e) {
  8340. return this.getFieldIndexes(t, e).next(io);
  8341. }
  8342. getMinOffset(t, e) {
  8343. return bt.mapArray(this.cn(e), (e => this.an(t, e).next((t => t || B())))).next(io);
  8344. }
  8345. }
  8346. /**
  8347. * Helper to get a typed SimpleDbStore for the collectionParents
  8348. * document store.
  8349. */ function to(t) {
  8350. return ge(t, "collectionParents");
  8351. }
  8352. /**
  8353. * Helper to get a typed SimpleDbStore for the index entry object store.
  8354. */ function eo(t) {
  8355. return ge(t, "indexEntries");
  8356. }
  8357. /**
  8358. * Helper to get a typed SimpleDbStore for the index configuration object store.
  8359. */ function no(t) {
  8360. return ge(t, "indexConfiguration");
  8361. }
  8362. /**
  8363. * Helper to get a typed SimpleDbStore for the index state object store.
  8364. */ function so(t) {
  8365. return ge(t, "indexState");
  8366. }
  8367. function io(t) {
  8368. L(0 !== t.length);
  8369. let e = t[0].indexState.offset, n = e.largestBatchId;
  8370. for (let s = 1; s < t.length; s++) {
  8371. const i = t[s].indexState.offset;
  8372. At(i, e) < 0 && (e = i), n < i.largestBatchId && (n = i.largestBatchId);
  8373. }
  8374. return new Et(e.readTime, e.documentKey, n);
  8375. }
  8376. /**
  8377. * @license
  8378. * Copyright 2018 Google LLC
  8379. *
  8380. * Licensed under the Apache License, Version 2.0 (the "License");
  8381. * you may not use this file except in compliance with the License.
  8382. * You may obtain a copy of the License at
  8383. *
  8384. * http://www.apache.org/licenses/LICENSE-2.0
  8385. *
  8386. * Unless required by applicable law or agreed to in writing, software
  8387. * distributed under the License is distributed on an "AS IS" BASIS,
  8388. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8389. * See the License for the specific language governing permissions and
  8390. * limitations under the License.
  8391. */ const ro = {
  8392. didRun: !1,
  8393. sequenceNumbersCollected: 0,
  8394. targetsRemoved: 0,
  8395. documentsRemoved: 0
  8396. };
  8397. class oo {
  8398. constructor(
  8399. // When we attempt to collect, we will only do so if the cache size is greater than this
  8400. // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.
  8401. t,
  8402. // The percentage of sequence numbers that we will attempt to collect
  8403. e,
  8404. // A cap on the total number of sequence numbers that will be collected. This prevents
  8405. // us from collecting a huge number of sequence numbers if the cache has grown very large.
  8406. n) {
  8407. this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;
  8408. }
  8409. static withCacheSize(t) {
  8410. return new oo(t, oo.DEFAULT_COLLECTION_PERCENTILE, oo.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);
  8411. }
  8412. }
  8413. /**
  8414. * @license
  8415. * Copyright 2020 Google LLC
  8416. *
  8417. * Licensed under the Apache License, Version 2.0 (the "License");
  8418. * you may not use this file except in compliance with the License.
  8419. * You may obtain a copy of the License at
  8420. *
  8421. * http://www.apache.org/licenses/LICENSE-2.0
  8422. *
  8423. * Unless required by applicable law or agreed to in writing, software
  8424. * distributed under the License is distributed on an "AS IS" BASIS,
  8425. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8426. * See the License for the specific language governing permissions and
  8427. * limitations under the License.
  8428. */
  8429. /**
  8430. * Delete a mutation batch and the associated document mutations.
  8431. * @returns A PersistencePromise of the document mutations that were removed.
  8432. */
  8433. function uo(t, e, n) {
  8434. const s = t.store("mutations"), i = t.store("documentMutations"), r = [], o = IDBKeyRange.only(n.batchId);
  8435. let u = 0;
  8436. const c = s.X({
  8437. range: o
  8438. }, ((t, e, n) => (u++, n.delete())));
  8439. r.push(c.next((() => {
  8440. L(1 === u);
  8441. })));
  8442. const a = [];
  8443. for (const t of n.mutations) {
  8444. const s = Ht(e, t.key.path, n.batchId);
  8445. r.push(i.delete(s)), a.push(t.key);
  8446. }
  8447. return bt.waitFor(r).next((() => a));
  8448. }
  8449. /**
  8450. * Returns an approximate size for the given document.
  8451. */ function co(t) {
  8452. if (!t) return 0;
  8453. let e;
  8454. if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {
  8455. if (!t.noDocument) throw B();
  8456. e = t.noDocument;
  8457. }
  8458. return JSON.stringify(e).length;
  8459. }
  8460. /**
  8461. * @license
  8462. * Copyright 2017 Google LLC
  8463. *
  8464. * Licensed under the Apache License, Version 2.0 (the "License");
  8465. * you may not use this file except in compliance with the License.
  8466. * You may obtain a copy of the License at
  8467. *
  8468. * http://www.apache.org/licenses/LICENSE-2.0
  8469. *
  8470. * Unless required by applicable law or agreed to in writing, software
  8471. * distributed under the License is distributed on an "AS IS" BASIS,
  8472. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8473. * See the License for the specific language governing permissions and
  8474. * limitations under the License.
  8475. */
  8476. /** A mutation queue for a specific user, backed by IndexedDB. */ oo.DEFAULT_COLLECTION_PERCENTILE = 10,
  8477. oo.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, oo.DEFAULT = new oo(41943040, oo.DEFAULT_COLLECTION_PERCENTILE, oo.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),
  8478. oo.DISABLED = new oo(-1, 0, 0);
  8479. class ao {
  8480. constructor(
  8481. /**
  8482. * The normalized userId (e.g. null UID => "" userId) used to store /
  8483. * retrieve mutations.
  8484. */
  8485. t, e, n, s) {
  8486. this.userId = t, this.serializer = e, this.indexManager = n, this.referenceDelegate = s,
  8487. /**
  8488. * Caches the document keys for pending mutation batches. If the mutation
  8489. * has been removed from IndexedDb, the cached value may continue to
  8490. * be used to retrieve the batch's document keys. To remove a cached value
  8491. * locally, `removeCachedMutationKeys()` should be invoked either directly
  8492. * or through `removeMutationBatches()`.
  8493. *
  8494. * With multi-tab, when the primary client acknowledges or rejects a mutation,
  8495. * this cache is used by secondary clients to invalidate the local
  8496. * view of the documents that were previously affected by the mutation.
  8497. */
  8498. // PORTING NOTE: Multi-tab only.
  8499. this.Vn = {};
  8500. }
  8501. /**
  8502. * Creates a new mutation queue for the given user.
  8503. * @param user - The user for which to create a mutation queue.
  8504. * @param serializer - The serializer to use when persisting to IndexedDb.
  8505. */ static de(t, e, n, s) {
  8506. // TODO(mcg): Figure out what constraints there are on userIDs
  8507. // In particular, are there any reserved characters? are empty ids allowed?
  8508. // For the moment store these together in the same mutations table assuming
  8509. // that empty userIDs aren't allowed.
  8510. L("" !== t.uid);
  8511. const i = t.isAuthenticated() ? t.uid : "";
  8512. return new ao(i, e, n, s);
  8513. }
  8514. checkEmpty(t) {
  8515. let e = !0;
  8516. const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8517. return lo(t).X({
  8518. index: "userMutationsIndex",
  8519. range: n
  8520. }, ((t, n, s) => {
  8521. e = !1, s.done();
  8522. })).next((() => e));
  8523. }
  8524. addMutationBatch(t, e, n, s) {
  8525. const i = fo(t), r = lo(t);
  8526. // The IndexedDb implementation in Chrome (and Firefox) does not handle
  8527. // compound indices that include auto-generated keys correctly. To ensure
  8528. // that the index entry is added correctly in all browsers, we perform two
  8529. // writes: The first write is used to retrieve the next auto-generated Batch
  8530. // ID, and the second write populates the index and stores the actual
  8531. // mutation batch.
  8532. // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972
  8533. // We write an empty object to obtain key
  8534. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8535. return r.add({}).next((o => {
  8536. L("number" == typeof o);
  8537. const u = new ni(o, e, n, s), c = function(t, e, n) {
  8538. const s = n.baseMutations.map((e => Hi(t.fe, e))), i = n.mutations.map((e => Hi(t.fe, e)));
  8539. return {
  8540. userId: e,
  8541. batchId: n.batchId,
  8542. localWriteTimeMs: n.localWriteTime.toMillis(),
  8543. baseMutations: s,
  8544. mutations: i
  8545. };
  8546. }(this.serializer, this.userId, u), a = [];
  8547. let h = new ve(((t, e) => st(t.canonicalString(), e.canonicalString())));
  8548. for (const t of s) {
  8549. const e = Ht(this.userId, t.key.path, o);
  8550. h = h.add(t.key.path.popLast()), a.push(r.put(c)), a.push(i.put(e, Jt));
  8551. }
  8552. return h.forEach((e => {
  8553. a.push(this.indexManager.addToCollectionParentIndex(t, e));
  8554. })), t.addOnCommittedListener((() => {
  8555. this.Vn[o] = u.keys();
  8556. })), bt.waitFor(a).next((() => u));
  8557. }));
  8558. }
  8559. lookupMutationBatch(t, e) {
  8560. return lo(t).get(e).next((t => t ? (L(t.userId === this.userId), yr(this.serializer, t)) : null));
  8561. }
  8562. /**
  8563. * Returns the document keys for the mutation batch with the given batchId.
  8564. * For primary clients, this method returns `null` after
  8565. * `removeMutationBatches()` has been called. Secondary clients return a
  8566. * cached result until `removeCachedMutationKeys()` is invoked.
  8567. */
  8568. // PORTING NOTE: Multi-tab only.
  8569. Sn(t, e) {
  8570. return this.Vn[e] ? bt.resolve(this.Vn[e]) : this.lookupMutationBatch(t, e).next((t => {
  8571. if (t) {
  8572. const n = t.keys();
  8573. return this.Vn[e] = n, n;
  8574. }
  8575. return null;
  8576. }));
  8577. }
  8578. getNextMutationBatchAfterBatchId(t, e) {
  8579. const n = e + 1, s = IDBKeyRange.lowerBound([ this.userId, n ]);
  8580. let i = null;
  8581. return lo(t).X({
  8582. index: "userMutationsIndex",
  8583. range: s
  8584. }, ((t, e, s) => {
  8585. e.userId === this.userId && (L(e.batchId >= n), i = yr(this.serializer, e)), s.done();
  8586. })).next((() => i));
  8587. }
  8588. getHighestUnacknowledgedBatchId(t) {
  8589. const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);
  8590. let n = -1;
  8591. return lo(t).X({
  8592. index: "userMutationsIndex",
  8593. range: e,
  8594. reverse: !0
  8595. }, ((t, e, s) => {
  8596. n = e.batchId, s.done();
  8597. })).next((() => n));
  8598. }
  8599. getAllMutationBatches(t) {
  8600. const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8601. return lo(t).j("userMutationsIndex", e).next((t => t.map((t => yr(this.serializer, t)))));
  8602. }
  8603. getAllMutationBatchesAffectingDocumentKey(t, e) {
  8604. // Scan the document-mutation index starting with a prefix starting with
  8605. // the given documentKey.
  8606. const n = Wt(this.userId, e.path), s = IDBKeyRange.lowerBound(n), i = [];
  8607. return fo(t).X({
  8608. range: s
  8609. }, ((n, s, r) => {
  8610. const [o, u, c] = n, a = jt(u);
  8611. // Only consider rows matching exactly the specific key of
  8612. // interest. Note that because we order by path first, and we
  8613. // order terminators before path separators, we'll encounter all
  8614. // the index rows for documentKey contiguously. In particular, all
  8615. // the rows for documentKey will occur before any rows for
  8616. // documents nested in a subcollection beneath documentKey so we
  8617. // can stop as soon as we hit any such row.
  8618. if (o === this.userId && e.path.isEqual(a))
  8619. // Look up the mutation batch in the store.
  8620. return lo(t).get(c).next((t => {
  8621. if (!t) throw B();
  8622. L(t.userId === this.userId), i.push(yr(this.serializer, t));
  8623. }));
  8624. r.done();
  8625. })).next((() => i));
  8626. }
  8627. getAllMutationBatchesAffectingDocumentKeys(t, e) {
  8628. let n = new ve(st);
  8629. const s = [];
  8630. return e.forEach((e => {
  8631. const i = Wt(this.userId, e.path), r = IDBKeyRange.lowerBound(i), o = fo(t).X({
  8632. range: r
  8633. }, ((t, s, i) => {
  8634. const [r, o, u] = t, c = jt(o);
  8635. // Only consider rows matching exactly the specific key of
  8636. // interest. Note that because we order by path first, and we
  8637. // order terminators before path separators, we'll encounter all
  8638. // the index rows for documentKey contiguously. In particular, all
  8639. // the rows for documentKey will occur before any rows for
  8640. // documents nested in a subcollection beneath documentKey so we
  8641. // can stop as soon as we hit any such row.
  8642. r === this.userId && e.path.isEqual(c) ? n = n.add(u) : i.done();
  8643. }));
  8644. s.push(o);
  8645. })), bt.waitFor(s).next((() => this.Dn(t, n)));
  8646. }
  8647. getAllMutationBatchesAffectingQuery(t, e) {
  8648. const n = e.path, s = n.length + 1, i = Wt(this.userId, n), r = IDBKeyRange.lowerBound(i);
  8649. // Collect up unique batchIDs encountered during a scan of the index. Use a
  8650. // SortedSet to accumulate batch IDs so they can be traversed in order in a
  8651. // scan of the main table.
  8652. let o = new ve(st);
  8653. return fo(t).X({
  8654. range: r
  8655. }, ((t, e, i) => {
  8656. const [r, u, c] = t, a = jt(u);
  8657. r === this.userId && n.isPrefixOf(a) ?
  8658. // Rows with document keys more than one segment longer than the
  8659. // query path can't be matches. For example, a query on 'rooms'
  8660. // can't match the document /rooms/abc/messages/xyx.
  8661. // TODO(mcg): we'll need a different scanner when we implement
  8662. // ancestor queries.
  8663. a.length === s && (o = o.add(c)) : i.done();
  8664. })).next((() => this.Dn(t, o)));
  8665. }
  8666. Dn(t, e) {
  8667. const n = [], s = [];
  8668. // TODO(rockwood): Implement this using iterate.
  8669. return e.forEach((e => {
  8670. s.push(lo(t).get(e).next((t => {
  8671. if (null === t) throw B();
  8672. L(t.userId === this.userId), n.push(yr(this.serializer, t));
  8673. })));
  8674. })), bt.waitFor(s).next((() => n));
  8675. }
  8676. removeMutationBatch(t, e) {
  8677. return uo(t.ht, this.userId, e).next((n => (t.addOnCommittedListener((() => {
  8678. this.Cn(e.batchId);
  8679. })), bt.forEach(n, (e => this.referenceDelegate.markPotentiallyOrphaned(t, e))))));
  8680. }
  8681. /**
  8682. * Clears the cached keys for a mutation batch. This method should be
  8683. * called by secondary clients after they process mutation updates.
  8684. *
  8685. * Note that this method does not have to be called from primary clients as
  8686. * the corresponding cache entries are cleared when an acknowledged or
  8687. * rejected batch is removed from the mutation queue.
  8688. */
  8689. // PORTING NOTE: Multi-tab only
  8690. Cn(t) {
  8691. delete this.Vn[t];
  8692. }
  8693. performConsistencyCheck(t) {
  8694. return this.checkEmpty(t).next((e => {
  8695. if (!e) return bt.resolve();
  8696. // Verify that there are no entries in the documentMutations index if
  8697. // the queue is empty.
  8698. const n = IDBKeyRange.lowerBound([ this.userId ]);
  8699. const s = [];
  8700. return fo(t).X({
  8701. range: n
  8702. }, ((t, e, n) => {
  8703. if (t[0] === this.userId) {
  8704. const e = jt(t[1]);
  8705. s.push(e);
  8706. } else n.done();
  8707. })).next((() => {
  8708. L(0 === s.length);
  8709. }));
  8710. }));
  8711. }
  8712. containsKey(t, e) {
  8713. return ho(t, this.userId, e);
  8714. }
  8715. // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
  8716. /** Returns the mutation queue's metadata from IndexedDb. */
  8717. xn(t) {
  8718. return wo(t).get(this.userId).next((t => t || {
  8719. userId: this.userId,
  8720. lastAcknowledgedBatchId: -1,
  8721. lastStreamToken: ""
  8722. }));
  8723. }
  8724. }
  8725. /**
  8726. * @returns true if the mutation queue for the given user contains a pending
  8727. * mutation for the given key.
  8728. */ function ho(t, e, n) {
  8729. const s = Wt(e, n.path), i = s[1], r = IDBKeyRange.lowerBound(s);
  8730. let o = !1;
  8731. return fo(t).X({
  8732. range: r,
  8733. Y: !0
  8734. }, ((t, n, s) => {
  8735. const [r, u, /*batchID*/ c] = t;
  8736. r === e && u === i && (o = !0), s.done();
  8737. })).next((() => o));
  8738. }
  8739. /** Returns true if any mutation queue contains the given document. */
  8740. /**
  8741. * Helper to get a typed SimpleDbStore for the mutations object store.
  8742. */
  8743. function lo(t) {
  8744. return ge(t, "mutations");
  8745. }
  8746. /**
  8747. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8748. */ function fo(t) {
  8749. return ge(t, "documentMutations");
  8750. }
  8751. /**
  8752. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8753. */ function wo(t) {
  8754. return ge(t, "mutationQueues");
  8755. }
  8756. /**
  8757. * @license
  8758. * Copyright 2017 Google LLC
  8759. *
  8760. * Licensed under the Apache License, Version 2.0 (the "License");
  8761. * you may not use this file except in compliance with the License.
  8762. * You may obtain a copy of the License at
  8763. *
  8764. * http://www.apache.org/licenses/LICENSE-2.0
  8765. *
  8766. * Unless required by applicable law or agreed to in writing, software
  8767. * distributed under the License is distributed on an "AS IS" BASIS,
  8768. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8769. * See the License for the specific language governing permissions and
  8770. * limitations under the License.
  8771. */
  8772. /** Offset to ensure non-overlapping target ids. */
  8773. /**
  8774. * Generates monotonically increasing target IDs for sending targets to the
  8775. * watch stream.
  8776. *
  8777. * The client constructs two generators, one for the target cache, and one for
  8778. * for the sync engine (to generate limbo documents targets). These
  8779. * generators produce non-overlapping IDs (by using even and odd IDs
  8780. * respectively).
  8781. *
  8782. * By separating the target ID space, the query cache can generate target IDs
  8783. * that persist across client restarts, while sync engine can independently
  8784. * generate in-memory target IDs that are transient and can be reused after a
  8785. * restart.
  8786. */
  8787. class _o {
  8788. constructor(t) {
  8789. this.Nn = t;
  8790. }
  8791. next() {
  8792. return this.Nn += 2, this.Nn;
  8793. }
  8794. static kn() {
  8795. // The target cache generator must return '2' in its first call to `next()`
  8796. // as there is no differentiation in the protocol layer between an unset
  8797. // number and the number '0'. If we were to sent a target with target ID
  8798. // '0', the backend would consider it unset and replace it with its own ID.
  8799. return new _o(0);
  8800. }
  8801. static $n() {
  8802. // Sync engine assigns target IDs for limbo document detection.
  8803. return new _o(-1);
  8804. }
  8805. }
  8806. /**
  8807. * @license
  8808. * Copyright 2017 Google LLC
  8809. *
  8810. * Licensed under the Apache License, Version 2.0 (the "License");
  8811. * you may not use this file except in compliance with the License.
  8812. * You may obtain a copy of the License at
  8813. *
  8814. * http://www.apache.org/licenses/LICENSE-2.0
  8815. *
  8816. * Unless required by applicable law or agreed to in writing, software
  8817. * distributed under the License is distributed on an "AS IS" BASIS,
  8818. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8819. * See the License for the specific language governing permissions and
  8820. * limitations under the License.
  8821. */ class mo {
  8822. constructor(t, e) {
  8823. this.referenceDelegate = t, this.serializer = e;
  8824. }
  8825. // PORTING NOTE: We don't cache global metadata for the target cache, since
  8826. // some of it (in particular `highestTargetId`) can be modified by secondary
  8827. // tabs. We could perhaps be more granular (and e.g. still cache
  8828. // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go
  8829. // to IndexedDb whenever we need to read metadata. We can revisit if it turns
  8830. // out to have a meaningful performance impact.
  8831. allocateTargetId(t) {
  8832. return this.Mn(t).next((e => {
  8833. const n = new _o(e.highestTargetId);
  8834. return e.highestTargetId = n.next(), this.On(t, e).next((() => e.highestTargetId));
  8835. }));
  8836. }
  8837. getLastRemoteSnapshotVersion(t) {
  8838. return this.Mn(t).next((t => ut.fromTimestamp(new ot(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds))));
  8839. }
  8840. getHighestSequenceNumber(t) {
  8841. return this.Mn(t).next((t => t.highestListenSequenceNumber));
  8842. }
  8843. setTargetsMetadata(t, e, n) {
  8844. return this.Mn(t).next((s => (s.highestListenSequenceNumber = e, n && (s.lastRemoteSnapshotVersion = n.toTimestamp()),
  8845. e > s.highestListenSequenceNumber && (s.highestListenSequenceNumber = e), this.On(t, s))));
  8846. }
  8847. addTargetData(t, e) {
  8848. return this.Fn(t, e).next((() => this.Mn(t).next((n => (n.targetCount += 1, this.Bn(e, n),
  8849. this.On(t, n))))));
  8850. }
  8851. updateTargetData(t, e) {
  8852. return this.Fn(t, e);
  8853. }
  8854. removeTargetData(t, e) {
  8855. return this.removeMatchingKeysForTargetId(t, e.targetId).next((() => go(t).delete(e.targetId))).next((() => this.Mn(t))).next((e => (L(e.targetCount > 0),
  8856. e.targetCount -= 1, this.On(t, e))));
  8857. }
  8858. /**
  8859. * Drops any targets with sequence number less than or equal to the upper bound, excepting those
  8860. * present in `activeTargetIds`. Document associations for the removed targets are also removed.
  8861. * Returns the number of targets removed.
  8862. */ removeTargets(t, e, n) {
  8863. let s = 0;
  8864. const i = [];
  8865. return go(t).X(((r, o) => {
  8866. const u = pr(o);
  8867. u.sequenceNumber <= e && null === n.get(u.targetId) && (s++, i.push(this.removeTargetData(t, u)));
  8868. })).next((() => bt.waitFor(i))).next((() => s));
  8869. }
  8870. /**
  8871. * Call provided function with each `TargetData` that we have cached.
  8872. */ forEachTarget(t, e) {
  8873. return go(t).X(((t, n) => {
  8874. const s = pr(n);
  8875. e(s);
  8876. }));
  8877. }
  8878. Mn(t) {
  8879. return yo(t).get("targetGlobalKey").next((t => (L(null !== t), t)));
  8880. }
  8881. On(t, e) {
  8882. return yo(t).put("targetGlobalKey", e);
  8883. }
  8884. Fn(t, e) {
  8885. return go(t).put(Ir(this.serializer, e));
  8886. }
  8887. /**
  8888. * In-place updates the provided metadata to account for values in the given
  8889. * TargetData. Saving is done separately. Returns true if there were any
  8890. * changes to the metadata.
  8891. */ Bn(t, e) {
  8892. let n = !1;
  8893. return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0),
  8894. t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber,
  8895. n = !0), n;
  8896. }
  8897. getTargetCount(t) {
  8898. return this.Mn(t).next((t => t.targetCount));
  8899. }
  8900. getTargetData(t, e) {
  8901. // Iterating by the canonicalId may yield more than one result because
  8902. // canonicalId values are not required to be unique per target. This query
  8903. // depends on the queryTargets index to be efficient.
  8904. const n = Bn(e), s = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);
  8905. let i = null;
  8906. return go(t).X({
  8907. range: s,
  8908. index: "queryTargetsIndex"
  8909. }, ((t, n, s) => {
  8910. const r = pr(n);
  8911. // After finding a potential match, check that the target is
  8912. // actually equal to the requested target.
  8913. Ln(e, r.target) && (i = r, s.done());
  8914. })).next((() => i));
  8915. }
  8916. addMatchingKeys(t, e, n) {
  8917. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8918. // IndexedDb.
  8919. const s = [], i = po(t);
  8920. return e.forEach((e => {
  8921. const r = Kt(e.path);
  8922. s.push(i.put({
  8923. targetId: n,
  8924. path: r
  8925. })), s.push(this.referenceDelegate.addReference(t, n, e));
  8926. })), bt.waitFor(s);
  8927. }
  8928. removeMatchingKeys(t, e, n) {
  8929. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8930. // IndexedDb.
  8931. const s = po(t);
  8932. return bt.forEach(e, (e => {
  8933. const i = Kt(e.path);
  8934. return bt.waitFor([ s.delete([ n, i ]), this.referenceDelegate.removeReference(t, n, e) ]);
  8935. }));
  8936. }
  8937. removeMatchingKeysForTargetId(t, e) {
  8938. const n = po(t), s = IDBKeyRange.bound([ e ], [ e + 1 ],
  8939. /*lowerOpen=*/ !1,
  8940. /*upperOpen=*/ !0);
  8941. return n.delete(s);
  8942. }
  8943. getMatchingKeysForTargetId(t, e) {
  8944. const n = IDBKeyRange.bound([ e ], [ e + 1 ],
  8945. /*lowerOpen=*/ !1,
  8946. /*upperOpen=*/ !0), s = po(t);
  8947. let i = Is();
  8948. return s.X({
  8949. range: n,
  8950. Y: !0
  8951. }, ((t, e, n) => {
  8952. const s = jt(t[1]), r = new ft(s);
  8953. i = i.add(r);
  8954. })).next((() => i));
  8955. }
  8956. containsKey(t, e) {
  8957. const n = Kt(e.path), s = IDBKeyRange.bound([ n ], [ rt(n) ],
  8958. /*lowerOpen=*/ !1,
  8959. /*upperOpen=*/ !0);
  8960. let i = 0;
  8961. return po(t).X({
  8962. index: "documentTargetsIndex",
  8963. Y: !0,
  8964. range: s
  8965. }, (([t, e], n, s) => {
  8966. // Having a sentinel row for a document does not count as containing that document;
  8967. // For the target cache, containing the document means the document is part of some
  8968. // target.
  8969. 0 !== t && (i++, s.done());
  8970. })).next((() => i > 0));
  8971. }
  8972. /**
  8973. * Looks up a TargetData entry by target ID.
  8974. *
  8975. * @param targetId - The target ID of the TargetData entry to look up.
  8976. * @returns The cached TargetData entry, or null if the cache has no entry for
  8977. * the target.
  8978. */
  8979. // PORTING NOTE: Multi-tab only.
  8980. le(t, e) {
  8981. return go(t).get(e).next((t => t ? pr(t) : null));
  8982. }
  8983. }
  8984. /**
  8985. * Helper to get a typed SimpleDbStore for the queries object store.
  8986. */ function go(t) {
  8987. return ge(t, "targets");
  8988. }
  8989. /**
  8990. * Helper to get a typed SimpleDbStore for the target globals object store.
  8991. */ function yo(t) {
  8992. return ge(t, "targetGlobal");
  8993. }
  8994. /**
  8995. * Helper to get a typed SimpleDbStore for the document target object store.
  8996. */ function po(t) {
  8997. return ge(t, "targetDocuments");
  8998. }
  8999. /**
  9000. * @license
  9001. * Copyright 2020 Google LLC
  9002. *
  9003. * Licensed under the Apache License, Version 2.0 (the "License");
  9004. * you may not use this file except in compliance with the License.
  9005. * You may obtain a copy of the License at
  9006. *
  9007. * http://www.apache.org/licenses/LICENSE-2.0
  9008. *
  9009. * Unless required by applicable law or agreed to in writing, software
  9010. * distributed under the License is distributed on an "AS IS" BASIS,
  9011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9012. * See the License for the specific language governing permissions and
  9013. * limitations under the License.
  9014. */ function Io([t, e], [n, s]) {
  9015. const i = st(t, n);
  9016. return 0 === i ? st(e, s) : i;
  9017. }
  9018. /**
  9019. * Used to calculate the nth sequence number. Keeps a rolling buffer of the
  9020. * lowest n values passed to `addElement`, and finally reports the largest of
  9021. * them in `maxValue`.
  9022. */ class To {
  9023. constructor(t) {
  9024. this.Ln = t, this.buffer = new ve(Io), this.qn = 0;
  9025. }
  9026. Un() {
  9027. return ++this.qn;
  9028. }
  9029. Kn(t) {
  9030. const e = [ t, this.Un() ];
  9031. if (this.buffer.size < this.Ln) this.buffer = this.buffer.add(e); else {
  9032. const t = this.buffer.last();
  9033. Io(e, t) < 0 && (this.buffer = this.buffer.delete(t).add(e));
  9034. }
  9035. }
  9036. get maxValue() {
  9037. // Guaranteed to be non-empty. If we decide we are not collecting any
  9038. // sequence numbers, nthSequenceNumber below short-circuits. If we have
  9039. // decided that we are collecting n sequence numbers, it's because n is some
  9040. // percentage of the existing sequence numbers. That means we should never
  9041. // be in a situation where we are collecting sequence numbers but don't
  9042. // actually have any.
  9043. return this.buffer.last()[0];
  9044. }
  9045. }
  9046. /**
  9047. * This class is responsible for the scheduling of LRU garbage collection. It handles checking
  9048. * whether or not GC is enabled, as well as which delay to use before the next run.
  9049. */ class Eo {
  9050. constructor(t, e, n) {
  9051. this.garbageCollector = t, this.asyncQueue = e, this.localStore = n, this.Gn = null;
  9052. }
  9053. start() {
  9054. -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Qn(6e4);
  9055. }
  9056. stop() {
  9057. this.Gn && (this.Gn.cancel(), this.Gn = null);
  9058. }
  9059. get started() {
  9060. return null !== this.Gn;
  9061. }
  9062. Qn(t) {
  9063. $("LruGarbageCollector", `Garbage collection scheduled in ${t}ms`), this.Gn = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */ , t, (async () => {
  9064. this.Gn = null;
  9065. try {
  9066. await this.localStore.collectGarbage(this.garbageCollector);
  9067. } catch (t) {
  9068. xt(t) ? $("LruGarbageCollector", "Ignoring IndexedDB error during garbage collection: ", t) : await Pt(t);
  9069. }
  9070. await this.Qn(3e5);
  9071. }));
  9072. }
  9073. }
  9074. /**
  9075. * Implements the steps for LRU garbage collection.
  9076. */ class Ao {
  9077. constructor(t, e) {
  9078. this.jn = t, this.params = e;
  9079. }
  9080. calculateTargetCount(t, e) {
  9081. return this.jn.zn(t).next((t => Math.floor(e / 100 * t)));
  9082. }
  9083. nthSequenceNumber(t, e) {
  9084. if (0 === e) return bt.resolve(Bt.ct);
  9085. const n = new To(e);
  9086. return this.jn.forEachTarget(t, (t => n.Kn(t.sequenceNumber))).next((() => this.jn.Wn(t, (t => n.Kn(t))))).next((() => n.maxValue));
  9087. }
  9088. removeTargets(t, e, n) {
  9089. return this.jn.removeTargets(t, e, n);
  9090. }
  9091. removeOrphanedDocuments(t, e) {
  9092. return this.jn.removeOrphanedDocuments(t, e);
  9093. }
  9094. collect(t, e) {
  9095. return -1 === this.params.cacheSizeCollectionThreshold ? ($("LruGarbageCollector", "Garbage collection skipped; disabled"),
  9096. bt.resolve(ro)) : this.getCacheSize(t).next((n => n < this.params.cacheSizeCollectionThreshold ? ($("LruGarbageCollector", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),
  9097. ro) : this.Hn(t, e)));
  9098. }
  9099. getCacheSize(t) {
  9100. return this.jn.getCacheSize(t);
  9101. }
  9102. Hn(t, e) {
  9103. let n, s, i, r, o, c, a;
  9104. const h = Date.now();
  9105. return this.calculateTargetCount(t, this.params.percentileToCollect).next((e => (
  9106. // Cap at the configured max
  9107. e > this.params.maximumSequenceNumbersToCollect ? ($("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),
  9108. s = this.params.maximumSequenceNumbersToCollect) : s = e, r = Date.now(), this.nthSequenceNumber(t, s)))).next((s => (n = s,
  9109. o = Date.now(), this.removeTargets(t, n, e)))).next((e => (i = e, c = Date.now(),
  9110. this.removeOrphanedDocuments(t, n)))).next((t => {
  9111. if (a = Date.now(), N() <= u.DEBUG) {
  9112. $("LruGarbageCollector", `LRU Garbage Collection\n\tCounted targets in ${r - h}ms\n\tDetermined least recently used ${s} in ` + (o - r) + "ms\n" + `\tRemoved ${i} targets in ` + (c - o) + "ms\n" + `\tRemoved ${t} documents in ` + (a - c) + "ms\n" + `Total Duration: ${a - h}ms`);
  9113. }
  9114. return bt.resolve({
  9115. didRun: !0,
  9116. sequenceNumbersCollected: s,
  9117. targetsRemoved: i,
  9118. documentsRemoved: t
  9119. });
  9120. }));
  9121. }
  9122. }
  9123. function vo(t, e) {
  9124. return new Ao(t, e);
  9125. }
  9126. /**
  9127. * @license
  9128. * Copyright 2020 Google LLC
  9129. *
  9130. * Licensed under the Apache License, Version 2.0 (the "License");
  9131. * you may not use this file except in compliance with the License.
  9132. * You may obtain a copy of the License at
  9133. *
  9134. * http://www.apache.org/licenses/LICENSE-2.0
  9135. *
  9136. * Unless required by applicable law or agreed to in writing, software
  9137. * distributed under the License is distributed on an "AS IS" BASIS,
  9138. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9139. * See the License for the specific language governing permissions and
  9140. * limitations under the License.
  9141. */
  9142. /** Provides LRU functionality for IndexedDB persistence. */ class Ro {
  9143. constructor(t, e) {
  9144. this.db = t, this.garbageCollector = vo(this, e);
  9145. }
  9146. zn(t) {
  9147. const e = this.Jn(t);
  9148. return this.db.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));
  9149. }
  9150. Jn(t) {
  9151. let e = 0;
  9152. return this.Wn(t, (t => {
  9153. e++;
  9154. })).next((() => e));
  9155. }
  9156. forEachTarget(t, e) {
  9157. return this.db.getTargetCache().forEachTarget(t, e);
  9158. }
  9159. Wn(t, e) {
  9160. return this.Yn(t, ((t, n) => e(n)));
  9161. }
  9162. addReference(t, e, n) {
  9163. return Po(t, n);
  9164. }
  9165. removeReference(t, e, n) {
  9166. return Po(t, n);
  9167. }
  9168. removeTargets(t, e, n) {
  9169. return this.db.getTargetCache().removeTargets(t, e, n);
  9170. }
  9171. markPotentiallyOrphaned(t, e) {
  9172. return Po(t, e);
  9173. }
  9174. /**
  9175. * Returns true if anything would prevent this document from being garbage
  9176. * collected, given that the document in question is not present in any
  9177. * targets and has a sequence number less than or equal to the upper bound for
  9178. * the collection run.
  9179. */ Xn(t, e) {
  9180. return function(t, e) {
  9181. let n = !1;
  9182. return wo(t).Z((s => ho(t, s, e).next((t => (t && (n = !0), bt.resolve(!t)))))).next((() => n));
  9183. }(t, e);
  9184. }
  9185. removeOrphanedDocuments(t, e) {
  9186. const n = this.db.getRemoteDocumentCache().newChangeBuffer(), s = [];
  9187. let i = 0;
  9188. return this.Yn(t, ((r, o) => {
  9189. if (o <= e) {
  9190. const e = this.Xn(t, r).next((e => {
  9191. if (!e)
  9192. // Our size accounting requires us to read all documents before
  9193. // removing them.
  9194. return i++, n.getEntry(t, r).next((() => (n.removeEntry(r, ut.min()), po(t).delete([ 0, Kt(r.path) ]))));
  9195. }));
  9196. s.push(e);
  9197. }
  9198. })).next((() => bt.waitFor(s))).next((() => n.apply(t))).next((() => i));
  9199. }
  9200. removeTarget(t, e) {
  9201. const n = e.withSequenceNumber(t.currentSequenceNumber);
  9202. return this.db.getTargetCache().updateTargetData(t, n);
  9203. }
  9204. updateLimboDocument(t, e) {
  9205. return Po(t, e);
  9206. }
  9207. /**
  9208. * Call provided function for each document in the cache that is 'orphaned'. Orphaned
  9209. * means not a part of any target, so the only entry in the target-document index for
  9210. * that document will be the sentinel row (targetId 0), which will also have the sequence
  9211. * number for the last time the document was accessed.
  9212. */ Yn(t, e) {
  9213. const n = po(t);
  9214. let s, i = Bt.ct;
  9215. return n.X({
  9216. index: "documentTargetsIndex"
  9217. }, (([t, n], {path: r, sequenceNumber: o}) => {
  9218. 0 === t ? (
  9219. // if nextToReport is valid, report it, this is a new key so the
  9220. // last one must not be a member of any targets.
  9221. i !== Bt.ct && e(new ft(jt(s)), i),
  9222. // set nextToReport to be this sequence number. It's the next one we
  9223. // might report, if we don't find any targets for this document.
  9224. // Note that the sequence number must be defined when the targetId
  9225. // is 0.
  9226. i = o, s = r) :
  9227. // set nextToReport to be invalid, we know we don't need to report
  9228. // this one since we found a target for it.
  9229. i = Bt.ct;
  9230. })).next((() => {
  9231. // Since we report sequence numbers after getting to the next key, we
  9232. // need to check if the last key we iterated over was an orphaned
  9233. // document and report it.
  9234. i !== Bt.ct && e(new ft(jt(s)), i);
  9235. }));
  9236. }
  9237. getCacheSize(t) {
  9238. return this.db.getRemoteDocumentCache().getSize(t);
  9239. }
  9240. }
  9241. function Po(t, e) {
  9242. return po(t).put(
  9243. /**
  9244. * @returns A value suitable for writing a sentinel row in the target-document
  9245. * store.
  9246. */
  9247. function(t, e) {
  9248. return {
  9249. targetId: 0,
  9250. path: Kt(t.path),
  9251. sequenceNumber: e
  9252. };
  9253. }(e, t.currentSequenceNumber));
  9254. }
  9255. /**
  9256. * @license
  9257. * Copyright 2017 Google LLC
  9258. *
  9259. * Licensed under the Apache License, Version 2.0 (the "License");
  9260. * you may not use this file except in compliance with the License.
  9261. * You may obtain a copy of the License at
  9262. *
  9263. * http://www.apache.org/licenses/LICENSE-2.0
  9264. *
  9265. * Unless required by applicable law or agreed to in writing, software
  9266. * distributed under the License is distributed on an "AS IS" BASIS,
  9267. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9268. * See the License for the specific language governing permissions and
  9269. * limitations under the License.
  9270. */
  9271. /**
  9272. * An in-memory buffer of entries to be written to a RemoteDocumentCache.
  9273. * It can be used to batch up a set of changes to be written to the cache, but
  9274. * additionally supports reading entries back with the `getEntry()` method,
  9275. * falling back to the underlying RemoteDocumentCache if no entry is
  9276. * buffered.
  9277. *
  9278. * Entries added to the cache *must* be read first. This is to facilitate
  9279. * calculating the size delta of the pending changes.
  9280. *
  9281. * PORTING NOTE: This class was implemented then removed from other platforms.
  9282. * If byte-counting ends up being needed on the other platforms, consider
  9283. * porting this class as part of that implementation work.
  9284. */ class bo {
  9285. constructor() {
  9286. // A mapping of document key to the new cache entry that should be written.
  9287. this.changes = new as((t => t.toString()), ((t, e) => t.isEqual(e))), this.changesApplied = !1;
  9288. }
  9289. /**
  9290. * Buffers a `RemoteDocumentCache.addEntry()` call.
  9291. *
  9292. * You can only modify documents that have already been retrieved via
  9293. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  9294. */ addEntry(t) {
  9295. this.assertNotApplied(), this.changes.set(t.key, t);
  9296. }
  9297. /**
  9298. * Buffers a `RemoteDocumentCache.removeEntry()` call.
  9299. *
  9300. * You can only remove documents that have already been retrieved via
  9301. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  9302. */ removeEntry(t, e) {
  9303. this.assertNotApplied(), this.changes.set(t, fn.newInvalidDocument(t).setReadTime(e));
  9304. }
  9305. /**
  9306. * Looks up an entry in the cache. The buffered changes will first be checked,
  9307. * and if no buffered change applies, this will forward to
  9308. * `RemoteDocumentCache.getEntry()`.
  9309. *
  9310. * @param transaction - The transaction in which to perform any persistence
  9311. * operations.
  9312. * @param documentKey - The key of the entry to look up.
  9313. * @returns The cached document or an invalid document if we have nothing
  9314. * cached.
  9315. */ getEntry(t, e) {
  9316. this.assertNotApplied();
  9317. const n = this.changes.get(e);
  9318. return void 0 !== n ? bt.resolve(n) : this.getFromCache(t, e);
  9319. }
  9320. /**
  9321. * Looks up several entries in the cache, forwarding to
  9322. * `RemoteDocumentCache.getEntry()`.
  9323. *
  9324. * @param transaction - The transaction in which to perform any persistence
  9325. * operations.
  9326. * @param documentKeys - The keys of the entries to look up.
  9327. * @returns A map of cached documents, indexed by key. If an entry cannot be
  9328. * found, the corresponding key will be mapped to an invalid document.
  9329. */ getEntries(t, e) {
  9330. return this.getAllFromCache(t, e);
  9331. }
  9332. /**
  9333. * Applies buffered changes to the underlying RemoteDocumentCache, using
  9334. * the provided transaction.
  9335. */ apply(t) {
  9336. return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);
  9337. }
  9338. /** Helper to assert this.changes is not null */ assertNotApplied() {}
  9339. }
  9340. /**
  9341. * @license
  9342. * Copyright 2017 Google LLC
  9343. *
  9344. * Licensed under the Apache License, Version 2.0 (the "License");
  9345. * you may not use this file except in compliance with the License.
  9346. * You may obtain a copy of the License at
  9347. *
  9348. * http://www.apache.org/licenses/LICENSE-2.0
  9349. *
  9350. * Unless required by applicable law or agreed to in writing, software
  9351. * distributed under the License is distributed on an "AS IS" BASIS,
  9352. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9353. * See the License for the specific language governing permissions and
  9354. * limitations under the License.
  9355. */
  9356. /**
  9357. * The RemoteDocumentCache for IndexedDb. To construct, invoke
  9358. * `newIndexedDbRemoteDocumentCache()`.
  9359. */ class Vo {
  9360. constructor(t) {
  9361. this.serializer = t;
  9362. }
  9363. setIndexManager(t) {
  9364. this.indexManager = t;
  9365. }
  9366. /**
  9367. * Adds the supplied entries to the cache.
  9368. *
  9369. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  9370. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9371. */ addEntry(t, e, n) {
  9372. return xo(t).put(n);
  9373. }
  9374. /**
  9375. * Removes a document from the cache.
  9376. *
  9377. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  9378. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9379. */ removeEntry(t, e, n) {
  9380. return xo(t).delete(
  9381. /**
  9382. * Returns a key that can be used for document lookups via the primary key of
  9383. * the DbRemoteDocument object store.
  9384. */
  9385. function(t, e) {
  9386. const n = t.path.toArray();
  9387. return [
  9388. /* prefix path */ n.slice(0, n.length - 2),
  9389. /* collection id */ n[n.length - 2], _r(e),
  9390. /* document id */ n[n.length - 1] ];
  9391. }
  9392. /**
  9393. * Returns a key that can be used for document lookups on the
  9394. * `DbRemoteDocumentDocumentCollectionGroupIndex` index.
  9395. */ (e, n));
  9396. }
  9397. /**
  9398. * Updates the current cache size.
  9399. *
  9400. * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
  9401. * cache's metadata.
  9402. */ updateMetadata(t, e) {
  9403. return this.getMetadata(t).next((n => (n.byteSize += e, this.Zn(t, n))));
  9404. }
  9405. getEntry(t, e) {
  9406. let n = fn.newInvalidDocument(e);
  9407. return xo(t).X({
  9408. index: "documentKeyIndex",
  9409. range: IDBKeyRange.only(No(e))
  9410. }, ((t, s) => {
  9411. n = this.ts(e, s);
  9412. })).next((() => n));
  9413. }
  9414. /**
  9415. * Looks up an entry in the cache.
  9416. *
  9417. * @param documentKey - The key of the entry to look up.
  9418. * @returns The cached document entry and its size.
  9419. */ es(t, e) {
  9420. let n = {
  9421. size: 0,
  9422. document: fn.newInvalidDocument(e)
  9423. };
  9424. return xo(t).X({
  9425. index: "documentKeyIndex",
  9426. range: IDBKeyRange.only(No(e))
  9427. }, ((t, s) => {
  9428. n = {
  9429. document: this.ts(e, s),
  9430. size: co(s)
  9431. };
  9432. })).next((() => n));
  9433. }
  9434. getEntries(t, e) {
  9435. let n = ls();
  9436. return this.ns(t, e, ((t, e) => {
  9437. const s = this.ts(t, e);
  9438. n = n.insert(t, s);
  9439. })).next((() => n));
  9440. }
  9441. /**
  9442. * Looks up several entries in the cache.
  9443. *
  9444. * @param documentKeys - The set of keys entries to look up.
  9445. * @returns A map of documents indexed by key and a map of sizes indexed by
  9446. * key (zero if the document does not exist).
  9447. */ ss(t, e) {
  9448. let n = ls(), s = new Te(ft.comparator);
  9449. return this.ns(t, e, ((t, e) => {
  9450. const i = this.ts(t, e);
  9451. n = n.insert(t, i), s = s.insert(t, co(e));
  9452. })).next((() => ({
  9453. documents: n,
  9454. rs: s
  9455. })));
  9456. }
  9457. ns(t, e, n) {
  9458. if (e.isEmpty()) return bt.resolve();
  9459. let s = new ve($o);
  9460. e.forEach((t => s = s.add(t)));
  9461. const i = IDBKeyRange.bound(No(s.first()), No(s.last())), r = s.getIterator();
  9462. let o = r.getNext();
  9463. return xo(t).X({
  9464. index: "documentKeyIndex",
  9465. range: i
  9466. }, ((t, e, s) => {
  9467. const i = ft.fromSegments([ ...e.prefixPath, e.collectionGroup, e.documentId ]);
  9468. // Go through keys not found in cache.
  9469. for (;o && $o(o, i) < 0; ) n(o, null), o = r.getNext();
  9470. o && o.isEqual(i) && (
  9471. // Key found in cache.
  9472. n(o, e), o = r.hasNext() ? r.getNext() : null),
  9473. // Skip to the next key (if there is one).
  9474. o ? s.G(No(o)) : s.done();
  9475. })).next((() => {
  9476. // The rest of the keys are not in the cache. One case where `iterate`
  9477. // above won't go through them is when the cache is empty.
  9478. for (;o; ) n(o, null), o = r.hasNext() ? r.getNext() : null;
  9479. }));
  9480. }
  9481. getDocumentsMatchingQuery(t, e, n, s) {
  9482. const i = e.path, r = [ i.popLast().toArray(), i.lastSegment(), _r(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment() ], o = [ i.popLast().toArray(), i.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], "" ];
  9483. return xo(t).j(IDBKeyRange.bound(r, o, !0)).next((t => {
  9484. let n = ls();
  9485. for (const i of t) {
  9486. const t = this.ts(ft.fromSegments(i.prefixPath.concat(i.collectionGroup, i.documentId)), i);
  9487. t.isFoundDocument() && (rs(e, t) || s.has(t.key)) && (
  9488. // Either the document matches the given query, or it is mutated.
  9489. n = n.insert(t.key, t));
  9490. }
  9491. return n;
  9492. }));
  9493. }
  9494. getAllFromCollectionGroup(t, e, n, s) {
  9495. let i = ls();
  9496. const r = ko(e, n), o = ko(e, Et.max());
  9497. return xo(t).X({
  9498. index: "collectionGroupIndex",
  9499. range: IDBKeyRange.bound(r, o, !0)
  9500. }, ((t, e, n) => {
  9501. const r = this.ts(ft.fromSegments(e.prefixPath.concat(e.collectionGroup, e.documentId)), e);
  9502. i = i.insert(r.key, r), i.size === s && n.done();
  9503. })).next((() => i));
  9504. }
  9505. newChangeBuffer(t) {
  9506. return new Do(this, !!t && t.trackRemovals);
  9507. }
  9508. getSize(t) {
  9509. return this.getMetadata(t).next((t => t.byteSize));
  9510. }
  9511. getMetadata(t) {
  9512. return Co(t).get("remoteDocumentGlobalKey").next((t => (L(!!t), t)));
  9513. }
  9514. Zn(t, e) {
  9515. return Co(t).put("remoteDocumentGlobalKey", e);
  9516. }
  9517. /**
  9518. * Decodes `dbRemoteDoc` and returns the document (or an invalid document if
  9519. * the document corresponds to the format used for sentinel deletes).
  9520. */ ts(t, e) {
  9521. if (e) {
  9522. const t = dr(this.serializer, e);
  9523. // Whether the document is a sentinel removal and should only be used in the
  9524. // `getNewDocumentChanges()`
  9525. if (!(t.isNoDocument() && t.version.isEqual(ut.min()))) return t;
  9526. }
  9527. return fn.newInvalidDocument(t);
  9528. }
  9529. }
  9530. /** Creates a new IndexedDbRemoteDocumentCache. */ function So(t) {
  9531. return new Vo(t);
  9532. }
  9533. /**
  9534. * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.
  9535. *
  9536. * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size
  9537. * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb
  9538. * when we apply the changes.
  9539. */ class Do extends bo {
  9540. /**
  9541. * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.
  9542. * @param trackRemovals - Whether to create sentinel deletes that can be tracked by
  9543. * `getNewDocumentChanges()`.
  9544. */
  9545. constructor(t, e) {
  9546. super(), this.os = t, this.trackRemovals = e,
  9547. // A map of document sizes and read times prior to applying the changes in
  9548. // this buffer.
  9549. this.us = new as((t => t.toString()), ((t, e) => t.isEqual(e)));
  9550. }
  9551. applyChanges(t) {
  9552. const e = [];
  9553. let n = 0, s = new ve(((t, e) => st(t.canonicalString(), e.canonicalString())));
  9554. return this.changes.forEach(((i, r) => {
  9555. const o = this.us.get(i);
  9556. if (e.push(this.os.removeEntry(t, i, o.readTime)), r.isValidDocument()) {
  9557. const u = wr(this.os.serializer, r);
  9558. s = s.add(i.path.popLast());
  9559. const c = co(u);
  9560. n += c - o.size, e.push(this.os.addEntry(t, i, u));
  9561. } else if (n -= o.size, this.trackRemovals) {
  9562. // In order to track removals, we store a "sentinel delete" in the
  9563. // RemoteDocumentCache. This entry is represented by a NoDocument
  9564. // with a version of 0 and ignored by `maybeDecodeDocument()` but
  9565. // preserved in `getNewDocumentChanges()`.
  9566. const n = wr(this.os.serializer, r.convertToNoDocument(ut.min()));
  9567. e.push(this.os.addEntry(t, i, n));
  9568. }
  9569. })), s.forEach((n => {
  9570. e.push(this.os.indexManager.addToCollectionParentIndex(t, n));
  9571. })), e.push(this.os.updateMetadata(t, n)), bt.waitFor(e);
  9572. }
  9573. getFromCache(t, e) {
  9574. // Record the size of everything we load from the cache so we can compute a delta later.
  9575. return this.os.es(t, e).next((t => (this.us.set(e, {
  9576. size: t.size,
  9577. readTime: t.document.readTime
  9578. }), t.document)));
  9579. }
  9580. getAllFromCache(t, e) {
  9581. // Record the size of everything we load from the cache so we can compute
  9582. // a delta later.
  9583. return this.os.ss(t, e).next((({documents: t, rs: e}) => (
  9584. // Note: `getAllFromCache` returns two maps instead of a single map from
  9585. // keys to `DocumentSizeEntry`s. This is to allow returning the
  9586. // `MutableDocumentMap` directly, without a conversion.
  9587. e.forEach(((e, n) => {
  9588. this.us.set(e, {
  9589. size: n,
  9590. readTime: t.get(e).readTime
  9591. });
  9592. })), t)));
  9593. }
  9594. }
  9595. function Co(t) {
  9596. return ge(t, "remoteDocumentGlobal");
  9597. }
  9598. /**
  9599. * Helper to get a typed SimpleDbStore for the remoteDocuments object store.
  9600. */ function xo(t) {
  9601. return ge(t, "remoteDocumentsV14");
  9602. }
  9603. /**
  9604. * Returns a key that can be used for document lookups on the
  9605. * `DbRemoteDocumentDocumentKeyIndex` index.
  9606. */ function No(t) {
  9607. const e = t.path.toArray();
  9608. return [
  9609. /* prefix path */ e.slice(0, e.length - 2),
  9610. /* collection id */ e[e.length - 2],
  9611. /* document id */ e[e.length - 1] ];
  9612. }
  9613. function ko(t, e) {
  9614. const n = e.documentKey.path.toArray();
  9615. return [
  9616. /* collection id */ t, _r(e.readTime),
  9617. /* prefix path */ n.slice(0, n.length - 2),
  9618. /* document id */ n.length > 0 ? n[n.length - 1] : "" ];
  9619. }
  9620. /**
  9621. * Comparator that compares document keys according to the primary key sorting
  9622. * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
  9623. * and then document ID).
  9624. *
  9625. * Visible for testing.
  9626. */ function $o(t, e) {
  9627. const n = t.path.toArray(), s = e.path.toArray();
  9628. // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
  9629. let i = 0;
  9630. for (let t = 0; t < n.length - 2 && t < s.length - 2; ++t) if (i = st(n[t], s[t]),
  9631. i) return i;
  9632. return i = st(n.length, s.length), i || (i = st(n[n.length - 2], s[s.length - 2]),
  9633. i || st(n[n.length - 1], s[s.length - 1]));
  9634. }
  9635. /**
  9636. * @license
  9637. * Copyright 2017 Google LLC
  9638. *
  9639. * Licensed under the Apache License, Version 2.0 (the "License");
  9640. * you may not use this file except in compliance with the License.
  9641. * You may obtain a copy of the License at
  9642. *
  9643. * http://www.apache.org/licenses/LICENSE-2.0
  9644. *
  9645. * Unless required by applicable law or agreed to in writing, software
  9646. * distributed under the License is distributed on an "AS IS" BASIS,
  9647. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9648. * See the License for the specific language governing permissions and
  9649. * limitations under the License.
  9650. */
  9651. /**
  9652. * Schema Version for the Web client:
  9653. * 1. Initial version including Mutation Queue, Query Cache, and Remote
  9654. * Document Cache
  9655. * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No
  9656. * longer required because migration 3 unconditionally clears it.
  9657. * 3. Dropped and re-created Query Cache to deal with cache corruption related
  9658. * to limbo resolution. Addresses
  9659. * https://github.com/firebase/firebase-ios-sdk/issues/1548
  9660. * 4. Multi-Tab Support.
  9661. * 5. Removal of held write acks.
  9662. * 6. Create document global for tracking document cache size.
  9663. * 7. Ensure every cached document has a sentinel row with a sequence number.
  9664. * 8. Add collection-parent index for Collection Group queries.
  9665. * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than
  9666. * an auto-incrementing ID. This is required for Index-Free queries.
  9667. * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
  9668. * 11. Add bundles and named_queries for bundle support.
  9669. * 12. Add document overlays.
  9670. * 13. Rewrite the keys of the remote document cache to allow for efficient
  9671. * document lookup via `getAll()`.
  9672. * 14. Add overlays.
  9673. * 15. Add indexing support.
  9674. */
  9675. /**
  9676. * @license
  9677. * Copyright 2022 Google LLC
  9678. *
  9679. * Licensed under the Apache License, Version 2.0 (the "License");
  9680. * you may not use this file except in compliance with the License.
  9681. * You may obtain a copy of the License at
  9682. *
  9683. * http://www.apache.org/licenses/LICENSE-2.0
  9684. *
  9685. * Unless required by applicable law or agreed to in writing, software
  9686. * distributed under the License is distributed on an "AS IS" BASIS,
  9687. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9688. * See the License for the specific language governing permissions and
  9689. * limitations under the License.
  9690. */
  9691. /**
  9692. * Represents a local view (overlay) of a document, and the fields that are
  9693. * locally mutated.
  9694. */
  9695. class Mo {
  9696. constructor(t,
  9697. /**
  9698. * The fields that are locally mutated by patch mutations.
  9699. *
  9700. * If the overlayed document is from set or delete mutations, this is `null`.
  9701. * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
  9702. */
  9703. e) {
  9704. this.overlayedDocument = t, this.mutatedFields = e;
  9705. }
  9706. }
  9707. /**
  9708. * @license
  9709. * Copyright 2017 Google LLC
  9710. *
  9711. * Licensed under the Apache License, Version 2.0 (the "License");
  9712. * you may not use this file except in compliance with the License.
  9713. * You may obtain a copy of the License at
  9714. *
  9715. * http://www.apache.org/licenses/LICENSE-2.0
  9716. *
  9717. * Unless required by applicable law or agreed to in writing, software
  9718. * distributed under the License is distributed on an "AS IS" BASIS,
  9719. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9720. * See the License for the specific language governing permissions and
  9721. * limitations under the License.
  9722. */
  9723. /**
  9724. * A readonly view of the local state of all documents we're tracking (i.e. we
  9725. * have a cached version in remoteDocumentCache or local mutations for the
  9726. * document). The view is computed by applying the mutations in the
  9727. * MutationQueue to the RemoteDocumentCache.
  9728. */ class Oo {
  9729. constructor(t, e, n, s) {
  9730. this.remoteDocumentCache = t, this.mutationQueue = e, this.documentOverlayCache = n,
  9731. this.indexManager = s;
  9732. }
  9733. /**
  9734. * Get the local view of the document identified by `key`.
  9735. *
  9736. * @returns Local view of the document or null if we don't have any cached
  9737. * state for it.
  9738. */ getDocument(t, e) {
  9739. let n = null;
  9740. return this.documentOverlayCache.getOverlay(t, e).next((s => (n = s, this.remoteDocumentCache.getEntry(t, e)))).next((t => (null !== n && js(n.mutation, t, be.empty(), ot.now()),
  9741. t)));
  9742. }
  9743. /**
  9744. * Gets the local view of the documents identified by `keys`.
  9745. *
  9746. * If we don't have cached state for a document in `keys`, a NoDocument will
  9747. * be stored for that key in the resulting set.
  9748. */ getDocuments(t, e) {
  9749. return this.remoteDocumentCache.getEntries(t, e).next((e => this.getLocalViewOfDocuments(t, e, Is()).next((() => e))));
  9750. }
  9751. /**
  9752. * Similar to `getDocuments`, but creates the local view from the given
  9753. * `baseDocs` without retrieving documents from the local store.
  9754. *
  9755. * @param transaction - The transaction this operation is scoped to.
  9756. * @param docs - The documents to apply local mutations to get the local views.
  9757. * @param existenceStateChanged - The set of document keys whose existence state
  9758. * is changed. This is useful to determine if some documents overlay needs
  9759. * to be recalculated.
  9760. */ getLocalViewOfDocuments(t, e, n = Is()) {
  9761. const s = _s();
  9762. return this.populateOverlays(t, s, e).next((() => this.computeViews(t, e, s, n).next((t => {
  9763. let e = ds();
  9764. return t.forEach(((t, n) => {
  9765. e = e.insert(t, n.overlayedDocument);
  9766. })), e;
  9767. }))));
  9768. }
  9769. /**
  9770. * Gets the overlayed documents for the given document map, which will include
  9771. * the local view of those documents and a `FieldMask` indicating which fields
  9772. * are mutated locally, `null` if overlay is a Set or Delete mutation.
  9773. */ getOverlayedDocuments(t, e) {
  9774. const n = _s();
  9775. return this.populateOverlays(t, n, e).next((() => this.computeViews(t, e, n, Is())));
  9776. }
  9777. /**
  9778. * Fetches the overlays for {@code docs} and adds them to provided overlay map
  9779. * if the map does not already contain an entry for the given document key.
  9780. */ populateOverlays(t, e, n) {
  9781. const s = [];
  9782. return n.forEach((t => {
  9783. e.has(t) || s.push(t);
  9784. })), this.documentOverlayCache.getOverlays(t, s).next((t => {
  9785. t.forEach(((t, n) => {
  9786. e.set(t, n);
  9787. }));
  9788. }));
  9789. }
  9790. /**
  9791. * Computes the local view for the given documents.
  9792. *
  9793. * @param docs - The documents to compute views for. It also has the base
  9794. * version of the documents.
  9795. * @param overlays - The overlays that need to be applied to the given base
  9796. * version of the documents.
  9797. * @param existenceStateChanged - A set of documents whose existence states
  9798. * might have changed. This is used to determine if we need to re-calculate
  9799. * overlays from mutation queues.
  9800. * @return A map represents the local documents view.
  9801. */ computeViews(t, e, n, s) {
  9802. let i = ls();
  9803. const r = gs(), o = gs();
  9804. return e.forEach(((t, e) => {
  9805. const o = n.get(e.key);
  9806. // Recalculate an overlay if the document's existence state changed due to
  9807. // a remote event *and* the overlay is a PatchMutation. This is because
  9808. // document existence state can change if some patch mutation's
  9809. // preconditions are met.
  9810. // NOTE: we recalculate when `overlay` is undefined as well, because there
  9811. // might be a patch mutation whose precondition does not match before the
  9812. // change (hence overlay is undefined), but would now match.
  9813. s.has(e.key) && (void 0 === o || o.mutation instanceof Js) ? i = i.insert(e.key, e) : void 0 !== o ? (r.set(e.key, o.mutation.getFieldMask()),
  9814. js(o.mutation, e, o.mutation.getFieldMask(), ot.now())) :
  9815. // no overlay exists
  9816. // Using EMPTY to indicate there is no overlay for the document.
  9817. r.set(e.key, be.empty());
  9818. })), this.recalculateAndSaveOverlays(t, i).next((t => (t.forEach(((t, e) => r.set(t, e))),
  9819. e.forEach(((t, e) => {
  9820. var n;
  9821. return o.set(t, new Mo(e, null !== (n = r.get(t)) && void 0 !== n ? n : null));
  9822. })), o)));
  9823. }
  9824. recalculateAndSaveOverlays(t, e) {
  9825. const n = gs();
  9826. // A reverse lookup map from batch id to the documents within that batch.
  9827. let s = new Te(((t, e) => t - e)), i = Is();
  9828. return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t, e).next((t => {
  9829. for (const i of t) i.keys().forEach((t => {
  9830. const r = e.get(t);
  9831. if (null === r) return;
  9832. let o = n.get(t) || be.empty();
  9833. o = i.applyToLocalView(r, o), n.set(t, o);
  9834. const u = (s.get(i.batchId) || Is()).add(t);
  9835. s = s.insert(i.batchId, u);
  9836. }));
  9837. })).next((() => {
  9838. const r = [], o = s.getReverseIterator();
  9839. // Iterate in descending order of batch IDs, and skip documents that are
  9840. // already saved.
  9841. for (;o.hasNext(); ) {
  9842. const s = o.getNext(), u = s.key, c = s.value, a = ms();
  9843. c.forEach((t => {
  9844. if (!i.has(t)) {
  9845. const s = Gs(e.get(t), n.get(t));
  9846. null !== s && a.set(t, s), i = i.add(t);
  9847. }
  9848. })), r.push(this.documentOverlayCache.saveOverlays(t, u, a));
  9849. }
  9850. return bt.waitFor(r);
  9851. })).next((() => n));
  9852. }
  9853. /**
  9854. * Recalculates overlays by reading the documents from remote document cache
  9855. * first, and saves them after they are calculated.
  9856. */ recalculateAndSaveOverlaysForDocumentKeys(t, e) {
  9857. return this.remoteDocumentCache.getEntries(t, e).next((e => this.recalculateAndSaveOverlays(t, e)));
  9858. }
  9859. /**
  9860. * Performs a query against the local view of all documents.
  9861. *
  9862. * @param transaction - The persistence transaction.
  9863. * @param query - The query to match documents against.
  9864. * @param offset - Read time and key to start scanning by (exclusive).
  9865. */ getDocumentsMatchingQuery(t, e, n) {
  9866. /**
  9867. * Returns whether the query matches a single document by path (rather than a
  9868. * collection).
  9869. */
  9870. return function(t) {
  9871. return ft.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  9872. }(e) ? this.getDocumentsMatchingDocumentQuery(t, e.path) : Yn(e) ? this.getDocumentsMatchingCollectionGroupQuery(t, e, n) : this.getDocumentsMatchingCollectionQuery(t, e, n);
  9873. }
  9874. /**
  9875. * Given a collection group, returns the next documents that follow the provided offset, along
  9876. * with an updated batch ID.
  9877. *
  9878. * <p>The documents returned by this method are ordered by remote version from the provided
  9879. * offset. If there are no more remote documents after the provided offset, documents with
  9880. * mutations in order of batch id from the offset are returned. Since all documents in a batch are
  9881. * returned together, the total number of documents returned can exceed {@code count}.
  9882. *
  9883. * @param transaction
  9884. * @param collectionGroup The collection group for the documents.
  9885. * @param offset The offset to index into.
  9886. * @param count The number of documents to return
  9887. * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
  9888. */ getNextDocuments(t, e, n, s) {
  9889. return this.remoteDocumentCache.getAllFromCollectionGroup(t, e, n, s).next((i => {
  9890. const r = s - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(t, e, n.largestBatchId, s - i.size) : bt.resolve(_s());
  9891. // The callsite will use the largest batch ID together with the latest read time to create
  9892. // a new index offset. Since we only process batch IDs if all remote documents have been read,
  9893. // no overlay will increase the overall read time. This is why we only need to special case
  9894. // the batch id.
  9895. let o = -1, u = i;
  9896. return r.next((e => bt.forEach(e, ((e, n) => (o < n.largestBatchId && (o = n.largestBatchId),
  9897. i.get(e) ? bt.resolve() : this.remoteDocumentCache.getEntry(t, e).next((t => {
  9898. u = u.insert(e, t);
  9899. }))))).next((() => this.populateOverlays(t, e, i))).next((() => this.computeViews(t, u, e, Is()))).next((t => ({
  9900. batchId: o,
  9901. changes: ws(t)
  9902. })))));
  9903. }));
  9904. }
  9905. getDocumentsMatchingDocumentQuery(t, e) {
  9906. // Just do a simple document lookup.
  9907. return this.getDocument(t, new ft(e)).next((t => {
  9908. let e = ds();
  9909. return t.isFoundDocument() && (e = e.insert(t.key, t)), e;
  9910. }));
  9911. }
  9912. getDocumentsMatchingCollectionGroupQuery(t, e, n) {
  9913. const s = e.collectionGroup;
  9914. let i = ds();
  9915. return this.indexManager.getCollectionParents(t, s).next((r => bt.forEach(r, (r => {
  9916. const o = function(t, e) {
  9917. return new Qn(e,
  9918. /*collectionGroup=*/ null, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  9919. }(e, r.child(s));
  9920. return this.getDocumentsMatchingCollectionQuery(t, o, n).next((t => {
  9921. t.forEach(((t, e) => {
  9922. i = i.insert(t, e);
  9923. }));
  9924. }));
  9925. })).next((() => i))));
  9926. }
  9927. getDocumentsMatchingCollectionQuery(t, e, n) {
  9928. // Query the remote documents and overlay mutations.
  9929. let s;
  9930. return this.documentOverlayCache.getOverlaysForCollection(t, e.path, n.largestBatchId).next((i => (s = i,
  9931. this.remoteDocumentCache.getDocumentsMatchingQuery(t, e, n, s)))).next((t => {
  9932. // As documents might match the query because of their overlay we need to
  9933. // include documents for all overlays in the initial document set.
  9934. s.forEach(((e, n) => {
  9935. const s = n.getKey();
  9936. null === t.get(s) && (t = t.insert(s, fn.newInvalidDocument(s)));
  9937. }));
  9938. // Apply the overlays and match against the query.
  9939. let n = ds();
  9940. return t.forEach(((t, i) => {
  9941. const r = s.get(t);
  9942. void 0 !== r && js(r.mutation, i, be.empty(), ot.now()),
  9943. // Finally, insert the documents that still match the query
  9944. rs(e, i) && (n = n.insert(t, i));
  9945. })), n;
  9946. }));
  9947. }
  9948. }
  9949. /**
  9950. * @license
  9951. * Copyright 2020 Google LLC
  9952. *
  9953. * Licensed under the Apache License, Version 2.0 (the "License");
  9954. * you may not use this file except in compliance with the License.
  9955. * You may obtain a copy of the License at
  9956. *
  9957. * http://www.apache.org/licenses/LICENSE-2.0
  9958. *
  9959. * Unless required by applicable law or agreed to in writing, software
  9960. * distributed under the License is distributed on an "AS IS" BASIS,
  9961. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9962. * See the License for the specific language governing permissions and
  9963. * limitations under the License.
  9964. */ class Fo {
  9965. constructor(t) {
  9966. this.serializer = t, this.cs = new Map, this.hs = new Map;
  9967. }
  9968. getBundleMetadata(t, e) {
  9969. return bt.resolve(this.cs.get(e));
  9970. }
  9971. saveBundleMetadata(t, e) {
  9972. /** Decodes a BundleMetadata proto into a BundleMetadata object. */
  9973. var n;
  9974. return this.cs.set(e.id, {
  9975. id: (n = e).id,
  9976. version: n.version,
  9977. createTime: Mi(n.createTime)
  9978. }), bt.resolve();
  9979. }
  9980. getNamedQuery(t, e) {
  9981. return bt.resolve(this.hs.get(e));
  9982. }
  9983. saveNamedQuery(t, e) {
  9984. return this.hs.set(e.name, function(t) {
  9985. return {
  9986. name: t.name,
  9987. query: Tr(t.bundledQuery),
  9988. readTime: Mi(t.readTime)
  9989. };
  9990. }(e)), bt.resolve();
  9991. }
  9992. }
  9993. /**
  9994. * @license
  9995. * Copyright 2022 Google LLC
  9996. *
  9997. * Licensed under the Apache License, Version 2.0 (the "License");
  9998. * you may not use this file except in compliance with the License.
  9999. * You may obtain a copy of the License at
  10000. *
  10001. * http://www.apache.org/licenses/LICENSE-2.0
  10002. *
  10003. * Unless required by applicable law or agreed to in writing, software
  10004. * distributed under the License is distributed on an "AS IS" BASIS,
  10005. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10006. * See the License for the specific language governing permissions and
  10007. * limitations under the License.
  10008. */
  10009. /**
  10010. * An in-memory implementation of DocumentOverlayCache.
  10011. */ class Bo {
  10012. constructor() {
  10013. // A map sorted by DocumentKey, whose value is a pair of the largest batch id
  10014. // for the overlay and the overlay itself.
  10015. this.overlays = new Te(ft.comparator), this.ls = new Map;
  10016. }
  10017. getOverlay(t, e) {
  10018. return bt.resolve(this.overlays.get(e));
  10019. }
  10020. getOverlays(t, e) {
  10021. const n = _s();
  10022. return bt.forEach(e, (e => this.getOverlay(t, e).next((t => {
  10023. null !== t && n.set(e, t);
  10024. })))).next((() => n));
  10025. }
  10026. saveOverlays(t, e, n) {
  10027. return n.forEach(((n, s) => {
  10028. this.we(t, e, s);
  10029. })), bt.resolve();
  10030. }
  10031. removeOverlaysForBatchId(t, e, n) {
  10032. const s = this.ls.get(n);
  10033. return void 0 !== s && (s.forEach((t => this.overlays = this.overlays.remove(t))),
  10034. this.ls.delete(n)), bt.resolve();
  10035. }
  10036. getOverlaysForCollection(t, e, n) {
  10037. const s = _s(), i = e.length + 1, r = new ft(e.child("")), o = this.overlays.getIteratorFrom(r);
  10038. for (;o.hasNext(); ) {
  10039. const t = o.getNext().value, r = t.getKey();
  10040. if (!e.isPrefixOf(r.path)) break;
  10041. // Documents from sub-collections
  10042. r.path.length === i && (t.largestBatchId > n && s.set(t.getKey(), t));
  10043. }
  10044. return bt.resolve(s);
  10045. }
  10046. getOverlaysForCollectionGroup(t, e, n, s) {
  10047. let i = new Te(((t, e) => t - e));
  10048. const r = this.overlays.getIterator();
  10049. for (;r.hasNext(); ) {
  10050. const t = r.getNext().value;
  10051. if (t.getKey().getCollectionGroup() === e && t.largestBatchId > n) {
  10052. let e = i.get(t.largestBatchId);
  10053. null === e && (e = _s(), i = i.insert(t.largestBatchId, e)), e.set(t.getKey(), t);
  10054. }
  10055. }
  10056. const o = _s(), u = i.getIterator();
  10057. for (;u.hasNext(); ) {
  10058. if (u.getNext().value.forEach(((t, e) => o.set(t, e))), o.size() >= s) break;
  10059. }
  10060. return bt.resolve(o);
  10061. }
  10062. we(t, e, n) {
  10063. // Remove the association of the overlay to its batch id.
  10064. const s = this.overlays.get(n.key);
  10065. if (null !== s) {
  10066. const t = this.ls.get(s.largestBatchId).delete(n.key);
  10067. this.ls.set(s.largestBatchId, t);
  10068. }
  10069. this.overlays = this.overlays.insert(n.key, new ii(e, n));
  10070. // Create the association of this overlay to the given largestBatchId.
  10071. let i = this.ls.get(e);
  10072. void 0 === i && (i = Is(), this.ls.set(e, i)), this.ls.set(e, i.add(n.key));
  10073. }
  10074. }
  10075. /**
  10076. * @license
  10077. * Copyright 2017 Google LLC
  10078. *
  10079. * Licensed under the Apache License, Version 2.0 (the "License");
  10080. * you may not use this file except in compliance with the License.
  10081. * You may obtain a copy of the License at
  10082. *
  10083. * http://www.apache.org/licenses/LICENSE-2.0
  10084. *
  10085. * Unless required by applicable law or agreed to in writing, software
  10086. * distributed under the License is distributed on an "AS IS" BASIS,
  10087. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10088. * See the License for the specific language governing permissions and
  10089. * limitations under the License.
  10090. */
  10091. /**
  10092. * A collection of references to a document from some kind of numbered entity
  10093. * (either a target ID or batch ID). As references are added to or removed from
  10094. * the set corresponding events are emitted to a registered garbage collector.
  10095. *
  10096. * Each reference is represented by a DocumentReference object. Each of them
  10097. * contains enough information to uniquely identify the reference. They are all
  10098. * stored primarily in a set sorted by key. A document is considered garbage if
  10099. * there's no references in that set (this can be efficiently checked thanks to
  10100. * sorting by key).
  10101. *
  10102. * ReferenceSet also keeps a secondary set that contains references sorted by
  10103. * IDs. This one is used to efficiently implement removal of all references by
  10104. * some target ID.
  10105. */ class Lo {
  10106. constructor() {
  10107. // A set of outstanding references to a document sorted by key.
  10108. this.fs = new ve(qo.ds),
  10109. // A set of outstanding references to a document sorted by target id.
  10110. this.ws = new ve(qo._s);
  10111. }
  10112. /** Returns true if the reference set contains no references. */ isEmpty() {
  10113. return this.fs.isEmpty();
  10114. }
  10115. /** Adds a reference to the given document key for the given ID. */ addReference(t, e) {
  10116. const n = new qo(t, e);
  10117. this.fs = this.fs.add(n), this.ws = this.ws.add(n);
  10118. }
  10119. /** Add references to the given document keys for the given ID. */ gs(t, e) {
  10120. t.forEach((t => this.addReference(t, e)));
  10121. }
  10122. /**
  10123. * Removes a reference to the given document key for the given
  10124. * ID.
  10125. */ removeReference(t, e) {
  10126. this.ys(new qo(t, e));
  10127. }
  10128. ps(t, e) {
  10129. t.forEach((t => this.removeReference(t, e)));
  10130. }
  10131. /**
  10132. * Clears all references with a given ID. Calls removeRef() for each key
  10133. * removed.
  10134. */ Is(t) {
  10135. const e = new ft(new at([])), n = new qo(e, t), s = new qo(e, t + 1), i = [];
  10136. return this.ws.forEachInRange([ n, s ], (t => {
  10137. this.ys(t), i.push(t.key);
  10138. })), i;
  10139. }
  10140. Ts() {
  10141. this.fs.forEach((t => this.ys(t)));
  10142. }
  10143. ys(t) {
  10144. this.fs = this.fs.delete(t), this.ws = this.ws.delete(t);
  10145. }
  10146. Es(t) {
  10147. const e = new ft(new at([])), n = new qo(e, t), s = new qo(e, t + 1);
  10148. let i = Is();
  10149. return this.ws.forEachInRange([ n, s ], (t => {
  10150. i = i.add(t.key);
  10151. })), i;
  10152. }
  10153. containsKey(t) {
  10154. const e = new qo(t, 0), n = this.fs.firstAfterOrEqual(e);
  10155. return null !== n && t.isEqual(n.key);
  10156. }
  10157. }
  10158. class qo {
  10159. constructor(t, e) {
  10160. this.key = t, this.As = e;
  10161. }
  10162. /** Compare by key then by ID */ static ds(t, e) {
  10163. return ft.comparator(t.key, e.key) || st(t.As, e.As);
  10164. }
  10165. /** Compare by ID then by key */ static _s(t, e) {
  10166. return st(t.As, e.As) || ft.comparator(t.key, e.key);
  10167. }
  10168. }
  10169. /**
  10170. * @license
  10171. * Copyright 2017 Google LLC
  10172. *
  10173. * Licensed under the Apache License, Version 2.0 (the "License");
  10174. * you may not use this file except in compliance with the License.
  10175. * You may obtain a copy of the License at
  10176. *
  10177. * http://www.apache.org/licenses/LICENSE-2.0
  10178. *
  10179. * Unless required by applicable law or agreed to in writing, software
  10180. * distributed under the License is distributed on an "AS IS" BASIS,
  10181. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10182. * See the License for the specific language governing permissions and
  10183. * limitations under the License.
  10184. */ class Uo {
  10185. constructor(t, e) {
  10186. this.indexManager = t, this.referenceDelegate = e,
  10187. /**
  10188. * The set of all mutations that have been sent but not yet been applied to
  10189. * the backend.
  10190. */
  10191. this.mutationQueue = [],
  10192. /** Next value to use when assigning sequential IDs to each mutation batch. */
  10193. this.vs = 1,
  10194. /** An ordered mapping between documents and the mutations batch IDs. */
  10195. this.Rs = new ve(qo.ds);
  10196. }
  10197. checkEmpty(t) {
  10198. return bt.resolve(0 === this.mutationQueue.length);
  10199. }
  10200. addMutationBatch(t, e, n, s) {
  10201. const i = this.vs;
  10202. this.vs++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];
  10203. const r = new ni(i, e, n, s);
  10204. this.mutationQueue.push(r);
  10205. // Track references by document key and index collection parents.
  10206. for (const e of s) this.Rs = this.Rs.add(new qo(e.key, i)), this.indexManager.addToCollectionParentIndex(t, e.key.path.popLast());
  10207. return bt.resolve(r);
  10208. }
  10209. lookupMutationBatch(t, e) {
  10210. return bt.resolve(this.Ps(e));
  10211. }
  10212. getNextMutationBatchAfterBatchId(t, e) {
  10213. const n = e + 1, s = this.bs(n), i = s < 0 ? 0 : s;
  10214. // The requested batchId may still be out of range so normalize it to the
  10215. // start of the queue.
  10216. return bt.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);
  10217. }
  10218. getHighestUnacknowledgedBatchId() {
  10219. return bt.resolve(0 === this.mutationQueue.length ? -1 : this.vs - 1);
  10220. }
  10221. getAllMutationBatches(t) {
  10222. return bt.resolve(this.mutationQueue.slice());
  10223. }
  10224. getAllMutationBatchesAffectingDocumentKey(t, e) {
  10225. const n = new qo(e, 0), s = new qo(e, Number.POSITIVE_INFINITY), i = [];
  10226. return this.Rs.forEachInRange([ n, s ], (t => {
  10227. const e = this.Ps(t.As);
  10228. i.push(e);
  10229. })), bt.resolve(i);
  10230. }
  10231. getAllMutationBatchesAffectingDocumentKeys(t, e) {
  10232. let n = new ve(st);
  10233. return e.forEach((t => {
  10234. const e = new qo(t, 0), s = new qo(t, Number.POSITIVE_INFINITY);
  10235. this.Rs.forEachInRange([ e, s ], (t => {
  10236. n = n.add(t.As);
  10237. }));
  10238. })), bt.resolve(this.Vs(n));
  10239. }
  10240. getAllMutationBatchesAffectingQuery(t, e) {
  10241. // Use the query path as a prefix for testing if a document matches the
  10242. // query.
  10243. const n = e.path, s = n.length + 1;
  10244. // Construct a document reference for actually scanning the index. Unlike
  10245. // the prefix the document key in this reference must have an even number of
  10246. // segments. The empty segment can be used a suffix of the query path
  10247. // because it precedes all other segments in an ordered traversal.
  10248. let i = n;
  10249. ft.isDocumentKey(i) || (i = i.child(""));
  10250. const r = new qo(new ft(i), 0);
  10251. // Find unique batchIDs referenced by all documents potentially matching the
  10252. // query.
  10253. let o = new ve(st);
  10254. return this.Rs.forEachWhile((t => {
  10255. const e = t.key.path;
  10256. return !!n.isPrefixOf(e) && (
  10257. // Rows with document keys more than one segment longer than the query
  10258. // path can't be matches. For example, a query on 'rooms' can't match
  10259. // the document /rooms/abc/messages/xyx.
  10260. // TODO(mcg): we'll need a different scanner when we implement
  10261. // ancestor queries.
  10262. e.length === s && (o = o.add(t.As)), !0);
  10263. }), r), bt.resolve(this.Vs(o));
  10264. }
  10265. Vs(t) {
  10266. // Construct an array of matching batches, sorted by batchID to ensure that
  10267. // multiple mutations affecting the same document key are applied in order.
  10268. const e = [];
  10269. return t.forEach((t => {
  10270. const n = this.Ps(t);
  10271. null !== n && e.push(n);
  10272. })), e;
  10273. }
  10274. removeMutationBatch(t, e) {
  10275. L(0 === this.Ss(e.batchId, "removed")), this.mutationQueue.shift();
  10276. let n = this.Rs;
  10277. return bt.forEach(e.mutations, (s => {
  10278. const i = new qo(s.key, e.batchId);
  10279. return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(t, s.key);
  10280. })).next((() => {
  10281. this.Rs = n;
  10282. }));
  10283. }
  10284. Cn(t) {
  10285. // No-op since the memory mutation queue does not maintain a separate cache.
  10286. }
  10287. containsKey(t, e) {
  10288. const n = new qo(e, 0), s = this.Rs.firstAfterOrEqual(n);
  10289. return bt.resolve(e.isEqual(s && s.key));
  10290. }
  10291. performConsistencyCheck(t) {
  10292. return this.mutationQueue.length, bt.resolve();
  10293. }
  10294. /**
  10295. * Finds the index of the given batchId in the mutation queue and asserts that
  10296. * the resulting index is within the bounds of the queue.
  10297. *
  10298. * @param batchId - The batchId to search for
  10299. * @param action - A description of what the caller is doing, phrased in passive
  10300. * form (e.g. "acknowledged" in a routine that acknowledges batches).
  10301. */ Ss(t, e) {
  10302. return this.bs(t);
  10303. }
  10304. /**
  10305. * Finds the index of the given batchId in the mutation queue. This operation
  10306. * is O(1).
  10307. *
  10308. * @returns The computed index of the batch with the given batchId, based on
  10309. * the state of the queue. Note this index can be negative if the requested
  10310. * batchId has already been remvoed from the queue or past the end of the
  10311. * queue if the batchId is larger than the last added batch.
  10312. */ bs(t) {
  10313. if (0 === this.mutationQueue.length)
  10314. // As an index this is past the end of the queue
  10315. return 0;
  10316. // Examine the front of the queue to figure out the difference between the
  10317. // batchId and indexes in the array. Note that since the queue is ordered
  10318. // by batchId, if the first batch has a larger batchId then the requested
  10319. // batchId doesn't exist in the queue.
  10320. return t - this.mutationQueue[0].batchId;
  10321. }
  10322. /**
  10323. * A version of lookupMutationBatch that doesn't return a promise, this makes
  10324. * other functions that uses this code easier to read and more efficent.
  10325. */ Ps(t) {
  10326. const e = this.bs(t);
  10327. if (e < 0 || e >= this.mutationQueue.length) return null;
  10328. return this.mutationQueue[e];
  10329. }
  10330. }
  10331. /**
  10332. * @license
  10333. * Copyright 2017 Google LLC
  10334. *
  10335. * Licensed under the Apache License, Version 2.0 (the "License");
  10336. * you may not use this file except in compliance with the License.
  10337. * You may obtain a copy of the License at
  10338. *
  10339. * http://www.apache.org/licenses/LICENSE-2.0
  10340. *
  10341. * Unless required by applicable law or agreed to in writing, software
  10342. * distributed under the License is distributed on an "AS IS" BASIS,
  10343. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10344. * See the License for the specific language governing permissions and
  10345. * limitations under the License.
  10346. */
  10347. /**
  10348. * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke
  10349. * `newMemoryRemoteDocumentCache()`.
  10350. */
  10351. class Ko {
  10352. /**
  10353. * @param sizer - Used to assess the size of a document. For eager GC, this is
  10354. * expected to just return 0 to avoid unnecessarily doing the work of
  10355. * calculating the size.
  10356. */
  10357. constructor(t) {
  10358. this.Ds = t,
  10359. /** Underlying cache of documents and their read times. */
  10360. this.docs = new Te(ft.comparator),
  10361. /** Size of all cached documents. */
  10362. this.size = 0;
  10363. }
  10364. setIndexManager(t) {
  10365. this.indexManager = t;
  10366. }
  10367. /**
  10368. * Adds the supplied entry to the cache and updates the cache size as appropriate.
  10369. *
  10370. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  10371. * returned by `newChangeBuffer()`.
  10372. */ addEntry(t, e) {
  10373. const n = e.key, s = this.docs.get(n), i = s ? s.size : 0, r = this.Ds(e);
  10374. return this.docs = this.docs.insert(n, {
  10375. document: e.mutableCopy(),
  10376. size: r
  10377. }), this.size += r - i, this.indexManager.addToCollectionParentIndex(t, n.path.popLast());
  10378. }
  10379. /**
  10380. * Removes the specified entry from the cache and updates the cache size as appropriate.
  10381. *
  10382. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  10383. * returned by `newChangeBuffer()`.
  10384. */ removeEntry(t) {
  10385. const e = this.docs.get(t);
  10386. e && (this.docs = this.docs.remove(t), this.size -= e.size);
  10387. }
  10388. getEntry(t, e) {
  10389. const n = this.docs.get(e);
  10390. return bt.resolve(n ? n.document.mutableCopy() : fn.newInvalidDocument(e));
  10391. }
  10392. getEntries(t, e) {
  10393. let n = ls();
  10394. return e.forEach((t => {
  10395. const e = this.docs.get(t);
  10396. n = n.insert(t, e ? e.document.mutableCopy() : fn.newInvalidDocument(t));
  10397. })), bt.resolve(n);
  10398. }
  10399. getDocumentsMatchingQuery(t, e, n, s) {
  10400. let i = ls();
  10401. // Documents are ordered by key, so we can use a prefix scan to narrow down
  10402. // the documents we need to match the query against.
  10403. const r = e.path, o = new ft(r.child("")), u = this.docs.getIteratorFrom(o);
  10404. for (;u.hasNext(); ) {
  10405. const {key: t, value: {document: o}} = u.getNext();
  10406. if (!r.isPrefixOf(t.path)) break;
  10407. t.path.length > r.length + 1 || (At(Tt(o), n) <= 0 || (s.has(o.key) || rs(e, o)) && (i = i.insert(o.key, o.mutableCopy())));
  10408. }
  10409. return bt.resolve(i);
  10410. }
  10411. getAllFromCollectionGroup(t, e, n, s) {
  10412. // This method should only be called from the IndexBackfiller if persistence
  10413. // is enabled.
  10414. B();
  10415. }
  10416. Cs(t, e) {
  10417. return bt.forEach(this.docs, (t => e(t)));
  10418. }
  10419. newChangeBuffer(t) {
  10420. // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
  10421. // a separate changelog and does not need special handling for removals.
  10422. return new Go(this);
  10423. }
  10424. getSize(t) {
  10425. return bt.resolve(this.size);
  10426. }
  10427. }
  10428. /**
  10429. * Creates a new memory-only RemoteDocumentCache.
  10430. *
  10431. * @param sizer - Used to assess the size of a document. For eager GC, this is
  10432. * expected to just return 0 to avoid unnecessarily doing the work of
  10433. * calculating the size.
  10434. */
  10435. /**
  10436. * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.
  10437. */
  10438. class Go extends bo {
  10439. constructor(t) {
  10440. super(), this.os = t;
  10441. }
  10442. applyChanges(t) {
  10443. const e = [];
  10444. return this.changes.forEach(((n, s) => {
  10445. s.isValidDocument() ? e.push(this.os.addEntry(t, s)) : this.os.removeEntry(n);
  10446. })), bt.waitFor(e);
  10447. }
  10448. getFromCache(t, e) {
  10449. return this.os.getEntry(t, e);
  10450. }
  10451. getAllFromCache(t, e) {
  10452. return this.os.getEntries(t, e);
  10453. }
  10454. }
  10455. /**
  10456. * @license
  10457. * Copyright 2017 Google LLC
  10458. *
  10459. * Licensed under the Apache License, Version 2.0 (the "License");
  10460. * you may not use this file except in compliance with the License.
  10461. * You may obtain a copy of the License at
  10462. *
  10463. * http://www.apache.org/licenses/LICENSE-2.0
  10464. *
  10465. * Unless required by applicable law or agreed to in writing, software
  10466. * distributed under the License is distributed on an "AS IS" BASIS,
  10467. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10468. * See the License for the specific language governing permissions and
  10469. * limitations under the License.
  10470. */ class Qo {
  10471. constructor(t) {
  10472. this.persistence = t,
  10473. /**
  10474. * Maps a target to the data about that target
  10475. */
  10476. this.xs = new as((t => Bn(t)), Ln),
  10477. /** The last received snapshot version. */
  10478. this.lastRemoteSnapshotVersion = ut.min(),
  10479. /** The highest numbered target ID encountered. */
  10480. this.highestTargetId = 0,
  10481. /** The highest sequence number encountered. */
  10482. this.Ns = 0,
  10483. /**
  10484. * A ordered bidirectional mapping between documents and the remote target
  10485. * IDs.
  10486. */
  10487. this.ks = new Lo, this.targetCount = 0, this.$s = _o.kn();
  10488. }
  10489. forEachTarget(t, e) {
  10490. return this.xs.forEach(((t, n) => e(n))), bt.resolve();
  10491. }
  10492. getLastRemoteSnapshotVersion(t) {
  10493. return bt.resolve(this.lastRemoteSnapshotVersion);
  10494. }
  10495. getHighestSequenceNumber(t) {
  10496. return bt.resolve(this.Ns);
  10497. }
  10498. allocateTargetId(t) {
  10499. return this.highestTargetId = this.$s.next(), bt.resolve(this.highestTargetId);
  10500. }
  10501. setTargetsMetadata(t, e, n) {
  10502. return n && (this.lastRemoteSnapshotVersion = n), e > this.Ns && (this.Ns = e),
  10503. bt.resolve();
  10504. }
  10505. Fn(t) {
  10506. this.xs.set(t.target, t);
  10507. const e = t.targetId;
  10508. e > this.highestTargetId && (this.$s = new _o(e), this.highestTargetId = e), t.sequenceNumber > this.Ns && (this.Ns = t.sequenceNumber);
  10509. }
  10510. addTargetData(t, e) {
  10511. return this.Fn(e), this.targetCount += 1, bt.resolve();
  10512. }
  10513. updateTargetData(t, e) {
  10514. return this.Fn(e), bt.resolve();
  10515. }
  10516. removeTargetData(t, e) {
  10517. return this.xs.delete(e.target), this.ks.Is(e.targetId), this.targetCount -= 1,
  10518. bt.resolve();
  10519. }
  10520. removeTargets(t, e, n) {
  10521. let s = 0;
  10522. const i = [];
  10523. return this.xs.forEach(((r, o) => {
  10524. o.sequenceNumber <= e && null === n.get(o.targetId) && (this.xs.delete(r), i.push(this.removeMatchingKeysForTargetId(t, o.targetId)),
  10525. s++);
  10526. })), bt.waitFor(i).next((() => s));
  10527. }
  10528. getTargetCount(t) {
  10529. return bt.resolve(this.targetCount);
  10530. }
  10531. getTargetData(t, e) {
  10532. const n = this.xs.get(e) || null;
  10533. return bt.resolve(n);
  10534. }
  10535. addMatchingKeys(t, e, n) {
  10536. return this.ks.gs(e, n), bt.resolve();
  10537. }
  10538. removeMatchingKeys(t, e, n) {
  10539. this.ks.ps(e, n);
  10540. const s = this.persistence.referenceDelegate, i = [];
  10541. return s && e.forEach((e => {
  10542. i.push(s.markPotentiallyOrphaned(t, e));
  10543. })), bt.waitFor(i);
  10544. }
  10545. removeMatchingKeysForTargetId(t, e) {
  10546. return this.ks.Is(e), bt.resolve();
  10547. }
  10548. getMatchingKeysForTargetId(t, e) {
  10549. const n = this.ks.Es(e);
  10550. return bt.resolve(n);
  10551. }
  10552. containsKey(t, e) {
  10553. return bt.resolve(this.ks.containsKey(e));
  10554. }
  10555. }
  10556. /**
  10557. * @license
  10558. * Copyright 2017 Google LLC
  10559. *
  10560. * Licensed under the Apache License, Version 2.0 (the "License");
  10561. * you may not use this file except in compliance with the License.
  10562. * You may obtain a copy of the License at
  10563. *
  10564. * http://www.apache.org/licenses/LICENSE-2.0
  10565. *
  10566. * Unless required by applicable law or agreed to in writing, software
  10567. * distributed under the License is distributed on an "AS IS" BASIS,
  10568. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10569. * See the License for the specific language governing permissions and
  10570. * limitations under the License.
  10571. */
  10572. /**
  10573. * A memory-backed instance of Persistence. Data is stored only in RAM and
  10574. * not persisted across sessions.
  10575. */
  10576. class jo {
  10577. /**
  10578. * The constructor accepts a factory for creating a reference delegate. This
  10579. * allows both the delegate and this instance to have strong references to
  10580. * each other without having nullable fields that would then need to be
  10581. * checked or asserted on every access.
  10582. */
  10583. constructor(t, e) {
  10584. this.Ms = {}, this.overlays = {}, this.Os = new Bt(0), this.Fs = !1, this.Fs = !0,
  10585. this.referenceDelegate = t(this), this.Bs = new Qo(this);
  10586. this.indexManager = new Jr, this.remoteDocumentCache = function(t) {
  10587. return new Ko(t);
  10588. }((t => this.referenceDelegate.Ls(t))), this.serializer = new fr(e), this.qs = new Fo(this.serializer);
  10589. }
  10590. start() {
  10591. return Promise.resolve();
  10592. }
  10593. shutdown() {
  10594. // No durable state to ensure is closed on shutdown.
  10595. return this.Fs = !1, Promise.resolve();
  10596. }
  10597. get started() {
  10598. return this.Fs;
  10599. }
  10600. setDatabaseDeletedListener() {
  10601. // No op.
  10602. }
  10603. setNetworkEnabled() {
  10604. // No op.
  10605. }
  10606. getIndexManager(t) {
  10607. // We do not currently support indices for memory persistence, so we can
  10608. // return the same shared instance of the memory index manager.
  10609. return this.indexManager;
  10610. }
  10611. getDocumentOverlayCache(t) {
  10612. let e = this.overlays[t.toKey()];
  10613. return e || (e = new Bo, this.overlays[t.toKey()] = e), e;
  10614. }
  10615. getMutationQueue(t, e) {
  10616. let n = this.Ms[t.toKey()];
  10617. return n || (n = new Uo(e, this.referenceDelegate), this.Ms[t.toKey()] = n), n;
  10618. }
  10619. getTargetCache() {
  10620. return this.Bs;
  10621. }
  10622. getRemoteDocumentCache() {
  10623. return this.remoteDocumentCache;
  10624. }
  10625. getBundleCache() {
  10626. return this.qs;
  10627. }
  10628. runTransaction(t, e, n) {
  10629. $("MemoryPersistence", "Starting transaction:", t);
  10630. const s = new zo(this.Os.next());
  10631. return this.referenceDelegate.Us(), n(s).next((t => this.referenceDelegate.Ks(s).next((() => t)))).toPromise().then((t => (s.raiseOnCommittedEvent(),
  10632. t)));
  10633. }
  10634. Gs(t, e) {
  10635. return bt.or(Object.values(this.Ms).map((n => () => n.containsKey(t, e))));
  10636. }
  10637. }
  10638. /**
  10639. * Memory persistence is not actually transactional, but future implementations
  10640. * may have transaction-scoped state.
  10641. */ class zo extends Rt {
  10642. constructor(t) {
  10643. super(), this.currentSequenceNumber = t;
  10644. }
  10645. }
  10646. class Wo {
  10647. constructor(t) {
  10648. this.persistence = t,
  10649. /** Tracks all documents that are active in Query views. */
  10650. this.Qs = new Lo,
  10651. /** The list of documents that are potentially GCed after each transaction. */
  10652. this.js = null;
  10653. }
  10654. static zs(t) {
  10655. return new Wo(t);
  10656. }
  10657. get Ws() {
  10658. if (this.js) return this.js;
  10659. throw B();
  10660. }
  10661. addReference(t, e, n) {
  10662. return this.Qs.addReference(n, e), this.Ws.delete(n.toString()), bt.resolve();
  10663. }
  10664. removeReference(t, e, n) {
  10665. return this.Qs.removeReference(n, e), this.Ws.add(n.toString()), bt.resolve();
  10666. }
  10667. markPotentiallyOrphaned(t, e) {
  10668. return this.Ws.add(e.toString()), bt.resolve();
  10669. }
  10670. removeTarget(t, e) {
  10671. this.Qs.Is(e.targetId).forEach((t => this.Ws.add(t.toString())));
  10672. const n = this.persistence.getTargetCache();
  10673. return n.getMatchingKeysForTargetId(t, e.targetId).next((t => {
  10674. t.forEach((t => this.Ws.add(t.toString())));
  10675. })).next((() => n.removeTargetData(t, e)));
  10676. }
  10677. Us() {
  10678. this.js = new Set;
  10679. }
  10680. Ks(t) {
  10681. // Remove newly orphaned documents.
  10682. const e = this.persistence.getRemoteDocumentCache().newChangeBuffer();
  10683. return bt.forEach(this.Ws, (n => {
  10684. const s = ft.fromPath(n);
  10685. return this.Hs(t, s).next((t => {
  10686. t || e.removeEntry(s, ut.min());
  10687. }));
  10688. })).next((() => (this.js = null, e.apply(t))));
  10689. }
  10690. updateLimboDocument(t, e) {
  10691. return this.Hs(t, e).next((t => {
  10692. t ? this.Ws.delete(e.toString()) : this.Ws.add(e.toString());
  10693. }));
  10694. }
  10695. Ls(t) {
  10696. // For eager GC, we don't care about the document size, there are no size thresholds.
  10697. return 0;
  10698. }
  10699. Hs(t, e) {
  10700. return bt.or([ () => bt.resolve(this.Qs.containsKey(e)), () => this.persistence.getTargetCache().containsKey(t, e), () => this.persistence.Gs(t, e) ]);
  10701. }
  10702. }
  10703. class Ho {
  10704. constructor(t, e) {
  10705. this.persistence = t, this.Js = new as((t => Kt(t.path)), ((t, e) => t.isEqual(e))),
  10706. this.garbageCollector = vo(this, e);
  10707. }
  10708. static zs(t, e) {
  10709. return new Ho(t, e);
  10710. }
  10711. // No-ops, present so memory persistence doesn't have to care which delegate
  10712. // it has.
  10713. Us() {}
  10714. Ks(t) {
  10715. return bt.resolve();
  10716. }
  10717. forEachTarget(t, e) {
  10718. return this.persistence.getTargetCache().forEachTarget(t, e);
  10719. }
  10720. zn(t) {
  10721. const e = this.Jn(t);
  10722. return this.persistence.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));
  10723. }
  10724. Jn(t) {
  10725. let e = 0;
  10726. return this.Wn(t, (t => {
  10727. e++;
  10728. })).next((() => e));
  10729. }
  10730. Wn(t, e) {
  10731. return bt.forEach(this.Js, ((n, s) => this.Xn(t, n, s).next((t => t ? bt.resolve() : e(s)))));
  10732. }
  10733. removeTargets(t, e, n) {
  10734. return this.persistence.getTargetCache().removeTargets(t, e, n);
  10735. }
  10736. removeOrphanedDocuments(t, e) {
  10737. let n = 0;
  10738. const s = this.persistence.getRemoteDocumentCache(), i = s.newChangeBuffer();
  10739. return s.Cs(t, (s => this.Xn(t, s, e).next((t => {
  10740. t || (n++, i.removeEntry(s, ut.min()));
  10741. })))).next((() => i.apply(t))).next((() => n));
  10742. }
  10743. markPotentiallyOrphaned(t, e) {
  10744. return this.Js.set(e, t.currentSequenceNumber), bt.resolve();
  10745. }
  10746. removeTarget(t, e) {
  10747. const n = e.withSequenceNumber(t.currentSequenceNumber);
  10748. return this.persistence.getTargetCache().updateTargetData(t, n);
  10749. }
  10750. addReference(t, e, n) {
  10751. return this.Js.set(n, t.currentSequenceNumber), bt.resolve();
  10752. }
  10753. removeReference(t, e, n) {
  10754. return this.Js.set(n, t.currentSequenceNumber), bt.resolve();
  10755. }
  10756. updateLimboDocument(t, e) {
  10757. return this.Js.set(e, t.currentSequenceNumber), bt.resolve();
  10758. }
  10759. Ls(t) {
  10760. let e = t.key.toString().length;
  10761. return t.isFoundDocument() && (e += Je(t.data.value)), e;
  10762. }
  10763. Xn(t, e, n) {
  10764. return bt.or([ () => this.persistence.Gs(t, e), () => this.persistence.getTargetCache().containsKey(t, e), () => {
  10765. const t = this.Js.get(e);
  10766. return bt.resolve(void 0 !== t && t > n);
  10767. } ]);
  10768. }
  10769. getCacheSize(t) {
  10770. return this.persistence.getRemoteDocumentCache().getSize(t);
  10771. }
  10772. }
  10773. /**
  10774. * @license
  10775. * Copyright 2020 Google LLC
  10776. *
  10777. * Licensed under the Apache License, Version 2.0 (the "License");
  10778. * you may not use this file except in compliance with the License.
  10779. * You may obtain a copy of the License at
  10780. *
  10781. * http://www.apache.org/licenses/LICENSE-2.0
  10782. *
  10783. * Unless required by applicable law or agreed to in writing, software
  10784. * distributed under the License is distributed on an "AS IS" BASIS,
  10785. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10786. * See the License for the specific language governing permissions and
  10787. * limitations under the License.
  10788. */
  10789. /** Performs database creation and schema upgrades. */ class Jo {
  10790. constructor(t) {
  10791. this.serializer = t;
  10792. }
  10793. /**
  10794. * Performs database creation and schema upgrades.
  10795. *
  10796. * Note that in production, this method is only ever used to upgrade the schema
  10797. * to SCHEMA_VERSION. Different values of toVersion are only used for testing
  10798. * and local feature development.
  10799. */ O(t, e, n, s) {
  10800. const i = new Vt("createOrUpgrade", e);
  10801. n < 1 && s >= 1 && (function(t) {
  10802. t.createObjectStore("owner");
  10803. }(t), function(t) {
  10804. t.createObjectStore("mutationQueues", {
  10805. keyPath: "userId"
  10806. });
  10807. t.createObjectStore("mutations", {
  10808. keyPath: "batchId",
  10809. autoIncrement: !0
  10810. }).createIndex("userMutationsIndex", zt, {
  10811. unique: !0
  10812. }), t.createObjectStore("documentMutations");
  10813. }
  10814. /**
  10815. * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads
  10816. * and rewrites all data.
  10817. */ (t), Yo(t), function(t) {
  10818. t.createObjectStore("remoteDocuments");
  10819. }(t));
  10820. // Migration 2 to populate the targetGlobal object no longer needed since
  10821. // migration 3 unconditionally clears it.
  10822. let r = bt.resolve();
  10823. return n < 3 && s >= 3 && (
  10824. // Brand new clients don't need to drop and recreate--only clients that
  10825. // potentially have corrupt data.
  10826. 0 !== n && (!function(t) {
  10827. t.deleteObjectStore("targetDocuments"), t.deleteObjectStore("targets"), t.deleteObjectStore("targetGlobal");
  10828. }(t), Yo(t)), r = r.next((() =>
  10829. /**
  10830. * Creates the target global singleton row.
  10831. *
  10832. * @param txn - The version upgrade transaction for indexeddb
  10833. */
  10834. function(t) {
  10835. const e = t.store("targetGlobal"), n = {
  10836. highestTargetId: 0,
  10837. highestListenSequenceNumber: 0,
  10838. lastRemoteSnapshotVersion: ut.min().toTimestamp(),
  10839. targetCount: 0
  10840. };
  10841. return e.put("targetGlobalKey", n);
  10842. }(i)))), n < 4 && s >= 4 && (0 !== n && (
  10843. // Schema version 3 uses auto-generated keys to generate globally unique
  10844. // mutation batch IDs (this was previously ensured internally by the
  10845. // client). To migrate to the new schema, we have to read all mutations
  10846. // and write them back out. We preserve the existing batch IDs to guarantee
  10847. // consistency with other object stores. Any further mutation batch IDs will
  10848. // be auto-generated.
  10849. r = r.next((() => function(t, e) {
  10850. return e.store("mutations").j().next((n => {
  10851. t.deleteObjectStore("mutations");
  10852. t.createObjectStore("mutations", {
  10853. keyPath: "batchId",
  10854. autoIncrement: !0
  10855. }).createIndex("userMutationsIndex", zt, {
  10856. unique: !0
  10857. });
  10858. const s = e.store("mutations"), i = n.map((t => s.put(t)));
  10859. return bt.waitFor(i);
  10860. }));
  10861. }(t, i)))), r = r.next((() => {
  10862. !function(t) {
  10863. t.createObjectStore("clientMetadata", {
  10864. keyPath: "clientId"
  10865. });
  10866. }(t);
  10867. }))), n < 5 && s >= 5 && (r = r.next((() => this.Ys(i)))), n < 6 && s >= 6 && (r = r.next((() => (function(t) {
  10868. t.createObjectStore("remoteDocumentGlobal");
  10869. }(t), this.Xs(i))))), n < 7 && s >= 7 && (r = r.next((() => this.Zs(i)))), n < 8 && s >= 8 && (r = r.next((() => this.ti(t, i)))),
  10870. n < 9 && s >= 9 && (r = r.next((() => {
  10871. // Multi-Tab used to manage its own changelog, but this has been moved
  10872. // to the DbRemoteDocument object store itself. Since the previous change
  10873. // log only contained transient data, we can drop its object store.
  10874. !function(t) {
  10875. t.objectStoreNames.contains("remoteDocumentChanges") && t.deleteObjectStore("remoteDocumentChanges");
  10876. }(t);
  10877. // Note: Schema version 9 used to create a read time index for the
  10878. // RemoteDocumentCache. This is now done with schema version 13.
  10879. }))), n < 10 && s >= 10 && (r = r.next((() => this.ei(i)))), n < 11 && s >= 11 && (r = r.next((() => {
  10880. !function(t) {
  10881. t.createObjectStore("bundles", {
  10882. keyPath: "bundleId"
  10883. });
  10884. }(t), function(t) {
  10885. t.createObjectStore("namedQueries", {
  10886. keyPath: "name"
  10887. });
  10888. }(t);
  10889. }))), n < 12 && s >= 12 && (r = r.next((() => {
  10890. !function(t) {
  10891. const e = t.createObjectStore("documentOverlays", {
  10892. keyPath: ce
  10893. });
  10894. e.createIndex("collectionPathOverlayIndex", ae, {
  10895. unique: !1
  10896. }), e.createIndex("collectionGroupOverlayIndex", he, {
  10897. unique: !1
  10898. });
  10899. }(t);
  10900. }))), n < 13 && s >= 13 && (r = r.next((() => function(t) {
  10901. const e = t.createObjectStore("remoteDocumentsV14", {
  10902. keyPath: Yt
  10903. });
  10904. e.createIndex("documentKeyIndex", Xt), e.createIndex("collectionGroupIndex", Zt);
  10905. }(t))).next((() => this.ni(t, i))).next((() => t.deleteObjectStore("remoteDocuments")))),
  10906. n < 14 && s >= 14 && (r = r.next((() => this.si(t, i)))), n < 15 && s >= 15 && (r = r.next((() => function(t) {
  10907. t.createObjectStore("indexConfiguration", {
  10908. keyPath: "indexId",
  10909. autoIncrement: !0
  10910. }).createIndex("collectionGroupIndex", "collectionGroup", {
  10911. unique: !1
  10912. });
  10913. t.createObjectStore("indexState", {
  10914. keyPath: ie
  10915. }).createIndex("sequenceNumberIndex", re, {
  10916. unique: !1
  10917. });
  10918. t.createObjectStore("indexEntries", {
  10919. keyPath: oe
  10920. }).createIndex("documentKeyIndex", ue, {
  10921. unique: !1
  10922. });
  10923. }(t)))), r;
  10924. }
  10925. Xs(t) {
  10926. let e = 0;
  10927. return t.store("remoteDocuments").X(((t, n) => {
  10928. e += co(n);
  10929. })).next((() => {
  10930. const n = {
  10931. byteSize: e
  10932. };
  10933. return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey", n);
  10934. }));
  10935. }
  10936. Ys(t) {
  10937. const e = t.store("mutationQueues"), n = t.store("mutations");
  10938. return e.j().next((e => bt.forEach(e, (e => {
  10939. const s = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);
  10940. return n.j("userMutationsIndex", s).next((n => bt.forEach(n, (n => {
  10941. L(n.userId === e.userId);
  10942. const s = yr(this.serializer, n);
  10943. return uo(t, e.userId, s).next((() => {}));
  10944. }))));
  10945. }))));
  10946. }
  10947. /**
  10948. * Ensures that every document in the remote document cache has a corresponding sentinel row
  10949. * with a sequence number. Missing rows are given the most recently used sequence number.
  10950. */ Zs(t) {
  10951. const e = t.store("targetDocuments"), n = t.store("remoteDocuments");
  10952. return t.store("targetGlobal").get("targetGlobalKey").next((t => {
  10953. const s = [];
  10954. return n.X(((n, i) => {
  10955. const r = new at(n), o = function(t) {
  10956. return [ 0, Kt(t) ];
  10957. }(r);
  10958. s.push(e.get(o).next((n => n ? bt.resolve() : (n => e.put({
  10959. targetId: 0,
  10960. path: Kt(n),
  10961. sequenceNumber: t.highestListenSequenceNumber
  10962. }))(r))));
  10963. })).next((() => bt.waitFor(s)));
  10964. }));
  10965. }
  10966. ti(t, e) {
  10967. // Create the index.
  10968. t.createObjectStore("collectionParents", {
  10969. keyPath: se
  10970. });
  10971. const n = e.store("collectionParents"), s = new Yr, i = t => {
  10972. if (s.add(t)) {
  10973. const e = t.lastSegment(), s = t.popLast();
  10974. return n.put({
  10975. collectionId: e,
  10976. parent: Kt(s)
  10977. });
  10978. }
  10979. };
  10980. // Helper to add an index entry iff we haven't already written it.
  10981. // Index existing remote documents.
  10982. return e.store("remoteDocuments").X({
  10983. Y: !0
  10984. }, ((t, e) => {
  10985. const n = new at(t);
  10986. return i(n.popLast());
  10987. })).next((() => e.store("documentMutations").X({
  10988. Y: !0
  10989. }, (([t, e, n], s) => {
  10990. const r = jt(e);
  10991. return i(r.popLast());
  10992. }))));
  10993. }
  10994. ei(t) {
  10995. const e = t.store("targets");
  10996. return e.X(((t, n) => {
  10997. const s = pr(n), i = Ir(this.serializer, s);
  10998. return e.put(i);
  10999. }));
  11000. }
  11001. ni(t, e) {
  11002. const n = e.store("remoteDocuments"), s = [];
  11003. return n.X(((t, n) => {
  11004. const i = e.store("remoteDocumentsV14"), r = (o = n, o.document ? new ft(at.fromString(o.document.name).popFirst(5)) : o.noDocument ? ft.fromSegments(o.noDocument.path) : o.unknownDocument ? ft.fromSegments(o.unknownDocument.path) : B()).path.toArray();
  11005. var o;
  11006. /**
  11007. * @license
  11008. * Copyright 2017 Google LLC
  11009. *
  11010. * Licensed under the Apache License, Version 2.0 (the "License");
  11011. * you may not use this file except in compliance with the License.
  11012. * You may obtain a copy of the License at
  11013. *
  11014. * http://www.apache.org/licenses/LICENSE-2.0
  11015. *
  11016. * Unless required by applicable law or agreed to in writing, software
  11017. * distributed under the License is distributed on an "AS IS" BASIS,
  11018. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11019. * See the License for the specific language governing permissions and
  11020. * limitations under the License.
  11021. */ const u = {
  11022. prefixPath: r.slice(0, r.length - 2),
  11023. collectionGroup: r[r.length - 2],
  11024. documentId: r[r.length - 1],
  11025. readTime: n.readTime || [ 0, 0 ],
  11026. unknownDocument: n.unknownDocument,
  11027. noDocument: n.noDocument,
  11028. document: n.document,
  11029. hasCommittedMutations: !!n.hasCommittedMutations
  11030. };
  11031. s.push(i.put(u));
  11032. })).next((() => bt.waitFor(s)));
  11033. }
  11034. si(t, e) {
  11035. const n = e.store("mutations"), s = So(this.serializer), i = new jo(Wo.zs, this.serializer.fe);
  11036. return n.j().next((t => {
  11037. const n = new Map;
  11038. return t.forEach((t => {
  11039. var e;
  11040. let s = null !== (e = n.get(t.userId)) && void 0 !== e ? e : Is();
  11041. yr(this.serializer, t).keys().forEach((t => s = s.add(t))), n.set(t.userId, s);
  11042. })), bt.forEach(n, ((t, n) => {
  11043. const r = new D(n), o = Vr.de(this.serializer, r), u = i.getIndexManager(r), c = ao.de(r, this.serializer, u, i.referenceDelegate);
  11044. return new Oo(s, c, o, u).recalculateAndSaveOverlaysForDocumentKeys(new me(e, Bt.ct), t).next();
  11045. }));
  11046. }));
  11047. }
  11048. }
  11049. function Yo(t) {
  11050. t.createObjectStore("targetDocuments", {
  11051. keyPath: ee
  11052. }).createIndex("documentTargetsIndex", ne, {
  11053. unique: !0
  11054. });
  11055. // NOTE: This is unique only because the TargetId is the suffix.
  11056. t.createObjectStore("targets", {
  11057. keyPath: "targetId"
  11058. }).createIndex("queryTargetsIndex", te, {
  11059. unique: !0
  11060. }), t.createObjectStore("targetGlobal");
  11061. }
  11062. const Xo = "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.";
  11063. /**
  11064. * Oldest acceptable age in milliseconds for client metadata before the client
  11065. * is considered inactive and its associated data is garbage collected.
  11066. */
  11067. /**
  11068. * An IndexedDB-backed instance of Persistence. Data is stored persistently
  11069. * across sessions.
  11070. *
  11071. * On Web only, the Firestore SDKs support shared access to its persistence
  11072. * layer. This allows multiple browser tabs to read and write to IndexedDb and
  11073. * to synchronize state even without network connectivity. Shared access is
  11074. * currently optional and not enabled unless all clients invoke
  11075. * `enablePersistence()` with `{synchronizeTabs:true}`.
  11076. *
  11077. * In multi-tab mode, if multiple clients are active at the same time, the SDK
  11078. * will designate one client as the “primary client”. An effort is made to pick
  11079. * a visible, network-connected and active client, and this client is
  11080. * responsible for letting other clients know about its presence. The primary
  11081. * client writes a unique client-generated identifier (the client ID) to
  11082. * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to
  11083. * update this entry, another client can acquire the lease and take over as
  11084. * primary.
  11085. *
  11086. * Some persistence operations in the SDK are designated as primary-client only
  11087. * operations. This includes the acknowledgment of mutations and all updates of
  11088. * remote documents. The effects of these operations are written to persistence
  11089. * and then broadcast to other tabs via LocalStorage (see
  11090. * `WebStorageSharedClientState`), which then refresh their state from
  11091. * persistence.
  11092. *
  11093. * Similarly, the primary client listens to notifications sent by secondary
  11094. * clients to discover persistence changes written by secondary clients, such as
  11095. * the addition of new mutations and query targets.
  11096. *
  11097. * If multi-tab is not enabled and another tab already obtained the primary
  11098. * lease, IndexedDbPersistence enters a failed state and all subsequent
  11099. * operations will automatically fail.
  11100. *
  11101. * Additionally, there is an optimization so that when a tab is closed, the
  11102. * primary lease is released immediately (this is especially important to make
  11103. * sure that a refreshed tab is able to immediately re-acquire the primary
  11104. * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload
  11105. * since it is an asynchronous API. So in addition to attempting to give up the
  11106. * lease, the leaseholder writes its client ID to a "zombiedClient" entry in
  11107. * LocalStorage which acts as an indicator that another tab should go ahead and
  11108. * take the primary lease immediately regardless of the current lease timestamp.
  11109. *
  11110. * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no
  11111. * longer optional.
  11112. */
  11113. class Zo {
  11114. constructor(
  11115. /**
  11116. * Whether to synchronize the in-memory state of multiple tabs and share
  11117. * access to local persistence.
  11118. */
  11119. t, e, n, s, i, r, o, u, c,
  11120. /**
  11121. * If set to true, forcefully obtains database access. Existing tabs will
  11122. * no longer be able to access IndexedDB.
  11123. */
  11124. a, h = 15) {
  11125. if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = n,
  11126. this.ii = i, this.window = r, this.document = o, this.ri = c, this.oi = a, this.ui = h,
  11127. this.Os = null, this.Fs = !1, this.isPrimary = !1, this.networkEnabled = !0,
  11128. /** Our window.unload handler, if registered. */
  11129. this.ci = null, this.inForeground = !1,
  11130. /** Our 'visibilitychange' listener if registered. */
  11131. this.ai = null,
  11132. /** The client metadata refresh task. */
  11133. this.hi = null,
  11134. /** The last time we garbage collected the client metadata object store. */
  11135. this.li = Number.NEGATIVE_INFINITY,
  11136. /** A listener to notify on primary state changes. */
  11137. this.fi = t => Promise.resolve(), !Zo.D()) throw new G(K.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
  11138. this.referenceDelegate = new Ro(this, s), this.di = e + "main", this.serializer = new fr(u),
  11139. this.wi = new St(this.di, this.ui, new Jo(this.serializer)), this.Bs = new mo(this.referenceDelegate, this.serializer),
  11140. this.remoteDocumentCache = So(this.serializer), this.qs = new Rr, this.window && this.window.localStorage ? this._i = this.window.localStorage : (this._i = null,
  11141. !1 === a && M("IndexedDbPersistence", "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."));
  11142. }
  11143. /**
  11144. * Attempt to start IndexedDb persistence.
  11145. *
  11146. * @returns Whether persistence was enabled.
  11147. */ start() {
  11148. // NOTE: This is expected to fail sometimes (in the case of another tab
  11149. // already having the persistence lock), so it's the first thing we should
  11150. // do.
  11151. return this.mi().then((() => {
  11152. if (!this.isPrimary && !this.allowTabSynchronization)
  11153. // Fail `start()` if `synchronizeTabs` is disabled and we cannot
  11154. // obtain the primary lease.
  11155. throw new G(K.FAILED_PRECONDITION, Xo);
  11156. return this.gi(), this.yi(), this.pi(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (t => this.Bs.getHighestSequenceNumber(t)));
  11157. })).then((t => {
  11158. this.Os = new Bt(t, this.ri);
  11159. })).then((() => {
  11160. this.Fs = !0;
  11161. })).catch((t => (this.wi && this.wi.close(), Promise.reject(t))));
  11162. }
  11163. /**
  11164. * Registers a listener that gets called when the primary state of the
  11165. * instance changes. Upon registering, this listener is invoked immediately
  11166. * with the current primary state.
  11167. *
  11168. * PORTING NOTE: This is only used for Web multi-tab.
  11169. */ Ii(t) {
  11170. return this.fi = async e => {
  11171. if (this.started) return t(e);
  11172. }, t(this.isPrimary);
  11173. }
  11174. /**
  11175. * Registers a listener that gets called when the database receives a
  11176. * version change event indicating that it has deleted.
  11177. *
  11178. * PORTING NOTE: This is only used for Web multi-tab.
  11179. */ setDatabaseDeletedListener(t) {
  11180. this.wi.B((async e => {
  11181. // Check if an attempt is made to delete IndexedDB.
  11182. null === e.newVersion && await t();
  11183. }));
  11184. }
  11185. /**
  11186. * Adjusts the current network state in the client's metadata, potentially
  11187. * affecting the primary lease.
  11188. *
  11189. * PORTING NOTE: This is only used for Web multi-tab.
  11190. */ setNetworkEnabled(t) {
  11191. this.networkEnabled !== t && (this.networkEnabled = t,
  11192. // Schedule a primary lease refresh for immediate execution. The eventual
  11193. // lease update will be propagated via `primaryStateListener`.
  11194. this.ii.enqueueAndForget((async () => {
  11195. this.started && await this.mi();
  11196. })));
  11197. }
  11198. /**
  11199. * Updates the client metadata in IndexedDb and attempts to either obtain or
  11200. * extend the primary lease for the local client. Asynchronously notifies the
  11201. * primary state listener if the client either newly obtained or released its
  11202. * primary lease.
  11203. */ mi() {
  11204. return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (t => eu(t).put({
  11205. clientId: this.clientId,
  11206. updateTimeMs: Date.now(),
  11207. networkEnabled: this.networkEnabled,
  11208. inForeground: this.inForeground
  11209. }).next((() => {
  11210. if (this.isPrimary) return this.Ti(t).next((t => {
  11211. t || (this.isPrimary = !1, this.ii.enqueueRetryable((() => this.fi(!1))));
  11212. }));
  11213. })).next((() => this.Ei(t))).next((e => this.isPrimary && !e ? this.Ai(t).next((() => !1)) : !!e && this.vi(t).next((() => !0)))))).catch((t => {
  11214. if (xt(t))
  11215. // Proceed with the existing state. Any subsequent access to
  11216. // IndexedDB will verify the lease.
  11217. return $("IndexedDbPersistence", "Failed to extend owner lease: ", t), this.isPrimary;
  11218. if (!this.allowTabSynchronization) throw t;
  11219. return $("IndexedDbPersistence", "Releasing owner lease after error during lease refresh", t),
  11220. /* isPrimary= */ !1;
  11221. })).then((t => {
  11222. this.isPrimary !== t && this.ii.enqueueRetryable((() => this.fi(t))), this.isPrimary = t;
  11223. }));
  11224. }
  11225. Ti(t) {
  11226. return tu(t).get("owner").next((t => bt.resolve(this.Ri(t))));
  11227. }
  11228. Pi(t) {
  11229. return eu(t).delete(this.clientId);
  11230. }
  11231. /**
  11232. * If the garbage collection threshold has passed, prunes the
  11233. * RemoteDocumentChanges and the ClientMetadata store based on the last update
  11234. * time of all clients.
  11235. */ async bi() {
  11236. if (this.isPrimary && !this.Vi(this.li, 18e5)) {
  11237. this.li = Date.now();
  11238. const t = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (t => {
  11239. const e = ge(t, "clientMetadata");
  11240. return e.j().next((t => {
  11241. const n = this.Si(t, 18e5), s = t.filter((t => -1 === n.indexOf(t)));
  11242. // Delete metadata for clients that are no longer considered active.
  11243. return bt.forEach(s, (t => e.delete(t.clientId))).next((() => s));
  11244. }));
  11245. })).catch((() => []));
  11246. // Delete potential leftover entries that may continue to mark the
  11247. // inactive clients as zombied in LocalStorage.
  11248. // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for
  11249. // the client atomically, but we can't. So we opt to delete the IndexedDb
  11250. // entries first to avoid potentially reviving a zombied client.
  11251. if (this._i) for (const e of t) this._i.removeItem(this.Di(e.clientId));
  11252. }
  11253. }
  11254. /**
  11255. * Schedules a recurring timer to update the client metadata and to either
  11256. * extend or acquire the primary lease if the client is eligible.
  11257. */ pi() {
  11258. this.hi = this.ii.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.mi().then((() => this.bi())).then((() => this.pi()))));
  11259. }
  11260. /** Checks whether `client` is the local client. */ Ri(t) {
  11261. return !!t && t.ownerId === this.clientId;
  11262. }
  11263. /**
  11264. * Evaluate the state of all active clients and determine whether the local
  11265. * client is or can act as the holder of the primary lease. Returns whether
  11266. * the client is eligible for the lease, but does not actually acquire it.
  11267. * May return 'false' even if there is no active leaseholder and another
  11268. * (foreground) client should become leaseholder instead.
  11269. */ Ei(t) {
  11270. if (this.oi) return bt.resolve(!0);
  11271. return tu(t).get("owner").next((e => {
  11272. // A client is eligible for the primary lease if:
  11273. // - its network is enabled and the client's tab is in the foreground.
  11274. // - its network is enabled and no other client's tab is in the
  11275. // foreground.
  11276. // - every clients network is disabled and the client's tab is in the
  11277. // foreground.
  11278. // - every clients network is disabled and no other client's tab is in
  11279. // the foreground.
  11280. // - the `forceOwningTab` setting was passed in.
  11281. if (null !== e && this.Vi(e.leaseTimestampMs, 5e3) && !this.Ci(e.ownerId)) {
  11282. if (this.Ri(e) && this.networkEnabled) return !0;
  11283. if (!this.Ri(e)) {
  11284. if (!e.allowTabSynchronization)
  11285. // Fail the `canActAsPrimary` check if the current leaseholder has
  11286. // not opted into multi-tab synchronization. If this happens at
  11287. // client startup, we reject the Promise returned by
  11288. // `enablePersistence()` and the user can continue to use Firestore
  11289. // with in-memory persistence.
  11290. // If this fails during a lease refresh, we will instead block the
  11291. // AsyncQueue from executing further operations. Note that this is
  11292. // acceptable since mixing & matching different `synchronizeTabs`
  11293. // settings is not supported.
  11294. // TODO(b/114226234): Remove this check when `synchronizeTabs` can
  11295. // no longer be turned off.
  11296. throw new G(K.FAILED_PRECONDITION, Xo);
  11297. return !1;
  11298. }
  11299. }
  11300. return !(!this.networkEnabled || !this.inForeground) || eu(t).j().next((t => void 0 === this.Si(t, 5e3).find((t => {
  11301. if (this.clientId !== t.clientId) {
  11302. const e = !this.networkEnabled && t.networkEnabled, n = !this.inForeground && t.inForeground, s = this.networkEnabled === t.networkEnabled;
  11303. if (e || n && s) return !0;
  11304. }
  11305. return !1;
  11306. }))));
  11307. })).next((t => (this.isPrimary !== t && $("IndexedDbPersistence", `Client ${t ? "is" : "is not"} eligible for a primary lease.`),
  11308. t)));
  11309. }
  11310. async shutdown() {
  11311. // The shutdown() operations are idempotent and can be called even when
  11312. // start() aborted (e.g. because it couldn't acquire the persistence lease).
  11313. this.Fs = !1, this.xi(), this.hi && (this.hi.cancel(), this.hi = null), this.Ni(),
  11314. this.ki(),
  11315. // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
  11316. // has obtained the primary lease.
  11317. await this.wi.runTransaction("shutdown", "readwrite", [ "owner", "clientMetadata" ], (t => {
  11318. const e = new me(t, Bt.ct);
  11319. return this.Ai(e).next((() => this.Pi(e)));
  11320. })), this.wi.close(),
  11321. // Remove the entry marking the client as zombied from LocalStorage since
  11322. // we successfully deleted its metadata from IndexedDb.
  11323. this.$i();
  11324. }
  11325. /**
  11326. * Returns clients that are not zombied and have an updateTime within the
  11327. * provided threshold.
  11328. */ Si(t, e) {
  11329. return t.filter((t => this.Vi(t.updateTimeMs, e) && !this.Ci(t.clientId)));
  11330. }
  11331. /**
  11332. * Returns the IDs of the clients that are currently active. If multi-tab
  11333. * is not supported, returns an array that only contains the local client's
  11334. * ID.
  11335. *
  11336. * PORTING NOTE: This is only used for Web multi-tab.
  11337. */ Mi() {
  11338. return this.runTransaction("getActiveClients", "readonly", (t => eu(t).j().next((t => this.Si(t, 18e5).map((t => t.clientId))))));
  11339. }
  11340. get started() {
  11341. return this.Fs;
  11342. }
  11343. getMutationQueue(t, e) {
  11344. return ao.de(t, this.serializer, e, this.referenceDelegate);
  11345. }
  11346. getTargetCache() {
  11347. return this.Bs;
  11348. }
  11349. getRemoteDocumentCache() {
  11350. return this.remoteDocumentCache;
  11351. }
  11352. getIndexManager(t) {
  11353. return new Zr(t, this.serializer.fe.databaseId);
  11354. }
  11355. getDocumentOverlayCache(t) {
  11356. return Vr.de(this.serializer, t);
  11357. }
  11358. getBundleCache() {
  11359. return this.qs;
  11360. }
  11361. runTransaction(t, e, n) {
  11362. $("IndexedDbPersistence", "Starting transaction:", t);
  11363. const s = "readonly" === e ? "readonly" : "readwrite", i = 15 === (r = this.ui) ? _e : 14 === r ? we : 13 === r ? de : 12 === r ? fe : 11 === r ? le : void B();
  11364. /** Returns the object stores for the provided schema. */
  11365. var r;
  11366. let o;
  11367. // Do all transactions as readwrite against all object stores, since we
  11368. // are the only reader/writer.
  11369. return this.wi.runTransaction(t, s, i, (s => (o = new me(s, this.Os ? this.Os.next() : Bt.ct),
  11370. "readwrite-primary" === e ? this.Ti(o).next((t => !!t || this.Ei(o))).next((e => {
  11371. if (!e) throw M(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1,
  11372. this.ii.enqueueRetryable((() => this.fi(!1))), new G(K.FAILED_PRECONDITION, vt);
  11373. return n(o);
  11374. })).next((t => this.vi(o).next((() => t)))) : this.Oi(o).next((() => n(o)))))).then((t => (o.raiseOnCommittedEvent(),
  11375. t)));
  11376. }
  11377. /**
  11378. * Verifies that the current tab is the primary leaseholder or alternatively
  11379. * that the leaseholder has opted into multi-tab synchronization.
  11380. */
  11381. // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
  11382. // be turned off.
  11383. Oi(t) {
  11384. return tu(t).get("owner").next((t => {
  11385. if (null !== t && this.Vi(t.leaseTimestampMs, 5e3) && !this.Ci(t.ownerId) && !this.Ri(t) && !(this.oi || this.allowTabSynchronization && t.allowTabSynchronization)) throw new G(K.FAILED_PRECONDITION, Xo);
  11386. }));
  11387. }
  11388. /**
  11389. * Obtains or extends the new primary lease for the local client. This
  11390. * method does not verify that the client is eligible for this lease.
  11391. */ vi(t) {
  11392. const e = {
  11393. ownerId: this.clientId,
  11394. allowTabSynchronization: this.allowTabSynchronization,
  11395. leaseTimestampMs: Date.now()
  11396. };
  11397. return tu(t).put("owner", e);
  11398. }
  11399. static D() {
  11400. return St.D();
  11401. }
  11402. /** Checks the primary lease and removes it if we are the current primary. */ Ai(t) {
  11403. const e = tu(t);
  11404. return e.get("owner").next((t => this.Ri(t) ? ($("IndexedDbPersistence", "Releasing primary lease."),
  11405. e.delete("owner")) : bt.resolve()));
  11406. }
  11407. /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ Vi(t, e) {
  11408. const n = Date.now();
  11409. return !(t < n - e) && (!(t > n) || (M(`Detected an update time that is in the future: ${t} > ${n}`),
  11410. !1));
  11411. }
  11412. gi() {
  11413. null !== this.document && "function" == typeof this.document.addEventListener && (this.ai = () => {
  11414. this.ii.enqueueAndForget((() => (this.inForeground = "visible" === this.document.visibilityState,
  11415. this.mi())));
  11416. }, this.document.addEventListener("visibilitychange", this.ai), this.inForeground = "visible" === this.document.visibilityState);
  11417. }
  11418. Ni() {
  11419. this.ai && (this.document.removeEventListener("visibilitychange", this.ai), this.ai = null);
  11420. }
  11421. /**
  11422. * Attaches a window.unload handler that will synchronously write our
  11423. * clientId to a "zombie client id" location in LocalStorage. This can be used
  11424. * by tabs trying to acquire the primary lease to determine that the lease
  11425. * is no longer valid even if the timestamp is recent. This is particularly
  11426. * important for the refresh case (so the tab correctly re-acquires the
  11427. * primary lease). LocalStorage is used for this rather than IndexedDb because
  11428. * it is a synchronous API and so can be used reliably from an unload
  11429. * handler.
  11430. */ yi() {
  11431. var t;
  11432. "function" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.ci = () => {
  11433. // Note: In theory, this should be scheduled on the AsyncQueue since it
  11434. // accesses internal state. We execute this code directly during shutdown
  11435. // to make sure it gets a chance to run.
  11436. this.xi();
  11437. const t = /(?:Version|Mobile)\/1[456]/;
  11438. d() && (navigator.appVersion.match(t) || navigator.userAgent.match(t)) &&
  11439. // On Safari 14, 15, and 16, we do not run any cleanup actions as it might
  11440. // trigger a bug that prevents Safari from re-opening IndexedDB during
  11441. // the next page load.
  11442. // See https://bugs.webkit.org/show_bug.cgi?id=226547
  11443. this.ii.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.ii.enqueueAndForget((() => this.shutdown()));
  11444. }, this.window.addEventListener("pagehide", this.ci));
  11445. }
  11446. ki() {
  11447. this.ci && (this.window.removeEventListener("pagehide", this.ci), this.ci = null);
  11448. }
  11449. /**
  11450. * Returns whether a client is "zombied" based on its LocalStorage entry.
  11451. * Clients become zombied when their tab closes without running all of the
  11452. * cleanup logic in `shutdown()`.
  11453. */ Ci(t) {
  11454. var e;
  11455. try {
  11456. const n = null !== (null === (e = this._i) || void 0 === e ? void 0 : e.getItem(this.Di(t)));
  11457. return $("IndexedDbPersistence", `Client '${t}' ${n ? "is" : "is not"} zombied in LocalStorage`),
  11458. n;
  11459. } catch (t) {
  11460. // Gracefully handle if LocalStorage isn't working.
  11461. return M("IndexedDbPersistence", "Failed to get zombied client id.", t), !1;
  11462. }
  11463. }
  11464. /**
  11465. * Record client as zombied (a client that had its tab closed). Zombied
  11466. * clients are ignored during primary tab selection.
  11467. */ xi() {
  11468. if (this._i) try {
  11469. this._i.setItem(this.Di(this.clientId), String(Date.now()));
  11470. } catch (t) {
  11471. // Gracefully handle if LocalStorage isn't available / working.
  11472. M("Failed to set zombie client id.", t);
  11473. }
  11474. }
  11475. /** Removes the zombied client entry if it exists. */ $i() {
  11476. if (this._i) try {
  11477. this._i.removeItem(this.Di(this.clientId));
  11478. } catch (t) {
  11479. // Ignore
  11480. }
  11481. }
  11482. Di(t) {
  11483. return `firestore_zombie_${this.persistenceKey}_${t}`;
  11484. }
  11485. }
  11486. /**
  11487. * Helper to get a typed SimpleDbStore for the primary client object store.
  11488. */ function tu(t) {
  11489. return ge(t, "owner");
  11490. }
  11491. /**
  11492. * Helper to get a typed SimpleDbStore for the client metadata object store.
  11493. */ function eu(t) {
  11494. return ge(t, "clientMetadata");
  11495. }
  11496. /**
  11497. * Generates a string used as a prefix when storing data in IndexedDB and
  11498. * LocalStorage.
  11499. */ function nu(t, e) {
  11500. // Use two different prefix formats:
  11501. // * firestore / persistenceKey / projectID . databaseID / ...
  11502. // * firestore / persistenceKey / projectID / ...
  11503. // projectIDs are DNS-compatible names and cannot contain dots
  11504. // so there's no danger of collisions.
  11505. let n = t.projectId;
  11506. return t.isDefaultDatabase || (n += "." + t.database), "firestore/" + e + "/" + n + "/";
  11507. }
  11508. /**
  11509. * @license
  11510. * Copyright 2017 Google LLC
  11511. *
  11512. * Licensed under the Apache License, Version 2.0 (the "License");
  11513. * you may not use this file except in compliance with the License.
  11514. * You may obtain a copy of the License at
  11515. *
  11516. * http://www.apache.org/licenses/LICENSE-2.0
  11517. *
  11518. * Unless required by applicable law or agreed to in writing, software
  11519. * distributed under the License is distributed on an "AS IS" BASIS,
  11520. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11521. * See the License for the specific language governing permissions and
  11522. * limitations under the License.
  11523. */
  11524. /**
  11525. * A set of changes to what documents are currently in view and out of view for
  11526. * a given query. These changes are sent to the LocalStore by the View (via
  11527. * the SyncEngine) and are used to pin / unpin documents as appropriate.
  11528. */
  11529. class su {
  11530. constructor(t, e, n, s) {
  11531. this.targetId = t, this.fromCache = e, this.Fi = n, this.Bi = s;
  11532. }
  11533. static Li(t, e) {
  11534. let n = Is(), s = Is();
  11535. for (const t of e.docChanges) switch (t.type) {
  11536. case 0 /* ChangeType.Added */ :
  11537. n = n.add(t.doc.key);
  11538. break;
  11539. case 1 /* ChangeType.Removed */ :
  11540. s = s.add(t.doc.key);
  11541. // do nothing
  11542. }
  11543. return new su(t, e.fromCache, n, s);
  11544. }
  11545. }
  11546. /**
  11547. * @license
  11548. * Copyright 2019 Google LLC
  11549. *
  11550. * Licensed under the Apache License, Version 2.0 (the "License");
  11551. * you may not use this file except in compliance with the License.
  11552. * You may obtain a copy of the License at
  11553. *
  11554. * http://www.apache.org/licenses/LICENSE-2.0
  11555. *
  11556. * Unless required by applicable law or agreed to in writing, software
  11557. * distributed under the License is distributed on an "AS IS" BASIS,
  11558. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11559. * See the License for the specific language governing permissions and
  11560. * limitations under the License.
  11561. */
  11562. /**
  11563. * The Firestore query engine.
  11564. *
  11565. * Firestore queries can be executed in three modes. The Query Engine determines
  11566. * what mode to use based on what data is persisted. The mode only determines
  11567. * the runtime complexity of the query - the result set is equivalent across all
  11568. * implementations.
  11569. *
  11570. * The Query engine will use indexed-based execution if a user has configured
  11571. * any index that can be used to execute query (via `setIndexConfiguration()`).
  11572. * Otherwise, the engine will try to optimize the query by re-using a previously
  11573. * persisted query result. If that is not possible, the query will be executed
  11574. * via a full collection scan.
  11575. *
  11576. * Index-based execution is the default when available. The query engine
  11577. * supports partial indexed execution and merges the result from the index
  11578. * lookup with documents that have not yet been indexed. The index evaluation
  11579. * matches the backend's format and as such, the SDK can use indexing for all
  11580. * queries that the backend supports.
  11581. *
  11582. * If no index exists, the query engine tries to take advantage of the target
  11583. * document mapping in the TargetCache. These mappings exists for all queries
  11584. * that have been synced with the backend at least once and allow the query
  11585. * engine to only read documents that previously matched a query plus any
  11586. * documents that were edited after the query was last listened to.
  11587. *
  11588. * There are some cases when this optimization is not guaranteed to produce
  11589. * the same results as full collection scans. In these cases, query
  11590. * processing falls back to full scans. These cases are:
  11591. *
  11592. * - Limit queries where a document that matched the query previously no longer
  11593. * matches the query.
  11594. *
  11595. * - Limit queries where a document edit may cause the document to sort below
  11596. * another document that is in the local cache.
  11597. *
  11598. * - Queries that have never been CURRENT or free of limbo documents.
  11599. */ class iu {
  11600. constructor() {
  11601. this.qi = !1;
  11602. }
  11603. /** Sets the document view to query against. */ initialize(t, e) {
  11604. this.Ui = t, this.indexManager = e, this.qi = !0;
  11605. }
  11606. /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(t, e, n, s) {
  11607. return this.Ki(t, e).next((i => i || this.Gi(t, e, s, n))).next((n => n || this.Qi(t, e)));
  11608. }
  11609. /**
  11610. * Performs an indexed query that evaluates the query based on a collection's
  11611. * persisted index values. Returns `null` if an index is not available.
  11612. */ Ki(t, e) {
  11613. if (Wn(e))
  11614. // Queries that match all documents don't benefit from using
  11615. // key-based lookups. It is more efficient to scan all documents in a
  11616. // collection, rather than to perform individual lookups.
  11617. return bt.resolve(null);
  11618. let n = Zn(e);
  11619. return this.indexManager.getIndexType(t, n).next((s => 0 /* IndexType.NONE */ === s ? null : (null !== e.limit && 1 /* IndexType.PARTIAL */ === s && (
  11620. // We cannot apply a limit for targets that are served using a partial
  11621. // index. If a partial index will be used to serve the target, the
  11622. // query may return a superset of documents that match the target
  11623. // (e.g. if the index doesn't include all the target's filters), or
  11624. // may return the correct set of documents in the wrong order (e.g. if
  11625. // the index doesn't include a segment for one of the orderBys).
  11626. // Therefore, a limit should not be applied in such cases.
  11627. e = es(e, null, "F" /* LimitType.First */), n = Zn(e)), this.indexManager.getDocumentsMatchingTarget(t, n).next((s => {
  11628. const i = Is(...s);
  11629. return this.Ui.getDocuments(t, i).next((s => this.indexManager.getMinOffset(t, n).next((n => {
  11630. const r = this.ji(e, s);
  11631. return this.zi(e, r, i, n.readTime) ? this.Ki(t, es(e, null, "F" /* LimitType.First */)) : this.Wi(t, r, e, n);
  11632. }))));
  11633. })))));
  11634. }
  11635. /**
  11636. * Performs a query based on the target's persisted query mapping. Returns
  11637. * `null` if the mapping is not available or cannot be used.
  11638. */ Gi(t, e, n, s) {
  11639. return Wn(e) || s.isEqual(ut.min()) ? this.Qi(t, e) : this.Ui.getDocuments(t, n).next((i => {
  11640. const r = this.ji(e, i);
  11641. return this.zi(e, r, n, s) ? this.Qi(t, e) : (N() <= u.DEBUG && $("QueryEngine", "Re-using previous result from %s to execute query: %s", s.toString(), is(e)),
  11642. this.Wi(t, r, e, It(s, -1)));
  11643. }));
  11644. // Queries that have never seen a snapshot without limbo free documents
  11645. // should also be run as a full collection scan.
  11646. }
  11647. /** Applies the query filter and sorting to the provided documents. */ ji(t, e) {
  11648. // Sort the documents and re-apply the query filter since previously
  11649. // matching documents do not necessarily still match the query.
  11650. let n = new ve(us(t));
  11651. return e.forEach(((e, s) => {
  11652. rs(t, s) && (n = n.add(s));
  11653. })), n;
  11654. }
  11655. /**
  11656. * Determines if a limit query needs to be refilled from cache, making it
  11657. * ineligible for index-free execution.
  11658. *
  11659. * @param query - The query.
  11660. * @param sortedPreviousResults - The documents that matched the query when it
  11661. * was last synchronized, sorted by the query's comparator.
  11662. * @param remoteKeys - The document keys that matched the query at the last
  11663. * snapshot.
  11664. * @param limboFreeSnapshotVersion - The version of the snapshot when the
  11665. * query was last synchronized.
  11666. */ zi(t, e, n, s) {
  11667. if (null === t.limit)
  11668. // Queries without limits do not need to be refilled.
  11669. return !1;
  11670. if (n.size !== e.size)
  11671. // The query needs to be refilled if a previously matching document no
  11672. // longer matches.
  11673. return !0;
  11674. // Limit queries are not eligible for index-free query execution if there is
  11675. // a potential that an older document from cache now sorts before a document
  11676. // that was previously part of the limit. This, however, can only happen if
  11677. // the document at the edge of the limit goes out of limit.
  11678. // If a document that is not the limit boundary sorts differently,
  11679. // the boundary of the limit itself did not change and documents from cache
  11680. // will continue to be "rejected" by this boundary. Therefore, we can ignore
  11681. // any modifications that don't affect the last document.
  11682. const i = "F" /* LimitType.First */ === t.limitType ? e.last() : e.first();
  11683. return !!i && (i.hasPendingWrites || i.version.compareTo(s) > 0);
  11684. }
  11685. Qi(t, e) {
  11686. return N() <= u.DEBUG && $("QueryEngine", "Using full collection scan to execute query:", is(e)),
  11687. this.Ui.getDocumentsMatchingQuery(t, e, Et.min());
  11688. }
  11689. /**
  11690. * Combines the results from an indexed execution with the remaining documents
  11691. * that have not yet been indexed.
  11692. */ Wi(t, e, n, s) {
  11693. // Retrieve all results for documents that were updated since the offset.
  11694. return this.Ui.getDocumentsMatchingQuery(t, n, s).next((t => (
  11695. // Merge with existing results
  11696. e.forEach((e => {
  11697. t = t.insert(e.key, e);
  11698. })), t)));
  11699. }
  11700. }
  11701. /**
  11702. * @license
  11703. * Copyright 2020 Google LLC
  11704. *
  11705. * Licensed under the Apache License, Version 2.0 (the "License");
  11706. * you may not use this file except in compliance with the License.
  11707. * You may obtain a copy of the License at
  11708. *
  11709. * http://www.apache.org/licenses/LICENSE-2.0
  11710. *
  11711. * Unless required by applicable law or agreed to in writing, software
  11712. * distributed under the License is distributed on an "AS IS" BASIS,
  11713. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11714. * See the License for the specific language governing permissions and
  11715. * limitations under the License.
  11716. */
  11717. /**
  11718. * Implements `LocalStore` interface.
  11719. *
  11720. * Note: some field defined in this class might have public access level, but
  11721. * the class is not exported so they are only accessible from this module.
  11722. * This is useful to implement optional features (like bundles) in free
  11723. * functions, such that they are tree-shakeable.
  11724. */
  11725. class ru {
  11726. constructor(
  11727. /** Manages our in-memory or durable persistence. */
  11728. t, e, n, s) {
  11729. this.persistence = t, this.Hi = e, this.serializer = s,
  11730. /**
  11731. * Maps a targetID to data about its target.
  11732. *
  11733. * PORTING NOTE: We are using an immutable data structure on Web to make re-runs
  11734. * of `applyRemoteEvent()` idempotent.
  11735. */
  11736. this.Ji = new Te(st),
  11737. /** Maps a target to its targetID. */
  11738. // TODO(wuandy): Evaluate if TargetId can be part of Target.
  11739. this.Yi = new as((t => Bn(t)), Ln),
  11740. /**
  11741. * A per collection group index of the last read time processed by
  11742. * `getNewDocumentChanges()`.
  11743. *
  11744. * PORTING NOTE: This is only used for multi-tab synchronization.
  11745. */
  11746. this.Xi = new Map, this.Zi = t.getRemoteDocumentCache(), this.Bs = t.getTargetCache(),
  11747. this.qs = t.getBundleCache(), this.tr(n);
  11748. }
  11749. tr(t) {
  11750. // TODO(indexing): Add spec tests that test these components change after a
  11751. // user change
  11752. this.documentOverlayCache = this.persistence.getDocumentOverlayCache(t), this.indexManager = this.persistence.getIndexManager(t),
  11753. this.mutationQueue = this.persistence.getMutationQueue(t, this.indexManager), this.localDocuments = new Oo(this.Zi, this.mutationQueue, this.documentOverlayCache, this.indexManager),
  11754. this.Zi.setIndexManager(this.indexManager), this.Hi.initialize(this.localDocuments, this.indexManager);
  11755. }
  11756. collectGarbage(t) {
  11757. return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (e => t.collect(e, this.Ji)));
  11758. }
  11759. }
  11760. function ou(
  11761. /** Manages our in-memory or durable persistence. */
  11762. t, e, n, s) {
  11763. return new ru(t, e, n, s);
  11764. }
  11765. /**
  11766. * Tells the LocalStore that the currently authenticated user has changed.
  11767. *
  11768. * In response the local store switches the mutation queue to the new user and
  11769. * returns any resulting document changes.
  11770. */
  11771. // PORTING NOTE: Android and iOS only return the documents affected by the
  11772. // change.
  11773. async function uu(t, e) {
  11774. const n = U(t);
  11775. return await n.persistence.runTransaction("Handle user change", "readonly", (t => {
  11776. // Swap out the mutation queue, grabbing the pending mutation batches
  11777. // before and after.
  11778. let s;
  11779. return n.mutationQueue.getAllMutationBatches(t).next((i => (s = i, n.tr(e), n.mutationQueue.getAllMutationBatches(t)))).next((e => {
  11780. const i = [], r = [];
  11781. // Union the old/new changed keys.
  11782. let o = Is();
  11783. for (const t of s) {
  11784. i.push(t.batchId);
  11785. for (const e of t.mutations) o = o.add(e.key);
  11786. }
  11787. for (const t of e) {
  11788. r.push(t.batchId);
  11789. for (const e of t.mutations) o = o.add(e.key);
  11790. }
  11791. // Return the set of all (potentially) changed documents and the list
  11792. // of mutation batch IDs that were affected by change.
  11793. return n.localDocuments.getDocuments(t, o).next((t => ({
  11794. er: t,
  11795. removedBatchIds: i,
  11796. addedBatchIds: r
  11797. })));
  11798. }));
  11799. }));
  11800. }
  11801. /* Accepts locally generated Mutations and commit them to storage. */
  11802. /**
  11803. * Acknowledges the given batch.
  11804. *
  11805. * On the happy path when a batch is acknowledged, the local store will
  11806. *
  11807. * + remove the batch from the mutation queue;
  11808. * + apply the changes to the remote document cache;
  11809. * + recalculate the latency compensated view implied by those changes (there
  11810. * may be mutations in the queue that affect the documents but haven't been
  11811. * acknowledged yet); and
  11812. * + give the changed documents back the sync engine
  11813. *
  11814. * @returns The resulting (modified) documents.
  11815. */
  11816. function cu(t, e) {
  11817. const n = U(t);
  11818. return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (t => {
  11819. const s = e.batch.keys(), i = n.Zi.newChangeBuffer({
  11820. trackRemovals: !0
  11821. });
  11822. return function(t, e, n, s) {
  11823. const i = n.batch, r = i.keys();
  11824. let o = bt.resolve();
  11825. return r.forEach((t => {
  11826. o = o.next((() => s.getEntry(e, t))).next((e => {
  11827. const r = n.docVersions.get(t);
  11828. L(null !== r), e.version.compareTo(r) < 0 && (i.applyToRemoteDocument(e, n), e.isValidDocument() && (
  11829. // We use the commitVersion as the readTime rather than the
  11830. // document's updateTime since the updateTime is not advanced
  11831. // for updates that do not modify the underlying document.
  11832. e.setReadTime(n.commitVersion), s.addEntry(e)));
  11833. }));
  11834. })), o.next((() => t.mutationQueue.removeMutationBatch(e, i)));
  11835. }
  11836. /** Returns the local view of the documents affected by a mutation batch. */
  11837. // PORTING NOTE: Multi-Tab only.
  11838. (n, t, e, i).next((() => i.apply(t))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, function(t) {
  11839. let e = Is();
  11840. for (let n = 0; n < t.mutationResults.length; ++n) {
  11841. t.mutationResults[n].transformResults.length > 0 && (e = e.add(t.batch.mutations[n].key));
  11842. }
  11843. return e;
  11844. }
  11845. /**
  11846. * Removes mutations from the MutationQueue for the specified batch;
  11847. * LocalDocuments will be recalculated.
  11848. *
  11849. * @returns The resulting modified documents.
  11850. */ (e)))).next((() => n.localDocuments.getDocuments(t, s)));
  11851. }));
  11852. }
  11853. /**
  11854. * Returns the last consistent snapshot processed (used by the RemoteStore to
  11855. * determine whether to buffer incoming snapshots from the backend).
  11856. */
  11857. function au(t) {
  11858. const e = U(t);
  11859. return e.persistence.runTransaction("Get last remote snapshot version", "readonly", (t => e.Bs.getLastRemoteSnapshotVersion(t)));
  11860. }
  11861. /**
  11862. * Updates the "ground-state" (remote) documents. We assume that the remote
  11863. * event reflects any write batches that have been acknowledged or rejected
  11864. * (i.e. we do not re-apply local mutations to updates from this event).
  11865. *
  11866. * LocalDocuments are re-calculated if there are remaining mutations in the
  11867. * queue.
  11868. */ function hu(t, e) {
  11869. const n = U(t), s = e.snapshotVersion;
  11870. let i = n.Ji;
  11871. return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (t => {
  11872. const r = n.Zi.newChangeBuffer({
  11873. trackRemovals: !0
  11874. });
  11875. // Reset newTargetDataByTargetMap in case this transaction gets re-run.
  11876. i = n.Ji;
  11877. const o = [];
  11878. e.targetChanges.forEach(((r, u) => {
  11879. const c = i.get(u);
  11880. if (!c) return;
  11881. // Only update the remote keys if the target is still active. This
  11882. // ensures that we can persist the updated target data along with
  11883. // the updated assignment.
  11884. o.push(n.Bs.removeMatchingKeys(t, r.removedDocuments, u).next((() => n.Bs.addMatchingKeys(t, r.addedDocuments, u))));
  11885. let a = c.withSequenceNumber(t.currentSequenceNumber);
  11886. null !== e.targetMismatches.get(u) ? a = a.withResumeToken(Ce.EMPTY_BYTE_STRING, ut.min()).withLastLimboFreeSnapshotVersion(ut.min()) : r.resumeToken.approximateByteSize() > 0 && (a = a.withResumeToken(r.resumeToken, s)),
  11887. i = i.insert(u, a),
  11888. // Update the target data if there are target changes (or if
  11889. // sufficient time has passed since the last update).
  11890. /**
  11891. * Returns true if the newTargetData should be persisted during an update of
  11892. * an active target. TargetData should always be persisted when a target is
  11893. * being released and should not call this function.
  11894. *
  11895. * While the target is active, TargetData updates can be omitted when nothing
  11896. * about the target has changed except metadata like the resume token or
  11897. * snapshot version. Occasionally it's worth the extra write to prevent these
  11898. * values from getting too stale after a crash, but this doesn't have to be
  11899. * too frequent.
  11900. */
  11901. function(t, e, n) {
  11902. // Always persist target data if we don't already have a resume token.
  11903. if (0 === t.resumeToken.approximateByteSize()) return !0;
  11904. // Don't allow resume token changes to be buffered indefinitely. This
  11905. // allows us to be reasonably up-to-date after a crash and avoids needing
  11906. // to loop over all active queries on shutdown. Especially in the browser
  11907. // we may not get time to do anything interesting while the current tab is
  11908. // closing.
  11909. if (e.snapshotVersion.toMicroseconds() - t.snapshotVersion.toMicroseconds() >= 3e8) return !0;
  11910. // Otherwise if the only thing that has changed about a target is its resume
  11911. // token it's not worth persisting. Note that the RemoteStore keeps an
  11912. // in-memory view of the currently active targets which includes the current
  11913. // resume token, so stream failure or user changes will still use an
  11914. // up-to-date resume token regardless of what we do here.
  11915. return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;
  11916. }
  11917. /**
  11918. * Notifies local store of the changed views to locally pin documents.
  11919. */ (c, a, r) && o.push(n.Bs.updateTargetData(t, a));
  11920. }));
  11921. let u = ls(), c = Is();
  11922. // HACK: The only reason we allow a null snapshot version is so that we
  11923. // can synthesize remote events when we get permission denied errors while
  11924. // trying to resolve the state of a locally cached document that is in
  11925. // limbo.
  11926. if (e.documentUpdates.forEach((s => {
  11927. e.resolvedLimboDocuments.has(s) && o.push(n.persistence.referenceDelegate.updateLimboDocument(t, s));
  11928. })),
  11929. // Each loop iteration only affects its "own" doc, so it's safe to get all
  11930. // the remote documents in advance in a single call.
  11931. o.push(lu(t, r, e.documentUpdates).next((t => {
  11932. u = t.nr, c = t.sr;
  11933. }))), !s.isEqual(ut.min())) {
  11934. const e = n.Bs.getLastRemoteSnapshotVersion(t).next((e => n.Bs.setTargetsMetadata(t, t.currentSequenceNumber, s)));
  11935. o.push(e);
  11936. }
  11937. return bt.waitFor(o).next((() => r.apply(t))).next((() => n.localDocuments.getLocalViewOfDocuments(t, u, c))).next((() => u));
  11938. })).then((t => (n.Ji = i, t)));
  11939. }
  11940. /**
  11941. * Populates document change buffer with documents from backend or a bundle.
  11942. * Returns the document changes resulting from applying those documents, and
  11943. * also a set of documents whose existence state are changed as a result.
  11944. *
  11945. * @param txn - Transaction to use to read existing documents from storage.
  11946. * @param documentBuffer - Document buffer to collect the resulted changes to be
  11947. * applied to storage.
  11948. * @param documents - Documents to be applied.
  11949. */ function lu(t, e, n) {
  11950. let s = Is(), i = Is();
  11951. return n.forEach((t => s = s.add(t))), e.getEntries(t, s).next((t => {
  11952. let s = ls();
  11953. return n.forEach(((n, r) => {
  11954. const o = t.get(n);
  11955. // Check if see if there is a existence state change for this document.
  11956. r.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)),
  11957. // Note: The order of the steps below is important, since we want
  11958. // to ensure that rejected limbo resolutions (which fabricate
  11959. // NoDocuments with SnapshotVersion.min()) never add documents to
  11960. // cache.
  11961. r.isNoDocument() && r.version.isEqual(ut.min()) ? (
  11962. // NoDocuments with SnapshotVersion.min() are used in manufactured
  11963. // events. We remove these documents from cache since we lost
  11964. // access.
  11965. e.removeEntry(n, r.readTime), s = s.insert(n, r)) : !o.isValidDocument() || r.version.compareTo(o.version) > 0 || 0 === r.version.compareTo(o.version) && o.hasPendingWrites ? (e.addEntry(r),
  11966. s = s.insert(n, r)) : $("LocalStore", "Ignoring outdated watch update for ", n, ". Current version:", o.version, " Watch version:", r.version);
  11967. })), {
  11968. nr: s,
  11969. sr: i
  11970. };
  11971. }));
  11972. }
  11973. /**
  11974. * Gets the mutation batch after the passed in batchId in the mutation queue
  11975. * or null if empty.
  11976. * @param afterBatchId - If provided, the batch to search after.
  11977. * @returns The next mutation or null if there wasn't one.
  11978. */
  11979. function fu(t, e) {
  11980. const n = U(t);
  11981. return n.persistence.runTransaction("Get next mutation batch", "readonly", (t => (void 0 === e && (e = -1),
  11982. n.mutationQueue.getNextMutationBatchAfterBatchId(t, e))));
  11983. }
  11984. /**
  11985. * Reads the current value of a Document with a given key or null if not
  11986. * found - used for testing.
  11987. */
  11988. /**
  11989. * Assigns the given target an internal ID so that its results can be pinned so
  11990. * they don't get GC'd. A target must be allocated in the local store before
  11991. * the store can be used to manage its view.
  11992. *
  11993. * Allocating an already allocated `Target` will return the existing `TargetData`
  11994. * for that `Target`.
  11995. */
  11996. function du(t, e) {
  11997. const n = U(t);
  11998. return n.persistence.runTransaction("Allocate target", "readwrite", (t => {
  11999. let s;
  12000. return n.Bs.getTargetData(t, e).next((i => i ? (
  12001. // This target has been listened to previously, so reuse the
  12002. // previous targetID.
  12003. // TODO(mcg): freshen last accessed date?
  12004. s = i, bt.resolve(s)) : n.Bs.allocateTargetId(t).next((i => (s = new lr(e, i, "TargetPurposeListen" /* TargetPurpose.Listen */ , t.currentSequenceNumber),
  12005. n.Bs.addTargetData(t, s).next((() => s)))))));
  12006. })).then((t => {
  12007. // If Multi-Tab is enabled, the existing target data may be newer than
  12008. // the in-memory data
  12009. const s = n.Ji.get(t.targetId);
  12010. return (null === s || t.snapshotVersion.compareTo(s.snapshotVersion) > 0) && (n.Ji = n.Ji.insert(t.targetId, t),
  12011. n.Yi.set(e, t.targetId)), t;
  12012. }));
  12013. }
  12014. /**
  12015. * Returns the TargetData as seen by the LocalStore, including updates that may
  12016. * have not yet been persisted to the TargetCache.
  12017. */
  12018. // Visible for testing.
  12019. /**
  12020. * Unpins all the documents associated with the given target. If
  12021. * `keepPersistedTargetData` is set to false and Eager GC enabled, the method
  12022. * directly removes the associated target data from the target cache.
  12023. *
  12024. * Releasing a non-existing `Target` is a no-op.
  12025. */
  12026. // PORTING NOTE: `keepPersistedTargetData` is multi-tab only.
  12027. async function wu(t, e, n) {
  12028. const s = U(t), i = s.Ji.get(e), r = n ? "readwrite" : "readwrite-primary";
  12029. try {
  12030. n || await s.persistence.runTransaction("Release target", r, (t => s.persistence.referenceDelegate.removeTarget(t, i)));
  12031. } catch (t) {
  12032. if (!xt(t)) throw t;
  12033. // All `releaseTarget` does is record the final metadata state for the
  12034. // target, but we've been recording this periodically during target
  12035. // activity. If we lose this write this could cause a very slight
  12036. // difference in the order of target deletion during GC, but we
  12037. // don't define exact LRU semantics so this is acceptable.
  12038. $("LocalStore", `Failed to update sequence numbers for target ${e}: ${t}`);
  12039. }
  12040. s.Ji = s.Ji.remove(e), s.Yi.delete(i.target);
  12041. }
  12042. /**
  12043. * Runs the specified query against the local store and returns the results,
  12044. * potentially taking advantage of query data from previous executions (such
  12045. * as the set of remote keys).
  12046. *
  12047. * @param usePreviousResults - Whether results from previous executions can
  12048. * be used to optimize this query execution.
  12049. */ function _u(t, e, n) {
  12050. const s = U(t);
  12051. let i = ut.min(), r = Is();
  12052. return s.persistence.runTransaction("Execute query", "readonly", (t => function(t, e, n) {
  12053. const s = U(t), i = s.Yi.get(n);
  12054. return void 0 !== i ? bt.resolve(s.Ji.get(i)) : s.Bs.getTargetData(e, n);
  12055. }(s, t, Zn(e)).next((e => {
  12056. if (e) return i = e.lastLimboFreeSnapshotVersion, s.Bs.getMatchingKeysForTargetId(t, e.targetId).next((t => {
  12057. r = t;
  12058. }));
  12059. })).next((() => s.Hi.getDocumentsMatchingQuery(t, e, n ? i : ut.min(), n ? r : Is()))).next((t => (yu(s, os(e), t),
  12060. {
  12061. documents: t,
  12062. ir: r
  12063. })))));
  12064. }
  12065. // PORTING NOTE: Multi-Tab only.
  12066. function mu(t, e) {
  12067. const n = U(t), s = U(n.Bs), i = n.Ji.get(e);
  12068. return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (t => s.le(t, e).next((t => t ? t.target : null))));
  12069. }
  12070. /**
  12071. * Returns the set of documents that have been updated since the last call.
  12072. * If this is the first call, returns the set of changes since client
  12073. * initialization. Further invocations will return document that have changed
  12074. * since the prior call.
  12075. */
  12076. // PORTING NOTE: Multi-Tab only.
  12077. function gu(t, e) {
  12078. const n = U(t), s = n.Xi.get(e) || ut.min();
  12079. // Get the current maximum read time for the collection. This should always
  12080. // exist, but to reduce the chance for regressions we default to
  12081. // SnapshotVersion.Min()
  12082. // TODO(indexing): Consider removing the default value.
  12083. return n.persistence.runTransaction("Get new document changes", "readonly", (t => n.Zi.getAllFromCollectionGroup(t, e, It(s, -1),
  12084. /* limit= */ Number.MAX_SAFE_INTEGER))).then((t => (yu(n, e, t), t)));
  12085. }
  12086. /** Sets the collection group's maximum read time from the given documents. */
  12087. // PORTING NOTE: Multi-Tab only.
  12088. function yu(t, e, n) {
  12089. let s = t.Xi.get(e) || ut.min();
  12090. n.forEach(((t, e) => {
  12091. e.readTime.compareTo(s) > 0 && (s = e.readTime);
  12092. })), t.Xi.set(e, s);
  12093. }
  12094. /**
  12095. * Creates a new target using the given bundle name, which will be used to
  12096. * hold the keys of all documents from the bundle in query-document mappings.
  12097. * This ensures that the loaded documents do not get garbage collected
  12098. * right away.
  12099. */
  12100. /**
  12101. * Applies the documents from a bundle to the "ground-state" (remote)
  12102. * documents.
  12103. *
  12104. * LocalDocuments are re-calculated if there are remaining mutations in the
  12105. * queue.
  12106. */
  12107. async function pu(t, e, n, s) {
  12108. const i = U(t);
  12109. let r = Is(), o = ls();
  12110. for (const t of n) {
  12111. const n = e.rr(t.metadata.name);
  12112. t.document && (r = r.add(n));
  12113. const s = e.ur(t);
  12114. s.setReadTime(e.cr(t.metadata.readTime)), o = o.insert(n, s);
  12115. }
  12116. const u = i.Zi.newChangeBuffer({
  12117. trackRemovals: !0
  12118. }), c = await du(i, function(t) {
  12119. // It is OK that the path used for the query is not valid, because this will
  12120. // not be read and queried.
  12121. return Zn(zn(at.fromString(`__bundle__/docs/${t}`)));
  12122. }(s));
  12123. // Allocates a target to hold all document keys from the bundle, such that
  12124. // they will not get garbage collected right away.
  12125. return i.persistence.runTransaction("Apply bundle documents", "readwrite", (t => lu(t, u, o).next((e => (u.apply(t),
  12126. e))).next((e => i.Bs.removeMatchingKeysForTargetId(t, c.targetId).next((() => i.Bs.addMatchingKeys(t, r, c.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(t, e.nr, e.sr))).next((() => e.nr))))));
  12127. }
  12128. /**
  12129. * Returns a promise of a boolean to indicate if the given bundle has already
  12130. * been loaded and the create time is newer than the current loading bundle.
  12131. */
  12132. /**
  12133. * Saves the given `NamedQuery` to local persistence.
  12134. */
  12135. async function Iu(t, e, n = Is()) {
  12136. // Allocate a target for the named query such that it can be resumed
  12137. // from associated read time if users use it to listen.
  12138. // NOTE: this also means if no corresponding target exists, the new target
  12139. // will remain active and will not get collected, unless users happen to
  12140. // unlisten the query somehow.
  12141. const s = await du(t, Zn(Tr(e.bundledQuery))), i = U(t);
  12142. return i.persistence.runTransaction("Save named query", "readwrite", (t => {
  12143. const r = Mi(e.readTime);
  12144. // Simply save the query itself if it is older than what the SDK already
  12145. // has.
  12146. if (s.snapshotVersion.compareTo(r) >= 0) return i.qs.saveNamedQuery(t, e);
  12147. // Update existing target data because the query from the bundle is newer.
  12148. const o = s.withResumeToken(Ce.EMPTY_BYTE_STRING, r);
  12149. return i.Ji = i.Ji.insert(o.targetId, o), i.Bs.updateTargetData(t, o).next((() => i.Bs.removeMatchingKeysForTargetId(t, s.targetId))).next((() => i.Bs.addMatchingKeys(t, n, s.targetId))).next((() => i.qs.saveNamedQuery(t, e)));
  12150. }));
  12151. }
  12152. /** Assembles the key for a client state in WebStorage */
  12153. function Tu(t, e) {
  12154. return `firestore_clients_${t}_${e}`;
  12155. }
  12156. // The format of the WebStorage key that stores the mutation state is:
  12157. // firestore_mutations_<persistence_prefix>_<batch_id>
  12158. // (for unauthenticated users)
  12159. // or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>
  12160. // 'user_uid' is last to avoid needing to escape '_' characters that it might
  12161. // contain.
  12162. /** Assembles the key for a mutation batch in WebStorage */
  12163. function Eu(t, e, n) {
  12164. let s = `firestore_mutations_${t}_${n}`;
  12165. return e.isAuthenticated() && (s += `_${e.uid}`), s;
  12166. }
  12167. // The format of the WebStorage key that stores a query target's metadata is:
  12168. // firestore_targets_<persistence_prefix>_<target_id>
  12169. /** Assembles the key for a query state in WebStorage */
  12170. function Au(t, e) {
  12171. return `firestore_targets_${t}_${e}`;
  12172. }
  12173. // The WebStorage prefix that stores the primary tab's online state. The
  12174. // format of the key is:
  12175. // firestore_online_state_<persistence_prefix>
  12176. /**
  12177. * Holds the state of a mutation batch, including its user ID, batch ID and
  12178. * whether the batch is 'pending', 'acknowledged' or 'rejected'.
  12179. */
  12180. // Visible for testing
  12181. class vu {
  12182. constructor(t, e, n, s) {
  12183. this.user = t, this.batchId = e, this.state = n, this.error = s;
  12184. }
  12185. /**
  12186. * Parses a MutationMetadata from its JSON representation in WebStorage.
  12187. * Logs a warning and returns null if the format of the data is not valid.
  12188. */ static ar(t, e, n) {
  12189. const s = JSON.parse(n);
  12190. let i, r = "object" == typeof s && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(s.state) && (void 0 === s.error || "object" == typeof s.error);
  12191. return r && s.error && (r = "string" == typeof s.error.message && "string" == typeof s.error.code,
  12192. r && (i = new G(s.error.code, s.error.message))), r ? new vu(t, e, s.state, i) : (M("SharedClientState", `Failed to parse mutation state for ID '${e}': ${n}`),
  12193. null);
  12194. }
  12195. hr() {
  12196. const t = {
  12197. state: this.state,
  12198. updateTimeMs: Date.now()
  12199. };
  12200. return this.error && (t.error = {
  12201. code: this.error.code,
  12202. message: this.error.message
  12203. }), JSON.stringify(t);
  12204. }
  12205. }
  12206. /**
  12207. * Holds the state of a query target, including its target ID and whether the
  12208. * target is 'not-current', 'current' or 'rejected'.
  12209. */
  12210. // Visible for testing
  12211. class Ru {
  12212. constructor(t, e, n) {
  12213. this.targetId = t, this.state = e, this.error = n;
  12214. }
  12215. /**
  12216. * Parses a QueryTargetMetadata from its JSON representation in WebStorage.
  12217. * Logs a warning and returns null if the format of the data is not valid.
  12218. */ static ar(t, e) {
  12219. const n = JSON.parse(e);
  12220. let s, i = "object" == typeof n && -1 !== [ "not-current", "current", "rejected" ].indexOf(n.state) && (void 0 === n.error || "object" == typeof n.error);
  12221. return i && n.error && (i = "string" == typeof n.error.message && "string" == typeof n.error.code,
  12222. i && (s = new G(n.error.code, n.error.message))), i ? new Ru(t, n.state, s) : (M("SharedClientState", `Failed to parse target state for ID '${t}': ${e}`),
  12223. null);
  12224. }
  12225. hr() {
  12226. const t = {
  12227. state: this.state,
  12228. updateTimeMs: Date.now()
  12229. };
  12230. return this.error && (t.error = {
  12231. code: this.error.code,
  12232. message: this.error.message
  12233. }), JSON.stringify(t);
  12234. }
  12235. }
  12236. /**
  12237. * This class represents the immutable ClientState for a client read from
  12238. * WebStorage, containing the list of active query targets.
  12239. */ class Pu {
  12240. constructor(t, e) {
  12241. this.clientId = t, this.activeTargetIds = e;
  12242. }
  12243. /**
  12244. * Parses a RemoteClientState from the JSON representation in WebStorage.
  12245. * Logs a warning and returns null if the format of the data is not valid.
  12246. */ static ar(t, e) {
  12247. const n = JSON.parse(e);
  12248. let s = "object" == typeof n && n.activeTargetIds instanceof Array, i = Es();
  12249. for (let t = 0; s && t < n.activeTargetIds.length; ++t) s = Ut(n.activeTargetIds[t]),
  12250. i = i.add(n.activeTargetIds[t]);
  12251. return s ? new Pu(t, i) : (M("SharedClientState", `Failed to parse client data for instance '${t}': ${e}`),
  12252. null);
  12253. }
  12254. }
  12255. /**
  12256. * This class represents the online state for all clients participating in
  12257. * multi-tab. The online state is only written to by the primary client, and
  12258. * used in secondary clients to update their query views.
  12259. */ class bu {
  12260. constructor(t, e) {
  12261. this.clientId = t, this.onlineState = e;
  12262. }
  12263. /**
  12264. * Parses a SharedOnlineState from its JSON representation in WebStorage.
  12265. * Logs a warning and returns null if the format of the data is not valid.
  12266. */ static ar(t) {
  12267. const e = JSON.parse(t);
  12268. return "object" == typeof e && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(e.onlineState) && "string" == typeof e.clientId ? new bu(e.clientId, e.onlineState) : (M("SharedClientState", `Failed to parse online state: ${t}`),
  12269. null);
  12270. }
  12271. }
  12272. /**
  12273. * Metadata state of the local client. Unlike `RemoteClientState`, this class is
  12274. * mutable and keeps track of all pending mutations, which allows us to
  12275. * update the range of pending mutation batch IDs as new mutations are added or
  12276. * removed.
  12277. *
  12278. * The data in `LocalClientState` is not read from WebStorage and instead
  12279. * updated via its instance methods. The updated state can be serialized via
  12280. * `toWebStorageJSON()`.
  12281. */
  12282. // Visible for testing.
  12283. class Vu {
  12284. constructor() {
  12285. this.activeTargetIds = Es();
  12286. }
  12287. lr(t) {
  12288. this.activeTargetIds = this.activeTargetIds.add(t);
  12289. }
  12290. dr(t) {
  12291. this.activeTargetIds = this.activeTargetIds.delete(t);
  12292. }
  12293. /**
  12294. * Converts this entry into a JSON-encoded format we can use for WebStorage.
  12295. * Does not encode `clientId` as it is part of the key in WebStorage.
  12296. */ hr() {
  12297. const t = {
  12298. activeTargetIds: this.activeTargetIds.toArray(),
  12299. updateTimeMs: Date.now()
  12300. };
  12301. return JSON.stringify(t);
  12302. }
  12303. }
  12304. /**
  12305. * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the
  12306. * backing store for the SharedClientState. It keeps track of all active
  12307. * clients and supports modifications of the local client's data.
  12308. */ class Su {
  12309. constructor(t, e, n, s, i) {
  12310. this.window = t, this.ii = e, this.persistenceKey = n, this.wr = s, this.syncEngine = null,
  12311. this.onlineStateHandler = null, this.sequenceNumberHandler = null, this._r = this.mr.bind(this),
  12312. this.gr = new Te(st), this.started = !1,
  12313. /**
  12314. * Captures WebStorage events that occur before `start()` is called. These
  12315. * events are replayed once `WebStorageSharedClientState` is started.
  12316. */
  12317. this.yr = [];
  12318. // Escape the special characters mentioned here:
  12319. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
  12320. const r = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  12321. this.storage = this.window.localStorage, this.currentUser = i, this.pr = Tu(this.persistenceKey, this.wr),
  12322. this.Ir =
  12323. /** Assembles the key for the current sequence number. */
  12324. function(t) {
  12325. return `firestore_sequence_number_${t}`;
  12326. }
  12327. /**
  12328. * @license
  12329. * Copyright 2018 Google LLC
  12330. *
  12331. * Licensed under the Apache License, Version 2.0 (the "License");
  12332. * you may not use this file except in compliance with the License.
  12333. * You may obtain a copy of the License at
  12334. *
  12335. * http://www.apache.org/licenses/LICENSE-2.0
  12336. *
  12337. * Unless required by applicable law or agreed to in writing, software
  12338. * distributed under the License is distributed on an "AS IS" BASIS,
  12339. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12340. * See the License for the specific language governing permissions and
  12341. * limitations under the License.
  12342. */ (this.persistenceKey), this.gr = this.gr.insert(this.wr, new Vu), this.Tr = new RegExp(`^firestore_clients_${r}_([^_]*)$`),
  12343. this.Er = new RegExp(`^firestore_mutations_${r}_(\\d+)(?:_(.*))?$`), this.Ar = new RegExp(`^firestore_targets_${r}_(\\d+)$`),
  12344. this.vr =
  12345. /** Assembles the key for the online state of the primary tab. */
  12346. function(t) {
  12347. return `firestore_online_state_${t}`;
  12348. }
  12349. // The WebStorage prefix that plays as a event to indicate the remote documents
  12350. // might have changed due to some secondary tabs loading a bundle.
  12351. // format of the key is:
  12352. // firestore_bundle_loaded_v2_<persistenceKey>
  12353. // The version ending with "v2" stores the list of modified collection groups.
  12354. (this.persistenceKey), this.Rr = function(t) {
  12355. return `firestore_bundle_loaded_v2_${t}`;
  12356. }
  12357. // The WebStorage key prefix for the key that stores the last sequence number allocated. The key
  12358. // looks like 'firestore_sequence_number_<persistence_prefix>'.
  12359. (this.persistenceKey),
  12360. // Rather than adding the storage observer during start(), we add the
  12361. // storage observer during initialization. This ensures that we collect
  12362. // events before other components populate their initial state (during their
  12363. // respective start() calls). Otherwise, we might for example miss a
  12364. // mutation that is added after LocalStore's start() processed the existing
  12365. // mutations but before we observe WebStorage events.
  12366. this.window.addEventListener("storage", this._r);
  12367. }
  12368. /** Returns 'true' if WebStorage is available in the current environment. */ static D(t) {
  12369. return !(!t || !t.localStorage);
  12370. }
  12371. async start() {
  12372. // Retrieve the list of existing clients to backfill the data in
  12373. // SharedClientState.
  12374. const t = await this.syncEngine.Mi();
  12375. for (const e of t) {
  12376. if (e === this.wr) continue;
  12377. const t = this.getItem(Tu(this.persistenceKey, e));
  12378. if (t) {
  12379. const n = Pu.ar(e, t);
  12380. n && (this.gr = this.gr.insert(n.clientId, n));
  12381. }
  12382. }
  12383. this.Pr();
  12384. // Check if there is an existing online state and call the callback handler
  12385. // if applicable.
  12386. const e = this.storage.getItem(this.vr);
  12387. if (e) {
  12388. const t = this.br(e);
  12389. t && this.Vr(t);
  12390. }
  12391. for (const t of this.yr) this.mr(t);
  12392. this.yr = [],
  12393. // Register a window unload hook to remove the client metadata entry from
  12394. // WebStorage even if `shutdown()` was not called.
  12395. this.window.addEventListener("pagehide", (() => this.shutdown())), this.started = !0;
  12396. }
  12397. writeSequenceNumber(t) {
  12398. this.setItem(this.Ir, JSON.stringify(t));
  12399. }
  12400. getAllActiveQueryTargets() {
  12401. return this.Sr(this.gr);
  12402. }
  12403. isActiveQueryTarget(t) {
  12404. let e = !1;
  12405. return this.gr.forEach(((n, s) => {
  12406. s.activeTargetIds.has(t) && (e = !0);
  12407. })), e;
  12408. }
  12409. addPendingMutation(t) {
  12410. this.Dr(t, "pending");
  12411. }
  12412. updateMutationState(t, e, n) {
  12413. this.Dr(t, e, n),
  12414. // Once a final mutation result is observed by other clients, they no longer
  12415. // access the mutation's metadata entry. Since WebStorage replays events
  12416. // in order, it is safe to delete the entry right after updating it.
  12417. this.Cr(t);
  12418. }
  12419. addLocalQueryTarget(t) {
  12420. let e = "not-current";
  12421. // Lookup an existing query state if the target ID was already registered
  12422. // by another tab
  12423. if (this.isActiveQueryTarget(t)) {
  12424. const n = this.storage.getItem(Au(this.persistenceKey, t));
  12425. if (n) {
  12426. const s = Ru.ar(t, n);
  12427. s && (e = s.state);
  12428. }
  12429. }
  12430. return this.Nr.lr(t), this.Pr(), e;
  12431. }
  12432. removeLocalQueryTarget(t) {
  12433. this.Nr.dr(t), this.Pr();
  12434. }
  12435. isLocalQueryTarget(t) {
  12436. return this.Nr.activeTargetIds.has(t);
  12437. }
  12438. clearQueryState(t) {
  12439. this.removeItem(Au(this.persistenceKey, t));
  12440. }
  12441. updateQueryState(t, e, n) {
  12442. this.kr(t, e, n);
  12443. }
  12444. handleUserChange(t, e, n) {
  12445. e.forEach((t => {
  12446. this.Cr(t);
  12447. })), this.currentUser = t, n.forEach((t => {
  12448. this.addPendingMutation(t);
  12449. }));
  12450. }
  12451. setOnlineState(t) {
  12452. this.$r(t);
  12453. }
  12454. notifyBundleLoaded(t) {
  12455. this.Mr(t);
  12456. }
  12457. shutdown() {
  12458. this.started && (this.window.removeEventListener("storage", this._r), this.removeItem(this.pr),
  12459. this.started = !1);
  12460. }
  12461. getItem(t) {
  12462. const e = this.storage.getItem(t);
  12463. return $("SharedClientState", "READ", t, e), e;
  12464. }
  12465. setItem(t, e) {
  12466. $("SharedClientState", "SET", t, e), this.storage.setItem(t, e);
  12467. }
  12468. removeItem(t) {
  12469. $("SharedClientState", "REMOVE", t), this.storage.removeItem(t);
  12470. }
  12471. mr(t) {
  12472. // Note: The function is typed to take Event to be interface-compatible with
  12473. // `Window.addEventListener`.
  12474. const e = t;
  12475. if (e.storageArea === this.storage) {
  12476. if ($("SharedClientState", "EVENT", e.key, e.newValue), e.key === this.pr) return void M("Received WebStorage notification for local change. Another client might have garbage-collected our state");
  12477. this.ii.enqueueRetryable((async () => {
  12478. if (this.started) {
  12479. if (null !== e.key) if (this.Tr.test(e.key)) {
  12480. if (null == e.newValue) {
  12481. const t = this.Or(e.key);
  12482. return this.Fr(t, null);
  12483. }
  12484. {
  12485. const t = this.Br(e.key, e.newValue);
  12486. if (t) return this.Fr(t.clientId, t);
  12487. }
  12488. } else if (this.Er.test(e.key)) {
  12489. if (null !== e.newValue) {
  12490. const t = this.Lr(e.key, e.newValue);
  12491. if (t) return this.qr(t);
  12492. }
  12493. } else if (this.Ar.test(e.key)) {
  12494. if (null !== e.newValue) {
  12495. const t = this.Ur(e.key, e.newValue);
  12496. if (t) return this.Kr(t);
  12497. }
  12498. } else if (e.key === this.vr) {
  12499. if (null !== e.newValue) {
  12500. const t = this.br(e.newValue);
  12501. if (t) return this.Vr(t);
  12502. }
  12503. } else if (e.key === this.Ir) {
  12504. const t = function(t) {
  12505. let e = Bt.ct;
  12506. if (null != t) try {
  12507. const n = JSON.parse(t);
  12508. L("number" == typeof n), e = n;
  12509. } catch (t) {
  12510. M("SharedClientState", "Failed to read sequence number from WebStorage", t);
  12511. }
  12512. return e;
  12513. }
  12514. /**
  12515. * `MemorySharedClientState` is a simple implementation of SharedClientState for
  12516. * clients using memory persistence. The state in this class remains fully
  12517. * isolated and no synchronization is performed.
  12518. */ (e.newValue);
  12519. t !== Bt.ct && this.sequenceNumberHandler(t);
  12520. } else if (e.key === this.Rr) {
  12521. const t = this.Gr(e.newValue);
  12522. await Promise.all(t.map((t => this.syncEngine.Qr(t))));
  12523. }
  12524. } else this.yr.push(e);
  12525. }));
  12526. }
  12527. }
  12528. get Nr() {
  12529. return this.gr.get(this.wr);
  12530. }
  12531. Pr() {
  12532. this.setItem(this.pr, this.Nr.hr());
  12533. }
  12534. Dr(t, e, n) {
  12535. const s = new vu(this.currentUser, t, e, n), i = Eu(this.persistenceKey, this.currentUser, t);
  12536. this.setItem(i, s.hr());
  12537. }
  12538. Cr(t) {
  12539. const e = Eu(this.persistenceKey, this.currentUser, t);
  12540. this.removeItem(e);
  12541. }
  12542. $r(t) {
  12543. const e = {
  12544. clientId: this.wr,
  12545. onlineState: t
  12546. };
  12547. this.storage.setItem(this.vr, JSON.stringify(e));
  12548. }
  12549. kr(t, e, n) {
  12550. const s = Au(this.persistenceKey, t), i = new Ru(t, e, n);
  12551. this.setItem(s, i.hr());
  12552. }
  12553. Mr(t) {
  12554. const e = JSON.stringify(Array.from(t));
  12555. this.setItem(this.Rr, e);
  12556. }
  12557. /**
  12558. * Parses a client state key in WebStorage. Returns null if the key does not
  12559. * match the expected key format.
  12560. */ Or(t) {
  12561. const e = this.Tr.exec(t);
  12562. return e ? e[1] : null;
  12563. }
  12564. /**
  12565. * Parses a client state in WebStorage. Returns 'null' if the value could not
  12566. * be parsed.
  12567. */ Br(t, e) {
  12568. const n = this.Or(t);
  12569. return Pu.ar(n, e);
  12570. }
  12571. /**
  12572. * Parses a mutation batch state in WebStorage. Returns 'null' if the value
  12573. * could not be parsed.
  12574. */ Lr(t, e) {
  12575. const n = this.Er.exec(t), s = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;
  12576. return vu.ar(new D(i), s, e);
  12577. }
  12578. /**
  12579. * Parses a query target state from WebStorage. Returns 'null' if the value
  12580. * could not be parsed.
  12581. */ Ur(t, e) {
  12582. const n = this.Ar.exec(t), s = Number(n[1]);
  12583. return Ru.ar(s, e);
  12584. }
  12585. /**
  12586. * Parses an online state from WebStorage. Returns 'null' if the value
  12587. * could not be parsed.
  12588. */ br(t) {
  12589. return bu.ar(t);
  12590. }
  12591. Gr(t) {
  12592. return JSON.parse(t);
  12593. }
  12594. async qr(t) {
  12595. if (t.user.uid === this.currentUser.uid) return this.syncEngine.jr(t.batchId, t.state, t.error);
  12596. $("SharedClientState", `Ignoring mutation for non-active user ${t.user.uid}`);
  12597. }
  12598. Kr(t) {
  12599. return this.syncEngine.zr(t.targetId, t.state, t.error);
  12600. }
  12601. Fr(t, e) {
  12602. const n = e ? this.gr.insert(t, e) : this.gr.remove(t), s = this.Sr(this.gr), i = this.Sr(n), r = [], o = [];
  12603. return i.forEach((t => {
  12604. s.has(t) || r.push(t);
  12605. })), s.forEach((t => {
  12606. i.has(t) || o.push(t);
  12607. })), this.syncEngine.Wr(r, o).then((() => {
  12608. this.gr = n;
  12609. }));
  12610. }
  12611. Vr(t) {
  12612. // We check whether the client that wrote this online state is still active
  12613. // by comparing its client ID to the list of clients kept active in
  12614. // IndexedDb. If a client does not update their IndexedDb client state
  12615. // within 5 seconds, it is considered inactive and we don't emit an online
  12616. // state event.
  12617. this.gr.get(t.clientId) && this.onlineStateHandler(t.onlineState);
  12618. }
  12619. Sr(t) {
  12620. let e = Es();
  12621. return t.forEach(((t, n) => {
  12622. e = e.unionWith(n.activeTargetIds);
  12623. })), e;
  12624. }
  12625. }
  12626. class Du {
  12627. constructor() {
  12628. this.Hr = new Vu, this.Jr = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;
  12629. }
  12630. addPendingMutation(t) {
  12631. // No op.
  12632. }
  12633. updateMutationState(t, e, n) {
  12634. // No op.
  12635. }
  12636. addLocalQueryTarget(t) {
  12637. return this.Hr.lr(t), this.Jr[t] || "not-current";
  12638. }
  12639. updateQueryState(t, e, n) {
  12640. this.Jr[t] = e;
  12641. }
  12642. removeLocalQueryTarget(t) {
  12643. this.Hr.dr(t);
  12644. }
  12645. isLocalQueryTarget(t) {
  12646. return this.Hr.activeTargetIds.has(t);
  12647. }
  12648. clearQueryState(t) {
  12649. delete this.Jr[t];
  12650. }
  12651. getAllActiveQueryTargets() {
  12652. return this.Hr.activeTargetIds;
  12653. }
  12654. isActiveQueryTarget(t) {
  12655. return this.Hr.activeTargetIds.has(t);
  12656. }
  12657. start() {
  12658. return this.Hr = new Vu, Promise.resolve();
  12659. }
  12660. handleUserChange(t, e, n) {
  12661. // No op.
  12662. }
  12663. setOnlineState(t) {
  12664. // No op.
  12665. }
  12666. shutdown() {}
  12667. writeSequenceNumber(t) {}
  12668. notifyBundleLoaded(t) {
  12669. // No op.
  12670. }
  12671. }
  12672. /**
  12673. * @license
  12674. * Copyright 2019 Google LLC
  12675. *
  12676. * Licensed under the Apache License, Version 2.0 (the "License");
  12677. * you may not use this file except in compliance with the License.
  12678. * You may obtain a copy of the License at
  12679. *
  12680. * http://www.apache.org/licenses/LICENSE-2.0
  12681. *
  12682. * Unless required by applicable law or agreed to in writing, software
  12683. * distributed under the License is distributed on an "AS IS" BASIS,
  12684. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12685. * See the License for the specific language governing permissions and
  12686. * limitations under the License.
  12687. */ class Cu {
  12688. Yr(t) {
  12689. // No-op.
  12690. }
  12691. shutdown() {
  12692. // No-op.
  12693. }
  12694. }
  12695. /**
  12696. * @license
  12697. * Copyright 2019 Google LLC
  12698. *
  12699. * Licensed under the Apache License, Version 2.0 (the "License");
  12700. * you may not use this file except in compliance with the License.
  12701. * You may obtain a copy of the License at
  12702. *
  12703. * http://www.apache.org/licenses/LICENSE-2.0
  12704. *
  12705. * Unless required by applicable law or agreed to in writing, software
  12706. * distributed under the License is distributed on an "AS IS" BASIS,
  12707. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12708. * See the License for the specific language governing permissions and
  12709. * limitations under the License.
  12710. */
  12711. // References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()
  12712. /* eslint-disable no-restricted-globals */
  12713. /**
  12714. * Browser implementation of ConnectivityMonitor.
  12715. */
  12716. class xu {
  12717. constructor() {
  12718. this.Xr = () => this.Zr(), this.eo = () => this.no(), this.so = [], this.io();
  12719. }
  12720. Yr(t) {
  12721. this.so.push(t);
  12722. }
  12723. shutdown() {
  12724. window.removeEventListener("online", this.Xr), window.removeEventListener("offline", this.eo);
  12725. }
  12726. io() {
  12727. window.addEventListener("online", this.Xr), window.addEventListener("offline", this.eo);
  12728. }
  12729. Zr() {
  12730. $("ConnectivityMonitor", "Network connectivity changed: AVAILABLE");
  12731. for (const t of this.so) t(0 /* NetworkStatus.AVAILABLE */);
  12732. }
  12733. no() {
  12734. $("ConnectivityMonitor", "Network connectivity changed: UNAVAILABLE");
  12735. for (const t of this.so) t(1 /* NetworkStatus.UNAVAILABLE */);
  12736. }
  12737. // TODO(chenbrian): Consider passing in window either into this component or
  12738. // here for testing via FakeWindow.
  12739. /** Checks that all used attributes of window are available. */
  12740. static D() {
  12741. return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
  12742. }
  12743. }
  12744. /**
  12745. * @license
  12746. * Copyright 2023 Google LLC
  12747. *
  12748. * Licensed under the Apache License, Version 2.0 (the "License");
  12749. * you may not use this file except in compliance with the License.
  12750. * You may obtain a copy of the License at
  12751. *
  12752. * http://www.apache.org/licenses/LICENSE-2.0
  12753. *
  12754. * Unless required by applicable law or agreed to in writing, software
  12755. * distributed under the License is distributed on an "AS IS" BASIS,
  12756. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12757. * See the License for the specific language governing permissions and
  12758. * limitations under the License.
  12759. */
  12760. /**
  12761. * The value returned from the most recent invocation of
  12762. * `generateUniqueDebugId()`, or null if it has never been invoked.
  12763. */ let Nu = null;
  12764. /**
  12765. * Generates and returns an initial value for `lastUniqueDebugId`.
  12766. *
  12767. * The returned value is randomly selected from a range of integers that are
  12768. * represented as 8 hexadecimal digits. This means that (within reason) any
  12769. * numbers generated by incrementing the returned number by 1 will also be
  12770. * represented by 8 hexadecimal digits. This leads to all "IDs" having the same
  12771. * length when converted to a hexadecimal string, making reading logs containing
  12772. * these IDs easier to follow. And since the return value is randomly selected
  12773. * it will help to differentiate between logs from different executions.
  12774. */
  12775. /**
  12776. * Generates and returns a unique ID as a hexadecimal string.
  12777. *
  12778. * The returned ID is intended to be used in debug logging messages to help
  12779. * correlate log messages that may be spatially separated in the logs, but
  12780. * logically related. For example, a network connection could include the same
  12781. * "debug ID" string in all of its log messages to help trace a specific
  12782. * connection over time.
  12783. *
  12784. * @return the 10-character generated ID (e.g. "0xa1b2c3d4").
  12785. */
  12786. function ku() {
  12787. return null === Nu ? Nu = 268435456 + Math.round(2147483648 * Math.random()) : Nu++,
  12788. "0x" + Nu.toString(16);
  12789. }
  12790. /**
  12791. * @license
  12792. * Copyright 2020 Google LLC
  12793. *
  12794. * Licensed under the Apache License, Version 2.0 (the "License");
  12795. * you may not use this file except in compliance with the License.
  12796. * You may obtain a copy of the License at
  12797. *
  12798. * http://www.apache.org/licenses/LICENSE-2.0
  12799. *
  12800. * Unless required by applicable law or agreed to in writing, software
  12801. * distributed under the License is distributed on an "AS IS" BASIS,
  12802. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12803. * See the License for the specific language governing permissions and
  12804. * limitations under the License.
  12805. */ const $u = {
  12806. BatchGetDocuments: "batchGet",
  12807. Commit: "commit",
  12808. RunQuery: "runQuery",
  12809. RunAggregationQuery: "runAggregationQuery"
  12810. };
  12811. /**
  12812. * Maps RPC names to the corresponding REST endpoint name.
  12813. *
  12814. * We use array notation to avoid mangling.
  12815. */
  12816. /**
  12817. * @license
  12818. * Copyright 2017 Google LLC
  12819. *
  12820. * Licensed under the Apache License, Version 2.0 (the "License");
  12821. * you may not use this file except in compliance with the License.
  12822. * You may obtain a copy of the License at
  12823. *
  12824. * http://www.apache.org/licenses/LICENSE-2.0
  12825. *
  12826. * Unless required by applicable law or agreed to in writing, software
  12827. * distributed under the License is distributed on an "AS IS" BASIS,
  12828. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12829. * See the License for the specific language governing permissions and
  12830. * limitations under the License.
  12831. */
  12832. /**
  12833. * Provides a simple helper class that implements the Stream interface to
  12834. * bridge to other implementations that are streams but do not implement the
  12835. * interface. The stream callbacks are invoked with the callOn... methods.
  12836. */
  12837. class Mu {
  12838. constructor(t) {
  12839. this.ro = t.ro, this.oo = t.oo;
  12840. }
  12841. uo(t) {
  12842. this.co = t;
  12843. }
  12844. ao(t) {
  12845. this.ho = t;
  12846. }
  12847. onMessage(t) {
  12848. this.lo = t;
  12849. }
  12850. close() {
  12851. this.oo();
  12852. }
  12853. send(t) {
  12854. this.ro(t);
  12855. }
  12856. fo() {
  12857. this.co();
  12858. }
  12859. wo(t) {
  12860. this.ho(t);
  12861. }
  12862. _o(t) {
  12863. this.lo(t);
  12864. }
  12865. }
  12866. /**
  12867. * @license
  12868. * Copyright 2017 Google LLC
  12869. *
  12870. * Licensed under the Apache License, Version 2.0 (the "License");
  12871. * you may not use this file except in compliance with the License.
  12872. * You may obtain a copy of the License at
  12873. *
  12874. * http://www.apache.org/licenses/LICENSE-2.0
  12875. *
  12876. * Unless required by applicable law or agreed to in writing, software
  12877. * distributed under the License is distributed on an "AS IS" BASIS,
  12878. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12879. * See the License for the specific language governing permissions and
  12880. * limitations under the License.
  12881. */ const Ou = "WebChannelConnection";
  12882. class Fu extends
  12883. /**
  12884. * Base class for all Rest-based connections to the backend (WebChannel and
  12885. * HTTP).
  12886. */
  12887. class {
  12888. constructor(t) {
  12889. this.databaseInfo = t, this.databaseId = t.databaseId;
  12890. const e = t.ssl ? "https" : "http";
  12891. this.mo = e + "://" + t.host, this.yo = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents";
  12892. }
  12893. get po() {
  12894. // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
  12895. // where to run the query, and expect the `request` to NOT specify the "path".
  12896. return !1;
  12897. }
  12898. Io(t, e, n, s, i) {
  12899. const r = ku(), o = this.To(t, e);
  12900. $("RestConnection", `Sending RPC '${t}' ${r}:`, o, n);
  12901. const u = {};
  12902. return this.Eo(u, s, i), this.Ao(t, o, u, n).then((e => ($("RestConnection", `Received RPC '${t}' ${r}: `, e),
  12903. e)), (e => {
  12904. throw O("RestConnection", `RPC '${t}' ${r} failed with error: `, e, "url: ", o, "request:", n),
  12905. e;
  12906. }));
  12907. }
  12908. vo(t, e, n, s, i, r) {
  12909. // The REST API automatically aggregates all of the streamed results, so we
  12910. // can just use the normal invoke() method.
  12911. return this.Io(t, e, n, s, i);
  12912. }
  12913. /**
  12914. * Modifies the headers for a request, adding any authorization token if
  12915. * present and any additional headers for the request.
  12916. */ Eo(t, e, n) {
  12917. t["X-Goog-Api-Client"] = "gl-js/ fire/" + C,
  12918. // Content-Type: text/plain will avoid preflight requests which might
  12919. // mess with CORS and redirects by proxies. If we add custom headers
  12920. // we will need to change this code to potentially use the $httpOverwrite
  12921. // parameter supported by ESF to avoid triggering preflight requests.
  12922. t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId),
  12923. e && e.headers.forEach(((e, n) => t[n] = e)), n && n.headers.forEach(((e, n) => t[n] = e));
  12924. }
  12925. To(t, e) {
  12926. const n = $u[t];
  12927. return `${this.mo}/v1/${e}:${n}`;
  12928. }
  12929. } {
  12930. constructor(t) {
  12931. super(t), this.forceLongPolling = t.forceLongPolling, this.autoDetectLongPolling = t.autoDetectLongPolling,
  12932. this.useFetchStreams = t.useFetchStreams, this.longPollingOptions = t.longPollingOptions;
  12933. }
  12934. Ao(t, e, n, s) {
  12935. const i = ku();
  12936. return new Promise(((r, o) => {
  12937. const u = new I;
  12938. u.setWithCredentials(!0), u.listenOnce(T.COMPLETE, (() => {
  12939. try {
  12940. switch (u.getLastErrorCode()) {
  12941. case E.NO_ERROR:
  12942. const e = u.getResponseJson();
  12943. $(Ou, `XHR for RPC '${t}' ${i} received:`, JSON.stringify(e)), r(e);
  12944. break;
  12945. case E.TIMEOUT:
  12946. $(Ou, `RPC '${t}' ${i} timed out`), o(new G(K.DEADLINE_EXCEEDED, "Request time out"));
  12947. break;
  12948. case E.HTTP_ERROR:
  12949. const n = u.getStatus();
  12950. if ($(Ou, `RPC '${t}' ${i} failed with status:`, n, "response text:", u.getResponseText()),
  12951. n > 0) {
  12952. let t = u.getResponseJson();
  12953. Array.isArray(t) && (t = t[0]);
  12954. const e = null == t ? void 0 : t.error;
  12955. if (e && e.status && e.message) {
  12956. const t = function(t) {
  12957. const e = t.toLowerCase().replace(/_/g, "-");
  12958. return Object.values(K).indexOf(e) >= 0 ? e : K.UNKNOWN;
  12959. }(e.status);
  12960. o(new G(t, e.message));
  12961. } else o(new G(K.UNKNOWN, "Server responded with status " + u.getStatus()));
  12962. } else
  12963. // If we received an HTTP_ERROR but there's no status code,
  12964. // it's most probably a connection issue
  12965. o(new G(K.UNAVAILABLE, "Connection failed."));
  12966. break;
  12967. default:
  12968. B();
  12969. }
  12970. } finally {
  12971. $(Ou, `RPC '${t}' ${i} completed.`);
  12972. }
  12973. }));
  12974. const c = JSON.stringify(s);
  12975. $(Ou, `RPC '${t}' ${i} sending request:`, s), u.send(e, "POST", c, n, 15);
  12976. }));
  12977. }
  12978. Ro(t, e, n) {
  12979. const s = ku(), i = [ this.mo, "/", "google.firestore.v1.Firestore", "/", t, "/channel" ], r = A(), o = v(), u = {
  12980. // Required for backend stickiness, routing behavior is based on this
  12981. // parameter.
  12982. httpSessionIdParam: "gsessionid",
  12983. initMessageHeaders: {},
  12984. messageUrlParams: {
  12985. // This param is used to improve routing and project isolation by the
  12986. // backend and must be included in every request.
  12987. database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`
  12988. },
  12989. sendRawJson: !0,
  12990. supportsCrossDomainXhr: !0,
  12991. internalChannelParams: {
  12992. // Override the default timeout (randomized between 10-20 seconds) since
  12993. // a large write batch on a slow internet connection may take a long
  12994. // time to send to the backend. Rather than have WebChannel impose a
  12995. // tight timeout which could lead to infinite timeouts and retries, we
  12996. // set it very large (5-10 minutes) and rely on the browser's builtin
  12997. // timeouts to kick in if the request isn't working.
  12998. forwardChannelRequestTimeoutMs: 6e5
  12999. },
  13000. forceLongPolling: this.forceLongPolling,
  13001. detectBufferingProxy: this.autoDetectLongPolling
  13002. }, c = this.longPollingOptions.timeoutSeconds;
  13003. void 0 !== c && (u.longPollingTimeout = Math.round(1e3 * c)), this.useFetchStreams && (u.xmlHttpFactory = new R({})),
  13004. this.Eo(u.initMessageHeaders, e, n),
  13005. // Sending the custom headers we just added to request.initMessageHeaders
  13006. // (Authorization, etc.) will trigger the browser to make a CORS preflight
  13007. // request because the XHR will no longer meet the criteria for a "simple"
  13008. // CORS request:
  13009. // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
  13010. // Therefore to avoid the CORS preflight request (an extra network
  13011. // roundtrip), we use the encodeInitMessageHeaders option to specify that
  13012. // the headers should instead be encoded in the request's POST payload,
  13013. // which is recognized by the webchannel backend.
  13014. u.encodeInitMessageHeaders = !0;
  13015. const a = i.join("");
  13016. $(Ou, `Creating RPC '${t}' stream ${s}: ${a}`, u);
  13017. const h = r.createWebChannel(a, u);
  13018. // WebChannel supports sending the first message with the handshake - saving
  13019. // a network round trip. However, it will have to call send in the same
  13020. // JS event loop as open. In order to enforce this, we delay actually
  13021. // opening the WebChannel until send is called. Whether we have called
  13022. // open is tracked with this variable.
  13023. let l = !1, f = !1;
  13024. // A flag to determine whether the stream was closed (by us or through an
  13025. // error/close event) to avoid delivering multiple close events or sending
  13026. // on a closed stream
  13027. const d = new Mu({
  13028. ro: e => {
  13029. f ? $(Ou, `Not sending because RPC '${t}' stream ${s} is closed:`, e) : (l || ($(Ou, `Opening RPC '${t}' stream ${s} transport.`),
  13030. h.open(), l = !0), $(Ou, `RPC '${t}' stream ${s} sending:`, e), h.send(e));
  13031. },
  13032. oo: () => h.close()
  13033. }), w = (t, e, n) => {
  13034. // TODO(dimond): closure typing seems broken because WebChannel does
  13035. // not implement goog.events.Listenable
  13036. t.listen(e, (t => {
  13037. try {
  13038. n(t);
  13039. } catch (t) {
  13040. setTimeout((() => {
  13041. throw t;
  13042. }), 0);
  13043. }
  13044. }));
  13045. };
  13046. // Closure events are guarded and exceptions are swallowed, so catch any
  13047. // exception and rethrow using a setTimeout so they become visible again.
  13048. // Note that eventually this function could go away if we are confident
  13049. // enough the code is exception free.
  13050. return w(h, P.EventType.OPEN, (() => {
  13051. f || $(Ou, `RPC '${t}' stream ${s} transport opened.`);
  13052. })), w(h, P.EventType.CLOSE, (() => {
  13053. f || (f = !0, $(Ou, `RPC '${t}' stream ${s} transport closed`), d.wo());
  13054. })), w(h, P.EventType.ERROR, (e => {
  13055. f || (f = !0, O(Ou, `RPC '${t}' stream ${s} transport errored:`, e), d.wo(new G(K.UNAVAILABLE, "The operation could not be completed")));
  13056. })), w(h, P.EventType.MESSAGE, (e => {
  13057. var n;
  13058. if (!f) {
  13059. const i = e.data[0];
  13060. L(!!i);
  13061. // TODO(b/35143891): There is a bug in One Platform that caused errors
  13062. // (and only errors) to be wrapped in an extra array. To be forward
  13063. // compatible with the bug we need to check either condition. The latter
  13064. // can be removed once the fix has been rolled out.
  13065. // Use any because msgData.error is not typed.
  13066. const r = i, o = r.error || (null === (n = r[0]) || void 0 === n ? void 0 : n.error);
  13067. if (o) {
  13068. $(Ou, `RPC '${t}' stream ${s} received error:`, o);
  13069. // error.status will be a string like 'OK' or 'NOT_FOUND'.
  13070. const e = o.status;
  13071. let n =
  13072. /**
  13073. * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
  13074. *
  13075. * @returns The Code equivalent to the given status string or undefined if
  13076. * there is no match.
  13077. */
  13078. function(t) {
  13079. // lookup by string
  13080. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13081. const e = ui[t];
  13082. if (void 0 !== e) return hi(e);
  13083. }(e), i = o.message;
  13084. void 0 === n && (n = K.INTERNAL, i = "Unknown error status: " + e + " with message " + o.message),
  13085. // Mark closed so no further events are propagated
  13086. f = !0, d.wo(new G(n, i)), h.close();
  13087. } else $(Ou, `RPC '${t}' stream ${s} received:`, i), d._o(i);
  13088. }
  13089. })), w(o, b.STAT_EVENT, (e => {
  13090. e.stat === V.PROXY ? $(Ou, `RPC '${t}' stream ${s} detected buffering proxy`) : e.stat === V.NOPROXY && $(Ou, `RPC '${t}' stream ${s} detected no buffering proxy`);
  13091. })), setTimeout((() => {
  13092. // Technically we could/should wait for the WebChannel opened event,
  13093. // but because we want to send the first message with the WebChannel
  13094. // handshake we pretend the channel opened here (asynchronously), and
  13095. // then delay the actual open until the first message is sent.
  13096. d.fo();
  13097. }), 0), d;
  13098. }
  13099. }
  13100. /**
  13101. * @license
  13102. * Copyright 2020 Google LLC
  13103. *
  13104. * Licensed under the Apache License, Version 2.0 (the "License");
  13105. * you may not use this file except in compliance with the License.
  13106. * You may obtain a copy of the License at
  13107. *
  13108. * http://www.apache.org/licenses/LICENSE-2.0
  13109. *
  13110. * Unless required by applicable law or agreed to in writing, software
  13111. * distributed under the License is distributed on an "AS IS" BASIS,
  13112. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13113. * See the License for the specific language governing permissions and
  13114. * limitations under the License.
  13115. */
  13116. /** Initializes the WebChannelConnection for the browser. */
  13117. /**
  13118. * @license
  13119. * Copyright 2020 Google LLC
  13120. *
  13121. * Licensed under the Apache License, Version 2.0 (the "License");
  13122. * you may not use this file except in compliance with the License.
  13123. * You may obtain a copy of the License at
  13124. *
  13125. * http://www.apache.org/licenses/LICENSE-2.0
  13126. *
  13127. * Unless required by applicable law or agreed to in writing, software
  13128. * distributed under the License is distributed on an "AS IS" BASIS,
  13129. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13130. * See the License for the specific language governing permissions and
  13131. * limitations under the License.
  13132. */
  13133. /** The Platform's 'window' implementation or null if not available. */
  13134. function Bu() {
  13135. // `window` is not always available, e.g. in ReactNative and WebWorkers.
  13136. // eslint-disable-next-line no-restricted-globals
  13137. return "undefined" != typeof window ? window : null;
  13138. }
  13139. /** The Platform's 'document' implementation or null if not available. */ function Lu() {
  13140. // `document` is not always available, e.g. in ReactNative and WebWorkers.
  13141. // eslint-disable-next-line no-restricted-globals
  13142. return "undefined" != typeof document ? document : null;
  13143. }
  13144. /**
  13145. * @license
  13146. * Copyright 2020 Google LLC
  13147. *
  13148. * Licensed under the Apache License, Version 2.0 (the "License");
  13149. * you may not use this file except in compliance with the License.
  13150. * You may obtain a copy of the License at
  13151. *
  13152. * http://www.apache.org/licenses/LICENSE-2.0
  13153. *
  13154. * Unless required by applicable law or agreed to in writing, software
  13155. * distributed under the License is distributed on an "AS IS" BASIS,
  13156. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13157. * See the License for the specific language governing permissions and
  13158. * limitations under the License.
  13159. */ function qu(t) {
  13160. return new Ci(t, /* useProto3Json= */ !0);
  13161. }
  13162. /**
  13163. * @license
  13164. * Copyright 2017 Google LLC
  13165. *
  13166. * Licensed under the Apache License, Version 2.0 (the "License");
  13167. * you may not use this file except in compliance with the License.
  13168. * You may obtain a copy of the License at
  13169. *
  13170. * http://www.apache.org/licenses/LICENSE-2.0
  13171. *
  13172. * Unless required by applicable law or agreed to in writing, software
  13173. * distributed under the License is distributed on an "AS IS" BASIS,
  13174. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13175. * See the License for the specific language governing permissions and
  13176. * limitations under the License.
  13177. */
  13178. /**
  13179. * A helper for running delayed tasks following an exponential backoff curve
  13180. * between attempts.
  13181. *
  13182. * Each delay is made up of a "base" delay which follows the exponential
  13183. * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
  13184. * base delay. This prevents clients from accidentally synchronizing their
  13185. * delays causing spikes of load to the backend.
  13186. */
  13187. class Uu {
  13188. constructor(
  13189. /**
  13190. * The AsyncQueue to run backoff operations on.
  13191. */
  13192. t,
  13193. /**
  13194. * The ID to use when scheduling backoff operations on the AsyncQueue.
  13195. */
  13196. e,
  13197. /**
  13198. * The initial delay (used as the base delay on the first retry attempt).
  13199. * Note that jitter will still be applied, so the actual delay could be as
  13200. * little as 0.5*initialDelayMs.
  13201. */
  13202. n = 1e3
  13203. /**
  13204. * The multiplier to use to determine the extended base delay after each
  13205. * attempt.
  13206. */ , s = 1.5
  13207. /**
  13208. * The maximum base delay after which no further backoff is performed.
  13209. * Note that jitter will still be applied, so the actual delay could be as
  13210. * much as 1.5*maxDelayMs.
  13211. */ , i = 6e4) {
  13212. this.ii = t, this.timerId = e, this.Po = n, this.bo = s, this.Vo = i, this.So = 0,
  13213. this.Do = null,
  13214. /** The last backoff attempt, as epoch milliseconds. */
  13215. this.Co = Date.now(), this.reset();
  13216. }
  13217. /**
  13218. * Resets the backoff delay.
  13219. *
  13220. * The very next backoffAndWait() will have no delay. If it is called again
  13221. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  13222. * subsequent ones will increase according to the backoffFactor.
  13223. */ reset() {
  13224. this.So = 0;
  13225. }
  13226. /**
  13227. * Resets the backoff delay to the maximum delay (e.g. for use after a
  13228. * RESOURCE_EXHAUSTED error).
  13229. */ xo() {
  13230. this.So = this.Vo;
  13231. }
  13232. /**
  13233. * Returns a promise that resolves after currentDelayMs, and increases the
  13234. * delay for any subsequent attempts. If there was a pending backoff operation
  13235. * already, it will be canceled.
  13236. */ No(t) {
  13237. // Cancel any pending backoff operation.
  13238. this.cancel();
  13239. // First schedule using the current base (which may be 0 and should be
  13240. // honored as such).
  13241. const e = Math.floor(this.So + this.ko()), n = Math.max(0, Date.now() - this.Co), s = Math.max(0, e - n);
  13242. // Guard against lastAttemptTime being in the future due to a clock change.
  13243. s > 0 && $("ExponentialBackoff", `Backing off for ${s} ms (base delay: ${this.So} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`),
  13244. this.Do = this.ii.enqueueAfterDelay(this.timerId, s, (() => (this.Co = Date.now(),
  13245. t()))),
  13246. // Apply backoff factor to determine next delay and ensure it is within
  13247. // bounds.
  13248. this.So *= this.bo, this.So < this.Po && (this.So = this.Po), this.So > this.Vo && (this.So = this.Vo);
  13249. }
  13250. $o() {
  13251. null !== this.Do && (this.Do.skipDelay(), this.Do = null);
  13252. }
  13253. cancel() {
  13254. null !== this.Do && (this.Do.cancel(), this.Do = null);
  13255. }
  13256. /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ ko() {
  13257. return (Math.random() - .5) * this.So;
  13258. }
  13259. }
  13260. /**
  13261. * @license
  13262. * Copyright 2017 Google LLC
  13263. *
  13264. * Licensed under the Apache License, Version 2.0 (the "License");
  13265. * you may not use this file except in compliance with the License.
  13266. * You may obtain a copy of the License at
  13267. *
  13268. * http://www.apache.org/licenses/LICENSE-2.0
  13269. *
  13270. * Unless required by applicable law or agreed to in writing, software
  13271. * distributed under the License is distributed on an "AS IS" BASIS,
  13272. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13273. * See the License for the specific language governing permissions and
  13274. * limitations under the License.
  13275. */
  13276. /**
  13277. * A PersistentStream is an abstract base class that represents a streaming RPC
  13278. * to the Firestore backend. It's built on top of the connections own support
  13279. * for streaming RPCs, and adds several critical features for our clients:
  13280. *
  13281. * - Exponential backoff on failure
  13282. * - Authentication via CredentialsProvider
  13283. * - Dispatching all callbacks into the shared worker queue
  13284. * - Closing idle streams after 60 seconds of inactivity
  13285. *
  13286. * Subclasses of PersistentStream implement serialization of models to and
  13287. * from the JSON representation of the protocol buffers for a specific
  13288. * streaming RPC.
  13289. *
  13290. * ## Starting and Stopping
  13291. *
  13292. * Streaming RPCs are stateful and need to be start()ed before messages can
  13293. * be sent and received. The PersistentStream will call the onOpen() function
  13294. * of the listener once the stream is ready to accept requests.
  13295. *
  13296. * Should a start() fail, PersistentStream will call the registered onClose()
  13297. * listener with a FirestoreError indicating what went wrong.
  13298. *
  13299. * A PersistentStream can be started and stopped repeatedly.
  13300. *
  13301. * Generic types:
  13302. * SendType: The type of the outgoing message of the underlying
  13303. * connection stream
  13304. * ReceiveType: The type of the incoming message of the underlying
  13305. * connection stream
  13306. * ListenerType: The type of the listener that will be used for callbacks
  13307. */
  13308. class Ku {
  13309. constructor(t, e, n, s, i, r, o, u) {
  13310. this.ii = t, this.Mo = n, this.Oo = s, this.connection = i, this.authCredentialsProvider = r,
  13311. this.appCheckCredentialsProvider = o, this.listener = u, this.state = 0 /* PersistentStreamState.Initial */ ,
  13312. /**
  13313. * A close count that's incremented every time the stream is closed; used by
  13314. * getCloseGuardedDispatcher() to invalidate callbacks that happen after
  13315. * close.
  13316. */
  13317. this.Fo = 0, this.Bo = null, this.Lo = null, this.stream = null, this.qo = new Uu(t, e);
  13318. }
  13319. /**
  13320. * Returns true if start() has been called and no error has occurred. True
  13321. * indicates the stream is open or in the process of opening (which
  13322. * encompasses respecting backoff, getting auth tokens, and starting the
  13323. * actual RPC). Use isOpen() to determine if the stream is open and ready for
  13324. * outbound requests.
  13325. */ Uo() {
  13326. return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.Ko();
  13327. }
  13328. /**
  13329. * Returns true if the underlying RPC is open (the onOpen() listener has been
  13330. * called) and the stream is ready for outbound requests.
  13331. */ Ko() {
  13332. return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;
  13333. }
  13334. /**
  13335. * Starts the RPC. Only allowed if isStarted() returns false. The stream is
  13336. * not immediately ready for use: onOpen() will be invoked when the RPC is
  13337. * ready for outbound requests, at which point isOpen() will return true.
  13338. *
  13339. * When start returns, isStarted() will return true.
  13340. */ start() {
  13341. 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Go();
  13342. }
  13343. /**
  13344. * Stops the RPC. This call is idempotent and allowed regardless of the
  13345. * current isStarted() state.
  13346. *
  13347. * When stop returns, isStarted() and isOpen() will both return false.
  13348. */ async stop() {
  13349. this.Uo() && await this.close(0 /* PersistentStreamState.Initial */);
  13350. }
  13351. /**
  13352. * After an error the stream will usually back off on the next attempt to
  13353. * start it. If the error warrants an immediate restart of the stream, the
  13354. * sender can use this to indicate that the receiver should not back off.
  13355. *
  13356. * Each error will call the onClose() listener. That function can decide to
  13357. * inhibit backoff if required.
  13358. */ Qo() {
  13359. this.state = 0 /* PersistentStreamState.Initial */ , this.qo.reset();
  13360. }
  13361. /**
  13362. * Marks this stream as idle. If no further actions are performed on the
  13363. * stream for one minute, the stream will automatically close itself and
  13364. * notify the stream's onClose() handler with Status.OK. The stream will then
  13365. * be in a !isStarted() state, requiring the caller to start the stream again
  13366. * before further use.
  13367. *
  13368. * Only streams that are in state 'Open' can be marked idle, as all other
  13369. * states imply pending network operations.
  13370. */ jo() {
  13371. // Starts the idle time if we are in state 'Open' and are not yet already
  13372. // running a timer (in which case the previous idle timeout still applies).
  13373. this.Ko() && null === this.Bo && (this.Bo = this.ii.enqueueAfterDelay(this.Mo, 6e4, (() => this.zo())));
  13374. }
  13375. /** Sends a message to the underlying stream. */ Wo(t) {
  13376. this.Ho(), this.stream.send(t);
  13377. }
  13378. /** Called by the idle timer when the stream should close due to inactivity. */ async zo() {
  13379. if (this.Ko())
  13380. // When timing out an idle stream there's no reason to force the stream into backoff when
  13381. // it restarts so set the stream state to Initial instead of Error.
  13382. return this.close(0 /* PersistentStreamState.Initial */);
  13383. }
  13384. /** Marks the stream as active again. */ Ho() {
  13385. this.Bo && (this.Bo.cancel(), this.Bo = null);
  13386. }
  13387. /** Cancels the health check delayed operation. */ Jo() {
  13388. this.Lo && (this.Lo.cancel(), this.Lo = null);
  13389. }
  13390. /**
  13391. * Closes the stream and cleans up as necessary:
  13392. *
  13393. * * closes the underlying GRPC stream;
  13394. * * calls the onClose handler with the given 'error';
  13395. * * sets internal stream state to 'finalState';
  13396. * * adjusts the backoff timer based on the error
  13397. *
  13398. * A new stream can be opened by calling start().
  13399. *
  13400. * @param finalState - the intended state of the stream after closing.
  13401. * @param error - the error the connection was closed with.
  13402. */ async close(t, e) {
  13403. // Cancel any outstanding timers (they're guaranteed not to execute).
  13404. this.Ho(), this.Jo(), this.qo.cancel(),
  13405. // Invalidates any stream-related callbacks (e.g. from auth or the
  13406. // underlying stream), guaranteeing they won't execute.
  13407. this.Fo++, 4 /* PersistentStreamState.Error */ !== t ?
  13408. // If this is an intentional close ensure we don't delay our next connection attempt.
  13409. this.qo.reset() : e && e.code === K.RESOURCE_EXHAUSTED ? (
  13410. // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
  13411. M(e.toString()), M("Using maximum backoff delay to prevent overloading the backend."),
  13412. this.qo.xo()) : e && e.code === K.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (
  13413. // "unauthenticated" error means the token was rejected. This should rarely
  13414. // happen since both Auth and AppCheck ensure a sufficient TTL when we
  13415. // request a token. If a user manually resets their system clock this can
  13416. // fail, however. In this case, we should get a Code.UNAUTHENTICATED error
  13417. // before we received the first message and we need to invalidate the token
  13418. // to ensure that we fetch a new token.
  13419. this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()),
  13420. // Clean up the underlying stream because we are no longer interested in events.
  13421. null !== this.stream && (this.Yo(), this.stream.close(), this.stream = null),
  13422. // This state must be assigned before calling onClose() to allow the callback to
  13423. // inhibit backoff or otherwise manipulate the state in its non-started state.
  13424. this.state = t,
  13425. // Notify the listener that the stream closed.
  13426. await this.listener.ao(e);
  13427. }
  13428. /**
  13429. * Can be overridden to perform additional cleanup before the stream is closed.
  13430. * Calling super.tearDown() is not required.
  13431. */ Yo() {}
  13432. auth() {
  13433. this.state = 1 /* PersistentStreamState.Starting */;
  13434. const t = this.Xo(this.Fo), e = this.Fo;
  13435. // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
  13436. Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([t, n]) => {
  13437. // Stream can be stopped while waiting for authentication.
  13438. // TODO(mikelehen): We really should just use dispatchIfNotClosed
  13439. // and let this dispatch onto the queue, but that opened a spec test can
  13440. // of worms that I don't want to deal with in this PR.
  13441. this.Fo === e &&
  13442. // Normally we'd have to schedule the callback on the AsyncQueue.
  13443. // However, the following calls are safe to be called outside the
  13444. // AsyncQueue since they don't chain asynchronous calls
  13445. this.Zo(t, n);
  13446. }), (e => {
  13447. t((() => {
  13448. const t = new G(K.UNKNOWN, "Fetching auth token failed: " + e.message);
  13449. return this.tu(t);
  13450. }));
  13451. }));
  13452. }
  13453. Zo(t, e) {
  13454. const n = this.Xo(this.Fo);
  13455. this.stream = this.eu(t, e), this.stream.uo((() => {
  13456. n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.Lo = this.ii.enqueueAfterDelay(this.Oo, 1e4, (() => (this.Ko() && (this.state = 3 /* PersistentStreamState.Healthy */),
  13457. Promise.resolve()))), this.listener.uo())));
  13458. })), this.stream.ao((t => {
  13459. n((() => this.tu(t)));
  13460. })), this.stream.onMessage((t => {
  13461. n((() => this.onMessage(t)));
  13462. }));
  13463. }
  13464. Go() {
  13465. this.state = 5 /* PersistentStreamState.Backoff */ , this.qo.No((async () => {
  13466. this.state = 0 /* PersistentStreamState.Initial */ , this.start();
  13467. }));
  13468. }
  13469. // Visible for tests
  13470. tu(t) {
  13471. // In theory the stream could close cleanly, however, in our current model
  13472. // we never expect this to happen because if we stop a stream ourselves,
  13473. // this callback will never be called. To prevent cases where we retry
  13474. // without a backoff accidentally, we set the stream to error in all cases.
  13475. return $("PersistentStream", `close with error: ${t}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , t);
  13476. }
  13477. /**
  13478. * Returns a "dispatcher" function that dispatches operations onto the
  13479. * AsyncQueue but only runs them if closeCount remains unchanged. This allows
  13480. * us to turn auth / stream callbacks into no-ops if the stream is closed /
  13481. * re-opened, etc.
  13482. */ Xo(t) {
  13483. return e => {
  13484. this.ii.enqueueAndForget((() => this.Fo === t ? e() : ($("PersistentStream", "stream callback skipped by getCloseGuardedDispatcher."),
  13485. Promise.resolve())));
  13486. };
  13487. }
  13488. }
  13489. /**
  13490. * A PersistentStream that implements the Listen RPC.
  13491. *
  13492. * Once the Listen stream has called the onOpen() listener, any number of
  13493. * listen() and unlisten() calls can be made to control what changes will be
  13494. * sent from the server for ListenResponses.
  13495. */ class Gu extends Ku {
  13496. constructor(t, e, n, s, i, r) {
  13497. super(t, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */ , "listen_stream_idle" /* TimerId.ListenStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , e, n, s, r),
  13498. this.serializer = i;
  13499. }
  13500. eu(t, e) {
  13501. return this.connection.Ro("Listen", t, e);
  13502. }
  13503. onMessage(t) {
  13504. // A successful response means the stream is healthy
  13505. this.qo.reset();
  13506. const e = Wi(this.serializer, t), n = function(t) {
  13507. // We have only reached a consistent snapshot for the entire stream if there
  13508. // is a read_time set and it applies to all targets (i.e. the list of
  13509. // targets is empty). The backend is guaranteed to send such responses.
  13510. if (!("targetChange" in t)) return ut.min();
  13511. const e = t.targetChange;
  13512. return e.targetIds && e.targetIds.length ? ut.min() : e.readTime ? Mi(e.readTime) : ut.min();
  13513. }(t);
  13514. return this.listener.nu(e, n);
  13515. }
  13516. /**
  13517. * Registers interest in the results of the given target. If the target
  13518. * includes a resumeToken it will be included in the request. Results that
  13519. * affect the target will be streamed back as WatchChange messages that
  13520. * reference the targetId.
  13521. */ su(t) {
  13522. const e = {};
  13523. e.database = Ki(this.serializer), e.addTarget = function(t, e) {
  13524. let n;
  13525. const s = e.target;
  13526. if (n = qn(s) ? {
  13527. documents: Xi(t, s)
  13528. } : {
  13529. query: Zi(t, s)
  13530. }, n.targetId = e.targetId, e.resumeToken.approximateByteSize() > 0) {
  13531. n.resumeToken = ki(t, e.resumeToken);
  13532. const s = xi(t, e.expectedCount);
  13533. null !== s && (n.expectedCount = s);
  13534. } else if (e.snapshotVersion.compareTo(ut.min()) > 0) {
  13535. // TODO(wuandy): Consider removing above check because it is most likely true.
  13536. // Right now, many tests depend on this behaviour though (leaving min() out
  13537. // of serialization).
  13538. n.readTime = Ni(t, e.snapshotVersion.toTimestamp());
  13539. const s = xi(t, e.expectedCount);
  13540. null !== s && (n.expectedCount = s);
  13541. }
  13542. return n;
  13543. }(this.serializer, t);
  13544. const n = er(this.serializer, t);
  13545. n && (e.labels = n), this.Wo(e);
  13546. }
  13547. /**
  13548. * Unregisters interest in the results of the target associated with the
  13549. * given targetId.
  13550. */ iu(t) {
  13551. const e = {};
  13552. e.database = Ki(this.serializer), e.removeTarget = t, this.Wo(e);
  13553. }
  13554. }
  13555. /**
  13556. * A Stream that implements the Write RPC.
  13557. *
  13558. * The Write RPC requires the caller to maintain special streamToken
  13559. * state in between calls, to help the server understand which responses the
  13560. * client has processed by the time the next request is made. Every response
  13561. * will contain a streamToken; this value must be passed to the next
  13562. * request.
  13563. *
  13564. * After calling start() on this stream, the next request must be a handshake,
  13565. * containing whatever streamToken is on hand. Once a response to this
  13566. * request is received, all pending mutations may be submitted. When
  13567. * submitting multiple batches of mutations at the same time, it's
  13568. * okay to use the same streamToken for the calls to writeMutations.
  13569. *
  13570. * TODO(b/33271235): Use proto types
  13571. */ class Qu extends Ku {
  13572. constructor(t, e, n, s, i, r) {
  13573. super(t, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */ , "write_stream_idle" /* TimerId.WriteStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , e, n, s, r),
  13574. this.serializer = i, this.ru = !1;
  13575. }
  13576. /**
  13577. * Tracks whether or not a handshake has been successfully exchanged and
  13578. * the stream is ready to accept mutations.
  13579. */ get ou() {
  13580. return this.ru;
  13581. }
  13582. // Override of PersistentStream.start
  13583. start() {
  13584. this.ru = !1, this.lastStreamToken = void 0, super.start();
  13585. }
  13586. Yo() {
  13587. this.ru && this.uu([]);
  13588. }
  13589. eu(t, e) {
  13590. return this.connection.Ro("Write", t, e);
  13591. }
  13592. onMessage(t) {
  13593. if (
  13594. // Always capture the last stream token.
  13595. L(!!t.streamToken), this.lastStreamToken = t.streamToken, this.ru) {
  13596. // A successful first write response means the stream is healthy,
  13597. // Note, that we could consider a successful handshake healthy, however,
  13598. // the write itself might be causing an error we want to back off from.
  13599. this.qo.reset();
  13600. const e = Yi(t.writeResults, t.commitTime), n = Mi(t.commitTime);
  13601. return this.listener.cu(n, e);
  13602. }
  13603. // The first response is always the handshake response
  13604. return L(!t.writeResults || 0 === t.writeResults.length), this.ru = !0, this.listener.au();
  13605. }
  13606. /**
  13607. * Sends an initial streamToken to the server, performing the handshake
  13608. * required to make the StreamingWrite RPC work. Subsequent
  13609. * calls should wait until onHandshakeComplete was called.
  13610. */ hu() {
  13611. // TODO(dimond): Support stream resumption. We intentionally do not set the
  13612. // stream token on the handshake, ignoring any stream token we might have.
  13613. const t = {};
  13614. t.database = Ki(this.serializer), this.Wo(t);
  13615. }
  13616. /** Sends a group of mutations to the Firestore backend to apply. */ uu(t) {
  13617. const e = {
  13618. streamToken: this.lastStreamToken,
  13619. writes: t.map((t => Hi(this.serializer, t)))
  13620. };
  13621. this.Wo(e);
  13622. }
  13623. }
  13624. /**
  13625. * @license
  13626. * Copyright 2017 Google LLC
  13627. *
  13628. * Licensed under the Apache License, Version 2.0 (the "License");
  13629. * you may not use this file except in compliance with the License.
  13630. * You may obtain a copy of the License at
  13631. *
  13632. * http://www.apache.org/licenses/LICENSE-2.0
  13633. *
  13634. * Unless required by applicable law or agreed to in writing, software
  13635. * distributed under the License is distributed on an "AS IS" BASIS,
  13636. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13637. * See the License for the specific language governing permissions and
  13638. * limitations under the License.
  13639. */
  13640. /**
  13641. * Datastore and its related methods are a wrapper around the external Google
  13642. * Cloud Datastore grpc API, which provides an interface that is more convenient
  13643. * for the rest of the client SDK architecture to consume.
  13644. */
  13645. /**
  13646. * An implementation of Datastore that exposes additional state for internal
  13647. * consumption.
  13648. */
  13649. class ju extends class {} {
  13650. constructor(t, e, n, s) {
  13651. super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = n,
  13652. this.serializer = s, this.lu = !1;
  13653. }
  13654. fu() {
  13655. if (this.lu) throw new G(K.FAILED_PRECONDITION, "The client has already been terminated.");
  13656. }
  13657. /** Invokes the provided RPC with auth and AppCheck tokens. */ Io(t, e, n) {
  13658. return this.fu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.connection.Io(t, e, n, s, i))).catch((t => {
  13659. throw "FirebaseError" === t.name ? (t.code === K.UNAUTHENTICATED && (this.authCredentials.invalidateToken(),
  13660. this.appCheckCredentials.invalidateToken()), t) : new G(K.UNKNOWN, t.toString());
  13661. }));
  13662. }
  13663. /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ vo(t, e, n, s) {
  13664. return this.fu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, r]) => this.connection.vo(t, e, n, i, r, s))).catch((t => {
  13665. throw "FirebaseError" === t.name ? (t.code === K.UNAUTHENTICATED && (this.authCredentials.invalidateToken(),
  13666. this.appCheckCredentials.invalidateToken()), t) : new G(K.UNKNOWN, t.toString());
  13667. }));
  13668. }
  13669. terminate() {
  13670. this.lu = !0;
  13671. }
  13672. }
  13673. // TODO(firestorexp): Make sure there is only one Datastore instance per
  13674. // firestore-exp client.
  13675. async function zu(t, e, n) {
  13676. var s;
  13677. const i = U(t), {request: r, du: o} = function(t, e, n) {
  13678. const s = Zi(t, e), i = {}, r = [];
  13679. let o = 0;
  13680. return n.forEach((t => {
  13681. // Map all client-side aliases to a unique short-form
  13682. // alias. This avoids issues with client-side aliases that
  13683. // exceed the 1500-byte string size limit.
  13684. const e = "aggregate_" + o++;
  13685. i[e] = t.alias, "count" === t.yt ? r.push({
  13686. alias: e,
  13687. count: {}
  13688. }) : "avg" === t.yt ? r.push({
  13689. alias: e,
  13690. avg: {
  13691. field: or(t.fieldPath)
  13692. }
  13693. }) : "sum" === t.yt && r.push({
  13694. alias: e,
  13695. sum: {
  13696. field: or(t.fieldPath)
  13697. }
  13698. });
  13699. })), {
  13700. request: {
  13701. structuredAggregationQuery: {
  13702. aggregations: r,
  13703. structuredQuery: s.structuredQuery
  13704. },
  13705. parent: s.parent
  13706. },
  13707. du: i
  13708. };
  13709. }(i.serializer, Zn(e), n), u = r.parent;
  13710. i.connection.po || delete r.parent;
  13711. const c = (await i.vo("RunAggregationQuery", u, r, /*expectedResponseCount=*/ 1)).filter((t => !!t.result));
  13712. // Omit RunAggregationQueryResponse that only contain readTimes.
  13713. L(1 === c.length);
  13714. // Remap the short-form aliases that were sent to the server
  13715. // to the client-side aliases. Users will access the results
  13716. // using the client-side alias.
  13717. const a = null === (s = c[0].result) || void 0 === s ? void 0 : s.aggregateFields;
  13718. return Object.keys(a).reduce(((t, e) => (t[o[e]] = a[e], t)), {});
  13719. }
  13720. /**
  13721. * A component used by the RemoteStore to track the OnlineState (that is,
  13722. * whether or not the client as a whole should be considered to be online or
  13723. * offline), implementing the appropriate heuristics.
  13724. *
  13725. * In particular, when the client is trying to connect to the backend, we
  13726. * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for
  13727. * a connection to succeed. If we have too many failures or the timeout elapses,
  13728. * then we set the OnlineState to Offline, and the client will behave as if
  13729. * it is offline (get()s will return cached data, etc.).
  13730. */
  13731. class Wu {
  13732. constructor(t, e) {
  13733. this.asyncQueue = t, this.onlineStateHandler = e,
  13734. /** The current OnlineState. */
  13735. this.state = "Unknown" /* OnlineState.Unknown */ ,
  13736. /**
  13737. * A count of consecutive failures to open the stream. If it reaches the
  13738. * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
  13739. * Offline.
  13740. */
  13741. this.wu = 0,
  13742. /**
  13743. * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
  13744. * transition from OnlineState.Unknown to OnlineState.Offline without waiting
  13745. * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
  13746. */
  13747. this._u = null,
  13748. /**
  13749. * Whether the client should log a warning message if it fails to connect to
  13750. * the backend (initially true, cleared after a successful stream, or if we've
  13751. * logged the message already).
  13752. */
  13753. this.mu = !0;
  13754. }
  13755. /**
  13756. * Called by RemoteStore when a watch stream is started (including on each
  13757. * backoff attempt).
  13758. *
  13759. * If this is the first attempt, it sets the OnlineState to Unknown and starts
  13760. * the onlineStateTimer.
  13761. */ gu() {
  13762. 0 === this.wu && (this.yu("Unknown" /* OnlineState.Unknown */), this._u = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this._u = null,
  13763. this.pu("Backend didn't respond within 10 seconds."), this.yu("Offline" /* OnlineState.Offline */),
  13764. Promise.resolve()))));
  13765. }
  13766. /**
  13767. * Updates our OnlineState as appropriate after the watch stream reports a
  13768. * failure. The first failure moves us to the 'Unknown' state. We then may
  13769. * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
  13770. * actually transition to the 'Offline' state.
  13771. */ Iu(t) {
  13772. "Online" /* OnlineState.Online */ === this.state ? this.yu("Unknown" /* OnlineState.Unknown */) : (this.wu++,
  13773. this.wu >= 1 && (this.Tu(), this.pu(`Connection failed 1 times. Most recent error: ${t.toString()}`),
  13774. this.yu("Offline" /* OnlineState.Offline */)));
  13775. }
  13776. /**
  13777. * Explicitly sets the OnlineState to the specified state.
  13778. *
  13779. * Note that this resets our timers / failure counters, etc. used by our
  13780. * Offline heuristics, so must not be used in place of
  13781. * handleWatchStreamStart() and handleWatchStreamFailure().
  13782. */ set(t) {
  13783. this.Tu(), this.wu = 0, "Online" /* OnlineState.Online */ === t && (
  13784. // We've connected to watch at least once. Don't warn the developer
  13785. // about being offline going forward.
  13786. this.mu = !1), this.yu(t);
  13787. }
  13788. yu(t) {
  13789. t !== this.state && (this.state = t, this.onlineStateHandler(t));
  13790. }
  13791. pu(t) {
  13792. const e = `Could not reach Cloud Firestore backend. ${t}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;
  13793. this.mu ? (M(e), this.mu = !1) : $("OnlineStateTracker", e);
  13794. }
  13795. Tu() {
  13796. null !== this._u && (this._u.cancel(), this._u = null);
  13797. }
  13798. }
  13799. /**
  13800. * @license
  13801. * Copyright 2017 Google LLC
  13802. *
  13803. * Licensed under the Apache License, Version 2.0 (the "License");
  13804. * you may not use this file except in compliance with the License.
  13805. * You may obtain a copy of the License at
  13806. *
  13807. * http://www.apache.org/licenses/LICENSE-2.0
  13808. *
  13809. * Unless required by applicable law or agreed to in writing, software
  13810. * distributed under the License is distributed on an "AS IS" BASIS,
  13811. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13812. * See the License for the specific language governing permissions and
  13813. * limitations under the License.
  13814. */ class Hu {
  13815. constructor(
  13816. /**
  13817. * The local store, used to fill the write pipeline with outbound mutations.
  13818. */
  13819. t,
  13820. /** The client-side proxy for interacting with the backend. */
  13821. e, n, s, i) {
  13822. this.localStore = t, this.datastore = e, this.asyncQueue = n, this.remoteSyncer = {},
  13823. /**
  13824. * A list of up to MAX_PENDING_WRITES writes that we have fetched from the
  13825. * LocalStore via fillWritePipeline() and have or will send to the write
  13826. * stream.
  13827. *
  13828. * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
  13829. * restart the write stream. When the stream is established the writes in the
  13830. * pipeline will be sent in order.
  13831. *
  13832. * Writes remain in writePipeline until they are acknowledged by the backend
  13833. * and thus will automatically be re-sent if the stream is interrupted /
  13834. * restarted before they're acknowledged.
  13835. *
  13836. * Write responses from the backend are linked to their originating request
  13837. * purely based on order, and so we can just shift() writes from the front of
  13838. * the writePipeline as we receive responses.
  13839. */
  13840. this.Eu = [],
  13841. /**
  13842. * A mapping of watched targets that the client cares about tracking and the
  13843. * user has explicitly called a 'listen' for this target.
  13844. *
  13845. * These targets may or may not have been sent to or acknowledged by the
  13846. * server. On re-establishing the listen stream, these targets should be sent
  13847. * to the server. The targets removed with unlistens are removed eagerly
  13848. * without waiting for confirmation from the listen stream.
  13849. */
  13850. this.Au = new Map,
  13851. /**
  13852. * A set of reasons for why the RemoteStore may be offline. If empty, the
  13853. * RemoteStore may start its network connections.
  13854. */
  13855. this.vu = new Set,
  13856. /**
  13857. * Event handlers that get called when the network is disabled or enabled.
  13858. *
  13859. * PORTING NOTE: These functions are used on the Web client to create the
  13860. * underlying streams (to support tree-shakeable streams). On Android and iOS,
  13861. * the streams are created during construction of RemoteStore.
  13862. */
  13863. this.Ru = [], this.Pu = i, this.Pu.Yr((t => {
  13864. n.enqueueAndForget((async () => {
  13865. // Porting Note: Unlike iOS, `restartNetwork()` is called even when the
  13866. // network becomes unreachable as we don't have any other way to tear
  13867. // down our streams.
  13868. ic(this) && ($("RemoteStore", "Restarting streams for network reachability change."),
  13869. await async function(t) {
  13870. const e = U(t);
  13871. e.vu.add(4 /* OfflineCause.ConnectivityChange */), await Yu(e), e.bu.set("Unknown" /* OnlineState.Unknown */),
  13872. e.vu.delete(4 /* OfflineCause.ConnectivityChange */), await Ju(e);
  13873. }(this));
  13874. }));
  13875. })), this.bu = new Wu(n, s);
  13876. }
  13877. }
  13878. async function Ju(t) {
  13879. if (ic(t)) for (const e of t.Ru) await e(/* enabled= */ !0);
  13880. }
  13881. /**
  13882. * Temporarily disables the network. The network can be re-enabled using
  13883. * enableNetwork().
  13884. */ async function Yu(t) {
  13885. for (const e of t.Ru) await e(/* enabled= */ !1);
  13886. }
  13887. /**
  13888. * Starts new listen for the given target. Uses resume token if provided. It
  13889. * is a no-op if the target of given `TargetData` is already being listened to.
  13890. */
  13891. function Xu(t, e) {
  13892. const n = U(t);
  13893. n.Au.has(e.targetId) || (
  13894. // Mark this as something the client is currently listening for.
  13895. n.Au.set(e.targetId, e), sc(n) ?
  13896. // The listen will be sent in onWatchStreamOpen
  13897. nc(n) : Ec(n).Ko() && tc(n, e));
  13898. }
  13899. /**
  13900. * Removes the listen from server. It is a no-op if the given target id is
  13901. * not being listened to.
  13902. */ function Zu(t, e) {
  13903. const n = U(t), s = Ec(n);
  13904. n.Au.delete(e), s.Ko() && ec(n, e), 0 === n.Au.size && (s.Ko() ? s.jo() : ic(n) &&
  13905. // Revert to OnlineState.Unknown if the watch stream is not open and we
  13906. // have no listeners, since without any listens to send we cannot
  13907. // confirm if the stream is healthy and upgrade to OnlineState.Online.
  13908. n.bu.set("Unknown" /* OnlineState.Unknown */));
  13909. }
  13910. /**
  13911. * We need to increment the the expected number of pending responses we're due
  13912. * from watch so we wait for the ack to process any messages from this target.
  13913. */ function tc(t, e) {
  13914. if (t.Vu.qt(e.targetId), e.resumeToken.approximateByteSize() > 0 || e.snapshotVersion.compareTo(ut.min()) > 0) {
  13915. const n = t.remoteSyncer.getRemoteKeysForTarget(e.targetId).size;
  13916. e = e.withExpectedCount(n);
  13917. }
  13918. Ec(t).su(e);
  13919. }
  13920. /**
  13921. * We need to increment the expected number of pending responses we're due
  13922. * from watch so we wait for the removal on the server before we process any
  13923. * messages from this target.
  13924. */ function ec(t, e) {
  13925. t.Vu.qt(e), Ec(t).iu(e);
  13926. }
  13927. function nc(t) {
  13928. t.Vu = new Ri({
  13929. getRemoteKeysForTarget: e => t.remoteSyncer.getRemoteKeysForTarget(e),
  13930. le: e => t.Au.get(e) || null,
  13931. ue: () => t.datastore.serializer.databaseId
  13932. }), Ec(t).start(), t.bu.gu();
  13933. }
  13934. /**
  13935. * Returns whether the watch stream should be started because it's necessary
  13936. * and has not yet been started.
  13937. */ function sc(t) {
  13938. return ic(t) && !Ec(t).Uo() && t.Au.size > 0;
  13939. }
  13940. function ic(t) {
  13941. return 0 === U(t).vu.size;
  13942. }
  13943. function rc(t) {
  13944. t.Vu = void 0;
  13945. }
  13946. async function oc(t) {
  13947. t.Au.forEach(((e, n) => {
  13948. tc(t, e);
  13949. }));
  13950. }
  13951. async function uc(t, e) {
  13952. rc(t),
  13953. // If we still need the watch stream, retry the connection.
  13954. sc(t) ? (t.bu.Iu(e), nc(t)) :
  13955. // No need to restart watch stream because there are no active targets.
  13956. // The online state is set to unknown because there is no active attempt
  13957. // at establishing a connection
  13958. t.bu.set("Unknown" /* OnlineState.Unknown */);
  13959. }
  13960. async function cc(t, e, n) {
  13961. if (
  13962. // Mark the client as online since we got a message from the server
  13963. t.bu.set("Online" /* OnlineState.Online */), e instanceof Ai && 2 /* WatchTargetChangeState.Removed */ === e.state && e.cause)
  13964. // There was an error on a target, don't wait for a consistent snapshot
  13965. // to raise events
  13966. try {
  13967. await
  13968. /** Handles an error on a target */
  13969. async function(t, e) {
  13970. const n = e.cause;
  13971. for (const s of e.targetIds)
  13972. // A watched target might have been removed already.
  13973. t.Au.has(s) && (await t.remoteSyncer.rejectListen(s, n), t.Au.delete(s), t.Vu.removeTarget(s));
  13974. }
  13975. /**
  13976. * Attempts to fill our write pipeline with writes from the LocalStore.
  13977. *
  13978. * Called internally to bootstrap or refill the write pipeline and by
  13979. * SyncEngine whenever there are new mutations to process.
  13980. *
  13981. * Starts the write stream if necessary.
  13982. */ (t, e);
  13983. } catch (n) {
  13984. $("RemoteStore", "Failed to remove targets %s: %s ", e.targetIds.join(","), n),
  13985. await ac(t, n);
  13986. } else if (e instanceof Ti ? t.Vu.Ht(e) : e instanceof Ei ? t.Vu.ne(e) : t.Vu.Xt(e),
  13987. !n.isEqual(ut.min())) try {
  13988. const e = await au(t.localStore);
  13989. n.compareTo(e) >= 0 &&
  13990. // We have received a target change with a global snapshot if the snapshot
  13991. // version is not equal to SnapshotVersion.min().
  13992. await
  13993. /**
  13994. * Takes a batch of changes from the Datastore, repackages them as a
  13995. * RemoteEvent, and passes that on to the listener, which is typically the
  13996. * SyncEngine.
  13997. */
  13998. function(t, e) {
  13999. const n = t.Vu.ce(e);
  14000. // Update in-memory resume tokens. LocalStore will update the
  14001. // persistent view of these when applying the completed RemoteEvent.
  14002. return n.targetChanges.forEach(((n, s) => {
  14003. if (n.resumeToken.approximateByteSize() > 0) {
  14004. const i = t.Au.get(s);
  14005. // A watched target might have been removed already.
  14006. i && t.Au.set(s, i.withResumeToken(n.resumeToken, e));
  14007. }
  14008. })),
  14009. // Re-establish listens for the targets that have been invalidated by
  14010. // existence filter mismatches.
  14011. n.targetMismatches.forEach(((e, n) => {
  14012. const s = t.Au.get(e);
  14013. if (!s)
  14014. // A watched target might have been removed already.
  14015. return;
  14016. // Clear the resume token for the target, since we're in a known mismatch
  14017. // state.
  14018. t.Au.set(e, s.withResumeToken(Ce.EMPTY_BYTE_STRING, s.snapshotVersion)),
  14019. // Cause a hard reset by unwatching and rewatching immediately, but
  14020. // deliberately don't send a resume token so that we get a full update.
  14021. ec(t, e);
  14022. // Mark the target we send as being on behalf of an existence filter
  14023. // mismatch, but don't actually retain that in listenTargets. This ensures
  14024. // that we flag the first re-listen this way without impacting future
  14025. // listens of this target (that might happen e.g. on reconnect).
  14026. const i = new lr(s.target, e, n, s.sequenceNumber);
  14027. tc(t, i);
  14028. })), t.remoteSyncer.applyRemoteEvent(n);
  14029. }(t, n);
  14030. } catch (e) {
  14031. $("RemoteStore", "Failed to raise snapshot:", e), await ac(t, e);
  14032. }
  14033. }
  14034. /**
  14035. * Recovery logic for IndexedDB errors that takes the network offline until
  14036. * `op` succeeds. Retries are scheduled with backoff using
  14037. * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is
  14038. * validated via a generic operation.
  14039. *
  14040. * The returned Promise is resolved once the network is disabled and before
  14041. * any retry attempt.
  14042. */ async function ac(t, e, n) {
  14043. if (!xt(e)) throw e;
  14044. t.vu.add(1 /* OfflineCause.IndexedDbFailed */),
  14045. // Disable network and raise offline snapshots
  14046. await Yu(t), t.bu.set("Offline" /* OnlineState.Offline */), n || (
  14047. // Use a simple read operation to determine if IndexedDB recovered.
  14048. // Ideally, we would expose a health check directly on SimpleDb, but
  14049. // RemoteStore only has access to persistence through LocalStore.
  14050. n = () => au(t.localStore)),
  14051. // Probe IndexedDB periodically and re-enable network
  14052. t.asyncQueue.enqueueRetryable((async () => {
  14053. $("RemoteStore", "Retrying IndexedDB access"), await n(), t.vu.delete(1 /* OfflineCause.IndexedDbFailed */),
  14054. await Ju(t);
  14055. }));
  14056. }
  14057. /**
  14058. * Executes `op`. If `op` fails, takes the network offline until `op`
  14059. * succeeds. Returns after the first attempt.
  14060. */ function hc(t, e) {
  14061. return e().catch((n => ac(t, n, e)));
  14062. }
  14063. async function lc(t) {
  14064. const e = U(t), n = Ac(e);
  14065. let s = e.Eu.length > 0 ? e.Eu[e.Eu.length - 1].batchId : -1;
  14066. for (;fc(e); ) try {
  14067. const t = await fu(e.localStore, s);
  14068. if (null === t) {
  14069. 0 === e.Eu.length && n.jo();
  14070. break;
  14071. }
  14072. s = t.batchId, dc(e, t);
  14073. } catch (t) {
  14074. await ac(e, t);
  14075. }
  14076. wc(e) && _c(e);
  14077. }
  14078. /**
  14079. * Returns true if we can add to the write pipeline (i.e. the network is
  14080. * enabled and the write pipeline is not full).
  14081. */ function fc(t) {
  14082. return ic(t) && t.Eu.length < 10;
  14083. }
  14084. /**
  14085. * Queues additional writes to be sent to the write stream, sending them
  14086. * immediately if the write stream is established.
  14087. */ function dc(t, e) {
  14088. t.Eu.push(e);
  14089. const n = Ac(t);
  14090. n.Ko() && n.ou && n.uu(e.mutations);
  14091. }
  14092. function wc(t) {
  14093. return ic(t) && !Ac(t).Uo() && t.Eu.length > 0;
  14094. }
  14095. function _c(t) {
  14096. Ac(t).start();
  14097. }
  14098. async function mc(t) {
  14099. Ac(t).hu();
  14100. }
  14101. async function gc(t) {
  14102. const e = Ac(t);
  14103. // Send the write pipeline now that the stream is established.
  14104. for (const n of t.Eu) e.uu(n.mutations);
  14105. }
  14106. async function yc(t, e, n) {
  14107. const s = t.Eu.shift(), i = si.from(s, e, n);
  14108. await hc(t, (() => t.remoteSyncer.applySuccessfulWrite(i))),
  14109. // It's possible that with the completion of this mutation another
  14110. // slot has freed up.
  14111. await lc(t);
  14112. }
  14113. async function pc(t, e) {
  14114. // If the write stream closed after the write handshake completes, a write
  14115. // operation failed and we fail the pending operation.
  14116. e && Ac(t).ou &&
  14117. // This error affects the actual write.
  14118. await async function(t, e) {
  14119. // Only handle permanent errors here. If it's transient, just let the retry
  14120. // logic kick in.
  14121. if (n = e.code, ai(n) && n !== K.ABORTED) {
  14122. // This was a permanent error, the request itself was the problem
  14123. // so it's not going to succeed if we resend it.
  14124. const n = t.Eu.shift();
  14125. // In this case it's also unlikely that the server itself is melting
  14126. // down -- this was just a bad request so inhibit backoff on the next
  14127. // restart.
  14128. Ac(t).Qo(), await hc(t, (() => t.remoteSyncer.rejectFailedWrite(n.batchId, e))),
  14129. // It's possible that with the completion of this mutation
  14130. // another slot has freed up.
  14131. await lc(t);
  14132. }
  14133. var n;
  14134. }(t, e),
  14135. // The write stream might have been started by refilling the write
  14136. // pipeline for failed writes
  14137. wc(t) && _c(t);
  14138. }
  14139. async function Ic(t, e) {
  14140. const n = U(t);
  14141. n.asyncQueue.verifyOperationInProgress(), $("RemoteStore", "RemoteStore received new credentials");
  14142. const s = ic(n);
  14143. // Tear down and re-create our network streams. This will ensure we get a
  14144. // fresh auth token for the new user and re-fill the write pipeline with
  14145. // new mutations from the LocalStore (since mutations are per-user).
  14146. n.vu.add(3 /* OfflineCause.CredentialChange */), await Yu(n), s &&
  14147. // Don't set the network status to Unknown if we are offline.
  14148. n.bu.set("Unknown" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(e),
  14149. n.vu.delete(3 /* OfflineCause.CredentialChange */), await Ju(n);
  14150. }
  14151. /**
  14152. * Toggles the network state when the client gains or loses its primary lease.
  14153. */ async function Tc(t, e) {
  14154. const n = U(t);
  14155. e ? (n.vu.delete(2 /* OfflineCause.IsSecondary */), await Ju(n)) : e || (n.vu.add(2 /* OfflineCause.IsSecondary */),
  14156. await Yu(n), n.bu.set("Unknown" /* OnlineState.Unknown */));
  14157. }
  14158. /**
  14159. * If not yet initialized, registers the WatchStream and its network state
  14160. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  14161. * already available.
  14162. *
  14163. * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.
  14164. * This is not done on Web to allow it to be tree-shaken.
  14165. */ function Ec(t) {
  14166. return t.Su || (
  14167. // Create stream (but note that it is not started yet).
  14168. t.Su = function(t, e, n) {
  14169. const s = U(t);
  14170. return s.fu(), new Gu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.serializer, n);
  14171. }
  14172. /**
  14173. * @license
  14174. * Copyright 2018 Google LLC
  14175. *
  14176. * Licensed under the Apache License, Version 2.0 (the "License");
  14177. * you may not use this file except in compliance with the License.
  14178. * You may obtain a copy of the License at
  14179. *
  14180. * http://www.apache.org/licenses/LICENSE-2.0
  14181. *
  14182. * Unless required by applicable law or agreed to in writing, software
  14183. * distributed under the License is distributed on an "AS IS" BASIS,
  14184. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14185. * See the License for the specific language governing permissions and
  14186. * limitations under the License.
  14187. */ (t.datastore, t.asyncQueue, {
  14188. uo: oc.bind(null, t),
  14189. ao: uc.bind(null, t),
  14190. nu: cc.bind(null, t)
  14191. }), t.Ru.push((async e => {
  14192. e ? (t.Su.Qo(), sc(t) ? nc(t) : t.bu.set("Unknown" /* OnlineState.Unknown */)) : (await t.Su.stop(),
  14193. rc(t));
  14194. }))), t.Su;
  14195. }
  14196. /**
  14197. * If not yet initialized, registers the WriteStream and its network state
  14198. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  14199. * already available.
  14200. *
  14201. * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.
  14202. * This is not done on Web to allow it to be tree-shaken.
  14203. */ function Ac(t) {
  14204. return t.Du || (
  14205. // Create stream (but note that it is not started yet).
  14206. t.Du = function(t, e, n) {
  14207. const s = U(t);
  14208. return s.fu(), new Qu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.serializer, n);
  14209. }(t.datastore, t.asyncQueue, {
  14210. uo: mc.bind(null, t),
  14211. ao: pc.bind(null, t),
  14212. au: gc.bind(null, t),
  14213. cu: yc.bind(null, t)
  14214. }), t.Ru.push((async e => {
  14215. e ? (t.Du.Qo(),
  14216. // This will start the write stream if necessary.
  14217. await lc(t)) : (await t.Du.stop(), t.Eu.length > 0 && ($("RemoteStore", `Stopping write stream with ${t.Eu.length} pending writes`),
  14218. t.Eu = []));
  14219. }))), t.Du;
  14220. }
  14221. /**
  14222. * @license
  14223. * Copyright 2017 Google LLC
  14224. *
  14225. * Licensed under the Apache License, Version 2.0 (the "License");
  14226. * you may not use this file except in compliance with the License.
  14227. * You may obtain a copy of the License at
  14228. *
  14229. * http://www.apache.org/licenses/LICENSE-2.0
  14230. *
  14231. * Unless required by applicable law or agreed to in writing, software
  14232. * distributed under the License is distributed on an "AS IS" BASIS,
  14233. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14234. * See the License for the specific language governing permissions and
  14235. * limitations under the License.
  14236. */
  14237. /**
  14238. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  14239. *
  14240. * It is created via DelayedOperation.createAndSchedule().
  14241. *
  14242. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  14243. *
  14244. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  14245. * in newer versions of TypeScript defines `finally`, which is not available in
  14246. * IE.
  14247. */
  14248. class vc {
  14249. constructor(t, e, n, s, i) {
  14250. this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = s, this.removalCallback = i,
  14251. this.deferred = new Q, this.then = this.deferred.promise.then.bind(this.deferred.promise),
  14252. // It's normal for the deferred promise to be canceled (due to cancellation)
  14253. // and so we attach a dummy catch callback to avoid
  14254. // 'UnhandledPromiseRejectionWarning' log spam.
  14255. this.deferred.promise.catch((t => {}));
  14256. }
  14257. /**
  14258. * Creates and returns a DelayedOperation that has been scheduled to be
  14259. * executed on the provided asyncQueue after the provided delayMs.
  14260. *
  14261. * @param asyncQueue - The queue to schedule the operation on.
  14262. * @param id - A Timer ID identifying the type of operation this is.
  14263. * @param delayMs - The delay (ms) before the operation should be scheduled.
  14264. * @param op - The operation to run.
  14265. * @param removalCallback - A callback to be called synchronously once the
  14266. * operation is executed or canceled, notifying the AsyncQueue to remove it
  14267. * from its delayedOperations list.
  14268. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  14269. * the DelayedOperation class public.
  14270. */ static createAndSchedule(t, e, n, s, i) {
  14271. const r = Date.now() + n, o = new vc(t, e, r, s, i);
  14272. return o.start(n), o;
  14273. }
  14274. /**
  14275. * Starts the timer. This is called immediately after construction by
  14276. * createAndSchedule().
  14277. */ start(t) {
  14278. this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t);
  14279. }
  14280. /**
  14281. * Queues the operation to run immediately (if it hasn't already been run or
  14282. * canceled).
  14283. */ skipDelay() {
  14284. return this.handleDelayElapsed();
  14285. }
  14286. /**
  14287. * Cancels the operation if it hasn't already been executed or canceled. The
  14288. * promise will be rejected.
  14289. *
  14290. * As long as the operation has not yet been run, calling cancel() provides a
  14291. * guarantee that the operation will not be run.
  14292. */ cancel(t) {
  14293. null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new G(K.CANCELLED, "Operation cancelled" + (t ? ": " + t : ""))));
  14294. }
  14295. handleDelayElapsed() {
  14296. this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(),
  14297. this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve()));
  14298. }
  14299. clearTimeout() {
  14300. null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle),
  14301. this.timerHandle = null);
  14302. }
  14303. }
  14304. /**
  14305. * Returns a FirestoreError that can be surfaced to the user if the provided
  14306. * error is an IndexedDbTransactionError. Re-throws the error otherwise.
  14307. */ function Rc(t, e) {
  14308. if (M("AsyncQueue", `${e}: ${t}`), xt(t)) return new G(K.UNAVAILABLE, `${e}: ${t}`);
  14309. throw t;
  14310. }
  14311. /**
  14312. * @license
  14313. * Copyright 2017 Google LLC
  14314. *
  14315. * Licensed under the Apache License, Version 2.0 (the "License");
  14316. * you may not use this file except in compliance with the License.
  14317. * You may obtain a copy of the License at
  14318. *
  14319. * http://www.apache.org/licenses/LICENSE-2.0
  14320. *
  14321. * Unless required by applicable law or agreed to in writing, software
  14322. * distributed under the License is distributed on an "AS IS" BASIS,
  14323. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14324. * See the License for the specific language governing permissions and
  14325. * limitations under the License.
  14326. */
  14327. /**
  14328. * DocumentSet is an immutable (copy-on-write) collection that holds documents
  14329. * in order specified by the provided comparator. We always add a document key
  14330. * comparator on top of what is provided to guarantee document equality based on
  14331. * the key.
  14332. */ class Pc {
  14333. /** The default ordering is by key if the comparator is omitted */
  14334. constructor(t) {
  14335. // We are adding document key comparator to the end as it's the only
  14336. // guaranteed unique property of a document.
  14337. this.comparator = t ? (e, n) => t(e, n) || ft.comparator(e.key, n.key) : (t, e) => ft.comparator(t.key, e.key),
  14338. this.keyedMap = ds(), this.sortedSet = new Te(this.comparator);
  14339. }
  14340. /**
  14341. * Returns an empty copy of the existing DocumentSet, using the same
  14342. * comparator.
  14343. */ static emptySet(t) {
  14344. return new Pc(t.comparator);
  14345. }
  14346. has(t) {
  14347. return null != this.keyedMap.get(t);
  14348. }
  14349. get(t) {
  14350. return this.keyedMap.get(t);
  14351. }
  14352. first() {
  14353. return this.sortedSet.minKey();
  14354. }
  14355. last() {
  14356. return this.sortedSet.maxKey();
  14357. }
  14358. isEmpty() {
  14359. return this.sortedSet.isEmpty();
  14360. }
  14361. /**
  14362. * Returns the index of the provided key in the document set, or -1 if the
  14363. * document key is not present in the set;
  14364. */ indexOf(t) {
  14365. const e = this.keyedMap.get(t);
  14366. return e ? this.sortedSet.indexOf(e) : -1;
  14367. }
  14368. get size() {
  14369. return this.sortedSet.size;
  14370. }
  14371. /** Iterates documents in order defined by "comparator" */ forEach(t) {
  14372. this.sortedSet.inorderTraversal(((e, n) => (t(e), !1)));
  14373. }
  14374. /** Inserts or updates a document with the same key */ add(t) {
  14375. // First remove the element if we have it.
  14376. const e = this.delete(t.key);
  14377. return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));
  14378. }
  14379. /** Deletes a document with a given key */ delete(t) {
  14380. const e = this.get(t);
  14381. return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;
  14382. }
  14383. isEqual(t) {
  14384. if (!(t instanceof Pc)) return !1;
  14385. if (this.size !== t.size) return !1;
  14386. const e = this.sortedSet.getIterator(), n = t.sortedSet.getIterator();
  14387. for (;e.hasNext(); ) {
  14388. const t = e.getNext().key, s = n.getNext().key;
  14389. if (!t.isEqual(s)) return !1;
  14390. }
  14391. return !0;
  14392. }
  14393. toString() {
  14394. const t = [];
  14395. return this.forEach((e => {
  14396. t.push(e.toString());
  14397. })), 0 === t.length ? "DocumentSet ()" : "DocumentSet (\n " + t.join(" \n") + "\n)";
  14398. }
  14399. copy(t, e) {
  14400. const n = new Pc;
  14401. return n.comparator = this.comparator, n.keyedMap = t, n.sortedSet = e, n;
  14402. }
  14403. }
  14404. /**
  14405. * @license
  14406. * Copyright 2017 Google LLC
  14407. *
  14408. * Licensed under the Apache License, Version 2.0 (the "License");
  14409. * you may not use this file except in compliance with the License.
  14410. * You may obtain a copy of the License at
  14411. *
  14412. * http://www.apache.org/licenses/LICENSE-2.0
  14413. *
  14414. * Unless required by applicable law or agreed to in writing, software
  14415. * distributed under the License is distributed on an "AS IS" BASIS,
  14416. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14417. * See the License for the specific language governing permissions and
  14418. * limitations under the License.
  14419. */
  14420. /**
  14421. * DocumentChangeSet keeps track of a set of changes to docs in a query, merging
  14422. * duplicate events for the same doc.
  14423. */ class bc {
  14424. constructor() {
  14425. this.Cu = new Te(ft.comparator);
  14426. }
  14427. track(t) {
  14428. const e = t.doc.key, n = this.Cu.get(e);
  14429. n ?
  14430. // Merge the new change with the existing change.
  14431. 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, {
  14432. type: n.type,
  14433. doc: t.doc
  14434. }) : 2 /* ChangeType.Modified */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Cu = this.Cu.insert(e, {
  14435. type: 2 /* ChangeType.Modified */ ,
  14436. doc: t.doc
  14437. }) : 2 /* ChangeType.Modified */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Cu = this.Cu.insert(e, {
  14438. type: 0 /* ChangeType.Added */ ,
  14439. doc: t.doc
  14440. }) : 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, {
  14441. type: 1 /* ChangeType.Removed */ ,
  14442. doc: n.doc
  14443. }) : 0 /* ChangeType.Added */ === t.type && 1 /* ChangeType.Removed */ === n.type ? this.Cu = this.Cu.insert(e, {
  14444. type: 2 /* ChangeType.Modified */ ,
  14445. doc: t.doc
  14446. }) :
  14447. // This includes these cases, which don't make sense:
  14448. // Added->Added
  14449. // Removed->Removed
  14450. // Modified->Added
  14451. // Removed->Modified
  14452. // Metadata->Added
  14453. // Removed->Metadata
  14454. B() : this.Cu = this.Cu.insert(e, t);
  14455. }
  14456. xu() {
  14457. const t = [];
  14458. return this.Cu.inorderTraversal(((e, n) => {
  14459. t.push(n);
  14460. })), t;
  14461. }
  14462. }
  14463. class Vc {
  14464. constructor(t, e, n, s, i, r, o, u, c) {
  14465. this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = s, this.mutatedKeys = i,
  14466. this.fromCache = r, this.syncStateChanged = o, this.excludesMetadataChanges = u,
  14467. this.hasCachedResults = c;
  14468. }
  14469. /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(t, e, n, s, i) {
  14470. const r = [];
  14471. return e.forEach((t => {
  14472. r.push({
  14473. type: 0 /* ChangeType.Added */ ,
  14474. doc: t
  14475. });
  14476. })), new Vc(t, e, Pc.emptySet(e), r, n, s,
  14477. /* syncStateChanged= */ !0,
  14478. /* excludesMetadataChanges= */ !1, i);
  14479. }
  14480. get hasPendingWrites() {
  14481. return !this.mutatedKeys.isEmpty();
  14482. }
  14483. isEqual(t) {
  14484. if (!(this.fromCache === t.fromCache && this.hasCachedResults === t.hasCachedResults && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && ns(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;
  14485. const e = this.docChanges, n = t.docChanges;
  14486. if (e.length !== n.length) return !1;
  14487. for (let t = 0; t < e.length; t++) if (e[t].type !== n[t].type || !e[t].doc.isEqual(n[t].doc)) return !1;
  14488. return !0;
  14489. }
  14490. }
  14491. /**
  14492. * @license
  14493. * Copyright 2017 Google LLC
  14494. *
  14495. * Licensed under the Apache License, Version 2.0 (the "License");
  14496. * you may not use this file except in compliance with the License.
  14497. * You may obtain a copy of the License at
  14498. *
  14499. * http://www.apache.org/licenses/LICENSE-2.0
  14500. *
  14501. * Unless required by applicable law or agreed to in writing, software
  14502. * distributed under the License is distributed on an "AS IS" BASIS,
  14503. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14504. * See the License for the specific language governing permissions and
  14505. * limitations under the License.
  14506. */
  14507. /**
  14508. * Holds the listeners and the last received ViewSnapshot for a query being
  14509. * tracked by EventManager.
  14510. */ class Sc {
  14511. constructor() {
  14512. this.Nu = void 0, this.listeners = [];
  14513. }
  14514. }
  14515. class Dc {
  14516. constructor() {
  14517. this.queries = new as((t => ss(t)), ns), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14518. this.ku = new Set;
  14519. }
  14520. }
  14521. async function Cc(t, e) {
  14522. const n = U(t), s = e.query;
  14523. let i = !1, r = n.queries.get(s);
  14524. if (r || (i = !0, r = new Sc), i) try {
  14525. r.Nu = await n.onListen(s);
  14526. } catch (t) {
  14527. const n = Rc(t, `Initialization of query '${is(e.query)}' failed`);
  14528. return void e.onError(n);
  14529. }
  14530. if (n.queries.set(s, r), r.listeners.push(e),
  14531. // Run global snapshot listeners if a consistent snapshot has been emitted.
  14532. e.$u(n.onlineState), r.Nu) {
  14533. e.Mu(r.Nu) && $c(n);
  14534. }
  14535. }
  14536. async function xc(t, e) {
  14537. const n = U(t), s = e.query;
  14538. let i = !1;
  14539. const r = n.queries.get(s);
  14540. if (r) {
  14541. const t = r.listeners.indexOf(e);
  14542. t >= 0 && (r.listeners.splice(t, 1), i = 0 === r.listeners.length);
  14543. }
  14544. if (i) return n.queries.delete(s), n.onUnlisten(s);
  14545. }
  14546. function Nc(t, e) {
  14547. const n = U(t);
  14548. let s = !1;
  14549. for (const t of e) {
  14550. const e = t.query, i = n.queries.get(e);
  14551. if (i) {
  14552. for (const e of i.listeners) e.Mu(t) && (s = !0);
  14553. i.Nu = t;
  14554. }
  14555. }
  14556. s && $c(n);
  14557. }
  14558. function kc(t, e, n) {
  14559. const s = U(t), i = s.queries.get(e);
  14560. if (i) for (const t of i.listeners) t.onError(n);
  14561. // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
  14562. // after an error.
  14563. s.queries.delete(e);
  14564. }
  14565. // Call all global snapshot listeners that have been set.
  14566. function $c(t) {
  14567. t.ku.forEach((t => {
  14568. t.next();
  14569. }));
  14570. }
  14571. /**
  14572. * QueryListener takes a series of internal view snapshots and determines
  14573. * when to raise the event.
  14574. *
  14575. * It uses an Observer to dispatch events.
  14576. */ class Mc {
  14577. constructor(t, e, n) {
  14578. this.query = t, this.Ou = e,
  14579. /**
  14580. * Initial snapshots (e.g. from cache) may not be propagated to the wrapped
  14581. * observer. This flag is set to true once we've actually raised an event.
  14582. */
  14583. this.Fu = !1, this.Bu = null, this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14584. this.options = n || {};
  14585. }
  14586. /**
  14587. * Applies the new ViewSnapshot to this listener, raising a user-facing event
  14588. * if applicable (depending on what changed, whether the user has opted into
  14589. * metadata-only changes, etc.). Returns true if a user-facing event was
  14590. * indeed raised.
  14591. */ Mu(t) {
  14592. if (!this.options.includeMetadataChanges) {
  14593. // Remove the metadata only changes.
  14594. const e = [];
  14595. for (const n of t.docChanges) 3 /* ChangeType.Metadata */ !== n.type && e.push(n);
  14596. t = new Vc(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged,
  14597. /* excludesMetadataChanges= */ !0, t.hasCachedResults);
  14598. }
  14599. let e = !1;
  14600. return this.Fu ? this.Lu(t) && (this.Ou.next(t), e = !0) : this.qu(t, this.onlineState) && (this.Uu(t),
  14601. e = !0), this.Bu = t, e;
  14602. }
  14603. onError(t) {
  14604. this.Ou.error(t);
  14605. }
  14606. /** Returns whether a snapshot was raised. */ $u(t) {
  14607. this.onlineState = t;
  14608. let e = !1;
  14609. return this.Bu && !this.Fu && this.qu(this.Bu, t) && (this.Uu(this.Bu), e = !0),
  14610. e;
  14611. }
  14612. qu(t, e) {
  14613. // Always raise the first event when we're synced
  14614. if (!t.fromCache) return !0;
  14615. // NOTE: We consider OnlineState.Unknown as online (it should become Offline
  14616. // or Online if we wait long enough).
  14617. const n = "Offline" /* OnlineState.Offline */ !== e;
  14618. // Don't raise the event if we're online, aren't synced yet (checked
  14619. // above) and are waiting for a sync.
  14620. return (!this.options.Ku || !n) && (!t.docs.isEmpty() || t.hasCachedResults || "Offline" /* OnlineState.Offline */ === e);
  14621. // Raise data from cache if we have any documents, have cached results before,
  14622. // or we are offline.
  14623. }
  14624. Lu(t) {
  14625. // We don't need to handle includeDocumentMetadataChanges here because
  14626. // the Metadata only changes have already been stripped out if needed.
  14627. // At this point the only changes we will see are the ones we should
  14628. // propagate.
  14629. if (t.docChanges.length > 0) return !0;
  14630. const e = this.Bu && this.Bu.hasPendingWrites !== t.hasPendingWrites;
  14631. return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;
  14632. // Generally we should have hit one of the cases above, but it's possible
  14633. // to get here if there were only metadata docChanges and they got
  14634. // stripped out.
  14635. }
  14636. Uu(t) {
  14637. t = Vc.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache, t.hasCachedResults),
  14638. this.Fu = !0, this.Ou.next(t);
  14639. }
  14640. }
  14641. /**
  14642. * @license
  14643. * Copyright 2020 Google LLC
  14644. *
  14645. * Licensed under the Apache License, Version 2.0 (the "License");
  14646. * you may not use this file except in compliance with the License.
  14647. * You may obtain a copy of the License at
  14648. *
  14649. * http://www.apache.org/licenses/LICENSE-2.0
  14650. *
  14651. * Unless required by applicable law or agreed to in writing, software
  14652. * distributed under the License is distributed on an "AS IS" BASIS,
  14653. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14654. * See the License for the specific language governing permissions and
  14655. * limitations under the License.
  14656. */
  14657. /**
  14658. * A complete element in the bundle stream, together with the byte length it
  14659. * occupies in the stream.
  14660. */ class Oc {
  14661. constructor(t,
  14662. // How many bytes this element takes to store in the bundle.
  14663. e) {
  14664. this.Gu = t, this.byteLength = e;
  14665. }
  14666. Qu() {
  14667. return "metadata" in this.Gu;
  14668. }
  14669. }
  14670. /**
  14671. * @license
  14672. * Copyright 2020 Google LLC
  14673. *
  14674. * Licensed under the Apache License, Version 2.0 (the "License");
  14675. * you may not use this file except in compliance with the License.
  14676. * You may obtain a copy of the License at
  14677. *
  14678. * http://www.apache.org/licenses/LICENSE-2.0
  14679. *
  14680. * Unless required by applicable law or agreed to in writing, software
  14681. * distributed under the License is distributed on an "AS IS" BASIS,
  14682. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14683. * See the License for the specific language governing permissions and
  14684. * limitations under the License.
  14685. */
  14686. /**
  14687. * Helper to convert objects from bundles to model objects in the SDK.
  14688. */ class Fc {
  14689. constructor(t) {
  14690. this.serializer = t;
  14691. }
  14692. rr(t) {
  14693. return Li(this.serializer, t);
  14694. }
  14695. /**
  14696. * Converts a BundleDocument to a MutableDocument.
  14697. */ ur(t) {
  14698. return t.metadata.exists ? ji(this.serializer, t.document, !1) : fn.newNoDocument(this.rr(t.metadata.name), this.cr(t.metadata.readTime));
  14699. }
  14700. cr(t) {
  14701. return Mi(t);
  14702. }
  14703. }
  14704. /**
  14705. * A class to process the elements from a bundle, load them into local
  14706. * storage and provide progress update while loading.
  14707. */ class Bc {
  14708. constructor(t, e, n) {
  14709. this.ju = t, this.localStore = e, this.serializer = n,
  14710. /** Batched queries to be saved into storage */
  14711. this.queries = [],
  14712. /** Batched documents to be saved into storage */
  14713. this.documents = [],
  14714. /** The collection groups affected by this bundle. */
  14715. this.collectionGroups = new Set, this.progress = Lc(t);
  14716. }
  14717. /**
  14718. * Adds an element from the bundle to the loader.
  14719. *
  14720. * Returns a new progress if adding the element leads to a new progress,
  14721. * otherwise returns null.
  14722. */ zu(t) {
  14723. this.progress.bytesLoaded += t.byteLength;
  14724. let e = this.progress.documentsLoaded;
  14725. if (t.Gu.namedQuery) this.queries.push(t.Gu.namedQuery); else if (t.Gu.documentMetadata) {
  14726. this.documents.push({
  14727. metadata: t.Gu.documentMetadata
  14728. }), t.Gu.documentMetadata.exists || ++e;
  14729. const n = at.fromString(t.Gu.documentMetadata.name);
  14730. this.collectionGroups.add(n.get(n.length - 2));
  14731. } else t.Gu.document && (this.documents[this.documents.length - 1].document = t.Gu.document,
  14732. ++e);
  14733. return e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e,
  14734. Object.assign({}, this.progress)) : null;
  14735. }
  14736. Wu(t) {
  14737. const e = new Map, n = new Fc(this.serializer);
  14738. for (const s of t) if (s.metadata.queries) {
  14739. const t = n.rr(s.metadata.name);
  14740. for (const n of s.metadata.queries) {
  14741. const s = (e.get(n) || Is()).add(t);
  14742. e.set(n, s);
  14743. }
  14744. }
  14745. return e;
  14746. }
  14747. /**
  14748. * Update the progress to 'Success' and return the updated progress.
  14749. */ async complete() {
  14750. const t = await pu(this.localStore, new Fc(this.serializer), this.documents, this.ju.id), e = this.Wu(this.documents);
  14751. for (const t of this.queries) await Iu(this.localStore, t, e.get(t.name));
  14752. return this.progress.taskState = "Success", {
  14753. progress: this.progress,
  14754. Hu: this.collectionGroups,
  14755. Ju: t
  14756. };
  14757. }
  14758. }
  14759. /**
  14760. * Returns a `LoadBundleTaskProgress` representing the initial progress of
  14761. * loading a bundle.
  14762. */ function Lc(t) {
  14763. return {
  14764. taskState: "Running",
  14765. documentsLoaded: 0,
  14766. bytesLoaded: 0,
  14767. totalDocuments: t.totalDocuments,
  14768. totalBytes: t.totalBytes
  14769. };
  14770. }
  14771. /**
  14772. * Returns a `LoadBundleTaskProgress` representing the progress that the loading
  14773. * has succeeded.
  14774. */
  14775. /**
  14776. * @license
  14777. * Copyright 2017 Google LLC
  14778. *
  14779. * Licensed under the Apache License, Version 2.0 (the "License");
  14780. * you may not use this file except in compliance with the License.
  14781. * You may obtain a copy of the License at
  14782. *
  14783. * http://www.apache.org/licenses/LICENSE-2.0
  14784. *
  14785. * Unless required by applicable law or agreed to in writing, software
  14786. * distributed under the License is distributed on an "AS IS" BASIS,
  14787. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14788. * See the License for the specific language governing permissions and
  14789. * limitations under the License.
  14790. */
  14791. class qc {
  14792. constructor(t) {
  14793. this.key = t;
  14794. }
  14795. }
  14796. class Uc {
  14797. constructor(t) {
  14798. this.key = t;
  14799. }
  14800. }
  14801. /**
  14802. * View is responsible for computing the final merged truth of what docs are in
  14803. * a query. It gets notified of local and remote changes to docs, and applies
  14804. * the query filters and limits to determine the most correct possible results.
  14805. */ class Kc {
  14806. constructor(t,
  14807. /** Documents included in the remote target */
  14808. e) {
  14809. this.query = t, this.Yu = e, this.Xu = null, this.hasCachedResults = !1,
  14810. /**
  14811. * A flag whether the view is current with the backend. A view is considered
  14812. * current after it has seen the current flag from the backend and did not
  14813. * lose consistency within the watch stream (e.g. because of an existence
  14814. * filter mismatch).
  14815. */
  14816. this.current = !1,
  14817. /** Documents in the view but not in the remote target */
  14818. this.Zu = Is(),
  14819. /** Document Keys that have local changes */
  14820. this.mutatedKeys = Is(), this.tc = us(t), this.ec = new Pc(this.tc);
  14821. }
  14822. /**
  14823. * The set of remote documents that the server has told us belongs to the target associated with
  14824. * this view.
  14825. */ get nc() {
  14826. return this.Yu;
  14827. }
  14828. /**
  14829. * Iterates over a set of doc changes, applies the query limit, and computes
  14830. * what the new results should be, what the changes were, and whether we may
  14831. * need to go back to the local cache for more results. Does not make any
  14832. * changes to the view.
  14833. * @param docChanges - The doc changes to apply to this view.
  14834. * @param previousChanges - If this is being called with a refill, then start
  14835. * with this set of docs and changes instead of the current view.
  14836. * @returns a new set of docs, changes, and refill flag.
  14837. */ sc(t, e) {
  14838. const n = e ? e.ic : new bc, s = e ? e.ec : this.ec;
  14839. let i = e ? e.mutatedKeys : this.mutatedKeys, r = s, o = !1;
  14840. // Track the last doc in a (full) limit. This is necessary, because some
  14841. // update (a delete, or an update moving a doc past the old limit) might
  14842. // mean there is some other document in the local cache that either should
  14843. // come (1) between the old last limit doc and the new last document, in the
  14844. // case of updates, or (2) after the new last document, in the case of
  14845. // deletes. So we keep this doc at the old limit to compare the updates to.
  14846. // Note that this should never get used in a refill (when previousChanges is
  14847. // set), because there will only be adds -- no deletes or updates.
  14848. const u = "F" /* LimitType.First */ === this.query.limitType && s.size === this.query.limit ? s.last() : null, c = "L" /* LimitType.Last */ === this.query.limitType && s.size === this.query.limit ? s.first() : null;
  14849. // Drop documents out to meet limit/limitToLast requirement.
  14850. if (t.inorderTraversal(((t, e) => {
  14851. const a = s.get(t), h = rs(this.query, e) ? e : null, l = !!a && this.mutatedKeys.has(a.key), f = !!h && (h.hasLocalMutations ||
  14852. // We only consider committed mutations for documents that were
  14853. // mutated during the lifetime of the view.
  14854. this.mutatedKeys.has(h.key) && h.hasCommittedMutations);
  14855. let d = !1;
  14856. // Calculate change
  14857. if (a && h) {
  14858. a.data.isEqual(h.data) ? l !== f && (n.track({
  14859. type: 3 /* ChangeType.Metadata */ ,
  14860. doc: h
  14861. }), d = !0) : this.rc(a, h) || (n.track({
  14862. type: 2 /* ChangeType.Modified */ ,
  14863. doc: h
  14864. }), d = !0, (u && this.tc(h, u) > 0 || c && this.tc(h, c) < 0) && (
  14865. // This doc moved from inside the limit to outside the limit.
  14866. // That means there may be some other doc in the local cache
  14867. // that should be included instead.
  14868. o = !0));
  14869. } else !a && h ? (n.track({
  14870. type: 0 /* ChangeType.Added */ ,
  14871. doc: h
  14872. }), d = !0) : a && !h && (n.track({
  14873. type: 1 /* ChangeType.Removed */ ,
  14874. doc: a
  14875. }), d = !0, (u || c) && (
  14876. // A doc was removed from a full limit query. We'll need to
  14877. // requery from the local cache to see if we know about some other
  14878. // doc that should be in the results.
  14879. o = !0));
  14880. d && (h ? (r = r.add(h), i = f ? i.add(t) : i.delete(t)) : (r = r.delete(t), i = i.delete(t)));
  14881. })), null !== this.query.limit) for (;r.size > this.query.limit; ) {
  14882. const t = "F" /* LimitType.First */ === this.query.limitType ? r.last() : r.first();
  14883. r = r.delete(t.key), i = i.delete(t.key), n.track({
  14884. type: 1 /* ChangeType.Removed */ ,
  14885. doc: t
  14886. });
  14887. }
  14888. return {
  14889. ec: r,
  14890. ic: n,
  14891. zi: o,
  14892. mutatedKeys: i
  14893. };
  14894. }
  14895. rc(t, e) {
  14896. // We suppress the initial change event for documents that were modified as
  14897. // part of a write acknowledgment (e.g. when the value of a server transform
  14898. // is applied) as Watch will send us the same document again.
  14899. // By suppressing the event, we only raise two user visible events (one with
  14900. // `hasPendingWrites` and the final state of the document) instead of three
  14901. // (one with `hasPendingWrites`, the modified document with
  14902. // `hasPendingWrites` and the final state of the document).
  14903. return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;
  14904. }
  14905. /**
  14906. * Updates the view with the given ViewDocumentChanges and optionally updates
  14907. * limbo docs and sync state from the provided target change.
  14908. * @param docChanges - The set of changes to make to the view's docs.
  14909. * @param updateLimboDocuments - Whether to update limbo documents based on
  14910. * this change.
  14911. * @param targetChange - A target change to apply for computing limbo docs and
  14912. * sync state.
  14913. * @returns A new ViewChange with the given docs, changes, and sync state.
  14914. */
  14915. // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
  14916. applyChanges(t, e, n) {
  14917. const s = this.ec;
  14918. this.ec = t.ec, this.mutatedKeys = t.mutatedKeys;
  14919. // Sort changes based on type and query comparator
  14920. const i = t.ic.xu();
  14921. i.sort(((t, e) => function(t, e) {
  14922. const n = t => {
  14923. switch (t) {
  14924. case 0 /* ChangeType.Added */ :
  14925. return 1;
  14926. case 2 /* ChangeType.Modified */ :
  14927. case 3 /* ChangeType.Metadata */ :
  14928. // A metadata change is converted to a modified change at the public
  14929. // api layer. Since we sort by document key and then change type,
  14930. // metadata and modified changes must be sorted equivalently.
  14931. return 2;
  14932. case 1 /* ChangeType.Removed */ :
  14933. return 0;
  14934. default:
  14935. return B();
  14936. }
  14937. };
  14938. return n(t) - n(e);
  14939. }
  14940. /**
  14941. * @license
  14942. * Copyright 2020 Google LLC
  14943. *
  14944. * Licensed under the Apache License, Version 2.0 (the "License");
  14945. * you may not use this file except in compliance with the License.
  14946. * You may obtain a copy of the License at
  14947. *
  14948. * http://www.apache.org/licenses/LICENSE-2.0
  14949. *
  14950. * Unless required by applicable law or agreed to in writing, software
  14951. * distributed under the License is distributed on an "AS IS" BASIS,
  14952. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14953. * See the License for the specific language governing permissions and
  14954. * limitations under the License.
  14955. */ (t.type, e.type) || this.tc(t.doc, e.doc))), this.oc(n);
  14956. const r = e ? this.uc() : [], o = 0 === this.Zu.size && this.current ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , u = o !== this.Xu;
  14957. if (this.Xu = o, 0 !== i.length || u) {
  14958. return {
  14959. snapshot: new Vc(this.query, t.ec, s, i, t.mutatedKeys, 0 /* SyncState.Local */ === o, u,
  14960. /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),
  14961. cc: r
  14962. };
  14963. }
  14964. // no changes
  14965. return {
  14966. cc: r
  14967. };
  14968. }
  14969. /**
  14970. * Applies an OnlineState change to the view, potentially generating a
  14971. * ViewChange if the view's syncState changes as a result.
  14972. */ $u(t) {
  14973. return this.current && "Offline" /* OnlineState.Offline */ === t ? (
  14974. // If we're offline, set `current` to false and then call applyChanges()
  14975. // to refresh our syncState and generate a ViewChange as appropriate. We
  14976. // are guaranteed to get a new TargetChange that sets `current` back to
  14977. // true once the client is back online.
  14978. this.current = !1, this.applyChanges({
  14979. ec: this.ec,
  14980. ic: new bc,
  14981. mutatedKeys: this.mutatedKeys,
  14982. zi: !1
  14983. },
  14984. /* updateLimboDocuments= */ !1)) : {
  14985. cc: []
  14986. };
  14987. }
  14988. /**
  14989. * Returns whether the doc for the given key should be in limbo.
  14990. */ ac(t) {
  14991. // If the remote end says it's part of this query, it's not in limbo.
  14992. return !this.Yu.has(t) && (
  14993. // The local store doesn't think it's a result, so it shouldn't be in limbo.
  14994. !!this.ec.has(t) && !this.ec.get(t).hasLocalMutations);
  14995. }
  14996. /**
  14997. * Updates syncedDocuments, current, and limbo docs based on the given change.
  14998. * Returns the list of changes to which docs are in limbo.
  14999. */ oc(t) {
  15000. t && (t.addedDocuments.forEach((t => this.Yu = this.Yu.add(t))), t.modifiedDocuments.forEach((t => {})),
  15001. t.removedDocuments.forEach((t => this.Yu = this.Yu.delete(t))), this.current = t.current);
  15002. }
  15003. uc() {
  15004. // We can only determine limbo documents when we're in-sync with the server.
  15005. if (!this.current) return [];
  15006. // TODO(klimt): Do this incrementally so that it's not quadratic when
  15007. // updating many documents.
  15008. const t = this.Zu;
  15009. this.Zu = Is(), this.ec.forEach((t => {
  15010. this.ac(t.key) && (this.Zu = this.Zu.add(t.key));
  15011. }));
  15012. // Diff the new limbo docs with the old limbo docs.
  15013. const e = [];
  15014. return t.forEach((t => {
  15015. this.Zu.has(t) || e.push(new Uc(t));
  15016. })), this.Zu.forEach((n => {
  15017. t.has(n) || e.push(new qc(n));
  15018. })), e;
  15019. }
  15020. /**
  15021. * Update the in-memory state of the current view with the state read from
  15022. * persistence.
  15023. *
  15024. * We update the query view whenever a client's primary status changes:
  15025. * - When a client transitions from primary to secondary, it can miss
  15026. * LocalStorage updates and its query views may temporarily not be
  15027. * synchronized with the state on disk.
  15028. * - For secondary to primary transitions, the client needs to update the list
  15029. * of `syncedDocuments` since secondary clients update their query views
  15030. * based purely on synthesized RemoteEvents.
  15031. *
  15032. * @param queryResult.documents - The documents that match the query according
  15033. * to the LocalStore.
  15034. * @param queryResult.remoteKeys - The keys of the documents that match the
  15035. * query according to the backend.
  15036. *
  15037. * @returns The ViewChange that resulted from this synchronization.
  15038. */
  15039. // PORTING NOTE: Multi-tab only.
  15040. hc(t) {
  15041. this.Yu = t.ir, this.Zu = Is();
  15042. const e = this.sc(t.documents);
  15043. return this.applyChanges(e, /*updateLimboDocuments=*/ !0);
  15044. }
  15045. /**
  15046. * Returns a view snapshot as if this query was just listened to. Contains
  15047. * a document add for every existing document and the `fromCache` and
  15048. * `hasPendingWrites` status of the already established view.
  15049. */
  15050. // PORTING NOTE: Multi-tab only.
  15051. lc() {
  15052. return Vc.fromInitialDocuments(this.query, this.ec, this.mutatedKeys, 0 /* SyncState.Local */ === this.Xu, this.hasCachedResults);
  15053. }
  15054. }
  15055. /**
  15056. * QueryView contains all of the data that SyncEngine needs to keep track of for
  15057. * a particular query.
  15058. */
  15059. class Gc {
  15060. constructor(
  15061. /**
  15062. * The query itself.
  15063. */
  15064. t,
  15065. /**
  15066. * The target number created by the client that is used in the watch
  15067. * stream to identify this query.
  15068. */
  15069. e,
  15070. /**
  15071. * The view is responsible for computing the final merged truth of what
  15072. * docs are in the query. It gets notified of local and remote changes,
  15073. * and applies the query filters and limits to determine the most correct
  15074. * possible results.
  15075. */
  15076. n) {
  15077. this.query = t, this.targetId = e, this.view = n;
  15078. }
  15079. }
  15080. /** Tracks a limbo resolution. */ class Qc {
  15081. constructor(t) {
  15082. this.key = t,
  15083. /**
  15084. * Set to true once we've received a document. This is used in
  15085. * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
  15086. * decide whether it needs to manufacture a delete event for the target once
  15087. * the target is CURRENT.
  15088. */
  15089. this.fc = !1;
  15090. }
  15091. }
  15092. /**
  15093. * An implementation of `SyncEngine` coordinating with other parts of SDK.
  15094. *
  15095. * The parts of SyncEngine that act as a callback to RemoteStore need to be
  15096. * registered individually. This is done in `syncEngineWrite()` and
  15097. * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods
  15098. * serve as entry points to RemoteStore's functionality.
  15099. *
  15100. * Note: some field defined in this class might have public access level, but
  15101. * the class is not exported so they are only accessible from this module.
  15102. * This is useful to implement optional features (like bundles) in free
  15103. * functions, such that they are tree-shakeable.
  15104. */ class jc {
  15105. constructor(t, e, n,
  15106. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  15107. s, i, r) {
  15108. this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = s,
  15109. this.currentUser = i, this.maxConcurrentLimboResolutions = r, this.dc = {}, this.wc = new as((t => ss(t)), ns),
  15110. this._c = new Map,
  15111. /**
  15112. * The keys of documents that are in limbo for which we haven't yet started a
  15113. * limbo resolution query. The strings in this set are the result of calling
  15114. * `key.path.canonicalString()` where `key` is a `DocumentKey` object.
  15115. *
  15116. * The `Set` type was chosen because it provides efficient lookup and removal
  15117. * of arbitrary elements and it also maintains insertion order, providing the
  15118. * desired queue-like FIFO semantics.
  15119. */
  15120. this.mc = new Set,
  15121. /**
  15122. * Keeps track of the target ID for each document that is in limbo with an
  15123. * active target.
  15124. */
  15125. this.gc = new Te(ft.comparator),
  15126. /**
  15127. * Keeps track of the information about an active limbo resolution for each
  15128. * active target ID that was started for the purpose of limbo resolution.
  15129. */
  15130. this.yc = new Map, this.Ic = new Lo,
  15131. /** Stores user completion handlers, indexed by User and BatchId. */
  15132. this.Tc = {},
  15133. /** Stores user callbacks waiting for all pending writes to be acknowledged. */
  15134. this.Ec = new Map, this.Ac = _o.$n(), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  15135. // The primary state is set to `true` or `false` immediately after Firestore
  15136. // startup. In the interim, a client should only be considered primary if
  15137. // `isPrimary` is true.
  15138. this.vc = void 0;
  15139. }
  15140. get isPrimaryClient() {
  15141. return !0 === this.vc;
  15142. }
  15143. }
  15144. /**
  15145. * Initiates the new listen, resolves promise when listen enqueued to the
  15146. * server. All the subsequent view snapshots or errors are sent to the
  15147. * subscribed handlers. Returns the initial snapshot.
  15148. */
  15149. async function zc(t, e) {
  15150. const n = Ea(t);
  15151. let s, i;
  15152. const r = n.wc.get(e);
  15153. if (r)
  15154. // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
  15155. // already exists when EventManager calls us for the first time. This
  15156. // happens when the primary tab is already listening to this query on
  15157. // behalf of another tab and the user of the primary also starts listening
  15158. // to the query. EventManager will not have an assigned target ID in this
  15159. // case and calls `listen` to obtain this ID.
  15160. s = r.targetId, n.sharedClientState.addLocalQueryTarget(s), i = r.view.lc(); else {
  15161. const t = await du(n.localStore, Zn(e)), r = n.sharedClientState.addLocalQueryTarget(t.targetId);
  15162. s = t.targetId, i = await Wc(n, e, s, "current" === r, t.resumeToken), n.isPrimaryClient && Xu(n.remoteStore, t);
  15163. }
  15164. return i;
  15165. }
  15166. /**
  15167. * Registers a view for a previously unknown query and computes its initial
  15168. * snapshot.
  15169. */ async function Wc(t, e, n, s, i) {
  15170. // PORTING NOTE: On Web only, we inject the code that registers new Limbo
  15171. // targets based on view changes. This allows us to only depend on Limbo
  15172. // changes when user code includes queries.
  15173. t.Rc = (e, n, s) => async function(t, e, n, s) {
  15174. let i = e.view.sc(n);
  15175. i.zi && (
  15176. // The query has a limit and some docs were removed, so we need
  15177. // to re-run the query against the local store to make sure we
  15178. // didn't lose any good docs that had been past the limit.
  15179. i = await _u(t.localStore, e.query,
  15180. /* usePreviousResults= */ !1).then((({documents: t}) => e.view.sc(t, i))));
  15181. const r = s && s.targetChanges.get(e.targetId), o = e.view.applyChanges(i,
  15182. /* updateLimboDocuments= */ t.isPrimaryClient, r);
  15183. return ua(t, e.targetId, o.cc), o.snapshot;
  15184. }(t, e, n, s);
  15185. const r = await _u(t.localStore, e,
  15186. /* usePreviousResults= */ !0), o = new Kc(e, r.ir), u = o.sc(r.documents), c = Ii.createSynthesizedTargetChangeForCurrentChange(n, s && "Offline" /* OnlineState.Offline */ !== t.onlineState, i), a = o.applyChanges(u,
  15187. /* updateLimboDocuments= */ t.isPrimaryClient, c);
  15188. ua(t, n, a.cc);
  15189. const h = new Gc(e, n, o);
  15190. return t.wc.set(e, h), t._c.has(n) ? t._c.get(n).push(e) : t._c.set(n, [ e ]), a.snapshot;
  15191. }
  15192. /** Stops listening to the query. */ async function Hc(t, e) {
  15193. const n = U(t), s = n.wc.get(e), i = n._c.get(s.targetId);
  15194. if (i.length > 1) return n._c.set(s.targetId, i.filter((t => !ns(t, e)))), void n.wc.delete(e);
  15195. // No other queries are mapped to the target, clean up the query and the target.
  15196. if (n.isPrimaryClient) {
  15197. // We need to remove the local query target first to allow us to verify
  15198. // whether any other client is still interested in this target.
  15199. n.sharedClientState.removeLocalQueryTarget(s.targetId);
  15200. n.sharedClientState.isActiveQueryTarget(s.targetId) || await wu(n.localStore, s.targetId,
  15201. /*keepPersistedTargetData=*/ !1).then((() => {
  15202. n.sharedClientState.clearQueryState(s.targetId), Zu(n.remoteStore, s.targetId),
  15203. ra(n, s.targetId);
  15204. })).catch(Pt);
  15205. } else ra(n, s.targetId), await wu(n.localStore, s.targetId,
  15206. /*keepPersistedTargetData=*/ !0);
  15207. }
  15208. /**
  15209. * Initiates the write of local mutation batch which involves adding the
  15210. * writes to the mutation queue, notifying the remote store about new
  15211. * mutations and raising events for any changes this write caused.
  15212. *
  15213. * The promise returned by this call is resolved when the above steps
  15214. * have completed, *not* when the write was acked by the backend. The
  15215. * userCallback is resolved once the write was acked/rejected by the
  15216. * backend (or failed locally for any other reason).
  15217. */ async function Jc(t, e, n) {
  15218. const s = Aa(t);
  15219. try {
  15220. const t = await function(t, e) {
  15221. const n = U(t), s = ot.now(), i = e.reduce(((t, e) => t.add(e.key)), Is());
  15222. let r, o;
  15223. return n.persistence.runTransaction("Locally write mutations", "readwrite", (t => {
  15224. // Figure out which keys do not have a remote version in the cache, this
  15225. // is needed to create the right overlay mutation: if no remote version
  15226. // presents, we do not need to create overlays as patch mutations.
  15227. // TODO(Overlay): Is there a better way to determine this? Using the
  15228. // document version does not work because local mutations set them back
  15229. // to 0.
  15230. let u = ls(), c = Is();
  15231. return n.Zi.getEntries(t, i).next((t => {
  15232. u = t, u.forEach(((t, e) => {
  15233. e.isValidDocument() || (c = c.add(t));
  15234. }));
  15235. })).next((() => n.localDocuments.getOverlayedDocuments(t, u))).next((i => {
  15236. r = i;
  15237. // For non-idempotent mutations (such as `FieldValue.increment()`),
  15238. // we record the base state in a separate patch mutation. This is
  15239. // later used to guarantee consistent values and prevents flicker
  15240. // even if the backend sends us an update that already includes our
  15241. // transform.
  15242. const o = [];
  15243. for (const t of e) {
  15244. const e = zs(t, r.get(t.key).overlayedDocument);
  15245. null != e &&
  15246. // NOTE: The base state should only be applied if there's some
  15247. // existing document to override, so use a Precondition of
  15248. // exists=true
  15249. o.push(new Js(t.key, e, ln(e.value.mapValue), qs.exists(!0)));
  15250. }
  15251. return n.mutationQueue.addMutationBatch(t, s, o, e);
  15252. })).next((e => {
  15253. o = e;
  15254. const s = e.applyToLocalDocumentSet(r, c);
  15255. return n.documentOverlayCache.saveOverlays(t, e.batchId, s);
  15256. }));
  15257. })).then((() => ({
  15258. batchId: o.batchId,
  15259. changes: ws(r)
  15260. })));
  15261. }(s.localStore, e);
  15262. s.sharedClientState.addPendingMutation(t.batchId), function(t, e, n) {
  15263. let s = t.Tc[t.currentUser.toKey()];
  15264. s || (s = new Te(st));
  15265. s = s.insert(e, n), t.Tc[t.currentUser.toKey()] = s;
  15266. }
  15267. /**
  15268. * Resolves or rejects the user callback for the given batch and then discards
  15269. * it.
  15270. */ (s, t.batchId, n), await ha(s, t.changes), await lc(s.remoteStore);
  15271. } catch (t) {
  15272. // If we can't persist the mutation, we reject the user callback and
  15273. // don't send the mutation. The user can then retry the write.
  15274. const e = Rc(t, "Failed to persist write");
  15275. n.reject(e);
  15276. }
  15277. }
  15278. /**
  15279. * Applies one remote event to the sync engine, notifying any views of the
  15280. * changes, and releasing any pending mutation batches that would become
  15281. * visible because of the snapshot version the remote event contains.
  15282. */ async function Yc(t, e) {
  15283. const n = U(t);
  15284. try {
  15285. const t = await hu(n.localStore, e);
  15286. // Update `receivedDocument` as appropriate for any limbo targets.
  15287. e.targetChanges.forEach(((t, e) => {
  15288. const s = n.yc.get(e);
  15289. s && (
  15290. // Since this is a limbo resolution lookup, it's for a single document
  15291. // and it could be added, modified, or removed, but not a combination.
  15292. L(t.addedDocuments.size + t.modifiedDocuments.size + t.removedDocuments.size <= 1),
  15293. t.addedDocuments.size > 0 ? s.fc = !0 : t.modifiedDocuments.size > 0 ? L(s.fc) : t.removedDocuments.size > 0 && (L(s.fc),
  15294. s.fc = !1));
  15295. })), await ha(n, t, e);
  15296. } catch (t) {
  15297. await Pt(t);
  15298. }
  15299. }
  15300. /**
  15301. * Applies an OnlineState change to the sync engine and notifies any views of
  15302. * the change.
  15303. */ function Xc(t, e, n) {
  15304. const s = U(t);
  15305. // If we are the secondary client, we explicitly ignore the remote store's
  15306. // online state (the local client may go offline, even though the primary
  15307. // tab remains online) and only apply the primary tab's online state from
  15308. // SharedClientState.
  15309. if (s.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !s.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {
  15310. const t = [];
  15311. s.wc.forEach(((n, s) => {
  15312. const i = s.view.$u(e);
  15313. i.snapshot && t.push(i.snapshot);
  15314. })), function(t, e) {
  15315. const n = U(t);
  15316. n.onlineState = e;
  15317. let s = !1;
  15318. n.queries.forEach(((t, n) => {
  15319. for (const t of n.listeners)
  15320. // Run global snapshot listeners if a consistent snapshot has been emitted.
  15321. t.$u(e) && (s = !0);
  15322. })), s && $c(n);
  15323. }(s.eventManager, e), t.length && s.dc.nu(t), s.onlineState = e, s.isPrimaryClient && s.sharedClientState.setOnlineState(e);
  15324. }
  15325. }
  15326. /**
  15327. * Rejects the listen for the given targetID. This can be triggered by the
  15328. * backend for any active target.
  15329. *
  15330. * @param syncEngine - The sync engine implementation.
  15331. * @param targetId - The targetID corresponds to one previously initiated by the
  15332. * user as part of TargetData passed to listen() on RemoteStore.
  15333. * @param err - A description of the condition that has forced the rejection.
  15334. * Nearly always this will be an indication that the user is no longer
  15335. * authorized to see the data matching the target.
  15336. */ async function Zc(t, e, n) {
  15337. const s = U(t);
  15338. // PORTING NOTE: Multi-tab only.
  15339. s.sharedClientState.updateQueryState(e, "rejected", n);
  15340. const i = s.yc.get(e), r = i && i.key;
  15341. if (r) {
  15342. // TODO(klimt): We really only should do the following on permission
  15343. // denied errors, but we don't have the cause code here.
  15344. // It's a limbo doc. Create a synthetic event saying it was deleted.
  15345. // This is kind of a hack. Ideally, we would have a method in the local
  15346. // store to purge a document. However, it would be tricky to keep all of
  15347. // the local store's invariants with another method.
  15348. let t = new Te(ft.comparator);
  15349. // TODO(b/217189216): This limbo document should ideally have a read time,
  15350. // so that it is picked up by any read-time based scans. The backend,
  15351. // however, does not send a read time for target removals.
  15352. t = t.insert(r, fn.newNoDocument(r, ut.min()));
  15353. const n = Is().add(r), i = new pi(ut.min(),
  15354. /* targetChanges= */ new Map,
  15355. /* targetMismatches= */ new Te(st), t, n);
  15356. await Yc(s, i),
  15357. // Since this query failed, we won't want to manually unlisten to it.
  15358. // We only remove it from bookkeeping after we successfully applied the
  15359. // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
  15360. // this query when the RemoteStore restarts the Watch stream, which should
  15361. // re-trigger the target failure.
  15362. s.gc = s.gc.remove(r), s.yc.delete(e), aa(s);
  15363. } else await wu(s.localStore, e,
  15364. /* keepPersistedTargetData */ !1).then((() => ra(s, e, n))).catch(Pt);
  15365. }
  15366. async function ta(t, e) {
  15367. const n = U(t), s = e.batch.batchId;
  15368. try {
  15369. const t = await cu(n.localStore, e);
  15370. // The local store may or may not be able to apply the write result and
  15371. // raise events immediately (depending on whether the watcher is caught
  15372. // up), so we raise user callbacks first so that they consistently happen
  15373. // before listen events.
  15374. ia(n, s, /*error=*/ null), sa(n, s), n.sharedClientState.updateMutationState(s, "acknowledged"),
  15375. await ha(n, t);
  15376. } catch (t) {
  15377. await Pt(t);
  15378. }
  15379. }
  15380. async function ea(t, e, n) {
  15381. const s = U(t);
  15382. try {
  15383. const t = await function(t, e) {
  15384. const n = U(t);
  15385. return n.persistence.runTransaction("Reject batch", "readwrite-primary", (t => {
  15386. let s;
  15387. return n.mutationQueue.lookupMutationBatch(t, e).next((e => (L(null !== e), s = e.keys(),
  15388. n.mutationQueue.removeMutationBatch(t, e)))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, s))).next((() => n.localDocuments.getDocuments(t, s)));
  15389. }));
  15390. }
  15391. /**
  15392. * Returns the largest (latest) batch id in mutation queue that is pending
  15393. * server response.
  15394. *
  15395. * Returns `BATCHID_UNKNOWN` if the queue is empty.
  15396. */ (s.localStore, e);
  15397. // The local store may or may not be able to apply the write result and
  15398. // raise events immediately (depending on whether the watcher is caught up),
  15399. // so we raise user callbacks first so that they consistently happen before
  15400. // listen events.
  15401. ia(s, e, n), sa(s, e), s.sharedClientState.updateMutationState(e, "rejected", n),
  15402. await ha(s, t);
  15403. } catch (n) {
  15404. await Pt(n);
  15405. }
  15406. }
  15407. /**
  15408. * Registers a user callback that resolves when all pending mutations at the moment of calling
  15409. * are acknowledged .
  15410. */ async function na(t, e) {
  15411. const n = U(t);
  15412. ic(n.remoteStore) || $("SyncEngine", "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");
  15413. try {
  15414. const t = await function(t) {
  15415. const e = U(t);
  15416. return e.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (t => e.mutationQueue.getHighestUnacknowledgedBatchId(t)));
  15417. }(n.localStore);
  15418. if (-1 === t)
  15419. // Trigger the callback right away if there is no pending writes at the moment.
  15420. return void e.resolve();
  15421. const s = n.Ec.get(t) || [];
  15422. s.push(e), n.Ec.set(t, s);
  15423. } catch (t) {
  15424. const n = Rc(t, "Initialization of waitForPendingWrites() operation failed");
  15425. e.reject(n);
  15426. }
  15427. }
  15428. /**
  15429. * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,
  15430. * if there are any.
  15431. */ function sa(t, e) {
  15432. (t.Ec.get(e) || []).forEach((t => {
  15433. t.resolve();
  15434. })), t.Ec.delete(e);
  15435. }
  15436. /** Reject all outstanding callbacks waiting for pending writes to complete. */ function ia(t, e, n) {
  15437. const s = U(t);
  15438. let i = s.Tc[s.currentUser.toKey()];
  15439. // NOTE: Mutations restored from persistence won't have callbacks, so it's
  15440. // okay for there to be no callback for this ID.
  15441. if (i) {
  15442. const t = i.get(e);
  15443. t && (n ? t.reject(n) : t.resolve(), i = i.remove(e)), s.Tc[s.currentUser.toKey()] = i;
  15444. }
  15445. }
  15446. function ra(t, e, n = null) {
  15447. t.sharedClientState.removeLocalQueryTarget(e);
  15448. for (const s of t._c.get(e)) t.wc.delete(s), n && t.dc.Pc(s, n);
  15449. if (t._c.delete(e), t.isPrimaryClient) {
  15450. t.Ic.Is(e).forEach((e => {
  15451. t.Ic.containsKey(e) ||
  15452. // We removed the last reference for this key
  15453. oa(t, e);
  15454. }));
  15455. }
  15456. }
  15457. function oa(t, e) {
  15458. t.mc.delete(e.path.canonicalString());
  15459. // It's possible that the target already got removed because the query failed. In that case,
  15460. // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.
  15461. const n = t.gc.get(e);
  15462. null !== n && (Zu(t.remoteStore, n), t.gc = t.gc.remove(e), t.yc.delete(n), aa(t));
  15463. }
  15464. function ua(t, e, n) {
  15465. for (const s of n) if (s instanceof qc) t.Ic.addReference(s.key, e), ca(t, s); else if (s instanceof Uc) {
  15466. $("SyncEngine", "Document no longer in limbo: " + s.key), t.Ic.removeReference(s.key, e);
  15467. t.Ic.containsKey(s.key) ||
  15468. // We removed the last reference for this key
  15469. oa(t, s.key);
  15470. } else B();
  15471. }
  15472. function ca(t, e) {
  15473. const n = e.key, s = n.path.canonicalString();
  15474. t.gc.get(n) || t.mc.has(s) || ($("SyncEngine", "New document in limbo: " + n), t.mc.add(s),
  15475. aa(t));
  15476. }
  15477. /**
  15478. * Starts listens for documents in limbo that are enqueued for resolution,
  15479. * subject to a maximum number of concurrent resolutions.
  15480. *
  15481. * Without bounding the number of concurrent resolutions, the server can fail
  15482. * with "resource exhausted" errors which can lead to pathological client
  15483. * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.
  15484. */ function aa(t) {
  15485. for (;t.mc.size > 0 && t.gc.size < t.maxConcurrentLimboResolutions; ) {
  15486. const e = t.mc.values().next().value;
  15487. t.mc.delete(e);
  15488. const n = new ft(at.fromString(e)), s = t.Ac.next();
  15489. t.yc.set(s, new Qc(n)), t.gc = t.gc.insert(n, s), Xu(t.remoteStore, new lr(Zn(zn(n.path)), s, "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ , Bt.ct));
  15490. }
  15491. }
  15492. async function ha(t, e, n) {
  15493. const s = U(t), i = [], r = [], o = [];
  15494. s.wc.isEmpty() || (s.wc.forEach(((t, u) => {
  15495. o.push(s.Rc(u, e, n).then((t => {
  15496. // Update views if there are actual changes.
  15497. if (
  15498. // If there are changes, or we are handling a global snapshot, notify
  15499. // secondary clients to update query state.
  15500. (t || n) && s.isPrimaryClient && s.sharedClientState.updateQueryState(u.targetId, (null == t ? void 0 : t.fromCache) ? "not-current" : "current"),
  15501. t) {
  15502. i.push(t);
  15503. const e = su.Li(u.targetId, t);
  15504. r.push(e);
  15505. }
  15506. })));
  15507. })), await Promise.all(o), s.dc.nu(i), await async function(t, e) {
  15508. const n = U(t);
  15509. try {
  15510. await n.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (t => bt.forEach(e, (e => bt.forEach(e.Fi, (s => n.persistence.referenceDelegate.addReference(t, e.targetId, s))).next((() => bt.forEach(e.Bi, (s => n.persistence.referenceDelegate.removeReference(t, e.targetId, s)))))))));
  15511. } catch (t) {
  15512. if (!xt(t)) throw t;
  15513. // If `notifyLocalViewChanges` fails, we did not advance the sequence
  15514. // number for the documents that were included in this transaction.
  15515. // This might trigger them to be deleted earlier than they otherwise
  15516. // would have, but it should not invalidate the integrity of the data.
  15517. $("LocalStore", "Failed to update sequence numbers: " + t);
  15518. }
  15519. for (const t of e) {
  15520. const e = t.targetId;
  15521. if (!t.fromCache) {
  15522. const t = n.Ji.get(e), s = t.snapshotVersion, i = t.withLastLimboFreeSnapshotVersion(s);
  15523. // Advance the last limbo free snapshot version
  15524. n.Ji = n.Ji.insert(e, i);
  15525. }
  15526. }
  15527. }(s.localStore, r));
  15528. }
  15529. async function la(t, e) {
  15530. const n = U(t);
  15531. if (!n.currentUser.isEqual(e)) {
  15532. $("SyncEngine", "User change. New user:", e.toKey());
  15533. const t = await uu(n.localStore, e);
  15534. n.currentUser = e,
  15535. // Fails tasks waiting for pending writes requested by previous user.
  15536. function(t, e) {
  15537. t.Ec.forEach((t => {
  15538. t.forEach((t => {
  15539. t.reject(new G(K.CANCELLED, e));
  15540. }));
  15541. })), t.Ec.clear();
  15542. }(n, "'waitForPendingWrites' promise is rejected due to a user change."),
  15543. // TODO(b/114226417): Consider calling this only in the primary tab.
  15544. n.sharedClientState.handleUserChange(e, t.removedBatchIds, t.addedBatchIds), await ha(n, t.er);
  15545. }
  15546. }
  15547. function fa(t, e) {
  15548. const n = U(t), s = n.yc.get(e);
  15549. if (s && s.fc) return Is().add(s.key);
  15550. {
  15551. let t = Is();
  15552. const s = n._c.get(e);
  15553. if (!s) return t;
  15554. for (const e of s) {
  15555. const s = n.wc.get(e);
  15556. t = t.unionWith(s.view.nc);
  15557. }
  15558. return t;
  15559. }
  15560. }
  15561. /**
  15562. * Reconcile the list of synced documents in an existing view with those
  15563. * from persistence.
  15564. */ async function da(t, e) {
  15565. const n = U(t), s = await _u(n.localStore, e.query,
  15566. /* usePreviousResults= */ !0), i = e.view.hc(s);
  15567. return n.isPrimaryClient && ua(n, e.targetId, i.cc), i;
  15568. }
  15569. /**
  15570. * Retrieves newly changed documents from remote document cache and raises
  15571. * snapshots if needed.
  15572. */
  15573. // PORTING NOTE: Multi-Tab only.
  15574. async function wa(t, e) {
  15575. const n = U(t);
  15576. return gu(n.localStore, e).then((t => ha(n, t)));
  15577. }
  15578. /** Applies a mutation state to an existing batch. */
  15579. // PORTING NOTE: Multi-Tab only.
  15580. async function _a(t, e, n, s) {
  15581. const i = U(t), r = await function(t, e) {
  15582. const n = U(t), s = U(n.mutationQueue);
  15583. return n.persistence.runTransaction("Lookup mutation documents", "readonly", (t => s.Sn(t, e).next((e => e ? n.localDocuments.getDocuments(t, e) : bt.resolve(null)))));
  15584. }
  15585. // PORTING NOTE: Multi-Tab only.
  15586. (i.localStore, e);
  15587. null !== r ? ("pending" === n ?
  15588. // If we are the primary client, we need to send this write to the
  15589. // backend. Secondary clients will ignore these writes since their remote
  15590. // connection is disabled.
  15591. await lc(i.remoteStore) : "acknowledged" === n || "rejected" === n ? (
  15592. // NOTE: Both these methods are no-ops for batches that originated from
  15593. // other clients.
  15594. ia(i, e, s || null), sa(i, e), function(t, e) {
  15595. U(U(t).mutationQueue).Cn(e);
  15596. }
  15597. // PORTING NOTE: Multi-Tab only.
  15598. (i.localStore, e)) : B(), await ha(i, r)) :
  15599. // A throttled tab may not have seen the mutation before it was completed
  15600. // and removed from the mutation queue, in which case we won't have cached
  15601. // the affected documents. In this case we can safely ignore the update
  15602. // since that means we didn't apply the mutation locally at all (if we
  15603. // had, we would have cached the affected documents), and so we will just
  15604. // see any resulting document changes via normal remote document updates
  15605. // as applicable.
  15606. $("SyncEngine", "Cannot apply mutation batch with id: " + e);
  15607. }
  15608. /** Applies a query target change from a different tab. */
  15609. // PORTING NOTE: Multi-Tab only.
  15610. async function ma(t, e) {
  15611. const n = U(t);
  15612. if (Ea(n), Aa(n), !0 === e && !0 !== n.vc) {
  15613. // Secondary tabs only maintain Views for their local listeners and the
  15614. // Views internal state may not be 100% populated (in particular
  15615. // secondary tabs don't track syncedDocuments, the set of documents the
  15616. // server considers to be in the target). So when a secondary becomes
  15617. // primary, we need to need to make sure that all views for all targets
  15618. // match the state on disk.
  15619. const t = n.sharedClientState.getAllActiveQueryTargets(), e = await ga(n, t.toArray());
  15620. n.vc = !0, await Tc(n.remoteStore, !0);
  15621. for (const t of e) Xu(n.remoteStore, t);
  15622. } else if (!1 === e && !1 !== n.vc) {
  15623. const t = [];
  15624. let e = Promise.resolve();
  15625. n._c.forEach(((s, i) => {
  15626. n.sharedClientState.isLocalQueryTarget(i) ? t.push(i) : e = e.then((() => (ra(n, i),
  15627. wu(n.localStore, i,
  15628. /*keepPersistedTargetData=*/ !0)))), Zu(n.remoteStore, i);
  15629. })), await e, await ga(n, t),
  15630. // PORTING NOTE: Multi-Tab only.
  15631. function(t) {
  15632. const e = U(t);
  15633. e.yc.forEach(((t, n) => {
  15634. Zu(e.remoteStore, n);
  15635. })), e.Ic.Ts(), e.yc = new Map, e.gc = new Te(ft.comparator);
  15636. }
  15637. /**
  15638. * Reconcile the query views of the provided query targets with the state from
  15639. * persistence. Raises snapshots for any changes that affect the local
  15640. * client and returns the updated state of all target's query data.
  15641. *
  15642. * @param syncEngine - The sync engine implementation
  15643. * @param targets - the list of targets with views that need to be recomputed
  15644. * @param transitionToPrimary - `true` iff the tab transitions from a secondary
  15645. * tab to a primary tab
  15646. */
  15647. // PORTING NOTE: Multi-Tab only.
  15648. (n), n.vc = !1, await Tc(n.remoteStore, !1);
  15649. }
  15650. }
  15651. async function ga(t, e, n) {
  15652. const s = U(t), i = [], r = [];
  15653. for (const t of e) {
  15654. let e;
  15655. const n = s._c.get(t);
  15656. if (n && 0 !== n.length) {
  15657. // For queries that have a local View, we fetch their current state
  15658. // from LocalStore (as the resume token and the snapshot version
  15659. // might have changed) and reconcile their views with the persisted
  15660. // state (the list of syncedDocuments may have gotten out of sync).
  15661. e = await du(s.localStore, Zn(n[0]));
  15662. for (const t of n) {
  15663. const e = s.wc.get(t), n = await da(s, e);
  15664. n.snapshot && r.push(n.snapshot);
  15665. }
  15666. } else {
  15667. // For queries that never executed on this client, we need to
  15668. // allocate the target in LocalStore and initialize a new View.
  15669. const n = await mu(s.localStore, t);
  15670. e = await du(s.localStore, n), await Wc(s, ya(n), t,
  15671. /*current=*/ !1, e.resumeToken);
  15672. }
  15673. i.push(e);
  15674. }
  15675. return s.dc.nu(r), i;
  15676. }
  15677. /**
  15678. * Creates a `Query` object from the specified `Target`. There is no way to
  15679. * obtain the original `Query`, so we synthesize a `Query` from the `Target`
  15680. * object.
  15681. *
  15682. * The synthesized result might be different from the original `Query`, but
  15683. * since the synthesized `Query` should return the same results as the
  15684. * original one (only the presentation of results might differ), the potential
  15685. * difference will not cause issues.
  15686. */
  15687. // PORTING NOTE: Multi-Tab only.
  15688. function ya(t) {
  15689. return jn(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, "F" /* LimitType.First */ , t.startAt, t.endAt);
  15690. }
  15691. /** Returns the IDs of the clients that are currently active. */
  15692. // PORTING NOTE: Multi-Tab only.
  15693. function pa(t) {
  15694. const e = U(t);
  15695. return U(U(e.localStore).persistence).Mi();
  15696. }
  15697. /** Applies a query target change from a different tab. */
  15698. // PORTING NOTE: Multi-Tab only.
  15699. async function Ia(t, e, n, s) {
  15700. const i = U(t);
  15701. if (i.vc)
  15702. // If we receive a target state notification via WebStorage, we are
  15703. // either already secondary or another tab has taken the primary lease.
  15704. return void $("SyncEngine", "Ignoring unexpected query state notification.");
  15705. const r = i._c.get(e);
  15706. if (r && r.length > 0) switch (n) {
  15707. case "current":
  15708. case "not-current":
  15709. {
  15710. const t = await gu(i.localStore, os(r[0])), s = pi.createSynthesizedRemoteEventForCurrentChange(e, "current" === n, Ce.EMPTY_BYTE_STRING);
  15711. await ha(i, t, s);
  15712. break;
  15713. }
  15714. case "rejected":
  15715. await wu(i.localStore, e,
  15716. /* keepPersistedTargetData */ !0), ra(i, e, s);
  15717. break;
  15718. default:
  15719. B();
  15720. }
  15721. }
  15722. /** Adds or removes Watch targets for queries from different tabs. */ async function Ta(t, e, n) {
  15723. const s = Ea(t);
  15724. if (s.vc) {
  15725. for (const t of e) {
  15726. if (s._c.has(t)) {
  15727. // A target might have been added in a previous attempt
  15728. $("SyncEngine", "Adding an already active target " + t);
  15729. continue;
  15730. }
  15731. const e = await mu(s.localStore, t), n = await du(s.localStore, e);
  15732. await Wc(s, ya(e), n.targetId,
  15733. /*current=*/ !1, n.resumeToken), Xu(s.remoteStore, n);
  15734. }
  15735. for (const t of n)
  15736. // Check that the target is still active since the target might have been
  15737. // removed if it has been rejected by the backend.
  15738. s._c.has(t) &&
  15739. // Release queries that are still active.
  15740. await wu(s.localStore, t,
  15741. /* keepPersistedTargetData */ !1).then((() => {
  15742. Zu(s.remoteStore, t), ra(s, t);
  15743. })).catch(Pt);
  15744. }
  15745. }
  15746. function Ea(t) {
  15747. const e = U(t);
  15748. return e.remoteStore.remoteSyncer.applyRemoteEvent = Yc.bind(null, e), e.remoteStore.remoteSyncer.getRemoteKeysForTarget = fa.bind(null, e),
  15749. e.remoteStore.remoteSyncer.rejectListen = Zc.bind(null, e), e.dc.nu = Nc.bind(null, e.eventManager),
  15750. e.dc.Pc = kc.bind(null, e.eventManager), e;
  15751. }
  15752. function Aa(t) {
  15753. const e = U(t);
  15754. return e.remoteStore.remoteSyncer.applySuccessfulWrite = ta.bind(null, e), e.remoteStore.remoteSyncer.rejectFailedWrite = ea.bind(null, e),
  15755. e;
  15756. }
  15757. /**
  15758. * Loads a Firestore bundle into the SDK. The returned promise resolves when
  15759. * the bundle finished loading.
  15760. *
  15761. * @param syncEngine - SyncEngine to use.
  15762. * @param bundleReader - Bundle to load into the SDK.
  15763. * @param task - LoadBundleTask used to update the loading progress to public API.
  15764. */ function va(t, e, n) {
  15765. const s = U(t);
  15766. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  15767. (
  15768. /** Loads a bundle and returns the list of affected collection groups. */
  15769. async function(t, e, n) {
  15770. try {
  15771. const s = await e.getMetadata();
  15772. if (await function(t, e) {
  15773. const n = U(t), s = Mi(e.createTime);
  15774. return n.persistence.runTransaction("hasNewerBundle", "readonly", (t => n.qs.getBundleMetadata(t, e.id))).then((t => !!t && t.createTime.compareTo(s) >= 0));
  15775. }
  15776. /**
  15777. * Saves the given `BundleMetadata` to local persistence.
  15778. */ (t.localStore, s)) return await e.close(), n._completeWith(function(t) {
  15779. return {
  15780. taskState: "Success",
  15781. documentsLoaded: t.totalDocuments,
  15782. bytesLoaded: t.totalBytes,
  15783. totalDocuments: t.totalDocuments,
  15784. totalBytes: t.totalBytes
  15785. };
  15786. }(s)), Promise.resolve(new Set);
  15787. n._updateProgress(Lc(s));
  15788. const i = new Bc(s, t.localStore, e.serializer);
  15789. let r = await e.bc();
  15790. for (;r; ) {
  15791. const t = await i.zu(r);
  15792. t && n._updateProgress(t), r = await e.bc();
  15793. }
  15794. const o = await i.complete();
  15795. return await ha(t, o.Ju,
  15796. /* remoteEvent */ void 0),
  15797. // Save metadata, so loading the same bundle will skip.
  15798. await function(t, e) {
  15799. const n = U(t);
  15800. return n.persistence.runTransaction("Save bundle", "readwrite", (t => n.qs.saveBundleMetadata(t, e)));
  15801. }
  15802. /**
  15803. * Returns a promise of a `NamedQuery` associated with given query name. Promise
  15804. * resolves to undefined if no persisted data can be found.
  15805. */ (t.localStore, s), n._completeWith(o.progress), Promise.resolve(o.Hu);
  15806. } catch (t) {
  15807. return O("SyncEngine", `Loading bundle failed with ${t}`), n._failWith(t), Promise.resolve(new Set);
  15808. }
  15809. }
  15810. /**
  15811. * @license
  15812. * Copyright 2020 Google LLC
  15813. *
  15814. * Licensed under the Apache License, Version 2.0 (the "License");
  15815. * you may not use this file except in compliance with the License.
  15816. * You may obtain a copy of the License at
  15817. *
  15818. * http://www.apache.org/licenses/LICENSE-2.0
  15819. *
  15820. * Unless required by applicable law or agreed to in writing, software
  15821. * distributed under the License is distributed on an "AS IS" BASIS,
  15822. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15823. * See the License for the specific language governing permissions and
  15824. * limitations under the License.
  15825. */
  15826. /**
  15827. * Provides all components needed for Firestore with in-memory persistence.
  15828. * Uses EagerGC garbage collection.
  15829. */)(s, e, n).then((t => {
  15830. s.sharedClientState.notifyBundleLoaded(t);
  15831. }));
  15832. }
  15833. class Ra {
  15834. constructor() {
  15835. this.synchronizeTabs = !1;
  15836. }
  15837. async initialize(t) {
  15838. this.serializer = qu(t.databaseInfo.databaseId), this.sharedClientState = this.createSharedClientState(t),
  15839. this.persistence = this.createPersistence(t), await this.persistence.start(), this.localStore = this.createLocalStore(t),
  15840. this.gcScheduler = this.createGarbageCollectionScheduler(t, this.localStore), this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(t, this.localStore);
  15841. }
  15842. createGarbageCollectionScheduler(t, e) {
  15843. return null;
  15844. }
  15845. createIndexBackfillerScheduler(t, e) {
  15846. return null;
  15847. }
  15848. createLocalStore(t) {
  15849. return ou(this.persistence, new iu, t.initialUser, this.serializer);
  15850. }
  15851. createPersistence(t) {
  15852. return new jo(Wo.zs, this.serializer);
  15853. }
  15854. createSharedClientState(t) {
  15855. return new Du;
  15856. }
  15857. async terminate() {
  15858. this.gcScheduler && this.gcScheduler.stop(), await this.sharedClientState.shutdown(),
  15859. await this.persistence.shutdown();
  15860. }
  15861. }
  15862. class Pa extends Ra {
  15863. constructor(t) {
  15864. super(), this.cacheSizeBytes = t;
  15865. }
  15866. createGarbageCollectionScheduler(t, e) {
  15867. L(this.persistence.referenceDelegate instanceof Ho);
  15868. const n = this.persistence.referenceDelegate.garbageCollector;
  15869. return new Eo(n, t.asyncQueue, e);
  15870. }
  15871. createPersistence(t) {
  15872. const e = void 0 !== this.cacheSizeBytes ? oo.withCacheSize(this.cacheSizeBytes) : oo.DEFAULT;
  15873. return new jo((t => Ho.zs(t, e)), this.serializer);
  15874. }
  15875. }
  15876. /**
  15877. * Provides all components needed for Firestore with IndexedDB persistence.
  15878. */ class ba extends Ra {
  15879. constructor(t, e, n) {
  15880. super(), this.Vc = t, this.cacheSizeBytes = e, this.forceOwnership = n, this.synchronizeTabs = !1;
  15881. }
  15882. async initialize(t) {
  15883. await super.initialize(t), await this.Vc.initialize(this, t),
  15884. // Enqueue writes from a previous session
  15885. await Aa(this.Vc.syncEngine), await lc(this.Vc.remoteStore),
  15886. // NOTE: This will immediately call the listener, so we make sure to
  15887. // set it after localStore / remoteStore are started.
  15888. await this.persistence.Ii((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(),
  15889. this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(),
  15890. Promise.resolve())));
  15891. }
  15892. createLocalStore(t) {
  15893. return ou(this.persistence, new iu, t.initialUser, this.serializer);
  15894. }
  15895. createGarbageCollectionScheduler(t, e) {
  15896. const n = this.persistence.referenceDelegate.garbageCollector;
  15897. return new Eo(n, t.asyncQueue, e);
  15898. }
  15899. createIndexBackfillerScheduler(t, e) {
  15900. const n = new Ft(e, this.persistence);
  15901. return new Ot(t.asyncQueue, n);
  15902. }
  15903. createPersistence(t) {
  15904. const e = nu(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? oo.withCacheSize(this.cacheSizeBytes) : oo.DEFAULT;
  15905. return new Zo(this.synchronizeTabs, e, t.clientId, n, t.asyncQueue, Bu(), Lu(), this.serializer, this.sharedClientState, !!this.forceOwnership);
  15906. }
  15907. createSharedClientState(t) {
  15908. return new Du;
  15909. }
  15910. }
  15911. /**
  15912. * Provides all components needed for Firestore with multi-tab IndexedDB
  15913. * persistence.
  15914. *
  15915. * In the legacy client, this provider is used to provide both multi-tab and
  15916. * non-multi-tab persistence since we cannot tell at build time whether
  15917. * `synchronizeTabs` will be enabled.
  15918. */ class Va extends ba {
  15919. constructor(t, e) {
  15920. super(t, e, /* forceOwnership= */ !1), this.Vc = t, this.cacheSizeBytes = e, this.synchronizeTabs = !0;
  15921. }
  15922. async initialize(t) {
  15923. await super.initialize(t);
  15924. const e = this.Vc.syncEngine;
  15925. this.sharedClientState instanceof Su && (this.sharedClientState.syncEngine = {
  15926. jr: _a.bind(null, e),
  15927. zr: Ia.bind(null, e),
  15928. Wr: Ta.bind(null, e),
  15929. Mi: pa.bind(null, e),
  15930. Qr: wa.bind(null, e)
  15931. }, await this.sharedClientState.start()),
  15932. // NOTE: This will immediately call the listener, so we make sure to
  15933. // set it after localStore / remoteStore are started.
  15934. await this.persistence.Ii((async t => {
  15935. await ma(this.Vc.syncEngine, t), this.gcScheduler && (t && !this.gcScheduler.started ? this.gcScheduler.start() : t || this.gcScheduler.stop()),
  15936. this.indexBackfillerScheduler && (t && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : t || this.indexBackfillerScheduler.stop());
  15937. }));
  15938. }
  15939. createSharedClientState(t) {
  15940. const e = Bu();
  15941. if (!Su.D(e)) throw new G(K.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
  15942. const n = nu(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey);
  15943. return new Su(e, t.asyncQueue, n, t.clientId, t.initialUser);
  15944. }
  15945. }
  15946. /**
  15947. * Initializes and wires the components that are needed to interface with the
  15948. * network.
  15949. */ class Sa {
  15950. async initialize(t, e) {
  15951. this.localStore || (this.localStore = t.localStore, this.sharedClientState = t.sharedClientState,
  15952. this.datastore = this.createDatastore(e), this.remoteStore = this.createRemoteStore(e),
  15953. this.eventManager = this.createEventManager(e), this.syncEngine = this.createSyncEngine(e,
  15954. /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = t => Xc(this.syncEngine, t, 1 /* OnlineStateSource.SharedClientState */),
  15955. this.remoteStore.remoteSyncer.handleCredentialChange = la.bind(null, this.syncEngine),
  15956. await Tc(this.remoteStore, this.syncEngine.isPrimaryClient));
  15957. }
  15958. createEventManager(t) {
  15959. return new Dc;
  15960. }
  15961. createDatastore(t) {
  15962. const e = qu(t.databaseInfo.databaseId), n = (s = t.databaseInfo, new Fu(s));
  15963. var s;
  15964. /** Return the Platform-specific connectivity monitor. */ return function(t, e, n, s) {
  15965. return new ju(t, e, n, s);
  15966. }(t.authCredentials, t.appCheckCredentials, n, e);
  15967. }
  15968. createRemoteStore(t) {
  15969. return e = this.localStore, n = this.datastore, s = t.asyncQueue, i = t => Xc(this.syncEngine, t, 0 /* OnlineStateSource.RemoteStore */),
  15970. r = xu.D() ? new xu : new Cu, new Hu(e, n, s, i, r);
  15971. var e, n, s, i, r;
  15972. /** Re-enables the network. Idempotent. */ }
  15973. createSyncEngine(t, e) {
  15974. return function(t, e, n,
  15975. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  15976. s, i, r, o) {
  15977. const u = new jc(t, e, n, s, i, r);
  15978. return o && (u.vc = !0), u;
  15979. }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);
  15980. }
  15981. terminate() {
  15982. return async function(t) {
  15983. const e = U(t);
  15984. $("RemoteStore", "RemoteStore shutting down."), e.vu.add(5 /* OfflineCause.Shutdown */),
  15985. await Yu(e), e.Pu.shutdown(),
  15986. // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
  15987. // triggering spurious listener events with cached data, etc.
  15988. e.bu.set("Unknown" /* OnlineState.Unknown */);
  15989. }(this.remoteStore);
  15990. }
  15991. }
  15992. /**
  15993. * @license
  15994. * Copyright 2020 Google LLC
  15995. *
  15996. * Licensed under the Apache License, Version 2.0 (the "License");
  15997. * you may not use this file except in compliance with the License.
  15998. * You may obtain a copy of the License at
  15999. *
  16000. * http://www.apache.org/licenses/LICENSE-2.0
  16001. *
  16002. * Unless required by applicable law or agreed to in writing, software
  16003. * distributed under the License is distributed on an "AS IS" BASIS,
  16004. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16005. * See the License for the specific language governing permissions and
  16006. * limitations under the License.
  16007. */
  16008. /**
  16009. * How many bytes to read each time when `ReadableStreamReader.read()` is
  16010. * called. Only applicable for byte streams that we control (e.g. those backed
  16011. * by an UInt8Array).
  16012. */
  16013. /**
  16014. * Builds a `ByteStreamReader` from a UInt8Array.
  16015. * @param source - The data source to use.
  16016. * @param bytesPerRead - How many bytes each `read()` from the returned reader
  16017. * will read.
  16018. */
  16019. function Da(t, e = 10240) {
  16020. let n = 0;
  16021. // The TypeScript definition for ReadableStreamReader changed. We use
  16022. // `any` here to allow this code to compile with different versions.
  16023. // See https://github.com/microsoft/TypeScript/issues/42970
  16024. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16025. return {
  16026. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16027. async read() {
  16028. if (n < t.byteLength) {
  16029. const s = {
  16030. value: t.slice(n, n + e),
  16031. done: !1
  16032. };
  16033. return n += e, s;
  16034. }
  16035. return {
  16036. done: !0
  16037. };
  16038. },
  16039. async cancel() {},
  16040. releaseLock() {},
  16041. closed: Promise.resolve()
  16042. };
  16043. }
  16044. /**
  16045. * @license
  16046. * Copyright 2020 Google LLC
  16047. *
  16048. * Licensed under the Apache License, Version 2.0 (the "License");
  16049. * you may not use this file except in compliance with the License.
  16050. * You may obtain a copy of the License at
  16051. *
  16052. * http://www.apache.org/licenses/LICENSE-2.0
  16053. *
  16054. * Unless required by applicable law or agreed to in writing, software
  16055. * distributed under the License is distributed on an "AS IS" BASIS,
  16056. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16057. * See the License for the specific language governing permissions and
  16058. * limitations under the License.
  16059. */
  16060. /**
  16061. * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.
  16062. */
  16063. /**
  16064. * @license
  16065. * Copyright 2017 Google LLC
  16066. *
  16067. * Licensed under the Apache License, Version 2.0 (the "License");
  16068. * you may not use this file except in compliance with the License.
  16069. * You may obtain a copy of the License at
  16070. *
  16071. * http://www.apache.org/licenses/LICENSE-2.0
  16072. *
  16073. * Unless required by applicable law or agreed to in writing, software
  16074. * distributed under the License is distributed on an "AS IS" BASIS,
  16075. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16076. * See the License for the specific language governing permissions and
  16077. * limitations under the License.
  16078. */
  16079. /*
  16080. * A wrapper implementation of Observer<T> that will dispatch events
  16081. * asynchronously. To allow immediate silencing, a mute call is added which
  16082. * causes events scheduled to no longer be raised.
  16083. */
  16084. class Ca {
  16085. constructor(t) {
  16086. this.observer = t,
  16087. /**
  16088. * When set to true, will not raise future events. Necessary to deal with
  16089. * async detachment of listener.
  16090. */
  16091. this.muted = !1;
  16092. }
  16093. next(t) {
  16094. this.observer.next && this.Sc(this.observer.next, t);
  16095. }
  16096. error(t) {
  16097. this.observer.error ? this.Sc(this.observer.error, t) : M("Uncaught Error in snapshot listener:", t.toString());
  16098. }
  16099. Dc() {
  16100. this.muted = !0;
  16101. }
  16102. Sc(t, e) {
  16103. this.muted || setTimeout((() => {
  16104. this.muted || t(e);
  16105. }), 0);
  16106. }
  16107. }
  16108. /**
  16109. * @license
  16110. * Copyright 2020 Google LLC
  16111. *
  16112. * Licensed under the Apache License, Version 2.0 (the "License");
  16113. * you may not use this file except in compliance with the License.
  16114. * You may obtain a copy of the License at
  16115. *
  16116. * http://www.apache.org/licenses/LICENSE-2.0
  16117. *
  16118. * Unless required by applicable law or agreed to in writing, software
  16119. * distributed under the License is distributed on an "AS IS" BASIS,
  16120. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16121. * See the License for the specific language governing permissions and
  16122. * limitations under the License.
  16123. */
  16124. /**
  16125. * A class representing a bundle.
  16126. *
  16127. * Takes a bundle stream or buffer, and presents abstractions to read bundled
  16128. * elements out of the underlying content.
  16129. */ class xa {
  16130. constructor(
  16131. /** The reader to read from underlying binary bundle data source. */
  16132. t, e) {
  16133. this.Cc = t, this.serializer = e,
  16134. /** Cached bundle metadata. */
  16135. this.metadata = new Q,
  16136. /**
  16137. * Internal buffer to hold bundle content, accumulating incomplete element
  16138. * content.
  16139. */
  16140. this.buffer = new Uint8Array, this.xc = new TextDecoder("utf-8"),
  16141. // Read the metadata (which is the first element).
  16142. this.Nc().then((t => {
  16143. t && t.Qu() ? this.metadata.resolve(t.Gu.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null == t ? void 0 : t.Gu)}`));
  16144. }), (t => this.metadata.reject(t)));
  16145. }
  16146. close() {
  16147. return this.Cc.cancel();
  16148. }
  16149. async getMetadata() {
  16150. return this.metadata.promise;
  16151. }
  16152. async bc() {
  16153. // Makes sure metadata is read before proceeding.
  16154. return await this.getMetadata(), this.Nc();
  16155. }
  16156. /**
  16157. * Reads from the head of internal buffer, and pulling more data from
  16158. * underlying stream if a complete element cannot be found, until an
  16159. * element(including the prefixed length and the JSON string) is found.
  16160. *
  16161. * Once a complete element is read, it is dropped from internal buffer.
  16162. *
  16163. * Returns either the bundled element, or null if we have reached the end of
  16164. * the stream.
  16165. */ async Nc() {
  16166. const t = await this.kc();
  16167. if (null === t) return null;
  16168. const e = this.xc.decode(t), n = Number(e);
  16169. isNaN(n) && this.$c(`length string (${e}) is not valid number`);
  16170. const s = await this.Mc(n);
  16171. return new Oc(JSON.parse(s), t.length + n);
  16172. }
  16173. /** First index of '{' from the underlying buffer. */ Oc() {
  16174. return this.buffer.findIndex((t => t === "{".charCodeAt(0)));
  16175. }
  16176. /**
  16177. * Reads from the beginning of the internal buffer, until the first '{', and
  16178. * return the content.
  16179. *
  16180. * If reached end of the stream, returns a null.
  16181. */ async kc() {
  16182. for (;this.Oc() < 0; ) {
  16183. if (await this.Fc()) break;
  16184. }
  16185. // Broke out of the loop because underlying stream is closed, and there
  16186. // happens to be no more data to process.
  16187. if (0 === this.buffer.length) return null;
  16188. const t = this.Oc();
  16189. // Broke out of the loop because underlying stream is closed, but still
  16190. // cannot find an open bracket.
  16191. t < 0 && this.$c("Reached the end of bundle when a length string is expected.");
  16192. const e = this.buffer.slice(0, t);
  16193. // Update the internal buffer to drop the read length.
  16194. return this.buffer = this.buffer.slice(t), e;
  16195. }
  16196. /**
  16197. * Reads from a specified position from the internal buffer, for a specified
  16198. * number of bytes, pulling more data from the underlying stream if needed.
  16199. *
  16200. * Returns a string decoded from the read bytes.
  16201. */ async Mc(t) {
  16202. for (;this.buffer.length < t; ) {
  16203. await this.Fc() && this.$c("Reached the end of bundle when more is expected.");
  16204. }
  16205. const e = this.xc.decode(this.buffer.slice(0, t));
  16206. // Update the internal buffer to drop the read json string.
  16207. return this.buffer = this.buffer.slice(t), e;
  16208. }
  16209. $c(t) {
  16210. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16211. throw this.Cc.cancel(), new Error(`Invalid bundle format: ${t}`);
  16212. }
  16213. /**
  16214. * Pulls more data from underlying stream to internal buffer.
  16215. * Returns a boolean indicating whether the stream is finished.
  16216. */ async Fc() {
  16217. const t = await this.Cc.read();
  16218. if (!t.done) {
  16219. const e = new Uint8Array(this.buffer.length + t.value.length);
  16220. e.set(this.buffer), e.set(t.value, this.buffer.length), this.buffer = e;
  16221. }
  16222. return t.done;
  16223. }
  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. * Internal transaction object responsible for accumulating the mutations to
  16243. * perform and the base versions for any documents read.
  16244. */
  16245. class Na {
  16246. constructor(t) {
  16247. this.datastore = t,
  16248. // The version of each document that was read during this transaction.
  16249. this.readVersions = new Map, this.mutations = [], this.committed = !1,
  16250. /**
  16251. * A deferred usage error that occurred previously in this transaction that
  16252. * will cause the transaction to fail once it actually commits.
  16253. */
  16254. this.lastWriteError = null,
  16255. /**
  16256. * Set of documents that have been written in the transaction.
  16257. *
  16258. * When there's more than one write to the same key in a transaction, any
  16259. * writes after the first are handled differently.
  16260. */
  16261. this.writtenDocs = new Set;
  16262. }
  16263. async lookup(t) {
  16264. if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new G(K.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes.");
  16265. const e = await async function(t, e) {
  16266. const n = U(t), s = Ki(n.serializer) + "/documents", i = {
  16267. documents: e.map((t => Bi(n.serializer, t)))
  16268. }, r = await n.vo("BatchGetDocuments", s, i, e.length), o = new Map;
  16269. r.forEach((t => {
  16270. const e = zi(n.serializer, t);
  16271. o.set(e.key.toString(), e);
  16272. }));
  16273. const u = [];
  16274. return e.forEach((t => {
  16275. const e = o.get(t.toString());
  16276. L(!!e), u.push(e);
  16277. })), u;
  16278. }(this.datastore, t);
  16279. return e.forEach((t => this.recordVersion(t))), e;
  16280. }
  16281. set(t, e) {
  16282. this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16283. }
  16284. update(t, e) {
  16285. try {
  16286. this.write(e.toMutation(t, this.preconditionForUpdate(t)));
  16287. } catch (t) {
  16288. this.lastWriteError = t;
  16289. }
  16290. this.writtenDocs.add(t.toString());
  16291. }
  16292. delete(t) {
  16293. this.write(new ti(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16294. }
  16295. async commit() {
  16296. if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;
  16297. const t = this.readVersions;
  16298. // For each mutation, note that the doc was written.
  16299. this.mutations.forEach((e => {
  16300. t.delete(e.key.toString());
  16301. })),
  16302. // For each document that was read but not written to, we want to perform
  16303. // a `verify` operation.
  16304. t.forEach(((t, e) => {
  16305. const n = ft.fromPath(e);
  16306. this.mutations.push(new ei(n, this.precondition(n)));
  16307. })), await async function(t, e) {
  16308. const n = U(t), s = Ki(n.serializer) + "/documents", i = {
  16309. writes: e.map((t => Hi(n.serializer, t)))
  16310. };
  16311. await n.Io("Commit", s, i);
  16312. }(this.datastore, this.mutations), this.committed = !0;
  16313. }
  16314. recordVersion(t) {
  16315. let e;
  16316. if (t.isFoundDocument()) e = t.version; else {
  16317. if (!t.isNoDocument()) throw B();
  16318. // Represent a deleted doc using SnapshotVersion.min().
  16319. e = ut.min();
  16320. }
  16321. const n = this.readVersions.get(t.key.toString());
  16322. if (n) {
  16323. if (!e.isEqual(n))
  16324. // This transaction will fail no matter what.
  16325. throw new G(K.ABORTED, "Document version changed between two reads.");
  16326. } else this.readVersions.set(t.key.toString(), e);
  16327. }
  16328. /**
  16329. * Returns the version of this document when it was read in this transaction,
  16330. * as a precondition, or no precondition if it was not read.
  16331. */ precondition(t) {
  16332. const e = this.readVersions.get(t.toString());
  16333. return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(ut.min()) ? qs.exists(!1) : qs.updateTime(e) : qs.none();
  16334. }
  16335. /**
  16336. * Returns the precondition for a document if the operation is an update.
  16337. */ preconditionForUpdate(t) {
  16338. const e = this.readVersions.get(t.toString());
  16339. // The first time a document is written, we want to take into account the
  16340. // read time and existence
  16341. if (!this.writtenDocs.has(t.toString()) && e) {
  16342. if (e.isEqual(ut.min()))
  16343. // The document doesn't exist, so fail the transaction.
  16344. // This has to be validated locally because you can't send a
  16345. // precondition that a document does not exist without changing the
  16346. // semantics of the backend write to be an insert. This is the reverse
  16347. // of what we want, since we want to assert that the document doesn't
  16348. // exist but then send the update and have it fail. Since we can't
  16349. // express that to the backend, we have to validate locally.
  16350. // Note: this can change once we can send separate verify writes in the
  16351. // transaction.
  16352. throw new G(K.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
  16353. // Document exists, base precondition on document update time.
  16354. return qs.updateTime(e);
  16355. }
  16356. // Document was not read, so we just use the preconditions for a blind
  16357. // update.
  16358. return qs.exists(!0);
  16359. }
  16360. write(t) {
  16361. this.ensureCommitNotCalled(), this.mutations.push(t);
  16362. }
  16363. ensureCommitNotCalled() {}
  16364. }
  16365. /**
  16366. * @license
  16367. * Copyright 2019 Google LLC
  16368. *
  16369. * Licensed under the Apache License, Version 2.0 (the "License");
  16370. * you may not use this file except in compliance with the License.
  16371. * You may obtain a copy of the License at
  16372. *
  16373. * http://www.apache.org/licenses/LICENSE-2.0
  16374. *
  16375. * Unless required by applicable law or agreed to in writing, software
  16376. * distributed under the License is distributed on an "AS IS" BASIS,
  16377. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16378. * See the License for the specific language governing permissions and
  16379. * limitations under the License.
  16380. */
  16381. /**
  16382. * TransactionRunner encapsulates the logic needed to run and retry transactions
  16383. * with backoff.
  16384. */ class ka {
  16385. constructor(t, e, n, s, i) {
  16386. this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = s,
  16387. this.deferred = i, this.Bc = n.maxAttempts, this.qo = new Uu(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */);
  16388. }
  16389. /** Runs the transaction and sets the result on deferred. */ run() {
  16390. this.Bc -= 1, this.Lc();
  16391. }
  16392. Lc() {
  16393. this.qo.No((async () => {
  16394. const t = new Na(this.datastore), e = this.qc(t);
  16395. e && e.then((e => {
  16396. this.asyncQueue.enqueueAndForget((() => t.commit().then((() => {
  16397. this.deferred.resolve(e);
  16398. })).catch((t => {
  16399. this.Uc(t);
  16400. }))));
  16401. })).catch((t => {
  16402. this.Uc(t);
  16403. }));
  16404. }));
  16405. }
  16406. qc(t) {
  16407. try {
  16408. const e = this.updateFunction(t);
  16409. return !Lt(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")),
  16410. null);
  16411. } catch (t) {
  16412. // Do not retry errors thrown by user provided updateFunction.
  16413. return this.deferred.reject(t), null;
  16414. }
  16415. }
  16416. Uc(t) {
  16417. this.Bc > 0 && this.Kc(t) ? (this.Bc -= 1, this.asyncQueue.enqueueAndForget((() => (this.Lc(),
  16418. Promise.resolve())))) : this.deferred.reject(t);
  16419. }
  16420. Kc(t) {
  16421. if ("FirebaseError" === t.name) {
  16422. // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
  16423. // non-matching document versions with ABORTED. These errors should be retried.
  16424. const e = t.code;
  16425. return "aborted" === e || "failed-precondition" === e || "already-exists" === e || !ai(e);
  16426. }
  16427. return !1;
  16428. }
  16429. }
  16430. /**
  16431. * @license
  16432. * Copyright 2017 Google LLC
  16433. *
  16434. * Licensed under the Apache License, Version 2.0 (the "License");
  16435. * you may not use this file except in compliance with the License.
  16436. * You may obtain a copy of the License at
  16437. *
  16438. * http://www.apache.org/licenses/LICENSE-2.0
  16439. *
  16440. * Unless required by applicable law or agreed to in writing, software
  16441. * distributed under the License is distributed on an "AS IS" BASIS,
  16442. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16443. * See the License for the specific language governing permissions and
  16444. * limitations under the License.
  16445. */
  16446. /**
  16447. * FirestoreClient is a top-level class that constructs and owns all of the //
  16448. * pieces of the client SDK architecture. It is responsible for creating the //
  16449. * async queue that is shared by all of the other components in the system. //
  16450. */
  16451. class $a {
  16452. constructor(t, e,
  16453. /**
  16454. * Asynchronous queue responsible for all of our internal processing. When
  16455. * we get incoming work from the user (via public API) or the network
  16456. * (incoming GRPC messages), we should always schedule onto this queue.
  16457. * This ensures all of our work is properly serialized (e.g. we don't
  16458. * start processing a new operation while the previous one is waiting for
  16459. * an async I/O to complete).
  16460. */
  16461. n, s) {
  16462. this.authCredentials = t, this.appCheckCredentials = e, this.asyncQueue = n, this.databaseInfo = s,
  16463. this.user = D.UNAUTHENTICATED, this.clientId = nt.A(), this.authCredentialListener = () => Promise.resolve(),
  16464. this.appCheckCredentialListener = () => Promise.resolve(), this.authCredentials.start(n, (async t => {
  16465. $("FirestoreClient", "Received user=", t.uid), await this.authCredentialListener(t),
  16466. this.user = t;
  16467. })), this.appCheckCredentials.start(n, (t => ($("FirestoreClient", "Received new app check token=", t),
  16468. this.appCheckCredentialListener(t, this.user))));
  16469. }
  16470. async getConfiguration() {
  16471. return {
  16472. asyncQueue: this.asyncQueue,
  16473. databaseInfo: this.databaseInfo,
  16474. clientId: this.clientId,
  16475. authCredentials: this.authCredentials,
  16476. appCheckCredentials: this.appCheckCredentials,
  16477. initialUser: this.user,
  16478. maxConcurrentLimboResolutions: 100
  16479. };
  16480. }
  16481. setCredentialChangeListener(t) {
  16482. this.authCredentialListener = t;
  16483. }
  16484. setAppCheckTokenChangeListener(t) {
  16485. this.appCheckCredentialListener = t;
  16486. }
  16487. /**
  16488. * Checks that the client has not been terminated. Ensures that other methods on //
  16489. * this class cannot be called after the client is terminated. //
  16490. */ verifyNotTerminated() {
  16491. if (this.asyncQueue.isShuttingDown) throw new G(K.FAILED_PRECONDITION, "The client has already been terminated.");
  16492. }
  16493. terminate() {
  16494. this.asyncQueue.enterRestrictedMode();
  16495. const t = new Q;
  16496. return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {
  16497. try {
  16498. this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(),
  16499. // The credentials provider must be terminated after shutting down the
  16500. // RemoteStore as it will prevent the RemoteStore from retrieving auth
  16501. // tokens.
  16502. this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), t.resolve();
  16503. } catch (e) {
  16504. const n = Rc(e, "Failed to shutdown persistence");
  16505. t.reject(n);
  16506. }
  16507. })), t.promise;
  16508. }
  16509. }
  16510. async function Ma(t, e) {
  16511. t.asyncQueue.verifyOperationInProgress(), $("FirestoreClient", "Initializing OfflineComponentProvider");
  16512. const n = await t.getConfiguration();
  16513. await e.initialize(n);
  16514. let s = n.initialUser;
  16515. t.setCredentialChangeListener((async t => {
  16516. s.isEqual(t) || (await uu(e.localStore, t), s = t);
  16517. })),
  16518. // When a user calls clearPersistence() in one client, all other clients
  16519. // need to be terminated to allow the delete to succeed.
  16520. e.persistence.setDatabaseDeletedListener((() => t.terminate())), t._offlineComponents = e;
  16521. }
  16522. async function Oa(t, e) {
  16523. t.asyncQueue.verifyOperationInProgress();
  16524. const n = await Ba(t);
  16525. $("FirestoreClient", "Initializing OnlineComponentProvider");
  16526. const s = await t.getConfiguration();
  16527. await e.initialize(n, s),
  16528. // The CredentialChangeListener of the online component provider takes
  16529. // precedence over the offline component provider.
  16530. t.setCredentialChangeListener((t => Ic(e.remoteStore, t))), t.setAppCheckTokenChangeListener(((t, n) => Ic(e.remoteStore, n))),
  16531. t._onlineComponents = e;
  16532. }
  16533. /**
  16534. * Decides whether the provided error allows us to gracefully disable
  16535. * persistence (as opposed to crashing the client).
  16536. */ function Fa(t) {
  16537. return "FirebaseError" === t.name ? t.code === K.FAILED_PRECONDITION || t.code === K.UNIMPLEMENTED : !("undefined" != typeof DOMException && t instanceof DOMException) || (
  16538. // When the browser is out of quota we could get either quota exceeded
  16539. // or an aborted error depending on whether the error happened during
  16540. // schema migration.
  16541. 22 === t.code || 20 === t.code ||
  16542. // Firefox Private Browsing mode disables IndexedDb and returns
  16543. // INVALID_STATE for any usage.
  16544. 11 === t.code);
  16545. }
  16546. async function Ba(t) {
  16547. if (!t._offlineComponents) if (t._uninitializedComponentsProvider) {
  16548. $("FirestoreClient", "Using user provided OfflineComponentProvider");
  16549. try {
  16550. await Ma(t, t._uninitializedComponentsProvider._offline);
  16551. } catch (e) {
  16552. const n = e;
  16553. if (!Fa(n)) throw n;
  16554. O("Error using user provided cache. Falling back to memory cache: " + n), await Ma(t, new Ra);
  16555. }
  16556. } else $("FirestoreClient", "Using default OfflineComponentProvider"), await Ma(t, new Ra);
  16557. return t._offlineComponents;
  16558. }
  16559. async function La(t) {
  16560. return t._onlineComponents || (t._uninitializedComponentsProvider ? ($("FirestoreClient", "Using user provided OnlineComponentProvider"),
  16561. await Oa(t, t._uninitializedComponentsProvider._online)) : ($("FirestoreClient", "Using default OnlineComponentProvider"),
  16562. await Oa(t, new Sa))), t._onlineComponents;
  16563. }
  16564. function qa(t) {
  16565. return Ba(t).then((t => t.persistence));
  16566. }
  16567. function Ua(t) {
  16568. return Ba(t).then((t => t.localStore));
  16569. }
  16570. function Ka(t) {
  16571. return La(t).then((t => t.remoteStore));
  16572. }
  16573. function Ga(t) {
  16574. return La(t).then((t => t.syncEngine));
  16575. }
  16576. function Qa(t) {
  16577. return La(t).then((t => t.datastore));
  16578. }
  16579. async function ja(t) {
  16580. const e = await La(t), n = e.eventManager;
  16581. return n.onListen = zc.bind(null, e.syncEngine), n.onUnlisten = Hc.bind(null, e.syncEngine),
  16582. n;
  16583. }
  16584. /** Enables the network connection and re-enqueues all pending operations. */ function za(t) {
  16585. return t.asyncQueue.enqueue((async () => {
  16586. const e = await qa(t), n = await Ka(t);
  16587. return e.setNetworkEnabled(!0), function(t) {
  16588. const e = U(t);
  16589. return e.vu.delete(0 /* OfflineCause.UserDisabled */), Ju(e);
  16590. }(n);
  16591. }));
  16592. }
  16593. /** Disables the network connection. Pending operations will not complete. */ function Wa(t) {
  16594. return t.asyncQueue.enqueue((async () => {
  16595. const e = await qa(t), n = await Ka(t);
  16596. return e.setNetworkEnabled(!1), async function(t) {
  16597. const e = U(t);
  16598. e.vu.add(0 /* OfflineCause.UserDisabled */), await Yu(e),
  16599. // Set the OnlineState to Offline so get()s return from cache, etc.
  16600. e.bu.set("Offline" /* OnlineState.Offline */);
  16601. }(n);
  16602. }));
  16603. }
  16604. /**
  16605. * Returns a Promise that resolves when all writes that were pending at the time
  16606. * this method was called received server acknowledgement. An acknowledgement
  16607. * can be either acceptance or rejection.
  16608. */ function Ha(t, e) {
  16609. const n = new Q;
  16610. return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {
  16611. try {
  16612. const s = await function(t, e) {
  16613. const n = U(t);
  16614. return n.persistence.runTransaction("read document", "readonly", (t => n.localDocuments.getDocument(t, e)));
  16615. }(t, e);
  16616. s.isFoundDocument() ? n.resolve(s) : s.isNoDocument() ? n.resolve(null) : n.reject(new G(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.)"));
  16617. } catch (t) {
  16618. const s = Rc(t, `Failed to get document '${e} from cache`);
  16619. n.reject(s);
  16620. }
  16621. }
  16622. /**
  16623. * Retrieves a latency-compensated document from the backend via a
  16624. * SnapshotListener.
  16625. */ (await Ua(t), e, n))), n.promise;
  16626. }
  16627. function Ja(t, e, n = {}) {
  16628. const s = new Q;
  16629. return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {
  16630. const r = new Ca({
  16631. next: r => {
  16632. // Remove query first before passing event to user to avoid
  16633. // user actions affecting the now stale query.
  16634. e.enqueueAndForget((() => xc(t, o)));
  16635. const u = r.docs.has(n);
  16636. !u && r.fromCache ?
  16637. // TODO(dimond): If we're online and the document doesn't
  16638. // exist then we resolve with a doc.exists set to false. If
  16639. // we're offline however, we reject the Promise in this
  16640. // case. Two options: 1) Cache the negative response from
  16641. // the server so we can deliver that even when you're
  16642. // offline 2) Actually reject the Promise in the online case
  16643. // if the document doesn't exist.
  16644. i.reject(new G(K.UNAVAILABLE, "Failed to get document because the client is offline.")) : u && r.fromCache && s && "server" === s.source ? i.reject(new G(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(r);
  16645. },
  16646. error: t => i.reject(t)
  16647. }), o = new Mc(zn(n.path), r, {
  16648. includeMetadataChanges: !0,
  16649. Ku: !0
  16650. });
  16651. return Cc(t, o);
  16652. }(await ja(t), t.asyncQueue, e, n, s))), s.promise;
  16653. }
  16654. function Ya(t, e) {
  16655. const n = new Q;
  16656. return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {
  16657. try {
  16658. const s = await _u(t, e,
  16659. /* usePreviousResults= */ !0), i = new Kc(e, s.ir), r = i.sc(s.documents), o = i.applyChanges(r,
  16660. /* updateLimboDocuments= */ !1);
  16661. n.resolve(o.snapshot);
  16662. } catch (t) {
  16663. const s = Rc(t, `Failed to execute query '${e} against cache`);
  16664. n.reject(s);
  16665. }
  16666. }
  16667. /**
  16668. * Retrieves a latency-compensated query snapshot from the backend via a
  16669. * SnapshotListener.
  16670. */ (await Ua(t), e, n))), n.promise;
  16671. }
  16672. function Xa(t, e, n = {}) {
  16673. const s = new Q;
  16674. return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {
  16675. const r = new Ca({
  16676. next: n => {
  16677. // Remove query first before passing event to user to avoid
  16678. // user actions affecting the now stale query.
  16679. e.enqueueAndForget((() => xc(t, o))), n.fromCache && "server" === s.source ? i.reject(new G(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);
  16680. },
  16681. error: t => i.reject(t)
  16682. }), o = new Mc(n, r, {
  16683. includeMetadataChanges: !0,
  16684. Ku: !0
  16685. });
  16686. return Cc(t, o);
  16687. }(await ja(t), t.asyncQueue, e, n, s))), s.promise;
  16688. }
  16689. function Za(t, e) {
  16690. const n = new Ca(e);
  16691. return t.asyncQueue.enqueueAndForget((async () => function(t, e) {
  16692. U(t).ku.add(e),
  16693. // Immediately fire an initial event, indicating all existing listeners
  16694. // are in-sync.
  16695. e.next();
  16696. }(await ja(t), n))), () => {
  16697. n.Dc(), t.asyncQueue.enqueueAndForget((async () => function(t, e) {
  16698. U(t).ku.delete(e);
  16699. }(await ja(t), n)));
  16700. };
  16701. }
  16702. /**
  16703. * Takes an updateFunction in which a set of reads and writes can be performed
  16704. * atomically. In the updateFunction, the client can read and write values
  16705. * using the supplied transaction object. After the updateFunction, all
  16706. * changes will be committed. If a retryable error occurs (ex: some other
  16707. * client has changed any of the data referenced), then the updateFunction
  16708. * will be called again after a backoff. If the updateFunction still fails
  16709. * after all retries, then the transaction will be rejected.
  16710. *
  16711. * The transaction object passed to the updateFunction contains methods for
  16712. * accessing documents and collections. Unlike other datastore access, data
  16713. * accessed with the transaction will not reflect local changes that have not
  16714. * been committed. For this reason, it is required that all reads are
  16715. * performed before any writes. Transactions must be performed while online.
  16716. */ function th(t, e, n, s) {
  16717. const i = function(t, e) {
  16718. let n;
  16719. n = "string" == typeof t ? di().encode(t) : t;
  16720. return function(t, e) {
  16721. return new xa(t, e);
  16722. }(function(t, e) {
  16723. if (t instanceof Uint8Array) return Da(t, e);
  16724. if (t instanceof ArrayBuffer) return Da(new Uint8Array(t), e);
  16725. if (t instanceof ReadableStream) return t.getReader();
  16726. throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream");
  16727. }(n), e);
  16728. }(n, qu(e));
  16729. t.asyncQueue.enqueueAndForget((async () => {
  16730. va(await Ga(t), i, s);
  16731. }));
  16732. }
  16733. function eh(t, e) {
  16734. return t.asyncQueue.enqueue((async () => function(t, e) {
  16735. const n = U(t);
  16736. return n.persistence.runTransaction("Get named query", "readonly", (t => n.qs.getNamedQuery(t, e)));
  16737. }(await Ua(t), e)));
  16738. }
  16739. function nh(t, e) {
  16740. return t.asyncQueue.enqueue((async () => async function(t, e) {
  16741. const n = U(t), s = n.indexManager, i = [];
  16742. return n.persistence.runTransaction("Configure indexes", "readwrite", (t => s.getFieldIndexes(t).next((n =>
  16743. /**
  16744. * @license
  16745. * Copyright 2017 Google LLC
  16746. *
  16747. * Licensed under the Apache License, Version 2.0 (the "License");
  16748. * you may not use this file except in compliance with the License.
  16749. * You may obtain a copy of the License at
  16750. *
  16751. * http://www.apache.org/licenses/LICENSE-2.0
  16752. *
  16753. * Unless required by applicable law or agreed to in writing, software
  16754. * distributed under the License is distributed on an "AS IS" BASIS,
  16755. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16756. * See the License for the specific language governing permissions and
  16757. * limitations under the License.
  16758. */
  16759. /**
  16760. * Compares two array for equality using comparator. The method computes the
  16761. * intersection and invokes `onAdd` for every element that is in `after` but not
  16762. * `before`. `onRemove` is invoked for every element in `before` but missing
  16763. * from `after`.
  16764. *
  16765. * The method creates a copy of both `before` and `after` and runs in O(n log
  16766. * n), where n is the size of the two lists.
  16767. *
  16768. * @param before - The elements that exist in the original array.
  16769. * @param after - The elements to diff against the original array.
  16770. * @param comparator - The comparator for the elements in before and after.
  16771. * @param onAdd - A function to invoke for every element that is part of `
  16772. * after` but not `before`.
  16773. * @param onRemove - A function to invoke for every element that is part of
  16774. * `before` but not `after`.
  16775. */
  16776. function(t, e, n, s, i) {
  16777. t = [ ...t ], e = [ ...e ], t.sort(n), e.sort(n);
  16778. const r = t.length, o = e.length;
  16779. let u = 0, c = 0;
  16780. for (;u < o && c < r; ) {
  16781. const r = n(t[c], e[u]);
  16782. r < 0 ?
  16783. // The element was removed if the next element in our ordered
  16784. // walkthrough is only in `before`.
  16785. i(t[c++]) : r > 0 ?
  16786. // The element was added if the next element in our ordered walkthrough
  16787. // is only in `after`.
  16788. s(e[u++]) : (u++, c++);
  16789. }
  16790. for (;u < o; ) s(e[u++]);
  16791. for (;c < r; ) i(t[c++]);
  16792. }(n, e, mt, (e => {
  16793. i.push(s.addFieldIndex(t, e));
  16794. }), (e => {
  16795. i.push(s.deleteFieldIndex(t, e));
  16796. })))).next((() => bt.waitFor(i)))));
  16797. }
  16798. /**
  16799. * @license
  16800. * Copyright 2019 Google LLC
  16801. *
  16802. * Licensed under the Apache License, Version 2.0 (the "License");
  16803. * you may not use this file except in compliance with the License.
  16804. * You may obtain a copy of the License at
  16805. *
  16806. * http://www.apache.org/licenses/LICENSE-2.0
  16807. *
  16808. * Unless required by applicable law or agreed to in writing, software
  16809. * distributed under the License is distributed on an "AS IS" BASIS,
  16810. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16811. * See the License for the specific language governing permissions and
  16812. * limitations under the License.
  16813. */
  16814. // The format of the LocalStorage key that stores the client state is:
  16815. // firestore_clients_<persistence_prefix>_<instance_key>
  16816. (await Ua(t), e)));
  16817. }
  16818. /**
  16819. * @license
  16820. * Copyright 2023 Google LLC
  16821. *
  16822. * Licensed under the Apache License, Version 2.0 (the "License");
  16823. * you may not use this file except in compliance with the License.
  16824. * You may obtain a copy of the License at
  16825. *
  16826. * http://www.apache.org/licenses/LICENSE-2.0
  16827. *
  16828. * Unless required by applicable law or agreed to in writing, software
  16829. * distributed under the License is distributed on an "AS IS" BASIS,
  16830. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16831. * See the License for the specific language governing permissions and
  16832. * limitations under the License.
  16833. */
  16834. /**
  16835. * Compares two `ExperimentalLongPollingOptions` objects for equality.
  16836. */
  16837. /**
  16838. * Creates and returns a new `ExperimentalLongPollingOptions` with the same
  16839. * option values as the given instance.
  16840. */
  16841. function sh(t) {
  16842. const e = {};
  16843. return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e;
  16844. }
  16845. /**
  16846. * @license
  16847. * Copyright 2020 Google LLC
  16848. *
  16849. * Licensed under the Apache License, Version 2.0 (the "License");
  16850. * you may not use this file except in compliance with the License.
  16851. * You may obtain a copy of the License at
  16852. *
  16853. * http://www.apache.org/licenses/LICENSE-2.0
  16854. *
  16855. * Unless required by applicable law or agreed to in writing, software
  16856. * distributed under the License is distributed on an "AS IS" BASIS,
  16857. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16858. * See the License for the specific language governing permissions and
  16859. * limitations under the License.
  16860. */ const ih = new Map;
  16861. /**
  16862. * An instance map that ensures only one Datastore exists per Firestore
  16863. * instance.
  16864. */
  16865. /**
  16866. * @license
  16867. * Copyright 2017 Google LLC
  16868. *
  16869. * Licensed under the Apache License, Version 2.0 (the "License");
  16870. * you may not use this file except in compliance with the License.
  16871. * You may obtain a copy of the License at
  16872. *
  16873. * http://www.apache.org/licenses/LICENSE-2.0
  16874. *
  16875. * Unless required by applicable law or agreed to in writing, software
  16876. * distributed under the License is distributed on an "AS IS" BASIS,
  16877. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16878. * See the License for the specific language governing permissions and
  16879. * limitations under the License.
  16880. */
  16881. function rh(t, e, n) {
  16882. if (!n) throw new G(K.INVALID_ARGUMENT, `Function ${t}() cannot be called with an empty ${e}.`);
  16883. }
  16884. /**
  16885. * Validates that two boolean options are not set at the same time.
  16886. * @internal
  16887. */ function oh(t, e, n, s) {
  16888. if (!0 === e && !0 === s) throw new G(K.INVALID_ARGUMENT, `${t} and ${n} cannot be used together.`);
  16889. }
  16890. /**
  16891. * Validates that `path` refers to a document (indicated by the fact it contains
  16892. * an even numbers of segments).
  16893. */ function uh(t) {
  16894. if (!ft.isDocumentKey(t)) throw new G(K.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);
  16895. }
  16896. /**
  16897. * Validates that `path` refers to a collection (indicated by the fact it
  16898. * contains an odd numbers of segments).
  16899. */ function ch(t) {
  16900. if (ft.isDocumentKey(t)) throw new G(K.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);
  16901. }
  16902. /**
  16903. * Returns true if it's a non-null object without a custom prototype
  16904. * (i.e. excludes Array, Date, etc.).
  16905. */
  16906. /** Returns a string describing the type / value of the provided input. */
  16907. function ah(t) {
  16908. if (void 0 === t) return "undefined";
  16909. if (null === t) return "null";
  16910. if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`),
  16911. JSON.stringify(t);
  16912. if ("number" == typeof t || "boolean" == typeof t) return "" + t;
  16913. if ("object" == typeof t) {
  16914. if (t instanceof Array) return "an array";
  16915. {
  16916. const e =
  16917. /** try to get the constructor name for an object. */
  16918. function(t) {
  16919. if (t.constructor) return t.constructor.name;
  16920. return null;
  16921. }
  16922. /**
  16923. * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
  16924. * underlying instance. Throws if `obj` is not an instance of `T`.
  16925. *
  16926. * This cast is used in the Lite and Full SDK to verify instance types for
  16927. * arguments passed to the public API.
  16928. * @internal
  16929. */ (t);
  16930. return e ? `a custom ${e} object` : "an object";
  16931. }
  16932. }
  16933. return "function" == typeof t ? "a function" : B();
  16934. }
  16935. function hh(t,
  16936. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16937. e) {
  16938. if ("_delegate" in t && (
  16939. // Unwrap Compat types
  16940. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  16941. t = t._delegate), !(t instanceof e)) {
  16942. if (e.name === t.constructor.name) throw new G(K.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
  16943. {
  16944. const n = ah(t);
  16945. throw new G(K.INVALID_ARGUMENT, `Expected type '${e.name}', but it was: ${n}`);
  16946. }
  16947. }
  16948. return t;
  16949. }
  16950. function lh(t, e) {
  16951. if (e <= 0) throw new G(K.INVALID_ARGUMENT, `Function ${t}() requires a positive number, but it was: ${e}.`);
  16952. }
  16953. /**
  16954. * @license
  16955. * Copyright 2020 Google LLC
  16956. *
  16957. * Licensed under the Apache License, Version 2.0 (the "License");
  16958. * you may not use this file except in compliance with the License.
  16959. * You may obtain a copy of the License at
  16960. *
  16961. * http://www.apache.org/licenses/LICENSE-2.0
  16962. *
  16963. * Unless required by applicable law or agreed to in writing, software
  16964. * distributed under the License is distributed on an "AS IS" BASIS,
  16965. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16966. * See the License for the specific language governing permissions and
  16967. * limitations under the License.
  16968. */
  16969. // settings() defaults:
  16970. /**
  16971. * A concrete type describing all the values that can be applied via a
  16972. * user-supplied `FirestoreSettings` object. This is a separate type so that
  16973. * defaults can be supplied and the value can be checked for equality.
  16974. */
  16975. class fh {
  16976. constructor(t) {
  16977. var e, n;
  16978. if (void 0 === t.host) {
  16979. if (void 0 !== t.ssl) throw new G(K.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
  16980. this.host = "firestore.googleapis.com", this.ssl = true;
  16981. } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;
  16982. if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties,
  16983. this.cache = t.localCache, void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {
  16984. if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new G(K.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  16985. this.cacheSizeBytes = t.cacheSizeBytes;
  16986. }
  16987. oh("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling),
  16988. this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true :
  16989. // For backwards compatibility, coerce the value to boolean even though
  16990. // the TypeScript compiler has narrowed the type to boolean already.
  16991. // noinspection PointlessBooleanExpressionJS
  16992. this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling,
  16993. this.experimentalLongPollingOptions = sh(null !== (n = t.experimentalLongPollingOptions) && void 0 !== n ? n : {}),
  16994. function(t) {
  16995. if (void 0 !== t.timeoutSeconds) {
  16996. if (isNaN(t.timeoutSeconds)) throw new G(K.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`);
  16997. if (t.timeoutSeconds < 5) throw new G(K.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`);
  16998. if (t.timeoutSeconds > 30) throw new G(K.INVALID_ARGUMENT, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`);
  16999. }
  17000. }
  17001. /**
  17002. * @license
  17003. * Copyright 2020 Google LLC
  17004. *
  17005. * Licensed under the Apache License, Version 2.0 (the "License");
  17006. * you may not use this file except in compliance with the License.
  17007. * You may obtain a copy of the License at
  17008. *
  17009. * http://www.apache.org/licenses/LICENSE-2.0
  17010. *
  17011. * Unless required by applicable law or agreed to in writing, software
  17012. * distributed under the License is distributed on an "AS IS" BASIS,
  17013. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17014. * See the License for the specific language governing permissions and
  17015. * limitations under the License.
  17016. */
  17017. /**
  17018. * The Cloud Firestore service interface.
  17019. *
  17020. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  17021. */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams;
  17022. }
  17023. isEqual(t) {
  17024. 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,
  17025. n = t.experimentalLongPollingOptions, e.timeoutSeconds === n.timeoutSeconds) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;
  17026. var e, n;
  17027. }
  17028. }
  17029. class dh {
  17030. /** @hideconstructor */
  17031. constructor(t, e, n, s) {
  17032. this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n,
  17033. this._app = s,
  17034. /**
  17035. * Whether it's a Firestore or Firestore Lite instance.
  17036. */
  17037. this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new fh({}),
  17038. this._settingsFrozen = !1;
  17039. }
  17040. /**
  17041. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  17042. * instance.
  17043. */ get app() {
  17044. if (!this._app) throw new G(K.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
  17045. return this._app;
  17046. }
  17047. get _initialized() {
  17048. return this._settingsFrozen;
  17049. }
  17050. get _terminated() {
  17051. return void 0 !== this._terminateTask;
  17052. }
  17053. _setSettings(t) {
  17054. if (this._settingsFrozen) throw new G(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.");
  17055. this._settings = new fh(t), void 0 !== t.credentials && (this._authCredentials = function(t) {
  17056. if (!t) return new z;
  17057. switch (t.type) {
  17058. case "firstParty":
  17059. return new Y(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null);
  17060. case "provider":
  17061. return t.client;
  17062. default:
  17063. throw new G(K.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type");
  17064. }
  17065. }(t.credentials));
  17066. }
  17067. _getSettings() {
  17068. return this._settings;
  17069. }
  17070. _freezeSettings() {
  17071. return this._settingsFrozen = !0, this._settings;
  17072. }
  17073. _delete() {
  17074. return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;
  17075. }
  17076. /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {
  17077. return {
  17078. app: this._app,
  17079. databaseId: this._databaseId,
  17080. settings: this._settings
  17081. };
  17082. }
  17083. /**
  17084. * Terminates all components used by this client. Subclasses can override
  17085. * this method to clean up their own dependencies, but must also call this
  17086. * method.
  17087. *
  17088. * Only ever called once.
  17089. */ _terminate() {
  17090. /**
  17091. * Removes all components associated with the provided instance. Must be called
  17092. * when the `Firestore` instance is terminated.
  17093. */
  17094. return function(t) {
  17095. const e = ih.get(t);
  17096. e && ($("ComponentProvider", "Removing Datastore"), ih.delete(t), e.terminate());
  17097. }(this), Promise.resolve();
  17098. }
  17099. }
  17100. /**
  17101. * Modify this instance to communicate with the Cloud Firestore emulator.
  17102. *
  17103. * Note: This must be called before this instance has been used to do any
  17104. * operations.
  17105. *
  17106. * @param firestore - The `Firestore` instance to configure to connect to the
  17107. * emulator.
  17108. * @param host - the emulator host (ex: localhost).
  17109. * @param port - the emulator port (ex: 9000).
  17110. * @param options.mockUserToken - the mock auth token to use for unit testing
  17111. * Security Rules.
  17112. */ function wh(t, e, n, s = {}) {
  17113. var i;
  17114. const r = (t = hh(t, dh))._getSettings(), o = `${e}:${n}`;
  17115. if ("firestore.googleapis.com" !== r.host && r.host !== o && O("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),
  17116. t._setSettings(Object.assign(Object.assign({}, r), {
  17117. host: o,
  17118. ssl: !1
  17119. })), s.mockUserToken) {
  17120. let e, n;
  17121. if ("string" == typeof s.mockUserToken) e = s.mockUserToken, n = D.MOCK_USER; else {
  17122. // Let createMockUserToken validate first (catches common mistakes like
  17123. // invalid field "uid" and missing field "sub" / "user_id".)
  17124. e = w(s.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId);
  17125. const r = s.mockUserToken.sub || s.mockUserToken.user_id;
  17126. if (!r) throw new G(K.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
  17127. n = new D(r);
  17128. }
  17129. t._authCredentials = new W(new j(e, n));
  17130. }
  17131. }
  17132. /**
  17133. * @license
  17134. * Copyright 2020 Google LLC
  17135. *
  17136. * Licensed under the Apache License, Version 2.0 (the "License");
  17137. * you may not use this file except in compliance with the License.
  17138. * You may obtain a copy of the License at
  17139. *
  17140. * http://www.apache.org/licenses/LICENSE-2.0
  17141. *
  17142. * Unless required by applicable law or agreed to in writing, software
  17143. * distributed under the License is distributed on an "AS IS" BASIS,
  17144. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17145. * See the License for the specific language governing permissions and
  17146. * limitations under the License.
  17147. */
  17148. /**
  17149. * A `DocumentReference` refers to a document location in a Firestore database
  17150. * and can be used to write, read, or listen to the location. The document at
  17151. * the referenced location may or may not exist.
  17152. */ class _h {
  17153. /** @hideconstructor */
  17154. constructor(t,
  17155. /**
  17156. * If provided, the `FirestoreDataConverter` associated with this instance.
  17157. */
  17158. e, n) {
  17159. this.converter = e, this._key = n,
  17160. /** The type of this Firestore reference. */
  17161. this.type = "document", this.firestore = t;
  17162. }
  17163. get _path() {
  17164. return this._key.path;
  17165. }
  17166. /**
  17167. * The document's identifier within its collection.
  17168. */ get id() {
  17169. return this._key.path.lastSegment();
  17170. }
  17171. /**
  17172. * A string representing the path of the referenced document (relative
  17173. * to the root of the database).
  17174. */ get path() {
  17175. return this._key.path.canonicalString();
  17176. }
  17177. /**
  17178. * The collection this `DocumentReference` belongs to.
  17179. */ get parent() {
  17180. return new gh(this.firestore, this.converter, this._key.path.popLast());
  17181. }
  17182. withConverter(t) {
  17183. return new _h(this.firestore, t, this._key);
  17184. }
  17185. }
  17186. /**
  17187. * A `Query` refers to a query which you can read or listen to. You can also
  17188. * construct refined `Query` objects by adding filters and ordering.
  17189. */ class mh {
  17190. // This is the lite version of the Query class in the main SDK.
  17191. /** @hideconstructor protected */
  17192. constructor(t,
  17193. /**
  17194. * If provided, the `FirestoreDataConverter` associated with this instance.
  17195. */
  17196. e, n) {
  17197. this.converter = e, this._query = n,
  17198. /** The type of this Firestore reference. */
  17199. this.type = "query", this.firestore = t;
  17200. }
  17201. withConverter(t) {
  17202. return new mh(this.firestore, t, this._query);
  17203. }
  17204. }
  17205. /**
  17206. * A `CollectionReference` object can be used for adding documents, getting
  17207. * document references, and querying for documents (using {@link (query:1)}).
  17208. */ class gh extends mh {
  17209. /** @hideconstructor */
  17210. constructor(t, e, n) {
  17211. super(t, e, zn(n)), this._path = n,
  17212. /** The type of this Firestore reference. */
  17213. this.type = "collection";
  17214. }
  17215. /** The collection's identifier. */ get id() {
  17216. return this._query.path.lastSegment();
  17217. }
  17218. /**
  17219. * A string representing the path of the referenced collection (relative
  17220. * to the root of the database).
  17221. */ get path() {
  17222. return this._query.path.canonicalString();
  17223. }
  17224. /**
  17225. * A reference to the containing `DocumentReference` if this is a
  17226. * subcollection. If this isn't a subcollection, the reference is null.
  17227. */ get parent() {
  17228. const t = this._path.popLast();
  17229. return t.isEmpty() ? null : new _h(this.firestore,
  17230. /* converter= */ null, new ft(t));
  17231. }
  17232. withConverter(t) {
  17233. return new gh(this.firestore, t, this._path);
  17234. }
  17235. }
  17236. function yh(t, e, ...n) {
  17237. if (t = _(t), rh("collection", "path", e), t instanceof dh) {
  17238. const s = at.fromString(e, ...n);
  17239. return ch(s), new gh(t, /* converter= */ null, s);
  17240. }
  17241. {
  17242. if (!(t instanceof _h || t instanceof gh)) throw new G(K.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  17243. const s = t._path.child(at.fromString(e, ...n));
  17244. return ch(s), new gh(t.firestore,
  17245. /* converter= */ null, s);
  17246. }
  17247. }
  17248. // TODO(firestorelite): Consider using ErrorFactory -
  17249. // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
  17250. /**
  17251. * Creates and returns a new `Query` instance that includes all documents in the
  17252. * database that are contained in a collection or subcollection with the
  17253. * given `collectionId`.
  17254. *
  17255. * @param firestore - A reference to the root `Firestore` instance.
  17256. * @param collectionId - Identifies the collections to query over. Every
  17257. * collection or subcollection with this ID as the last segment of its path
  17258. * will be included. Cannot contain a slash.
  17259. * @returns The created `Query`.
  17260. */ function ph(t, e) {
  17261. if (t = hh(t, dh), rh("collectionGroup", "collection id", e), e.indexOf("/") >= 0) throw new G(K.INVALID_ARGUMENT, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);
  17262. return new mh(t,
  17263. /* converter= */ null, function(t) {
  17264. return new Qn(at.emptyPath(), t);
  17265. }(e));
  17266. }
  17267. function Ih(t, e, ...n) {
  17268. if (t = _(t),
  17269. // We allow omission of 'pathString' but explicitly prohibit passing in both
  17270. // 'undefined' and 'null'.
  17271. 1 === arguments.length && (e = nt.A()), rh("doc", "path", e), t instanceof dh) {
  17272. const s = at.fromString(e, ...n);
  17273. return uh(s), new _h(t,
  17274. /* converter= */ null, new ft(s));
  17275. }
  17276. {
  17277. if (!(t instanceof _h || t instanceof gh)) throw new G(K.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  17278. const s = t._path.child(at.fromString(e, ...n));
  17279. return uh(s), new _h(t.firestore, t instanceof gh ? t.converter : null, new ft(s));
  17280. }
  17281. }
  17282. /**
  17283. * Returns true if the provided references are equal.
  17284. *
  17285. * @param left - A reference to compare.
  17286. * @param right - A reference to compare.
  17287. * @returns true if the references point to the same location in the same
  17288. * Firestore database.
  17289. */ function Th(t, e) {
  17290. return t = _(t), e = _(e), (t instanceof _h || t instanceof gh) && (e instanceof _h || e instanceof gh) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter);
  17291. }
  17292. /**
  17293. * Returns true if the provided queries point to the same collection and apply
  17294. * the same constraints.
  17295. *
  17296. * @param left - A `Query` to compare.
  17297. * @param right - A `Query` to compare.
  17298. * @returns true if the references point to the same location in the same
  17299. * Firestore database.
  17300. */ function Eh(t, e) {
  17301. return t = _(t), e = _(e), t instanceof mh && e instanceof mh && (t.firestore === e.firestore && ns(t._query, e._query) && t.converter === e.converter);
  17302. }
  17303. /**
  17304. * @license
  17305. * Copyright 2020 Google LLC
  17306. *
  17307. * Licensed under the Apache License, Version 2.0 (the "License");
  17308. * you may not use this file except in compliance with the License.
  17309. * You may obtain a copy of the License at
  17310. *
  17311. * http://www.apache.org/licenses/LICENSE-2.0
  17312. *
  17313. * Unless required by applicable law or agreed to in writing, software
  17314. * distributed under the License is distributed on an "AS IS" BASIS,
  17315. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17316. * See the License for the specific language governing permissions and
  17317. * limitations under the License.
  17318. */ class Ah {
  17319. constructor() {
  17320. // The last promise in the queue.
  17321. this.Gc = Promise.resolve(),
  17322. // A list of retryable operations. Retryable operations are run in order and
  17323. // retried with backoff.
  17324. this.Qc = [],
  17325. // Is this AsyncQueue being shut down? Once it is set to true, it will not
  17326. // be changed again.
  17327. this.jc = !1,
  17328. // Operations scheduled to be queued in the future. Operations are
  17329. // automatically removed after they are run or canceled.
  17330. this.zc = [],
  17331. // visible for testing
  17332. this.Wc = null,
  17333. // Flag set while there's an outstanding AsyncQueue operation, used for
  17334. // assertion sanity-checks.
  17335. this.Hc = !1,
  17336. // Enabled during shutdown on Safari to prevent future access to IndexedDB.
  17337. this.Jc = !1,
  17338. // List of TimerIds to fast-forward delays for.
  17339. this.Yc = [],
  17340. // Backoff timer used to schedule retries for retryable operations
  17341. this.qo = new Uu(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */),
  17342. // Visibility handler that triggers an immediate retry of all retryable
  17343. // operations. Meant to speed up recovery when we regain file system access
  17344. // after page comes into foreground.
  17345. this.Xc = () => {
  17346. const t = Lu();
  17347. t && $("AsyncQueue", "Visibility state changed to " + t.visibilityState), this.qo.$o();
  17348. };
  17349. const t = Lu();
  17350. t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.Xc);
  17351. }
  17352. get isShuttingDown() {
  17353. return this.jc;
  17354. }
  17355. /**
  17356. * Adds a new operation to the queue without waiting for it to complete (i.e.
  17357. * we ignore the Promise result).
  17358. */ enqueueAndForget(t) {
  17359. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  17360. this.enqueue(t);
  17361. }
  17362. enqueueAndForgetEvenWhileRestricted(t) {
  17363. this.Zc(),
  17364. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  17365. this.ta(t);
  17366. }
  17367. enterRestrictedMode(t) {
  17368. if (!this.jc) {
  17369. this.jc = !0, this.Jc = t || !1;
  17370. const e = Lu();
  17371. e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Xc);
  17372. }
  17373. }
  17374. enqueue(t) {
  17375. if (this.Zc(), this.jc)
  17376. // Return a Promise which never resolves.
  17377. return new Promise((() => {}));
  17378. // Create a deferred Promise that we can return to the callee. This
  17379. // allows us to return a "hanging Promise" only to the callee and still
  17380. // advance the queue even when the operation is not run.
  17381. const e = new Q;
  17382. return this.ta((() => this.jc && this.Jc ? Promise.resolve() : (t().then(e.resolve, e.reject),
  17383. e.promise))).then((() => e.promise));
  17384. }
  17385. enqueueRetryable(t) {
  17386. this.enqueueAndForget((() => (this.Qc.push(t), this.ea())));
  17387. }
  17388. /**
  17389. * Runs the next operation from the retryable queue. If the operation fails,
  17390. * reschedules with backoff.
  17391. */ async ea() {
  17392. if (0 !== this.Qc.length) {
  17393. try {
  17394. await this.Qc[0](), this.Qc.shift(), this.qo.reset();
  17395. } catch (t) {
  17396. if (!xt(t)) throw t;
  17397. // Failure will be handled by AsyncQueue
  17398. $("AsyncQueue", "Operation failed with retryable error: " + t);
  17399. }
  17400. this.Qc.length > 0 &&
  17401. // If there are additional operations, we re-schedule `retryNextOp()`.
  17402. // This is necessary to run retryable operations that failed during
  17403. // their initial attempt since we don't know whether they are already
  17404. // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
  17405. // needs to be re-run, we will run `op1`, `op1`, `op2` using the
  17406. // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
  17407. // call scheduled here.
  17408. // Since `backoffAndRun()` cancels an existing backoff and schedules a
  17409. // new backoff on every call, there is only ever a single additional
  17410. // operation in the queue.
  17411. this.qo.No((() => this.ea()));
  17412. }
  17413. }
  17414. ta(t) {
  17415. const e = this.Gc.then((() => (this.Hc = !0, t().catch((t => {
  17416. this.Wc = t, this.Hc = !1;
  17417. const e =
  17418. /**
  17419. * Chrome includes Error.message in Error.stack. Other browsers do not.
  17420. * This returns expected output of message + stack when available.
  17421. * @param error - Error or FirestoreError
  17422. */
  17423. function(t) {
  17424. let e = t.message || "";
  17425. t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack);
  17426. return e;
  17427. }
  17428. /**
  17429. * @license
  17430. * Copyright 2017 Google LLC
  17431. *
  17432. * Licensed under the Apache License, Version 2.0 (the "License");
  17433. * you may not use this file except in compliance with the License.
  17434. * You may obtain a copy of the License at
  17435. *
  17436. * http://www.apache.org/licenses/LICENSE-2.0
  17437. *
  17438. * Unless required by applicable law or agreed to in writing, software
  17439. * distributed under the License is distributed on an "AS IS" BASIS,
  17440. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17441. * See the License for the specific language governing permissions and
  17442. * limitations under the License.
  17443. */ (t);
  17444. // Re-throw the error so that this.tail becomes a rejected Promise and
  17445. // all further attempts to chain (via .then) will just short-circuit
  17446. // and return the rejected Promise.
  17447. throw M("INTERNAL UNHANDLED ERROR: ", e), t;
  17448. })).then((t => (this.Hc = !1, t))))));
  17449. return this.Gc = e, e;
  17450. }
  17451. enqueueAfterDelay(t, e, n) {
  17452. this.Zc(),
  17453. // Fast-forward delays for timerIds that have been overriden.
  17454. this.Yc.indexOf(t) > -1 && (e = 0);
  17455. const s = vc.createAndSchedule(this, t, e, n, (t => this.na(t)));
  17456. return this.zc.push(s), s;
  17457. }
  17458. Zc() {
  17459. this.Wc && B();
  17460. }
  17461. verifyOperationInProgress() {}
  17462. /**
  17463. * Waits until all currently queued tasks are finished executing. Delayed
  17464. * operations are not run.
  17465. */ async sa() {
  17466. // Operations in the queue prior to draining may have enqueued additional
  17467. // operations. Keep draining the queue until the tail is no longer advanced,
  17468. // which indicates that no more new operations were enqueued and that all
  17469. // operations were executed.
  17470. let t;
  17471. do {
  17472. t = this.Gc, await t;
  17473. } while (t !== this.Gc);
  17474. }
  17475. /**
  17476. * For Tests: Determine if a delayed operation with a particular TimerId
  17477. * exists.
  17478. */ ia(t) {
  17479. for (const e of this.zc) if (e.timerId === t) return !0;
  17480. return !1;
  17481. }
  17482. /**
  17483. * For Tests: Runs some or all delayed operations early.
  17484. *
  17485. * @param lastTimerId - Delayed operations up to and including this TimerId
  17486. * will be drained. Pass TimerId.All to run all delayed operations.
  17487. * @returns a Promise that resolves once all operations have been run.
  17488. */ ra(t) {
  17489. // Note that draining may generate more delayed ops, so we do that first.
  17490. return this.sa().then((() => {
  17491. // Run ops in the same order they'd run if they ran naturally.
  17492. this.zc.sort(((t, e) => t.targetTimeMs - e.targetTimeMs));
  17493. for (const e of this.zc) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break;
  17494. return this.sa();
  17495. }));
  17496. }
  17497. /**
  17498. * For Tests: Skip all subsequent delays for a timer id.
  17499. */ oa(t) {
  17500. this.Yc.push(t);
  17501. }
  17502. /** Called once a DelayedOperation is run or canceled. */ na(t) {
  17503. // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
  17504. const e = this.zc.indexOf(t);
  17505. this.zc.splice(e, 1);
  17506. }
  17507. }
  17508. function vh(t) {
  17509. /**
  17510. * Returns true if obj is an object and contains at least one of the specified
  17511. * methods.
  17512. */
  17513. return function(t, e) {
  17514. if ("object" != typeof t || null === t) return !1;
  17515. const n = t;
  17516. for (const t of e) if (t in n && "function" == typeof n[t]) return !0;
  17517. return !1;
  17518. }
  17519. /**
  17520. * @license
  17521. * Copyright 2020 Google LLC
  17522. *
  17523. * Licensed under the Apache License, Version 2.0 (the "License");
  17524. * you may not use this file except in compliance with the License.
  17525. * You may obtain a copy of the License at
  17526. *
  17527. * http://www.apache.org/licenses/LICENSE-2.0
  17528. *
  17529. * Unless required by applicable law or agreed to in writing, software
  17530. * distributed under the License is distributed on an "AS IS" BASIS,
  17531. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17532. * See the License for the specific language governing permissions and
  17533. * limitations under the License.
  17534. */
  17535. /**
  17536. * Represents the task of loading a Firestore bundle. It provides progress of bundle
  17537. * loading, as well as task completion and error events.
  17538. *
  17539. * The API is compatible with `Promise<LoadBundleTaskProgress>`.
  17540. */ (t, [ "next", "error", "complete" ]);
  17541. }
  17542. class Rh {
  17543. constructor() {
  17544. this._progressObserver = {}, this._taskCompletionResolver = new Q, this._lastProgress = {
  17545. taskState: "Running",
  17546. totalBytes: 0,
  17547. totalDocuments: 0,
  17548. bytesLoaded: 0,
  17549. documentsLoaded: 0
  17550. };
  17551. }
  17552. /**
  17553. * Registers functions to listen to bundle loading progress events.
  17554. * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
  17555. * each time a Firestore document is loaded from the bundle.
  17556. * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
  17557. * error, and there should be no more updates after this.
  17558. * @param complete - Called when the loading task is complete.
  17559. */ onProgress(t, e, n) {
  17560. this._progressObserver = {
  17561. next: t,
  17562. error: e,
  17563. complete: n
  17564. };
  17565. }
  17566. /**
  17567. * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
  17568. *
  17569. * @param onRejected - Called when an error occurs during bundle loading.
  17570. */ catch(t) {
  17571. return this._taskCompletionResolver.promise.catch(t);
  17572. }
  17573. /**
  17574. * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
  17575. *
  17576. * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
  17577. * The update will always have its `taskState` set to `"Success"`.
  17578. * @param onRejected - Called when an error occurs during bundle loading.
  17579. */ then(t, e) {
  17580. return this._taskCompletionResolver.promise.then(t, e);
  17581. }
  17582. /**
  17583. * Notifies all observers that bundle loading has completed, with a provided
  17584. * `LoadBundleTaskProgress` object.
  17585. *
  17586. * @private
  17587. */ _completeWith(t) {
  17588. this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(),
  17589. this._taskCompletionResolver.resolve(t);
  17590. }
  17591. /**
  17592. * Notifies all observers that bundle loading has failed, with a provided
  17593. * `Error` as the reason.
  17594. *
  17595. * @private
  17596. */ _failWith(t) {
  17597. this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress),
  17598. this._progressObserver.error && this._progressObserver.error(t), this._taskCompletionResolver.reject(t);
  17599. }
  17600. /**
  17601. * Notifies a progress update of loading a bundle.
  17602. * @param progress - The new progress.
  17603. *
  17604. * @private
  17605. */ _updateProgress(t) {
  17606. this._lastProgress = t, this._progressObserver.next && this._progressObserver.next(t);
  17607. }
  17608. }
  17609. /**
  17610. * @license
  17611. * Copyright 2020 Google LLC
  17612. *
  17613. * Licensed under the Apache License, Version 2.0 (the "License");
  17614. * you may not use this file except in compliance with the License.
  17615. * You may obtain a copy of the License at
  17616. *
  17617. * http://www.apache.org/licenses/LICENSE-2.0
  17618. *
  17619. * Unless required by applicable law or agreed to in writing, software
  17620. * distributed under the License is distributed on an "AS IS" BASIS,
  17621. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17622. * See the License for the specific language governing permissions and
  17623. * limitations under the License.
  17624. */
  17625. /**
  17626. * Constant used to indicate the LRU garbage collection should be disabled.
  17627. * Set this value as the `cacheSizeBytes` on the settings passed to the
  17628. * {@link Firestore} instance.
  17629. */ const Ph = -1;
  17630. /**
  17631. * The Cloud Firestore service interface.
  17632. *
  17633. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  17634. */ class bh extends dh {
  17635. /** @hideconstructor */
  17636. constructor(t, e, n, s) {
  17637. super(t, e, n, s),
  17638. /**
  17639. * Whether it's a {@link Firestore} or Firestore Lite instance.
  17640. */
  17641. this.type = "firestore", this._queue = new Ah, this._persistenceKey = (null == s ? void 0 : s.name) || "[DEFAULT]";
  17642. }
  17643. _terminate() {
  17644. return this._firestoreClient ||
  17645. // The client must be initialized to ensure that all subsequent API
  17646. // usage throws an exception.
  17647. Ch(this), this._firestoreClient.terminate();
  17648. }
  17649. }
  17650. /**
  17651. * Initializes a new instance of {@link Firestore} with the provided settings.
  17652. * Can only be called before any other function, including
  17653. * {@link (getFirestore:1)}. If the custom settings are empty, this function is
  17654. * equivalent to calling {@link (getFirestore:1)}.
  17655. *
  17656. * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
  17657. * be associated.
  17658. * @param settings - A settings object to configure the {@link Firestore} instance.
  17659. * @param databaseId - The name of the database.
  17660. * @returns A newly initialized {@link Firestore} instance.
  17661. */ function Vh(t, e, n) {
  17662. n || (n = "(default)");
  17663. const s = _getProvider(t, "firestore");
  17664. if (s.isInitialized(n)) {
  17665. const t = s.getImmediate({
  17666. identifier: n
  17667. }), i = s.getOptions(n);
  17668. if (m(i, e)) return t;
  17669. throw new G(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.");
  17670. }
  17671. if (void 0 !== e.cacheSizeBytes && void 0 !== e.localCache) throw new G(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");
  17672. if (void 0 !== e.cacheSizeBytes && -1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new G(K.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  17673. return s.initialize({
  17674. options: e,
  17675. instanceIdentifier: n
  17676. });
  17677. }
  17678. function Sh(e, n) {
  17679. const s = "object" == typeof e ? e : t(), i = "string" == typeof e ? e : n || "(default)", r = _getProvider(s, "firestore").getImmediate({
  17680. identifier: i
  17681. });
  17682. if (!r._initialized) {
  17683. const t = g("firestore");
  17684. t && wh(r, ...t);
  17685. }
  17686. return r;
  17687. }
  17688. /**
  17689. * @internal
  17690. */ function Dh(t) {
  17691. return t._firestoreClient || Ch(t), t._firestoreClient.verifyNotTerminated(), t._firestoreClient;
  17692. }
  17693. function Ch(t) {
  17694. var e, n, s;
  17695. const i = t._freezeSettings(), r = function(t, e, n, s) {
  17696. return new Be(t, e, n, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, sh(s.experimentalLongPollingOptions), s.useFetchStreams);
  17697. }(t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || "", t._persistenceKey, i);
  17698. t._firestoreClient = new $a(t._authCredentials, t._appCheckCredentials, t._queue, r),
  17699. (null === (n = i.cache) || void 0 === n ? void 0 : n._offlineComponentProvider) && (null === (s = i.cache) || void 0 === s ? void 0 : s._onlineComponentProvider) && (t._firestoreClient._uninitializedComponentsProvider = {
  17700. _offlineKind: i.cache.kind,
  17701. _offline: i.cache._offlineComponentProvider,
  17702. _online: i.cache._onlineComponentProvider
  17703. });
  17704. }
  17705. /**
  17706. * Attempts to enable persistent storage, if possible.
  17707. *
  17708. * Must be called before any other functions (other than
  17709. * {@link initializeFirestore}, {@link (getFirestore:1)} or
  17710. * {@link clearIndexedDbPersistence}.
  17711. *
  17712. * If this fails, `enableIndexedDbPersistence()` will reject the promise it
  17713. * returns. Note that even after this failure, the {@link Firestore} instance will
  17714. * remain usable, however offline persistence will be disabled.
  17715. *
  17716. * There are several reasons why this can fail, which can be identified by
  17717. * the `code` on the error.
  17718. *
  17719. * * failed-precondition: The app is already open in another browser tab.
  17720. * * unimplemented: The browser is incompatible with the offline
  17721. * persistence implementation.
  17722. *
  17723. * Persistence cannot be used in a Node.js environment.
  17724. *
  17725. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17726. * @param persistenceSettings - Optional settings object to configure
  17727. * persistence.
  17728. * @returns A `Promise` that represents successfully enabling persistent storage.
  17729. * @deprecated This function will be removed in a future major release. Instead, set
  17730. * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to
  17731. * turn on IndexedDb cache. Calling this function when `FirestoreSettings.cache`
  17732. * is already specified will throw an exception.
  17733. */ function xh(t, e) {
  17734. Uh(t = hh(t, bh));
  17735. const n = Dh(t);
  17736. if (n._uninitializedComponentsProvider) throw new G(K.FAILED_PRECONDITION, "SDK cache is already specified.");
  17737. O("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
  17738. const s = t._freezeSettings(), i = new Sa;
  17739. return kh(n, i, new ba(i, s.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));
  17740. }
  17741. /**
  17742. * Attempts to enable multi-tab persistent storage, if possible. If enabled
  17743. * across all tabs, all operations share access to local persistence, including
  17744. * shared execution of queries and latency-compensated local document updates
  17745. * across all connected instances.
  17746. *
  17747. * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
  17748. * it returns. Note that even after this failure, the {@link Firestore} instance will
  17749. * remain usable, however offline persistence will be disabled.
  17750. *
  17751. * There are several reasons why this can fail, which can be identified by
  17752. * the `code` on the error.
  17753. *
  17754. * * failed-precondition: The app is already open in another browser tab and
  17755. * multi-tab is not enabled.
  17756. * * unimplemented: The browser is incompatible with the offline
  17757. * persistence implementation.
  17758. *
  17759. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17760. * @returns A `Promise` that represents successfully enabling persistent
  17761. * storage.
  17762. * @deprecated This function will be removed in a future major release. Instead, set
  17763. * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to
  17764. * turn on indexeddb cache. Calling this function when `FirestoreSettings.cache`
  17765. * is already specified will throw an exception.
  17766. */ function Nh(t) {
  17767. Uh(t = hh(t, bh));
  17768. const e = Dh(t);
  17769. if (e._uninitializedComponentsProvider) throw new G(K.FAILED_PRECONDITION, "SDK cache is already specified.");
  17770. O("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
  17771. const n = t._freezeSettings(), s = new Sa;
  17772. return kh(e, s, new Va(s, n.cacheSizeBytes));
  17773. }
  17774. /**
  17775. * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.
  17776. * If the operation fails with a recoverable error (see
  17777. * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected
  17778. * but the client remains usable.
  17779. */ function kh(t, e, n) {
  17780. const s = new Q;
  17781. return t.asyncQueue.enqueue((async () => {
  17782. try {
  17783. await Ma(t, n), await Oa(t, e), s.resolve();
  17784. } catch (t) {
  17785. const e = t;
  17786. if (!Fa(e)) throw e;
  17787. O("Error enabling indexeddb cache. Falling back to memory cache: " + e), s.reject(e);
  17788. }
  17789. })).then((() => s.promise));
  17790. }
  17791. /**
  17792. * Clears the persistent storage. This includes pending writes and cached
  17793. * documents.
  17794. *
  17795. * Must be called while the {@link Firestore} instance is not started (after the app is
  17796. * terminated or when the app is first initialized). On startup, this function
  17797. * must be called before other functions (other than {@link
  17798. * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}
  17799. * instance is still running, the promise will be rejected with the error code
  17800. * of `failed-precondition`.
  17801. *
  17802. * Note: `clearIndexedDbPersistence()` is primarily intended to help write
  17803. * reliable tests that use Cloud Firestore. It uses an efficient mechanism for
  17804. * dropping existing data but does not attempt to securely overwrite or
  17805. * otherwise make cached data unrecoverable. For applications that are sensitive
  17806. * to the disclosure of cached data in between user sessions, we strongly
  17807. * recommend not enabling persistence at all.
  17808. *
  17809. * @param firestore - The {@link Firestore} instance to clear persistence for.
  17810. * @returns A `Promise` that is resolved when the persistent storage is
  17811. * cleared. Otherwise, the promise is rejected with an error.
  17812. */ function $h(t) {
  17813. if (t._initialized && !t._terminated) throw new G(K.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");
  17814. const e = new Q;
  17815. return t._queue.enqueueAndForgetEvenWhileRestricted((async () => {
  17816. try {
  17817. await async function(t) {
  17818. if (!St.D()) return Promise.resolve();
  17819. const e = t + "main";
  17820. await St.delete(e);
  17821. }(nu(t._databaseId, t._persistenceKey)), e.resolve();
  17822. } catch (t) {
  17823. e.reject(t);
  17824. }
  17825. })), e.promise;
  17826. }
  17827. /**
  17828. * Waits until all currently pending writes for the active user have been
  17829. * acknowledged by the backend.
  17830. *
  17831. * The returned promise resolves immediately if there are no outstanding writes.
  17832. * Otherwise, the promise waits for all previously issued writes (including
  17833. * those written in a previous app session), but it does not wait for writes
  17834. * that were added after the function is called. If you want to wait for
  17835. * additional writes, call `waitForPendingWrites()` again.
  17836. *
  17837. * Any outstanding `waitForPendingWrites()` promises are rejected during user
  17838. * changes.
  17839. *
  17840. * @returns A `Promise` which resolves when all currently pending writes have been
  17841. * acknowledged by the backend.
  17842. */ function Mh(t) {
  17843. return function(t) {
  17844. const e = new Q;
  17845. return t.asyncQueue.enqueueAndForget((async () => na(await Ga(t), e))), e.promise;
  17846. }(Dh(t = hh(t, bh)));
  17847. }
  17848. /**
  17849. * Re-enables use of the network for this {@link Firestore} instance after a prior
  17850. * call to {@link disableNetwork}.
  17851. *
  17852. * @returns A `Promise` that is resolved once the network has been enabled.
  17853. */ function Oh(t) {
  17854. return za(Dh(t = hh(t, bh)));
  17855. }
  17856. /**
  17857. * Disables network usage for this instance. It can be re-enabled via {@link
  17858. * enableNetwork}. While the network is disabled, any snapshot listeners,
  17859. * `getDoc()` or `getDocs()` calls will return results from cache, and any write
  17860. * operations will be queued until the network is restored.
  17861. *
  17862. * @returns A `Promise` that is resolved once the network has been disabled.
  17863. */ function Fh(t) {
  17864. return Wa(Dh(t = hh(t, bh)));
  17865. }
  17866. /**
  17867. * Terminates the provided {@link Firestore} instance.
  17868. *
  17869. * After calling `terminate()` only the `clearIndexedDbPersistence()` function
  17870. * may be used. Any other function will throw a `FirestoreError`.
  17871. *
  17872. * To restart after termination, create a new instance of FirebaseFirestore with
  17873. * {@link (getFirestore:1)}.
  17874. *
  17875. * Termination does not cancel any pending writes, and any promises that are
  17876. * awaiting a response from the server will not be resolved. If you have
  17877. * persistence enabled, the next time you start this instance, it will resume
  17878. * sending these writes to the server.
  17879. *
  17880. * Note: Under normal circumstances, calling `terminate()` is not required. This
  17881. * function is useful only when you want to force this instance to release all
  17882. * of its resources or in combination with `clearIndexedDbPersistence()` to
  17883. * ensure that all local state is destroyed between test runs.
  17884. *
  17885. * @returns A `Promise` that is resolved when the instance has been successfully
  17886. * terminated.
  17887. */ function Bh(t) {
  17888. return e(t.app, "firestore", t._databaseId.database), t._delete();
  17889. }
  17890. /**
  17891. * Loads a Firestore bundle into the local cache.
  17892. *
  17893. * @param firestore - The {@link Firestore} instance to load bundles for.
  17894. * @param bundleData - An object representing the bundle to be loaded. Valid
  17895. * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.
  17896. *
  17897. * @returns A `LoadBundleTask` object, which notifies callers with progress
  17898. * updates, and completion or error events. It can be used as a
  17899. * `Promise<LoadBundleTaskProgress>`.
  17900. */ function Lh(t, e) {
  17901. const n = Dh(t = hh(t, bh)), s = new Rh;
  17902. return th(n, t._databaseId, e, s), s;
  17903. }
  17904. /**
  17905. * Reads a Firestore {@link Query} from local cache, identified by the given
  17906. * name.
  17907. *
  17908. * The named queries are packaged into bundles on the server side (along
  17909. * with resulting documents), and loaded to local cache using `loadBundle`. Once
  17910. * in local cache, use this method to extract a {@link Query} by name.
  17911. *
  17912. * @param firestore - The {@link Firestore} instance to read the query from.
  17913. * @param name - The name of the query.
  17914. * @returns A `Promise` that is resolved with the Query or `null`.
  17915. */ function qh(t, e) {
  17916. return eh(Dh(t = hh(t, bh)), e).then((e => e ? new mh(t, null, e.query) : null));
  17917. }
  17918. function Uh(t) {
  17919. if (t._initialized || t._terminated) throw new G(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.");
  17920. }
  17921. /**
  17922. * @license
  17923. * Copyright 2020 Google LLC
  17924. *
  17925. * Licensed under the Apache License, Version 2.0 (the "License");
  17926. * you may not use this file except in compliance with the License.
  17927. * You may obtain a copy of the License at
  17928. *
  17929. * http://www.apache.org/licenses/LICENSE-2.0
  17930. *
  17931. * Unless required by applicable law or agreed to in writing, software
  17932. * distributed under the License is distributed on an "AS IS" BASIS,
  17933. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17934. * See the License for the specific language governing permissions and
  17935. * limitations under the License.
  17936. */
  17937. /**
  17938. * @license
  17939. * Copyright 2022 Google LLC
  17940. *
  17941. * Licensed under the Apache License, Version 2.0 (the "License");
  17942. * you may not use this file except in compliance with the License.
  17943. * You may obtain a copy of the License at
  17944. *
  17945. * http://www.apache.org/licenses/LICENSE-2.0
  17946. *
  17947. * Unless required by applicable law or agreed to in writing, software
  17948. * distributed under the License is distributed on an "AS IS" BASIS,
  17949. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17950. * See the License for the specific language governing permissions and
  17951. * limitations under the License.
  17952. */
  17953. /**
  17954. * Represents an aggregation that can be performed by Firestore.
  17955. */
  17956. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  17957. class Kh {
  17958. /**
  17959. * Create a new AggregateField<T>
  17960. * @param _aggregateType Specifies the type of aggregation operation to perform.
  17961. * @param _internalFieldPath Optionally specifies the field that is aggregated.
  17962. * @internal
  17963. */
  17964. constructor(
  17965. // TODO (sum/avg) make aggregateType public when the feature is supported
  17966. t = "count", e) {
  17967. this._aggregateType = t, this._internalFieldPath = e,
  17968. /** A type string to uniquely identify instances of this class. */
  17969. this.type = "AggregateField";
  17970. }
  17971. }
  17972. /**
  17973. * The results of executing an aggregation query.
  17974. */ class Gh {
  17975. /** @hideconstructor */
  17976. constructor(t, e, n) {
  17977. this._userDataWriter = e, this._data = n,
  17978. /** A type string to uniquely identify instances of this class. */
  17979. this.type = "AggregateQuerySnapshot", this.query = t;
  17980. }
  17981. /**
  17982. * Returns the results of the aggregations performed over the underlying
  17983. * query.
  17984. *
  17985. * The keys of the returned object will be the same as those of the
  17986. * `AggregateSpec` object specified to the aggregation method, and the values
  17987. * will be the corresponding aggregation result.
  17988. *
  17989. * @returns The results of the aggregations performed over the underlying
  17990. * query.
  17991. */ data() {
  17992. return this._userDataWriter.convertObjectMap(this._data);
  17993. }
  17994. }
  17995. /**
  17996. * @license
  17997. * Copyright 2020 Google LLC
  17998. *
  17999. * Licensed under the Apache License, Version 2.0 (the "License");
  18000. * you may not use this file except in compliance with the License.
  18001. * You may obtain a copy of the License at
  18002. *
  18003. * http://www.apache.org/licenses/LICENSE-2.0
  18004. *
  18005. * Unless required by applicable law or agreed to in writing, software
  18006. * distributed under the License is distributed on an "AS IS" BASIS,
  18007. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18008. * See the License for the specific language governing permissions and
  18009. * limitations under the License.
  18010. */
  18011. /**
  18012. * An immutable object representing an array of bytes.
  18013. */ class Qh {
  18014. /** @hideconstructor */
  18015. constructor(t) {
  18016. this._byteString = t;
  18017. }
  18018. /**
  18019. * Creates a new `Bytes` object from the given Base64 string, converting it to
  18020. * bytes.
  18021. *
  18022. * @param base64 - The Base64 string used to create the `Bytes` object.
  18023. */ static fromBase64String(t) {
  18024. try {
  18025. return new Qh(Ce.fromBase64String(t));
  18026. } catch (t) {
  18027. throw new G(K.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + t);
  18028. }
  18029. }
  18030. /**
  18031. * Creates a new `Bytes` object from the given Uint8Array.
  18032. *
  18033. * @param array - The Uint8Array used to create the `Bytes` object.
  18034. */ static fromUint8Array(t) {
  18035. return new Qh(Ce.fromUint8Array(t));
  18036. }
  18037. /**
  18038. * Returns the underlying bytes as a Base64-encoded string.
  18039. *
  18040. * @returns The Base64-encoded string created from the `Bytes` object.
  18041. */ toBase64() {
  18042. return this._byteString.toBase64();
  18043. }
  18044. /**
  18045. * Returns the underlying bytes in a new `Uint8Array`.
  18046. *
  18047. * @returns The Uint8Array created from the `Bytes` object.
  18048. */ toUint8Array() {
  18049. return this._byteString.toUint8Array();
  18050. }
  18051. /**
  18052. * Returns a string representation of the `Bytes` object.
  18053. *
  18054. * @returns A string representation of the `Bytes` object.
  18055. */ toString() {
  18056. return "Bytes(base64: " + this.toBase64() + ")";
  18057. }
  18058. /**
  18059. * Returns true if this `Bytes` object is equal to the provided one.
  18060. *
  18061. * @param other - The `Bytes` object to compare against.
  18062. * @returns true if this `Bytes` object is equal to the provided one.
  18063. */ isEqual(t) {
  18064. return this._byteString.isEqual(t._byteString);
  18065. }
  18066. }
  18067. /**
  18068. * @license
  18069. * Copyright 2020 Google LLC
  18070. *
  18071. * Licensed under the Apache License, Version 2.0 (the "License");
  18072. * you may not use this file except in compliance with the License.
  18073. * You may obtain a copy of the License at
  18074. *
  18075. * http://www.apache.org/licenses/LICENSE-2.0
  18076. *
  18077. * Unless required by applicable law or agreed to in writing, software
  18078. * distributed under the License is distributed on an "AS IS" BASIS,
  18079. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18080. * See the License for the specific language governing permissions and
  18081. * limitations under the License.
  18082. */
  18083. /**
  18084. * A `FieldPath` refers to a field in a document. The path may consist of a
  18085. * single field name (referring to a top-level field in the document), or a
  18086. * list of field names (referring to a nested field in the document).
  18087. *
  18088. * Create a `FieldPath` by providing field names. If more than one field
  18089. * name is provided, the path will point to a nested field in a document.
  18090. */ class jh {
  18091. /**
  18092. * Creates a `FieldPath` from the provided field names. If more than one field
  18093. * name is provided, the path will point to a nested field in a document.
  18094. *
  18095. * @param fieldNames - A list of field names.
  18096. */
  18097. constructor(...t) {
  18098. for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new G(K.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
  18099. this._internalPath = new lt(t);
  18100. }
  18101. /**
  18102. * Returns true if this `FieldPath` is equal to the provided one.
  18103. *
  18104. * @param other - The `FieldPath` to compare against.
  18105. * @returns true if this `FieldPath` is equal to the provided one.
  18106. */ isEqual(t) {
  18107. return this._internalPath.isEqual(t._internalPath);
  18108. }
  18109. }
  18110. /**
  18111. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  18112. * It can be used in queries to sort or filter by the document ID.
  18113. */ function zh() {
  18114. return new jh("__name__");
  18115. }
  18116. /**
  18117. * @license
  18118. * Copyright 2020 Google LLC
  18119. *
  18120. * Licensed under the Apache License, Version 2.0 (the "License");
  18121. * you may not use this file except in compliance with the License.
  18122. * You may obtain a copy of the License at
  18123. *
  18124. * http://www.apache.org/licenses/LICENSE-2.0
  18125. *
  18126. * Unless required by applicable law or agreed to in writing, software
  18127. * distributed under the License is distributed on an "AS IS" BASIS,
  18128. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18129. * See the License for the specific language governing permissions and
  18130. * limitations under the License.
  18131. */
  18132. /**
  18133. * Sentinel values that can be used when writing document fields with `set()`
  18134. * or `update()`.
  18135. */ class Wh {
  18136. /**
  18137. * @param _methodName - The public API endpoint that returns this class.
  18138. * @hideconstructor
  18139. */
  18140. constructor(t) {
  18141. this._methodName = t;
  18142. }
  18143. }
  18144. /**
  18145. * @license
  18146. * Copyright 2017 Google LLC
  18147. *
  18148. * Licensed under the Apache License, Version 2.0 (the "License");
  18149. * you may not use this file except in compliance with the License.
  18150. * You may obtain a copy of the License at
  18151. *
  18152. * http://www.apache.org/licenses/LICENSE-2.0
  18153. *
  18154. * Unless required by applicable law or agreed to in writing, software
  18155. * distributed under the License is distributed on an "AS IS" BASIS,
  18156. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18157. * See the License for the specific language governing permissions and
  18158. * limitations under the License.
  18159. */
  18160. /**
  18161. * An immutable object representing a geographic location in Firestore. The
  18162. * location is represented as latitude/longitude pair.
  18163. *
  18164. * Latitude values are in the range of [-90, 90].
  18165. * Longitude values are in the range of [-180, 180].
  18166. */ class Hh {
  18167. /**
  18168. * Creates a new immutable `GeoPoint` object with the provided latitude and
  18169. * longitude values.
  18170. * @param latitude - The latitude as number between -90 and 90.
  18171. * @param longitude - The longitude as number between -180 and 180.
  18172. */
  18173. constructor(t, e) {
  18174. if (!isFinite(t) || t < -90 || t > 90) throw new G(K.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + t);
  18175. if (!isFinite(e) || e < -180 || e > 180) throw new G(K.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + e);
  18176. this._lat = t, this._long = e;
  18177. }
  18178. /**
  18179. * The latitude of this `GeoPoint` instance.
  18180. */ get latitude() {
  18181. return this._lat;
  18182. }
  18183. /**
  18184. * The longitude of this `GeoPoint` instance.
  18185. */ get longitude() {
  18186. return this._long;
  18187. }
  18188. /**
  18189. * Returns true if this `GeoPoint` is equal to the provided one.
  18190. *
  18191. * @param other - The `GeoPoint` to compare against.
  18192. * @returns true if this `GeoPoint` is equal to the provided one.
  18193. */ isEqual(t) {
  18194. return this._lat === t._lat && this._long === t._long;
  18195. }
  18196. /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {
  18197. return {
  18198. latitude: this._lat,
  18199. longitude: this._long
  18200. };
  18201. }
  18202. /**
  18203. * Actually private to JS consumers of our API, so this function is prefixed
  18204. * with an underscore.
  18205. */ _compareTo(t) {
  18206. return st(this._lat, t._lat) || st(this._long, t._long);
  18207. }
  18208. }
  18209. /**
  18210. * @license
  18211. * Copyright 2017 Google LLC
  18212. *
  18213. * Licensed under the Apache License, Version 2.0 (the "License");
  18214. * you may not use this file except in compliance with the License.
  18215. * You may obtain a copy of the License at
  18216. *
  18217. * http://www.apache.org/licenses/LICENSE-2.0
  18218. *
  18219. * Unless required by applicable law or agreed to in writing, software
  18220. * distributed under the License is distributed on an "AS IS" BASIS,
  18221. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18222. * See the License for the specific language governing permissions and
  18223. * limitations under the License.
  18224. */ const Jh = /^__.*__$/;
  18225. /** The result of parsing document data (e.g. for a setData call). */ class Yh {
  18226. constructor(t, e, n) {
  18227. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  18228. }
  18229. toMutation(t, e) {
  18230. return null !== this.fieldMask ? new Js(t, this.data, this.fieldMask, e, this.fieldTransforms) : new Hs(t, this.data, e, this.fieldTransforms);
  18231. }
  18232. }
  18233. /** The result of parsing "update" data (i.e. for an updateData call). */ class Xh {
  18234. constructor(t,
  18235. // The fieldMask does not include document transforms.
  18236. e, n) {
  18237. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  18238. }
  18239. toMutation(t, e) {
  18240. return new Js(t, this.data, this.fieldMask, e, this.fieldTransforms);
  18241. }
  18242. }
  18243. function Zh(t) {
  18244. switch (t) {
  18245. case 0 /* UserDataSource.Set */ :
  18246. // fall through
  18247. case 2 /* UserDataSource.MergeSet */ :
  18248. // fall through
  18249. case 1 /* UserDataSource.Update */ :
  18250. return !0;
  18251. case 3 /* UserDataSource.Argument */ :
  18252. case 4 /* UserDataSource.ArrayArgument */ :
  18253. return !1;
  18254. default:
  18255. throw B();
  18256. }
  18257. }
  18258. /** A "context" object passed around while parsing user data. */ class tl {
  18259. /**
  18260. * Initializes a ParseContext with the given source and path.
  18261. *
  18262. * @param settings - The settings for the parser.
  18263. * @param databaseId - The database ID of the Firestore instance.
  18264. * @param serializer - The serializer to use to generate the Value proto.
  18265. * @param ignoreUndefinedProperties - Whether to ignore undefined properties
  18266. * rather than throw.
  18267. * @param fieldTransforms - A mutable list of field transforms encountered
  18268. * while parsing the data.
  18269. * @param fieldMask - A mutable list of field paths encountered while parsing
  18270. * the data.
  18271. *
  18272. * TODO(b/34871131): We don't support array paths right now, so path can be
  18273. * null to indicate the context represents any location within an array (in
  18274. * which case certain features will not work and errors will be somewhat
  18275. * compromised).
  18276. */
  18277. constructor(t, e, n, s, i, r) {
  18278. this.settings = t, this.databaseId = e, this.serializer = n, this.ignoreUndefinedProperties = s,
  18279. // Minor hack: If fieldTransforms is undefined, we assume this is an
  18280. // external call and we need to validate the entire path.
  18281. void 0 === i && this.ua(), this.fieldTransforms = i || [], this.fieldMask = r || [];
  18282. }
  18283. get path() {
  18284. return this.settings.path;
  18285. }
  18286. get ca() {
  18287. return this.settings.ca;
  18288. }
  18289. /** Returns a new context with the specified settings overwritten. */ aa(t) {
  18290. return new tl(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  18291. }
  18292. ha(t) {
  18293. var e;
  18294. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.aa({
  18295. path: n,
  18296. la: !1
  18297. });
  18298. return s.fa(t), s;
  18299. }
  18300. da(t) {
  18301. var e;
  18302. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.aa({
  18303. path: n,
  18304. la: !1
  18305. });
  18306. return s.ua(), s;
  18307. }
  18308. wa(t) {
  18309. // TODO(b/34871131): We don't support array paths right now; so make path
  18310. // undefined.
  18311. return this.aa({
  18312. path: void 0,
  18313. la: !0
  18314. });
  18315. }
  18316. _a(t) {
  18317. return Il(t, this.settings.methodName, this.settings.ma || !1, this.path, this.settings.ga);
  18318. }
  18319. /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) {
  18320. return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field)));
  18321. }
  18322. ua() {
  18323. // TODO(b/34871131): Remove null check once we have proper paths for fields
  18324. // within arrays.
  18325. if (this.path) for (let t = 0; t < this.path.length; t++) this.fa(this.path.get(t));
  18326. }
  18327. fa(t) {
  18328. if (0 === t.length) throw this._a("Document fields must not be empty");
  18329. if (Zh(this.ca) && Jh.test(t)) throw this._a('Document fields cannot begin and end with "__"');
  18330. }
  18331. }
  18332. /**
  18333. * Helper for parsing raw user input (provided via the API) into internal model
  18334. * classes.
  18335. */ class el {
  18336. constructor(t, e, n) {
  18337. this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = n || qu(t);
  18338. }
  18339. /** Creates a new top-level parse context. */ ya(t, e, n, s = !1) {
  18340. return new tl({
  18341. ca: t,
  18342. methodName: e,
  18343. ga: n,
  18344. path: lt.emptyPath(),
  18345. la: !1,
  18346. ma: s
  18347. }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);
  18348. }
  18349. }
  18350. function nl(t) {
  18351. const e = t._freezeSettings(), n = qu(t._databaseId);
  18352. return new el(t._databaseId, !!e.ignoreUndefinedProperties, n);
  18353. }
  18354. /** Parse document data from a set() call. */ function sl(t, e, n, s, i, r = {}) {
  18355. const o = t.ya(r.merge || r.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, i);
  18356. ml("Data must be an object, but it was:", o, s);
  18357. const u = wl(s, o);
  18358. let c, a;
  18359. if (r.merge) c = new be(o.fieldMask), a = o.fieldTransforms; else if (r.mergeFields) {
  18360. const t = [];
  18361. for (const s of r.mergeFields) {
  18362. const i = gl(e, s, n);
  18363. if (!o.contains(i)) throw new G(K.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);
  18364. Tl(t, i) || t.push(i);
  18365. }
  18366. c = new be(t), a = o.fieldTransforms.filter((t => c.covers(t.field)));
  18367. } else c = null, a = o.fieldTransforms;
  18368. return new Yh(new hn(u), c, a);
  18369. }
  18370. class il extends Wh {
  18371. _toFieldTransform(t) {
  18372. if (2 /* UserDataSource.MergeSet */ !== t.ca) throw 1 /* UserDataSource.Update */ === t.ca ? t._a(`${this._methodName}() can only appear at the top level of your update data`) : t._a(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);
  18373. // No transform to add for a delete, but we need to add it to our
  18374. // fieldMask so it gets deleted.
  18375. return t.fieldMask.push(t.path), null;
  18376. }
  18377. isEqual(t) {
  18378. return t instanceof il;
  18379. }
  18380. }
  18381. /**
  18382. * Creates a child context for parsing SerializableFieldValues.
  18383. *
  18384. * This is different than calling `ParseContext.contextWith` because it keeps
  18385. * the fieldTransforms and fieldMask separate.
  18386. *
  18387. * The created context has its `dataSource` set to `UserDataSource.Argument`.
  18388. * Although these values are used with writes, any elements in these FieldValues
  18389. * are not considered writes since they cannot contain any FieldValue sentinels,
  18390. * etc.
  18391. *
  18392. * @param fieldValue - The sentinel FieldValue for which to create a child
  18393. * context.
  18394. * @param context - The parent context.
  18395. * @param arrayElement - Whether or not the FieldValue has an array.
  18396. */ function rl(t, e, n) {
  18397. return new tl({
  18398. ca: 3 /* UserDataSource.Argument */ ,
  18399. ga: e.settings.ga,
  18400. methodName: t._methodName,
  18401. la: n
  18402. }, e.databaseId, e.serializer, e.ignoreUndefinedProperties);
  18403. }
  18404. class ol extends Wh {
  18405. _toFieldTransform(t) {
  18406. return new Fs(t.path, new Ds);
  18407. }
  18408. isEqual(t) {
  18409. return t instanceof ol;
  18410. }
  18411. }
  18412. class ul extends Wh {
  18413. constructor(t, e) {
  18414. super(t), this.pa = e;
  18415. }
  18416. _toFieldTransform(t) {
  18417. const e = rl(this, t,
  18418. /*array=*/ !0), n = this.pa.map((t => dl(t, e))), s = new Cs(n);
  18419. return new Fs(t.path, s);
  18420. }
  18421. isEqual(t) {
  18422. // TODO(mrschmidt): Implement isEquals
  18423. return this === t;
  18424. }
  18425. }
  18426. class cl extends Wh {
  18427. constructor(t, e) {
  18428. super(t), this.pa = e;
  18429. }
  18430. _toFieldTransform(t) {
  18431. const e = rl(this, t,
  18432. /*array=*/ !0), n = this.pa.map((t => dl(t, e))), s = new Ns(n);
  18433. return new Fs(t.path, s);
  18434. }
  18435. isEqual(t) {
  18436. // TODO(mrschmidt): Implement isEquals
  18437. return this === t;
  18438. }
  18439. }
  18440. class al extends Wh {
  18441. constructor(t, e) {
  18442. super(t), this.Ia = e;
  18443. }
  18444. _toFieldTransform(t) {
  18445. const e = new $s(t.serializer, Rs(t.serializer, this.Ia));
  18446. return new Fs(t.path, e);
  18447. }
  18448. isEqual(t) {
  18449. // TODO(mrschmidt): Implement isEquals
  18450. return this === t;
  18451. }
  18452. }
  18453. /** Parse update data from an update() call. */ function hl(t, e, n, s) {
  18454. const i = t.ya(1 /* UserDataSource.Update */ , e, n);
  18455. ml("Data must be an object, but it was:", i, s);
  18456. const r = [], o = hn.empty();
  18457. pe(s, ((t, s) => {
  18458. const u = pl(e, t, n);
  18459. // For Compat types, we have to "extract" the underlying types before
  18460. // performing validation.
  18461. s = _(s);
  18462. const c = i.da(u);
  18463. if (s instanceof il)
  18464. // Add it to the field mask, but don't add anything to updateData.
  18465. r.push(u); else {
  18466. const t = dl(s, c);
  18467. null != t && (r.push(u), o.set(u, t));
  18468. }
  18469. }));
  18470. const u = new be(r);
  18471. return new Xh(o, u, i.fieldTransforms);
  18472. }
  18473. /** Parse update data from a list of field/value arguments. */ function ll(t, e, n, s, i, r) {
  18474. const o = t.ya(1 /* UserDataSource.Update */ , e, n), u = [ gl(e, s, n) ], c = [ i ];
  18475. if (r.length % 2 != 0) throw new G(K.INVALID_ARGUMENT, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);
  18476. for (let t = 0; t < r.length; t += 2) u.push(gl(e, r[t])), c.push(r[t + 1]);
  18477. const a = [], h = hn.empty();
  18478. // We iterate in reverse order to pick the last value for a field if the
  18479. // user specified the field multiple times.
  18480. for (let t = u.length - 1; t >= 0; --t) if (!Tl(a, u[t])) {
  18481. const e = u[t];
  18482. let n = c[t];
  18483. // For Compat types, we have to "extract" the underlying types before
  18484. // performing validation.
  18485. n = _(n);
  18486. const s = o.da(e);
  18487. if (n instanceof il)
  18488. // Add it to the field mask, but don't add anything to updateData.
  18489. a.push(e); else {
  18490. const t = dl(n, s);
  18491. null != t && (a.push(e), h.set(e, t));
  18492. }
  18493. }
  18494. const l = new be(a);
  18495. return new Xh(h, l, o.fieldTransforms);
  18496. }
  18497. /**
  18498. * Parse a "query value" (e.g. value in a where filter or a value in a cursor
  18499. * bound).
  18500. *
  18501. * @param allowArrays - Whether the query value is an array that may directly
  18502. * contain additional arrays (e.g. the operand of an `in` query).
  18503. */ function fl(t, e, n, s = !1) {
  18504. return dl(n, t.ya(s ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));
  18505. }
  18506. /**
  18507. * Parses user data to Protobuf Values.
  18508. *
  18509. * @param input - Data to be parsed.
  18510. * @param context - A context object representing the current path being parsed,
  18511. * the source of the data being parsed, etc.
  18512. * @returns The parsed value, or null if the value was a FieldValue sentinel
  18513. * that should not be included in the resulting parsed data.
  18514. */ function dl(t, e) {
  18515. if (_l(
  18516. // Unwrap the API type from the Compat SDK. This will return the API type
  18517. // from firestore-exp.
  18518. t = _(t))) return ml("Unsupported field value:", e, t), wl(t, e);
  18519. if (t instanceof Wh)
  18520. // FieldValues usually parse into transforms (except deleteField())
  18521. // in which case we do not want to include this field in our parsed data
  18522. // (as doing so will overwrite the field directly prior to the transform
  18523. // trying to transform it). So we don't add this location to
  18524. // context.fieldMask and we return null as our parsing result.
  18525. /**
  18526. * "Parses" the provided FieldValueImpl, adding any necessary transforms to
  18527. * context.fieldTransforms.
  18528. */
  18529. return function(t, e) {
  18530. // Sentinels are only supported with writes, and not within arrays.
  18531. if (!Zh(e.ca)) throw e._a(`${t._methodName}() can only be used with update() and set()`);
  18532. if (!e.path) throw e._a(`${t._methodName}() is not currently supported inside arrays`);
  18533. const n = t._toFieldTransform(e);
  18534. n && e.fieldTransforms.push(n);
  18535. }
  18536. /**
  18537. * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
  18538. *
  18539. * @returns The parsed value
  18540. */ (t, e), null;
  18541. if (void 0 === t && e.ignoreUndefinedProperties)
  18542. // If the input is undefined it can never participate in the fieldMask, so
  18543. // don't handle this below. If `ignoreUndefinedProperties` is false,
  18544. // `parseScalarValue` will reject an undefined value.
  18545. return null;
  18546. if (
  18547. // If context.path is null we are inside an array and we don't support
  18548. // field mask paths more granular than the top-level array.
  18549. e.path && e.fieldMask.push(e.path), t instanceof Array) {
  18550. // TODO(b/34871131): Include the path containing the array in the error
  18551. // message.
  18552. // In the case of IN queries, the parsed data is an array (representing
  18553. // the set of values to be included for the IN query) that may directly
  18554. // contain additional arrays (each representing an individual field
  18555. // value), so we disable this validation.
  18556. if (e.settings.la && 4 /* UserDataSource.ArrayArgument */ !== e.ca) throw e._a("Nested arrays are not supported");
  18557. return function(t, e) {
  18558. const n = [];
  18559. let s = 0;
  18560. for (const i of t) {
  18561. let t = dl(i, e.wa(s));
  18562. null == t && (
  18563. // Just include nulls in the array for fields being replaced with a
  18564. // sentinel.
  18565. t = {
  18566. nullValue: "NULL_VALUE"
  18567. }), n.push(t), s++;
  18568. }
  18569. return {
  18570. arrayValue: {
  18571. values: n
  18572. }
  18573. };
  18574. }(t, e);
  18575. }
  18576. return function(t, e) {
  18577. if (null === (t = _(t))) return {
  18578. nullValue: "NULL_VALUE"
  18579. };
  18580. if ("number" == typeof t) return Rs(e.serializer, t);
  18581. if ("boolean" == typeof t) return {
  18582. booleanValue: t
  18583. };
  18584. if ("string" == typeof t) return {
  18585. stringValue: t
  18586. };
  18587. if (t instanceof Date) {
  18588. const n = ot.fromDate(t);
  18589. return {
  18590. timestampValue: Ni(e.serializer, n)
  18591. };
  18592. }
  18593. if (t instanceof ot) {
  18594. // Firestore backend truncates precision down to microseconds. To ensure
  18595. // offline mode works the same with regards to truncation, perform the
  18596. // truncation immediately without waiting for the backend to do that.
  18597. const n = new ot(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
  18598. return {
  18599. timestampValue: Ni(e.serializer, n)
  18600. };
  18601. }
  18602. if (t instanceof Hh) return {
  18603. geoPointValue: {
  18604. latitude: t.latitude,
  18605. longitude: t.longitude
  18606. }
  18607. };
  18608. if (t instanceof Qh) return {
  18609. bytesValue: ki(e.serializer, t._byteString)
  18610. };
  18611. if (t instanceof _h) {
  18612. const n = e.databaseId, s = t.firestore._databaseId;
  18613. if (!s.isEqual(n)) throw e._a(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);
  18614. return {
  18615. referenceValue: Oi(t.firestore._databaseId || e.databaseId, t._key.path)
  18616. };
  18617. }
  18618. throw e._a(`Unsupported field value: ${ah(t)}`);
  18619. }
  18620. /**
  18621. * Checks whether an object looks like a JSON object that should be converted
  18622. * into a struct. Normal class/prototype instances are considered to look like
  18623. * JSON objects since they should be converted to a struct value. Arrays, Dates,
  18624. * GeoPoints, etc. are not considered to look like JSON objects since they map
  18625. * to specific FieldValue types other than ObjectValue.
  18626. */ (t, e);
  18627. }
  18628. function wl(t, e) {
  18629. const n = {};
  18630. return Ie(t) ?
  18631. // If we encounter an empty object, we explicitly add it to the update
  18632. // mask to ensure that the server creates a map entry.
  18633. e.path && e.path.length > 0 && e.fieldMask.push(e.path) : pe(t, ((t, s) => {
  18634. const i = dl(s, e.ha(t));
  18635. null != i && (n[t] = i);
  18636. })), {
  18637. mapValue: {
  18638. fields: n
  18639. }
  18640. };
  18641. }
  18642. function _l(t) {
  18643. return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof ot || t instanceof Hh || t instanceof Qh || t instanceof _h || t instanceof Wh);
  18644. }
  18645. function ml(t, e, n) {
  18646. if (!_l(n) || !function(t) {
  18647. return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));
  18648. }(n)) {
  18649. const s = ah(n);
  18650. throw "an object" === s ? e._a(t + " a custom object") : e._a(t + " " + s);
  18651. }
  18652. }
  18653. /**
  18654. * Helper that calls fromDotSeparatedString() but wraps any error thrown.
  18655. */ function gl(t, e, n) {
  18656. if ((
  18657. // If required, replace the FieldPath Compat class with with the firestore-exp
  18658. // FieldPath.
  18659. e = _(e)) instanceof jh) return e._internalPath;
  18660. if ("string" == typeof e) return pl(t, e);
  18661. throw Il("Field path arguments must be of type string or ", t,
  18662. /* hasConverter= */ !1,
  18663. /* path= */ void 0, n);
  18664. }
  18665. /**
  18666. * Matches any characters in a field path string that are reserved.
  18667. */ const yl = new RegExp("[~\\*/\\[\\]]");
  18668. /**
  18669. * Wraps fromDotSeparatedString with an error message about the method that
  18670. * was thrown.
  18671. * @param methodName - The publicly visible method name
  18672. * @param path - The dot-separated string form of a field path which will be
  18673. * split on dots.
  18674. * @param targetDoc - The document against which the field path will be
  18675. * evaluated.
  18676. */ function pl(t, e, n) {
  18677. if (e.search(yl) >= 0) throw Il(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t,
  18678. /* hasConverter= */ !1,
  18679. /* path= */ void 0, n);
  18680. try {
  18681. return new jh(...e.split("."))._internalPath;
  18682. } catch (s) {
  18683. throw Il(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t,
  18684. /* hasConverter= */ !1,
  18685. /* path= */ void 0, n);
  18686. }
  18687. }
  18688. function Il(t, e, n, s, i) {
  18689. const r = s && !s.isEmpty(), o = void 0 !== i;
  18690. let u = `Function ${e}() called with invalid data`;
  18691. n && (u += " (via `toFirestore()`)"), u += ". ";
  18692. let c = "";
  18693. return (r || o) && (c += " (found", r && (c += ` in field ${s}`), o && (c += ` in document ${i}`),
  18694. c += ")"), new G(K.INVALID_ARGUMENT, u + t + c);
  18695. }
  18696. /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function Tl(t, e) {
  18697. return t.some((t => t.isEqual(e)));
  18698. }
  18699. /**
  18700. * @license
  18701. * Copyright 2020 Google LLC
  18702. *
  18703. * Licensed under the Apache License, Version 2.0 (the "License");
  18704. * you may not use this file except in compliance with the License.
  18705. * You may obtain a copy of the License at
  18706. *
  18707. * http://www.apache.org/licenses/LICENSE-2.0
  18708. *
  18709. * Unless required by applicable law or agreed to in writing, software
  18710. * distributed under the License is distributed on an "AS IS" BASIS,
  18711. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18712. * See the License for the specific language governing permissions and
  18713. * limitations under the License.
  18714. */
  18715. /**
  18716. * A `DocumentSnapshot` contains data read from a document in your Firestore
  18717. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  18718. * get a specific field.
  18719. *
  18720. * For a `DocumentSnapshot` that points to a non-existing document, any data
  18721. * access will return 'undefined'. You can use the `exists()` method to
  18722. * explicitly verify a document's existence.
  18723. */ class El {
  18724. // Note: This class is stripped down version of the DocumentSnapshot in
  18725. // the legacy SDK. The changes are:
  18726. // - No support for SnapshotMetadata.
  18727. // - No support for SnapshotOptions.
  18728. /** @hideconstructor protected */
  18729. constructor(t, e, n, s, i) {
  18730. this._firestore = t, this._userDataWriter = e, this._key = n, this._document = s,
  18731. this._converter = i;
  18732. }
  18733. /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {
  18734. return this._key.path.lastSegment();
  18735. }
  18736. /**
  18737. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  18738. */ get ref() {
  18739. return new _h(this._firestore, this._converter, this._key);
  18740. }
  18741. /**
  18742. * Signals whether or not the document at the snapshot's location exists.
  18743. *
  18744. * @returns true if the document exists.
  18745. */ exists() {
  18746. return null !== this._document;
  18747. }
  18748. /**
  18749. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  18750. * the document doesn't exist.
  18751. *
  18752. * @returns An `Object` containing all fields in the document or `undefined`
  18753. * if the document doesn't exist.
  18754. */ data() {
  18755. if (this._document) {
  18756. if (this._converter) {
  18757. // We only want to use the converter and create a new DocumentSnapshot
  18758. // if a converter has been provided.
  18759. const t = new Al(this._firestore, this._userDataWriter, this._key, this._document,
  18760. /* converter= */ null);
  18761. return this._converter.fromFirestore(t);
  18762. }
  18763. return this._userDataWriter.convertValue(this._document.data.value);
  18764. }
  18765. }
  18766. /**
  18767. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  18768. * document or field doesn't exist.
  18769. *
  18770. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  18771. * field.
  18772. * @returns The data at the specified field location or undefined if no such
  18773. * field exists in the document.
  18774. */
  18775. // We are using `any` here to avoid an explicit cast by our users.
  18776. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18777. get(t) {
  18778. if (this._document) {
  18779. const e = this._document.data.field(vl("DocumentSnapshot.get", t));
  18780. if (null !== e) return this._userDataWriter.convertValue(e);
  18781. }
  18782. }
  18783. }
  18784. /**
  18785. * A `QueryDocumentSnapshot` contains data read from a document in your
  18786. * Firestore database as part of a query. The document is guaranteed to exist
  18787. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  18788. * specific field.
  18789. *
  18790. * A `QueryDocumentSnapshot` offers the same API surface as a
  18791. * `DocumentSnapshot`. Since query results contain only existing documents, the
  18792. * `exists` property will always be true and `data()` will never return
  18793. * 'undefined'.
  18794. */ class Al extends El {
  18795. /**
  18796. * Retrieves all fields in the document as an `Object`.
  18797. *
  18798. * @override
  18799. * @returns An `Object` containing all fields in the document.
  18800. */
  18801. data() {
  18802. return super.data();
  18803. }
  18804. }
  18805. /**
  18806. * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
  18807. */ function vl(t, e) {
  18808. return "string" == typeof e ? pl(t, e) : e instanceof jh ? e._internalPath : e._delegate._internalPath;
  18809. }
  18810. /**
  18811. * @license
  18812. * Copyright 2020 Google LLC
  18813. *
  18814. * Licensed under the Apache License, Version 2.0 (the "License");
  18815. * you may not use this file except in compliance with the License.
  18816. * You may obtain a copy of the License at
  18817. *
  18818. * http://www.apache.org/licenses/LICENSE-2.0
  18819. *
  18820. * Unless required by applicable law or agreed to in writing, software
  18821. * distributed under the License is distributed on an "AS IS" BASIS,
  18822. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18823. * See the License for the specific language governing permissions and
  18824. * limitations under the License.
  18825. */ function Rl(t) {
  18826. if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new G(K.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
  18827. }
  18828. /**
  18829. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  18830. * to a Firestore query.
  18831. */ class Pl {}
  18832. /**
  18833. * A `QueryConstraint` is used to narrow the set of documents returned by a
  18834. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  18835. * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
  18836. * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and
  18837. * can then be passed to {@link (query:1)} to create a new query instance that
  18838. * also contains this `QueryConstraint`.
  18839. */ class bl extends Pl {}
  18840. function Vl(t, e, ...n) {
  18841. let s = [];
  18842. e instanceof Pl && s.push(e), s = s.concat(n), function(t) {
  18843. const e = t.filter((t => t instanceof Cl)).length, n = t.filter((t => t instanceof Sl)).length;
  18844. if (e > 1 || e > 0 && n > 0) throw new G(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(...)))`.");
  18845. }
  18846. /**
  18847. * @license
  18848. * Copyright 2020 Google LLC
  18849. *
  18850. * Licensed under the Apache License, Version 2.0 (the "License");
  18851. * you may not use this file except in compliance with the License.
  18852. * You may obtain a copy of the License at
  18853. *
  18854. * http://www.apache.org/licenses/LICENSE-2.0
  18855. *
  18856. * Unless required by applicable law or agreed to in writing, software
  18857. * distributed under the License is distributed on an "AS IS" BASIS,
  18858. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18859. * See the License for the specific language governing permissions and
  18860. * limitations under the License.
  18861. */
  18862. /**
  18863. * Converts Firestore's internal types to the JavaScript types that we expose
  18864. * to the user.
  18865. *
  18866. * @internal
  18867. */ (s);
  18868. for (const e of s) t = e._apply(t);
  18869. return t;
  18870. }
  18871. /**
  18872. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  18873. * a Firestore query by filtering on one or more document fields.
  18874. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  18875. * be passed to {@link (query:1)} to create a new query instance that also contains
  18876. * this `QueryFieldFilterConstraint`.
  18877. */ class Sl extends bl {
  18878. /**
  18879. * @internal
  18880. */
  18881. constructor(t, e, n) {
  18882. super(), this._field = t, this._op = e, this._value = n,
  18883. /** The type of this query constraint */
  18884. this.type = "where";
  18885. }
  18886. static _create(t, e, n) {
  18887. return new Sl(t, e, n);
  18888. }
  18889. _apply(t) {
  18890. const e = this._parse(t);
  18891. return Wl(t._query, e), new mh(t.firestore, t.converter, ts(t._query, e));
  18892. }
  18893. _parse(t) {
  18894. const e = nl(t.firestore), n = function(t, e, n, s, i, r, o) {
  18895. let u;
  18896. if (i.isKeyField()) {
  18897. if ("array-contains" /* Operator.ARRAY_CONTAINS */ === r || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === r) throw new G(K.INVALID_ARGUMENT, `Invalid Query. You can't perform '${r}' queries on documentId().`);
  18898. if ("in" /* Operator.IN */ === r || "not-in" /* Operator.NOT_IN */ === r) {
  18899. zl(o, r);
  18900. const e = [];
  18901. for (const n of o) e.push(jl(s, t, n));
  18902. u = {
  18903. arrayValue: {
  18904. values: e
  18905. }
  18906. };
  18907. } else u = jl(s, t, o);
  18908. } else "in" /* Operator.IN */ !== r && "not-in" /* Operator.NOT_IN */ !== r && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== r || zl(o, r),
  18909. u = fl(n, e, o,
  18910. /* allowArrays= */ "in" /* Operator.IN */ === r || "not-in" /* Operator.NOT_IN */ === r);
  18911. return pn.create(i, r, u);
  18912. }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value);
  18913. return n;
  18914. }
  18915. }
  18916. /**
  18917. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  18918. * must contain the specified field and that the value should satisfy the
  18919. * relation constraint provided.
  18920. *
  18921. * @param fieldPath - The path to compare
  18922. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  18923. * "&lt;=", "!=").
  18924. * @param value - The value for comparison
  18925. * @returns The created {@link QueryFieldFilterConstraint}.
  18926. */ function Dl(t, e, n) {
  18927. const s = e, i = vl("where", t);
  18928. return Sl._create(i, s, n);
  18929. }
  18930. /**
  18931. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  18932. * returned by a Firestore query by performing the logical OR or AND of multiple
  18933. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  18934. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  18935. * {@link and} and can then be passed to {@link (query:1)} to create a new query
  18936. * instance that also contains the `QueryCompositeFilterConstraint`.
  18937. */ class Cl extends Pl {
  18938. /**
  18939. * @internal
  18940. */
  18941. constructor(
  18942. /** The type of this query constraint */
  18943. t, e) {
  18944. super(), this.type = t, this._queryConstraints = e;
  18945. }
  18946. static _create(t, e) {
  18947. return new Cl(t, e);
  18948. }
  18949. _parse(t) {
  18950. const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0));
  18951. return 1 === e.length ? e[0] : In.create(e, this._getOperator());
  18952. }
  18953. _apply(t) {
  18954. const e = this._parse(t);
  18955. return 0 === e.getFilters().length ? t : (function(t, e) {
  18956. let n = t;
  18957. const s = e.getFlattenedFilters();
  18958. for (const t of s) Wl(n, t), n = ts(n, t);
  18959. }
  18960. // Checks if any of the provided filter operators are included in the given list of filters and
  18961. // returns the first one that is, or null if none are.
  18962. (t._query, e), new mh(t.firestore, t.converter, ts(t._query, e)));
  18963. }
  18964. _getQueryConstraints() {
  18965. return this._queryConstraints;
  18966. }
  18967. _getOperator() {
  18968. return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
  18969. }
  18970. }
  18971. /**
  18972. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  18973. * the given filter constraints. A disjunction filter includes a document if it
  18974. * satisfies any of the given filters.
  18975. *
  18976. * @param queryConstraints - Optional. The list of
  18977. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  18978. * created with calls to {@link where}, {@link or}, or {@link and}.
  18979. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18980. */ function xl(...t) {
  18981. // Only support QueryFilterConstraints
  18982. return t.forEach((t => Jl("or", t))), Cl._create("or" /* CompositeOperator.OR */ , t);
  18983. }
  18984. /**
  18985. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  18986. * the given filter constraints. A conjunction filter includes a document if it
  18987. * satisfies all of the given filters.
  18988. *
  18989. * @param queryConstraints - Optional. The list of
  18990. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  18991. * created with calls to {@link where}, {@link or}, or {@link and}.
  18992. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18993. */ function Nl(...t) {
  18994. // Only support QueryFilterConstraints
  18995. return t.forEach((t => Jl("and", t))), Cl._create("and" /* CompositeOperator.AND */ , t);
  18996. }
  18997. /**
  18998. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  18999. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  19000. * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query
  19001. * instance that also contains this `QueryOrderByConstraint`.
  19002. *
  19003. * Note: Documents that do not contain the orderBy field will not be present in
  19004. * the query result.
  19005. */ class kl extends bl {
  19006. /**
  19007. * @internal
  19008. */
  19009. constructor(t, e) {
  19010. super(), this._field = t, this._direction = e,
  19011. /** The type of this query constraint */
  19012. this.type = "orderBy";
  19013. }
  19014. static _create(t, e) {
  19015. return new kl(t, e);
  19016. }
  19017. _apply(t) {
  19018. const e = function(t, e, n) {
  19019. if (null !== t.startAt) throw new G(K.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
  19020. if (null !== t.endAt) throw new G(K.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
  19021. const s = new mn(e, n);
  19022. return function(t, e) {
  19023. if (null === Hn(t)) {
  19024. // This is the first order by. It must match any inequality.
  19025. const n = Jn(t);
  19026. null !== n && Hl(t, n, e.field);
  19027. }
  19028. }(t, s), s;
  19029. }
  19030. /**
  19031. * Create a `Bound` from a query and a document.
  19032. *
  19033. * Note that the `Bound` will always include the key of the document
  19034. * and so only the provided document will compare equal to the returned
  19035. * position.
  19036. *
  19037. * Will throw if the document does not contain all fields of the order by
  19038. * of the query or if any of the fields in the order by are an uncommitted
  19039. * server timestamp.
  19040. */ (t._query, this._field, this._direction);
  19041. return new mh(t.firestore, t.converter, function(t, e) {
  19042. // TODO(dimond): validate that orderBy does not list the same key twice.
  19043. const n = t.explicitOrderBy.concat([ e ]);
  19044. return new Qn(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  19045. }(t._query, e));
  19046. }
  19047. }
  19048. /**
  19049. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  19050. * specified field, optionally in descending order instead of ascending.
  19051. *
  19052. * Note: Documents that do not contain the specified field will not be present
  19053. * in the query result.
  19054. *
  19055. * @param fieldPath - The field to sort by.
  19056. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  19057. * not specified, order will be ascending.
  19058. * @returns The created {@link QueryOrderByConstraint}.
  19059. */ function $l(t, e = "asc") {
  19060. const n = e, s = vl("orderBy", t);
  19061. return kl._create(s, n);
  19062. }
  19063. /**
  19064. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  19065. * a Firestore query.
  19066. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  19067. * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new
  19068. * query instance that also contains this `QueryLimitConstraint`.
  19069. */ class Ml extends bl {
  19070. /**
  19071. * @internal
  19072. */
  19073. constructor(
  19074. /** The type of this query constraint */
  19075. t, e, n) {
  19076. super(), this.type = t, this._limit = e, this._limitType = n;
  19077. }
  19078. static _create(t, e, n) {
  19079. return new Ml(t, e, n);
  19080. }
  19081. _apply(t) {
  19082. return new mh(t.firestore, t.converter, es(t._query, this._limit, this._limitType));
  19083. }
  19084. }
  19085. /**
  19086. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  19087. * documents.
  19088. *
  19089. * @param limit - The maximum number of items to return.
  19090. * @returns The created {@link QueryLimitConstraint}.
  19091. */ function Ol(t) {
  19092. return lh("limit", t), Ml._create("limit", t, "F" /* LimitType.First */);
  19093. }
  19094. /**
  19095. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  19096. * documents.
  19097. *
  19098. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  19099. * otherwise an exception will be thrown during execution.
  19100. *
  19101. * @param limit - The maximum number of items to return.
  19102. * @returns The created {@link QueryLimitConstraint}.
  19103. */ function Fl(t) {
  19104. return lh("limitToLast", t), Ml._create("limitToLast", t, "L" /* LimitType.Last */);
  19105. }
  19106. /**
  19107. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  19108. * result set returned by a Firestore query.
  19109. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  19110. * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a
  19111. * new query instance that also contains this `QueryStartAtConstraint`.
  19112. */ class Bl extends bl {
  19113. /**
  19114. * @internal
  19115. */
  19116. constructor(
  19117. /** The type of this query constraint */
  19118. t, e, n) {
  19119. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  19120. }
  19121. static _create(t, e, n) {
  19122. return new Bl(t, e, n);
  19123. }
  19124. _apply(t) {
  19125. const e = Ql(t, this.type, this._docOrFields, this._inclusive);
  19126. return new mh(t.firestore, t.converter, function(t, e) {
  19127. return new Qn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);
  19128. }(t._query, e));
  19129. }
  19130. }
  19131. function Ll(...t) {
  19132. return Bl._create("startAt", t,
  19133. /*inclusive=*/ !0);
  19134. }
  19135. function ql(...t) {
  19136. return Bl._create("startAfter", t,
  19137. /*inclusive=*/ !1);
  19138. }
  19139. /**
  19140. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  19141. * result set returned by a Firestore query.
  19142. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  19143. * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new
  19144. * query instance that also contains this `QueryEndAtConstraint`.
  19145. */ class Ul extends bl {
  19146. /**
  19147. * @internal
  19148. */
  19149. constructor(
  19150. /** The type of this query constraint */
  19151. t, e, n) {
  19152. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  19153. }
  19154. static _create(t, e, n) {
  19155. return new Ul(t, e, n);
  19156. }
  19157. _apply(t) {
  19158. const e = Ql(t, this.type, this._docOrFields, this._inclusive);
  19159. return new mh(t.firestore, t.converter, function(t, e) {
  19160. return new Qn(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);
  19161. }(t._query, e));
  19162. }
  19163. }
  19164. function Kl(...t) {
  19165. return Ul._create("endBefore", t,
  19166. /*inclusive=*/ !1);
  19167. }
  19168. function Gl(...t) {
  19169. return Ul._create("endAt", t,
  19170. /*inclusive=*/ !0);
  19171. }
  19172. /** Helper function to create a bound from a document or fields */ function Ql(t, e, n, s) {
  19173. if (n[0] = _(n[0]), n[0] instanceof El) return function(t, e, n, s, i) {
  19174. if (!s) throw new G(K.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);
  19175. const r = [];
  19176. // Because people expect to continue/end a query at the exact document
  19177. // provided, we need to use the implicit sort order rather than the explicit
  19178. // sort order, because it's guaranteed to contain the document key. That way
  19179. // the position becomes unambiguous and the query continues/ends exactly at
  19180. // the provided document. Without the key (by using the explicit sort
  19181. // orders), multiple documents could match the position, yielding duplicate
  19182. // results.
  19183. for (const n of Xn(t)) if (n.field.isKeyField()) r.push(Ye(e, s.key)); else {
  19184. const t = s.data.field(n.field);
  19185. if (Me(t)) throw new G(K.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
  19186. if (null === t) {
  19187. const t = n.field.canonicalString();
  19188. throw new G(K.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`);
  19189. }
  19190. r.push(t);
  19191. }
  19192. return new dn(r, i);
  19193. }
  19194. /**
  19195. * Converts a list of field values to a `Bound` for the given query.
  19196. */ (t._query, t.firestore._databaseId, e, n[0]._document, s);
  19197. {
  19198. const i = nl(t.firestore);
  19199. return function(t, e, n, s, i, r) {
  19200. // Use explicit order by's because it has to match the query the user made
  19201. const o = t.explicitOrderBy;
  19202. if (i.length > o.length) throw new G(K.INVALID_ARGUMENT, `Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);
  19203. const u = [];
  19204. for (let r = 0; r < i.length; r++) {
  19205. const c = i[r];
  19206. if (o[r].field.isKeyField()) {
  19207. if ("string" != typeof c) throw new G(K.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${s}(), but got a ${typeof c}`);
  19208. if (!Yn(t) && -1 !== c.indexOf("/")) throw new G(K.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${s}() must be a plain document ID, but '${c}' contains a slash.`);
  19209. const n = t.path.child(at.fromString(c));
  19210. if (!ft.isDocumentKey(n)) throw new G(K.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${s}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);
  19211. const i = new ft(n);
  19212. u.push(Ye(e, i));
  19213. } else {
  19214. const t = fl(n, s, c);
  19215. u.push(t);
  19216. }
  19217. }
  19218. return new dn(u, r);
  19219. }
  19220. /**
  19221. * Parses the given `documentIdValue` into a `ReferenceValue`, throwing
  19222. * appropriate errors if the value is anything other than a `DocumentReference`
  19223. * or `string`, or if the string is malformed.
  19224. */ (t._query, t.firestore._databaseId, i, e, n, s);
  19225. }
  19226. }
  19227. function jl(t, e, n) {
  19228. if ("string" == typeof (n = _(n))) {
  19229. if ("" === n) throw new G(K.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");
  19230. if (!Yn(e) && -1 !== n.indexOf("/")) throw new G(K.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);
  19231. const s = e.path.child(at.fromString(n));
  19232. if (!ft.isDocumentKey(s)) throw new G(K.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);
  19233. return Ye(t, new ft(s));
  19234. }
  19235. if (n instanceof _h) return Ye(t, n._key);
  19236. throw new G(K.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${ah(n)}.`);
  19237. }
  19238. /**
  19239. * Validates that the value passed into a disjunctive filter satisfies all
  19240. * array requirements.
  19241. */ function zl(t, e) {
  19242. if (!Array.isArray(t) || 0 === t.length) throw new G(K.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);
  19243. }
  19244. /**
  19245. * Given an operator, returns the set of operators that cannot be used with it.
  19246. *
  19247. * This is not a comprehensive check, and this function should be removed in the
  19248. * long term. Validations should occur in the Firestore backend.
  19249. *
  19250. * Operators in a query must adhere to the following set of rules:
  19251. * 1. Only one inequality per query.
  19252. * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.
  19253. */ function Wl(t, e) {
  19254. if (e.isInequality()) {
  19255. const n = Jn(t), s = e.field;
  19256. if (null !== n && !n.isEqual(s)) throw new G(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 '${n.toString()}' and '${s.toString()}'`);
  19257. const i = Hn(t);
  19258. null !== i && Hl(t, s, i);
  19259. }
  19260. const n = function(t, e) {
  19261. for (const n of t) for (const t of n.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op;
  19262. return null;
  19263. }(t.filters, function(t) {
  19264. switch (t) {
  19265. case "!=" /* Operator.NOT_EQUAL */ :
  19266. return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ];
  19267. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  19268. case "in" /* Operator.IN */ :
  19269. return [ "not-in" /* Operator.NOT_IN */ ];
  19270. case "not-in" /* Operator.NOT_IN */ :
  19271. return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ];
  19272. default:
  19273. return [];
  19274. }
  19275. }(e.op));
  19276. if (null !== n)
  19277. // Special case when it's a duplicate op to give a slightly clearer error message.
  19278. throw n === e.op ? new G(K.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new G(K.INVALID_ARGUMENT, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);
  19279. }
  19280. function Hl(t, e, n) {
  19281. if (!n.isEqual(e)) throw new G(K.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`);
  19282. }
  19283. function Jl(t, e) {
  19284. if (!(e instanceof Sl || e instanceof Cl)) throw new G(K.INVALID_ARGUMENT, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
  19285. }
  19286. class Yl {
  19287. convertValue(t, e = "none") {
  19288. switch (Ke(t)) {
  19289. case 0 /* TypeOrder.NullValue */ :
  19290. return null;
  19291. case 1 /* TypeOrder.BooleanValue */ :
  19292. return t.booleanValue;
  19293. case 2 /* TypeOrder.NumberValue */ :
  19294. return ke(t.integerValue || t.doubleValue);
  19295. case 3 /* TypeOrder.TimestampValue */ :
  19296. return this.convertTimestamp(t.timestampValue);
  19297. case 4 /* TypeOrder.ServerTimestampValue */ :
  19298. return this.convertServerTimestamp(t, e);
  19299. case 5 /* TypeOrder.StringValue */ :
  19300. return t.stringValue;
  19301. case 6 /* TypeOrder.BlobValue */ :
  19302. return this.convertBytes($e(t.bytesValue));
  19303. case 7 /* TypeOrder.RefValue */ :
  19304. return this.convertReference(t.referenceValue);
  19305. case 8 /* TypeOrder.GeoPointValue */ :
  19306. return this.convertGeoPoint(t.geoPointValue);
  19307. case 9 /* TypeOrder.ArrayValue */ :
  19308. return this.convertArray(t.arrayValue, e);
  19309. case 10 /* TypeOrder.ObjectValue */ :
  19310. return this.convertObject(t.mapValue, e);
  19311. default:
  19312. throw B();
  19313. }
  19314. }
  19315. convertObject(t, e) {
  19316. return this.convertObjectMap(t.fields, e);
  19317. }
  19318. /**
  19319. * @internal
  19320. */ convertObjectMap(t, e = "none") {
  19321. const n = {};
  19322. return pe(t, ((t, s) => {
  19323. n[t] = this.convertValue(s, e);
  19324. })), n;
  19325. }
  19326. convertGeoPoint(t) {
  19327. return new Hh(ke(t.latitude), ke(t.longitude));
  19328. }
  19329. convertArray(t, e) {
  19330. return (t.values || []).map((t => this.convertValue(t, e)));
  19331. }
  19332. convertServerTimestamp(t, e) {
  19333. switch (e) {
  19334. case "previous":
  19335. const n = Oe(t);
  19336. return null == n ? null : this.convertValue(n, e);
  19337. case "estimate":
  19338. return this.convertTimestamp(Fe(t));
  19339. default:
  19340. return null;
  19341. }
  19342. }
  19343. convertTimestamp(t) {
  19344. const e = Ne(t);
  19345. return new ot(e.seconds, e.nanos);
  19346. }
  19347. convertDocumentKey(t, e) {
  19348. const n = at.fromString(t);
  19349. L(hr(n));
  19350. const s = new Le(n.get(1), n.get(3)), i = new ft(n.popFirst(5));
  19351. return s.isEqual(e) ||
  19352. // TODO(b/64130202): Somehow support foreign references.
  19353. M(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`),
  19354. i;
  19355. }
  19356. }
  19357. /**
  19358. * @license
  19359. * Copyright 2020 Google LLC
  19360. *
  19361. * Licensed under the Apache License, Version 2.0 (the "License");
  19362. * you may not use this file except in compliance with the License.
  19363. * You may obtain a copy of the License at
  19364. *
  19365. * http://www.apache.org/licenses/LICENSE-2.0
  19366. *
  19367. * Unless required by applicable law or agreed to in writing, software
  19368. * distributed under the License is distributed on an "AS IS" BASIS,
  19369. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19370. * See the License for the specific language governing permissions and
  19371. * limitations under the License.
  19372. */
  19373. /**
  19374. * Converts custom model object of type T into `DocumentData` by applying the
  19375. * converter if it exists.
  19376. *
  19377. * This function is used when converting user objects to `DocumentData`
  19378. * because we want to provide the user with a more specific error message if
  19379. * their `set()` or fails due to invalid data originating from a `toFirestore()`
  19380. * call.
  19381. */ function Xl(t, e, n) {
  19382. let s;
  19383. // Cast to `any` in order to satisfy the union type constraint on
  19384. // toFirestore().
  19385. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19386. return s = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e,
  19387. s;
  19388. }
  19389. class Zl extends Yl {
  19390. constructor(t) {
  19391. super(), this.firestore = t;
  19392. }
  19393. convertBytes(t) {
  19394. return new Qh(t);
  19395. }
  19396. convertReference(t) {
  19397. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  19398. return new _h(this.firestore, /* converter= */ null, e);
  19399. }
  19400. }
  19401. /**
  19402. * @license
  19403. * Copyright 2022 Google LLC
  19404. *
  19405. * Licensed under the Apache License, Version 2.0 (the "License");
  19406. * you may not use this file except in compliance with the License.
  19407. * You may obtain a copy of the License at
  19408. *
  19409. * http://www.apache.org/licenses/LICENSE-2.0
  19410. *
  19411. * Unless required by applicable law or agreed to in writing, software
  19412. * distributed under the License is distributed on an "AS IS" BASIS,
  19413. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19414. * See the License for the specific language governing permissions and
  19415. * limitations under the License.
  19416. */
  19417. /**
  19418. * Create an AggregateField object that can be used to compute the sum of
  19419. * a specified field over a range of documents in the result set of a query.
  19420. * @param field Specifies the field to sum across the result set.
  19421. * @internal TODO (sum/avg) remove when public
  19422. */ function tf(t) {
  19423. return new Kh("sum", gl("sum", t));
  19424. }
  19425. /**
  19426. * Create an AggregateField object that can be used to compute the average of
  19427. * a specified field over a range of documents in the result set of a query.
  19428. * @param field Specifies the field to average across the result set.
  19429. * @internal TODO (sum/avg) remove when public
  19430. */ function ef(t) {
  19431. return new Kh("avg", gl("average", t));
  19432. }
  19433. /**
  19434. * Create an AggregateField object that can be used to compute the count of
  19435. * documents in the result set of a query.
  19436. * @internal TODO (sum/avg) remove when public
  19437. */ function nf() {
  19438. return new Kh("count");
  19439. }
  19440. /**
  19441. * Compares two 'AggregateField` instances for equality.
  19442. *
  19443. * @param left Compare this AggregateField to the `right`.
  19444. * @param right Compare this AggregateField to the `left`.
  19445. * @internal TODO (sum/avg) remove when public
  19446. */ function sf(t, e) {
  19447. var n, s;
  19448. return t instanceof Kh && e instanceof Kh && t._aggregateType === e._aggregateType && (null === (n = t._internalFieldPath) || void 0 === n ? void 0 : n.canonicalString()) === (null === (s = e._internalFieldPath) || void 0 === s ? void 0 : s.canonicalString());
  19449. }
  19450. /**
  19451. * Compares two `AggregateQuerySnapshot` instances for equality.
  19452. *
  19453. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  19454. * underlying queries that compare equal, and the same data.
  19455. *
  19456. * @param left - The first `AggregateQuerySnapshot` to compare.
  19457. * @param right - The second `AggregateQuerySnapshot` to compare.
  19458. *
  19459. * @returns `true` if the objects are "equal", as defined above, or `false`
  19460. * otherwise.
  19461. */ function rf(t, e) {
  19462. return Eh(t.query, e.query) && m(t.data(), e.data());
  19463. }
  19464. /**
  19465. * @license
  19466. * Copyright 2020 Google LLC
  19467. *
  19468. * Licensed under the Apache License, Version 2.0 (the "License");
  19469. * you may not use this file except in compliance with the License.
  19470. * You may obtain a copy of the License at
  19471. *
  19472. * http://www.apache.org/licenses/LICENSE-2.0
  19473. *
  19474. * Unless required by applicable law or agreed to in writing, software
  19475. * distributed under the License is distributed on an "AS IS" BASIS,
  19476. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19477. * See the License for the specific language governing permissions and
  19478. * limitations under the License.
  19479. */
  19480. /**
  19481. * Metadata about a snapshot, describing the state of the snapshot.
  19482. */ class of {
  19483. /** @hideconstructor */
  19484. constructor(t, e) {
  19485. this.hasPendingWrites = t, this.fromCache = e;
  19486. }
  19487. /**
  19488. * Returns true if this `SnapshotMetadata` is equal to the provided one.
  19489. *
  19490. * @param other - The `SnapshotMetadata` to compare against.
  19491. * @returns true if this `SnapshotMetadata` is equal to the provided one.
  19492. */ isEqual(t) {
  19493. return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;
  19494. }
  19495. }
  19496. /**
  19497. * A `DocumentSnapshot` contains data read from a document in your Firestore
  19498. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  19499. * get a specific field.
  19500. *
  19501. * For a `DocumentSnapshot` that points to a non-existing document, any data
  19502. * access will return 'undefined'. You can use the `exists()` method to
  19503. * explicitly verify a document's existence.
  19504. */ class uf extends El {
  19505. /** @hideconstructor protected */
  19506. constructor(t, e, n, s, i, r) {
  19507. super(t, e, n, s, r), this._firestore = t, this._firestoreImpl = t, this.metadata = i;
  19508. }
  19509. /**
  19510. * Returns whether or not the data exists. True if the document exists.
  19511. */ exists() {
  19512. return super.exists();
  19513. }
  19514. /**
  19515. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  19516. * the document doesn't exist.
  19517. *
  19518. * By default, `serverTimestamp()` values that have not yet been
  19519. * set to their final value will be returned as `null`. You can override
  19520. * this by passing an options object.
  19521. *
  19522. * @param options - An options object to configure how data is retrieved from
  19523. * the snapshot (for example the desired behavior for server timestamps that
  19524. * have not yet been set to their final value).
  19525. * @returns An `Object` containing all fields in the document or `undefined` if
  19526. * the document doesn't exist.
  19527. */ data(t = {}) {
  19528. if (this._document) {
  19529. if (this._converter) {
  19530. // We only want to use the converter and create a new DocumentSnapshot
  19531. // if a converter has been provided.
  19532. const e = new cf(this._firestore, this._userDataWriter, this._key, this._document, this.metadata,
  19533. /* converter= */ null);
  19534. return this._converter.fromFirestore(e, t);
  19535. }
  19536. return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);
  19537. }
  19538. }
  19539. /**
  19540. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  19541. * document or field doesn't exist.
  19542. *
  19543. * By default, a `serverTimestamp()` that has not yet been set to
  19544. * its final value will be returned as `null`. You can override this by
  19545. * passing an options object.
  19546. *
  19547. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  19548. * field.
  19549. * @param options - An options object to configure how the field is retrieved
  19550. * from the snapshot (for example the desired behavior for server timestamps
  19551. * that have not yet been set to their final value).
  19552. * @returns The data at the specified field location or undefined if no such
  19553. * field exists in the document.
  19554. */
  19555. // We are using `any` here to avoid an explicit cast by our users.
  19556. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  19557. get(t, e = {}) {
  19558. if (this._document) {
  19559. const n = this._document.data.field(vl("DocumentSnapshot.get", t));
  19560. if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);
  19561. }
  19562. }
  19563. }
  19564. /**
  19565. * A `QueryDocumentSnapshot` contains data read from a document in your
  19566. * Firestore database as part of a query. The document is guaranteed to exist
  19567. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  19568. * specific field.
  19569. *
  19570. * A `QueryDocumentSnapshot` offers the same API surface as a
  19571. * `DocumentSnapshot`. Since query results contain only existing documents, the
  19572. * `exists` property will always be true and `data()` will never return
  19573. * 'undefined'.
  19574. */ class cf extends uf {
  19575. /**
  19576. * Retrieves all fields in the document as an `Object`.
  19577. *
  19578. * By default, `serverTimestamp()` values that have not yet been
  19579. * set to their final value will be returned as `null`. You can override
  19580. * this by passing an options object.
  19581. *
  19582. * @override
  19583. * @param options - An options object to configure how data is retrieved from
  19584. * the snapshot (for example the desired behavior for server timestamps that
  19585. * have not yet been set to their final value).
  19586. * @returns An `Object` containing all fields in the document.
  19587. */
  19588. data(t = {}) {
  19589. return super.data(t);
  19590. }
  19591. }
  19592. /**
  19593. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  19594. * representing the results of a query. The documents can be accessed as an
  19595. * array via the `docs` property or enumerated using the `forEach` method. The
  19596. * number of documents can be determined via the `empty` and `size`
  19597. * properties.
  19598. */ class af {
  19599. /** @hideconstructor */
  19600. constructor(t, e, n, s) {
  19601. this._firestore = t, this._userDataWriter = e, this._snapshot = s, this.metadata = new of(s.hasPendingWrites, s.fromCache),
  19602. this.query = n;
  19603. }
  19604. /** An array of all the documents in the `QuerySnapshot`. */ get docs() {
  19605. const t = [];
  19606. return this.forEach((e => t.push(e))), t;
  19607. }
  19608. /** The number of documents in the `QuerySnapshot`. */ get size() {
  19609. return this._snapshot.docs.size;
  19610. }
  19611. /** True if there are no documents in the `QuerySnapshot`. */ get empty() {
  19612. return 0 === this.size;
  19613. }
  19614. /**
  19615. * Enumerates all of the documents in the `QuerySnapshot`.
  19616. *
  19617. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  19618. * each document in the snapshot.
  19619. * @param thisArg - The `this` binding for the callback.
  19620. */ forEach(t, e) {
  19621. this._snapshot.docs.forEach((n => {
  19622. t.call(e, new cf(this._firestore, this._userDataWriter, n.key, n, new of(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));
  19623. }));
  19624. }
  19625. /**
  19626. * Returns an array of the documents changes since the last snapshot. If this
  19627. * is the first snapshot, all documents will be in the list as 'added'
  19628. * changes.
  19629. *
  19630. * @param options - `SnapshotListenOptions` that control whether metadata-only
  19631. * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
  19632. * snapshot events.
  19633. */ docChanges(t = {}) {
  19634. const e = !!t.includeMetadataChanges;
  19635. if (e && this._snapshot.excludesMetadataChanges) throw new G(K.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
  19636. return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges =
  19637. /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */
  19638. function(t, e) {
  19639. if (t._snapshot.oldDocs.isEmpty()) {
  19640. let e = 0;
  19641. return t._snapshot.docChanges.map((n => {
  19642. const s = new cf(t._firestore, t._userDataWriter, n.doc.key, n.doc, new of(t._snapshot.mutatedKeys.has(n.doc.key), t._snapshot.fromCache), t.query.converter);
  19643. return n.doc, {
  19644. type: "added",
  19645. doc: s,
  19646. oldIndex: -1,
  19647. newIndex: e++
  19648. };
  19649. }));
  19650. }
  19651. {
  19652. // A `DocumentSet` that is updated incrementally as changes are applied to use
  19653. // to lookup the index of a document.
  19654. let n = t._snapshot.oldDocs;
  19655. return t._snapshot.docChanges.filter((t => e || 3 /* ChangeType.Metadata */ !== t.type)).map((e => {
  19656. const s = new cf(t._firestore, t._userDataWriter, e.doc.key, e.doc, new of(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);
  19657. let i = -1, r = -1;
  19658. return 0 /* ChangeType.Added */ !== e.type && (i = n.indexOf(e.doc.key), n = n.delete(e.doc.key)),
  19659. 1 /* ChangeType.Removed */ !== e.type && (n = n.add(e.doc), r = n.indexOf(e.doc.key)),
  19660. {
  19661. type: hf(e.type),
  19662. doc: s,
  19663. oldIndex: i,
  19664. newIndex: r
  19665. };
  19666. }));
  19667. }
  19668. }(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;
  19669. }
  19670. }
  19671. function hf(t) {
  19672. switch (t) {
  19673. case 0 /* ChangeType.Added */ :
  19674. return "added";
  19675. case 2 /* ChangeType.Modified */ :
  19676. case 3 /* ChangeType.Metadata */ :
  19677. return "modified";
  19678. case 1 /* ChangeType.Removed */ :
  19679. return "removed";
  19680. default:
  19681. return B();
  19682. }
  19683. }
  19684. // TODO(firestoreexp): Add tests for snapshotEqual with different snapshot
  19685. // metadata
  19686. /**
  19687. * Returns true if the provided snapshots are equal.
  19688. *
  19689. * @param left - A snapshot to compare.
  19690. * @param right - A snapshot to compare.
  19691. * @returns true if the snapshots are equal.
  19692. */ function lf(t, e) {
  19693. return t instanceof uf && e instanceof uf ? 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 af && e instanceof af && (t._firestore === e._firestore && Eh(t.query, e.query) && t.metadata.isEqual(e.metadata) && t._snapshot.isEqual(e._snapshot));
  19694. }
  19695. /**
  19696. * @license
  19697. * Copyright 2020 Google LLC
  19698. *
  19699. * Licensed under the Apache License, Version 2.0 (the "License");
  19700. * you may not use this file except in compliance with the License.
  19701. * You may obtain a copy of the License at
  19702. *
  19703. * http://www.apache.org/licenses/LICENSE-2.0
  19704. *
  19705. * Unless required by applicable law or agreed to in writing, software
  19706. * distributed under the License is distributed on an "AS IS" BASIS,
  19707. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19708. * See the License for the specific language governing permissions and
  19709. * limitations under the License.
  19710. */
  19711. /**
  19712. * Reads the document referred to by this `DocumentReference`.
  19713. *
  19714. * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting
  19715. * for data from the server, but it may return cached data or fail if you are
  19716. * offline and the server cannot be reached. To specify this behavior, invoke
  19717. * {@link getDocFromCache} or {@link getDocFromServer}.
  19718. *
  19719. * @param reference - The reference of the document to fetch.
  19720. * @returns A Promise resolved with a `DocumentSnapshot` containing the
  19721. * current document contents.
  19722. */ function ff(t) {
  19723. t = hh(t, _h);
  19724. const e = hh(t.firestore, bh);
  19725. return Ja(Dh(e), t._key).then((n => Pf(e, t, n)));
  19726. }
  19727. class df extends Yl {
  19728. constructor(t) {
  19729. super(), this.firestore = t;
  19730. }
  19731. convertBytes(t) {
  19732. return new Qh(t);
  19733. }
  19734. convertReference(t) {
  19735. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  19736. return new _h(this.firestore, /* converter= */ null, e);
  19737. }
  19738. }
  19739. /**
  19740. * Reads the document referred to by this `DocumentReference` from cache.
  19741. * Returns an error if the document is not currently cached.
  19742. *
  19743. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19744. * current document contents.
  19745. */ function wf(t) {
  19746. t = hh(t, _h);
  19747. const e = hh(t.firestore, bh), n = Dh(e), s = new df(e);
  19748. return Ha(n, t._key).then((n => new uf(e, s, t._key, n, new of(null !== n && n.hasLocalMutations,
  19749. /* fromCache= */ !0), t.converter)));
  19750. }
  19751. /**
  19752. * Reads the document referred to by this `DocumentReference` from the server.
  19753. * Returns an error if the network is not available.
  19754. *
  19755. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19756. * current document contents.
  19757. */ function _f(t) {
  19758. t = hh(t, _h);
  19759. const e = hh(t.firestore, bh);
  19760. return Ja(Dh(e), t._key, {
  19761. source: "server"
  19762. }).then((n => Pf(e, t, n)));
  19763. }
  19764. /**
  19765. * Executes the query and returns the results as a `QuerySnapshot`.
  19766. *
  19767. * Note: `getDocs()` attempts to provide up-to-date data when possible by
  19768. * waiting for data from the server, but it may return cached data or fail if
  19769. * you are offline and the server cannot be reached. To specify this behavior,
  19770. * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
  19771. *
  19772. * @returns A `Promise` that will be resolved with the results of the query.
  19773. */ function mf(t) {
  19774. t = hh(t, mh);
  19775. const e = hh(t.firestore, bh), n = Dh(e), s = new df(e);
  19776. return Rl(t._query), Xa(n, t._query).then((n => new af(e, s, t, n)));
  19777. }
  19778. /**
  19779. * Executes the query and returns the results as a `QuerySnapshot` from cache.
  19780. * Returns an empty result set if no documents matching the query are currently
  19781. * cached.
  19782. *
  19783. * @returns A `Promise` that will be resolved with the results of the query.
  19784. */ function gf(t) {
  19785. t = hh(t, mh);
  19786. const e = hh(t.firestore, bh), n = Dh(e), s = new df(e);
  19787. return Ya(n, t._query).then((n => new af(e, s, t, n)));
  19788. }
  19789. /**
  19790. * Executes the query and returns the results as a `QuerySnapshot` from the
  19791. * server. Returns an error if the network is not available.
  19792. *
  19793. * @returns A `Promise` that will be resolved with the results of the query.
  19794. */ function yf(t) {
  19795. t = hh(t, mh);
  19796. const e = hh(t.firestore, bh), n = Dh(e), s = new df(e);
  19797. return Xa(n, t._query, {
  19798. source: "server"
  19799. }).then((n => new af(e, s, t, n)));
  19800. }
  19801. function pf(t, e, n) {
  19802. t = hh(t, _h);
  19803. const s = hh(t.firestore, bh), i = Xl(t.converter, e, n);
  19804. return Rf(s, [ sl(nl(s), "setDoc", t._key, i, null !== t.converter, n).toMutation(t._key, qs.none()) ]);
  19805. }
  19806. function If(t, e, n, ...s) {
  19807. t = hh(t, _h);
  19808. const i = hh(t.firestore, bh), r = nl(i);
  19809. let o;
  19810. o = "string" == typeof (
  19811. // For Compat types, we have to "extract" the underlying types before
  19812. // performing validation.
  19813. e = _(e)) || e instanceof jh ? ll(r, "updateDoc", t._key, e, n, s) : hl(r, "updateDoc", t._key, e);
  19814. return Rf(i, [ o.toMutation(t._key, qs.exists(!0)) ]);
  19815. }
  19816. /**
  19817. * Deletes the document referred to by the specified `DocumentReference`.
  19818. *
  19819. * @param reference - A reference to the document to delete.
  19820. * @returns A Promise resolved once the document has been successfully
  19821. * deleted from the backend (note that it won't resolve while you're offline).
  19822. */ function Tf(t) {
  19823. return Rf(hh(t.firestore, bh), [ new ti(t._key, qs.none()) ]);
  19824. }
  19825. /**
  19826. * Add a new document to specified `CollectionReference` with the given data,
  19827. * assigning it a document ID automatically.
  19828. *
  19829. * @param reference - A reference to the collection to add this document to.
  19830. * @param data - An Object containing the data for the new document.
  19831. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  19832. * newly created document after it has been written to the backend (Note that it
  19833. * won't resolve while you're offline).
  19834. */ function Ef(t, e) {
  19835. const n = hh(t.firestore, bh), s = Ih(t), i = Xl(t.converter, e);
  19836. return Rf(n, [ sl(nl(t.firestore), "addDoc", s._key, i, null !== t.converter, {}).toMutation(s._key, qs.exists(!1)) ]).then((() => s));
  19837. }
  19838. function Af(t, ...e) {
  19839. var n, s, i;
  19840. t = _(t);
  19841. let r = {
  19842. includeMetadataChanges: !1
  19843. }, o = 0;
  19844. "object" != typeof e[o] || vh(e[o]) || (r = e[o], o++);
  19845. const u = {
  19846. includeMetadataChanges: r.includeMetadataChanges
  19847. };
  19848. if (vh(e[o])) {
  19849. const t = e[o];
  19850. e[o] = null === (n = t.next) || void 0 === n ? void 0 : n.bind(t), e[o + 1] = null === (s = t.error) || void 0 === s ? void 0 : s.bind(t),
  19851. e[o + 2] = null === (i = t.complete) || void 0 === i ? void 0 : i.bind(t);
  19852. }
  19853. let c, a, h;
  19854. if (t instanceof _h) a = hh(t.firestore, bh), h = zn(t._key.path), c = {
  19855. next: n => {
  19856. e[o] && e[o](Pf(a, t, n));
  19857. },
  19858. error: e[o + 1],
  19859. complete: e[o + 2]
  19860. }; else {
  19861. const n = hh(t, mh);
  19862. a = hh(n.firestore, bh), h = n._query;
  19863. const s = new df(a);
  19864. c = {
  19865. next: t => {
  19866. e[o] && e[o](new af(a, s, n, t));
  19867. },
  19868. error: e[o + 1],
  19869. complete: e[o + 2]
  19870. }, Rl(t._query);
  19871. }
  19872. return function(t, e, n, s) {
  19873. const i = new Ca(s), r = new Mc(e, i, n);
  19874. return t.asyncQueue.enqueueAndForget((async () => Cc(await ja(t), r))), () => {
  19875. i.Dc(), t.asyncQueue.enqueueAndForget((async () => xc(await ja(t), r)));
  19876. };
  19877. }(Dh(a), h, u, c);
  19878. }
  19879. function vf(t, e) {
  19880. return Za(Dh(t = hh(t, bh)), vh(e) ? e : {
  19881. next: e
  19882. });
  19883. }
  19884. /**
  19885. * Locally writes `mutations` on the async queue.
  19886. * @internal
  19887. */ function Rf(t, e) {
  19888. return function(t, e) {
  19889. const n = new Q;
  19890. return t.asyncQueue.enqueueAndForget((async () => Jc(await Ga(t), e, n))), n.promise;
  19891. }(Dh(t), e);
  19892. }
  19893. /**
  19894. * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`
  19895. * to a {@link DocumentSnapshot}.
  19896. */ function Pf(t, e, n) {
  19897. const s = n.docs.get(e._key), i = new df(t);
  19898. return new uf(t, i, e._key, s, new of(n.hasPendingWrites, n.fromCache), e.converter);
  19899. }
  19900. /**
  19901. * @license
  19902. * Copyright 2022 Google LLC
  19903. *
  19904. * Licensed under the Apache License, Version 2.0 (the "License");
  19905. * you may not use this file except in compliance with the License.
  19906. * You may obtain a copy of the License at
  19907. *
  19908. * http://www.apache.org/licenses/LICENSE-2.0
  19909. *
  19910. * Unless required by applicable law or agreed to in writing, software
  19911. * distributed under the License is distributed on an "AS IS" BASIS,
  19912. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19913. * See the License for the specific language governing permissions and
  19914. * limitations under the License.
  19915. */
  19916. /**
  19917. * Calculates the number of documents in the result set of the given query,
  19918. * without actually downloading the documents.
  19919. *
  19920. * Using this function to count the documents is efficient because only the
  19921. * final count, not the documents' data, is downloaded. This function can even
  19922. * count the documents if the result set would be prohibitively large to
  19923. * download entirely (e.g. thousands of documents).
  19924. *
  19925. * The result received from the server is presented, unaltered, without
  19926. * considering any local state. That is, documents in the local cache are not
  19927. * taken into consideration, neither are local modifications not yet
  19928. * synchronized with the server. Previously-downloaded results, if any, are not
  19929. * used: every request using this source necessarily involves a round trip to
  19930. * the server.
  19931. *
  19932. * @param query - The query whose result set size to calculate.
  19933. * @returns A Promise that will be resolved with the count; the count can be
  19934. * retrieved from `snapshot.data().count`, where `snapshot` is the
  19935. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  19936. */ function bf(t) {
  19937. return Vf(t, {
  19938. count: nf()
  19939. });
  19940. }
  19941. /**
  19942. * Calculates the specified aggregations over the documents in the result
  19943. * set of the given query, without actually downloading the documents.
  19944. *
  19945. * Using this function to perform aggregations is efficient because only the
  19946. * final aggregation values, not the documents' data, is downloaded. This
  19947. * function can even perform aggregations of the documents if the result set
  19948. * would be prohibitively large to download entirely (e.g. thousands of documents).
  19949. *
  19950. * The result received from the server is presented, unaltered, without
  19951. * considering any local state. That is, documents in the local cache are not
  19952. * taken into consideration, neither are local modifications not yet
  19953. * synchronized with the server. Previously-downloaded results, if any, are not
  19954. * used: every request using this source necessarily involves a round trip to
  19955. * the server.
  19956. *
  19957. * @param query The query whose result set to aggregate over.
  19958. * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates
  19959. * to perform over the result set. The AggregateSpec specifies aliases for each
  19960. * aggregate, which can be used to retrieve the aggregate result.
  19961. * @example
  19962. * ```typescript
  19963. * const aggregateSnapshot = await getAggregateFromServer(query, {
  19964. * countOfDocs: count(),
  19965. * totalHours: sum('hours'),
  19966. * averageScore: average('score')
  19967. * });
  19968. *
  19969. * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;
  19970. * const totalHours: number = aggregateSnapshot.data().totalHours;
  19971. * const averageScore: number | null = aggregateSnapshot.data().averageScore;
  19972. * ```
  19973. * @internal TODO (sum/avg) remove when public
  19974. */ function Vf(t, e) {
  19975. const n = hh(t.firestore, bh), s = Dh(n), i = function(t, e) {
  19976. const n = [];
  19977. for (const s in t) Object.prototype.hasOwnProperty.call(t, s) && n.push(e(t[s], s, t));
  19978. return n;
  19979. }(e, ((t, e) => new ri(e, t._aggregateType, t._internalFieldPath)));
  19980. // Run the aggregation and convert the results
  19981. return function(t, e, n) {
  19982. const s = new Q;
  19983. return t.asyncQueue.enqueueAndForget((async () => {
  19984. // TODO (sum/avg) should we update this to use the event manager?
  19985. // Implement and call executeAggregateQueryViaSnapshotListener, similar
  19986. // to the implementation in firestoreClientGetDocumentsViaSnapshotListener
  19987. // above
  19988. try {
  19989. // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.
  19990. const i = await Qa(t);
  19991. s.resolve(zu(i, e, n));
  19992. } catch (t) {
  19993. s.reject(t);
  19994. }
  19995. })), s.promise;
  19996. }(s, t._query, i).then((e =>
  19997. /**
  19998. * Converts the core aggregration result to an `AggregateQuerySnapshot`
  19999. * that can be returned to the consumer.
  20000. * @param query
  20001. * @param aggregateResult Core aggregation result
  20002. * @internal
  20003. */
  20004. function(t, e, n) {
  20005. const s = new df(t);
  20006. return new Gh(e, s, n);
  20007. }
  20008. /**
  20009. * @license
  20010. * Copyright 2023 Google LLC
  20011. *
  20012. * Licensed under the Apache License, Version 2.0 (the "License");
  20013. * you may not use this file except in compliance with the License.
  20014. * You may obtain a copy of the License at
  20015. *
  20016. * http://www.apache.org/licenses/LICENSE-2.0
  20017. *
  20018. * Unless required by applicable law or agreed to in writing, software
  20019. * distributed under the License is distributed on an "AS IS" BASIS,
  20020. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20021. * See the License for the specific language governing permissions and
  20022. * limitations under the License.
  20023. */ (n, t, e)));
  20024. }
  20025. class Sf {
  20026. constructor(t) {
  20027. this.kind = "memory", this._onlineComponentProvider = new Sa, (null == t ? void 0 : t.garbageCollector) ? this._offlineComponentProvider = t.garbageCollector._offlineComponentProvider : this._offlineComponentProvider = new Ra;
  20028. }
  20029. toJSON() {
  20030. return {
  20031. kind: this.kind
  20032. };
  20033. }
  20034. }
  20035. class Df {
  20036. constructor(t) {
  20037. let e;
  20038. this.kind = "persistent", (null == t ? void 0 : t.tabManager) ? (t.tabManager._initialize(t),
  20039. e = t.tabManager) : (e = Bf(void 0), e._initialize(t)), this._onlineComponentProvider = e._onlineComponentProvider,
  20040. this._offlineComponentProvider = e._offlineComponentProvider;
  20041. }
  20042. toJSON() {
  20043. return {
  20044. kind: this.kind
  20045. };
  20046. }
  20047. }
  20048. class Cf {
  20049. constructor() {
  20050. this.kind = "memoryEager", this._offlineComponentProvider = new Ra;
  20051. }
  20052. toJSON() {
  20053. return {
  20054. kind: this.kind
  20055. };
  20056. }
  20057. }
  20058. class xf {
  20059. constructor(t) {
  20060. this.kind = "memoryLru", this._offlineComponentProvider = new Pa(t);
  20061. }
  20062. toJSON() {
  20063. return {
  20064. kind: this.kind
  20065. };
  20066. }
  20067. }
  20068. /**
  20069. * Creates an instance of `MemoryEagerGarbageCollector`. This is also the
  20070. * default garbage collector unless it is explicitly specified otherwise.
  20071. */ function Nf() {
  20072. return new Cf;
  20073. }
  20074. /**
  20075. * Creates an instance of `MemoryLruGarbageCollector`.
  20076. *
  20077. * A target size can be specified as part of the setting parameter. The
  20078. * collector will start deleting documents once the cache size exceeds
  20079. * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).
  20080. */ function kf(t) {
  20081. return new xf(null == t ? void 0 : t.cacheSizeBytes);
  20082. }
  20083. /**
  20084. * Creates an instance of `MemoryLocalCache`. The instance can be set to
  20085. * `FirestoreSettings.cache` to tell the SDK which cache layer to use.
  20086. */ function $f(t) {
  20087. return new Sf(t);
  20088. }
  20089. /**
  20090. * Creates an instance of `PersistentLocalCache`. The instance can be set to
  20091. * `FirestoreSettings.cache` to tell the SDK which cache layer to use.
  20092. *
  20093. * Persistent cache cannot be used in a Node.js environment.
  20094. */ function Mf(t) {
  20095. return new Df(t);
  20096. }
  20097. class Of {
  20098. constructor(t) {
  20099. this.forceOwnership = t, this.kind = "persistentSingleTab";
  20100. }
  20101. toJSON() {
  20102. return {
  20103. kind: this.kind
  20104. };
  20105. }
  20106. /**
  20107. * @internal
  20108. */ _initialize(t) {
  20109. this._onlineComponentProvider = new Sa, this._offlineComponentProvider = new ba(this._onlineComponentProvider, null == t ? void 0 : t.cacheSizeBytes, this.forceOwnership);
  20110. }
  20111. }
  20112. class Ff {
  20113. constructor() {
  20114. this.kind = "PersistentMultipleTab";
  20115. }
  20116. toJSON() {
  20117. return {
  20118. kind: this.kind
  20119. };
  20120. }
  20121. /**
  20122. * @internal
  20123. */ _initialize(t) {
  20124. this._onlineComponentProvider = new Sa, this._offlineComponentProvider = new Va(this._onlineComponentProvider, null == t ? void 0 : t.cacheSizeBytes);
  20125. }
  20126. }
  20127. /**
  20128. * Creates an instance of `PersistentSingleTabManager`.
  20129. *
  20130. * @param settings Configures the created tab manager.
  20131. */ function Bf(t) {
  20132. return new Of(null == t ? void 0 : t.forceOwnership);
  20133. }
  20134. /**
  20135. * Creates an instance of `PersistentMultipleTabManager`.
  20136. */ function Lf() {
  20137. return new Ff;
  20138. }
  20139. /**
  20140. * @license
  20141. * Copyright 2022 Google LLC
  20142. *
  20143. * Licensed under the Apache License, Version 2.0 (the "License");
  20144. * you may not use this file except in compliance with the License.
  20145. * You may obtain a copy of the License at
  20146. *
  20147. * http://www.apache.org/licenses/LICENSE-2.0
  20148. *
  20149. * Unless required by applicable law or agreed to in writing, software
  20150. * distributed under the License is distributed on an "AS IS" BASIS,
  20151. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20152. * See the License for the specific language governing permissions and
  20153. * limitations under the License.
  20154. */ const qf = {
  20155. maxAttempts: 5
  20156. };
  20157. /**
  20158. * @license
  20159. * Copyright 2020 Google LLC
  20160. *
  20161. * Licensed under the Apache License, Version 2.0 (the "License");
  20162. * you may not use this file except in compliance with the License.
  20163. * You may obtain a copy of the License at
  20164. *
  20165. * http://www.apache.org/licenses/LICENSE-2.0
  20166. *
  20167. * Unless required by applicable law or agreed to in writing, software
  20168. * distributed under the License is distributed on an "AS IS" BASIS,
  20169. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20170. * See the License for the specific language governing permissions and
  20171. * limitations under the License.
  20172. */
  20173. /**
  20174. * A write batch, used to perform multiple writes as a single atomic unit.
  20175. *
  20176. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  20177. * provides methods for adding writes to the write batch. None of the writes
  20178. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  20179. * called.
  20180. */
  20181. class Uf {
  20182. /** @hideconstructor */
  20183. constructor(t, e) {
  20184. this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1,
  20185. this._dataReader = nl(t);
  20186. }
  20187. set(t, e, n) {
  20188. this._verifyNotCommitted();
  20189. const s = Kf(t, this._firestore), i = Xl(s.converter, e, n), r = sl(this._dataReader, "WriteBatch.set", s._key, i, null !== s.converter, n);
  20190. return this._mutations.push(r.toMutation(s._key, qs.none())), this;
  20191. }
  20192. update(t, e, n, ...s) {
  20193. this._verifyNotCommitted();
  20194. const i = Kf(t, this._firestore);
  20195. // For Compat types, we have to "extract" the underlying types before
  20196. // performing validation.
  20197. let r;
  20198. return r = "string" == typeof (e = _(e)) || e instanceof jh ? ll(this._dataReader, "WriteBatch.update", i._key, e, n, s) : hl(this._dataReader, "WriteBatch.update", i._key, e),
  20199. this._mutations.push(r.toMutation(i._key, qs.exists(!0))), this;
  20200. }
  20201. /**
  20202. * Deletes the document referred to by the provided {@link DocumentReference}.
  20203. *
  20204. * @param documentRef - A reference to the document to be deleted.
  20205. * @returns This `WriteBatch` instance. Used for chaining method calls.
  20206. */ delete(t) {
  20207. this._verifyNotCommitted();
  20208. const e = Kf(t, this._firestore);
  20209. return this._mutations = this._mutations.concat(new ti(e._key, qs.none())), this;
  20210. }
  20211. /**
  20212. * Commits all of the writes in this write batch as a single atomic unit.
  20213. *
  20214. * The result of these writes will only be reflected in document reads that
  20215. * occur after the returned promise resolves. If the client is offline, the
  20216. * write fails. If you would like to see local modifications or buffer writes
  20217. * until the client is online, use the full Firestore SDK.
  20218. *
  20219. * @returns A `Promise` resolved once all of the writes in the batch have been
  20220. * successfully written to the backend as an atomic unit (note that it won't
  20221. * resolve while you're offline).
  20222. */ commit() {
  20223. return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();
  20224. }
  20225. _verifyNotCommitted() {
  20226. if (this._committed) throw new G(K.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
  20227. }
  20228. }
  20229. function Kf(t, e) {
  20230. if ((t = _(t)).firestore !== e) throw new G(K.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
  20231. return t;
  20232. }
  20233. /**
  20234. * @license
  20235. * Copyright 2020 Google LLC
  20236. *
  20237. * Licensed under the Apache License, Version 2.0 (the "License");
  20238. * you may not use this file except in compliance with the License.
  20239. * You may obtain a copy of the License at
  20240. *
  20241. * http://www.apache.org/licenses/LICENSE-2.0
  20242. *
  20243. * Unless required by applicable law or agreed to in writing, software
  20244. * distributed under the License is distributed on an "AS IS" BASIS,
  20245. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20246. * See the License for the specific language governing permissions and
  20247. * limitations under the License.
  20248. */
  20249. // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
  20250. // legacy SDK.
  20251. /**
  20252. * A reference to a transaction.
  20253. *
  20254. * The `Transaction` object passed to a transaction's `updateFunction` provides
  20255. * the methods to read and write data within the transaction context. See
  20256. * {@link runTransaction}.
  20257. */
  20258. /**
  20259. * @license
  20260. * Copyright 2020 Google LLC
  20261. *
  20262. * Licensed under the Apache License, Version 2.0 (the "License");
  20263. * you may not use this file except in compliance with the License.
  20264. * You may obtain a copy of the License at
  20265. *
  20266. * http://www.apache.org/licenses/LICENSE-2.0
  20267. *
  20268. * Unless required by applicable law or agreed to in writing, software
  20269. * distributed under the License is distributed on an "AS IS" BASIS,
  20270. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20271. * See the License for the specific language governing permissions and
  20272. * limitations under the License.
  20273. */
  20274. /**
  20275. * A reference to a transaction.
  20276. *
  20277. * The `Transaction` object passed to a transaction's `updateFunction` provides
  20278. * the methods to read and write data within the transaction context. See
  20279. * {@link runTransaction}.
  20280. */
  20281. class Gf extends class {
  20282. /** @hideconstructor */
  20283. constructor(t, e) {
  20284. this._firestore = t, this._transaction = e, this._dataReader = nl(t);
  20285. }
  20286. /**
  20287. * Reads the document referenced by the provided {@link DocumentReference}.
  20288. *
  20289. * @param documentRef - A reference to the document to be read.
  20290. * @returns A `DocumentSnapshot` with the read data.
  20291. */ get(t) {
  20292. const e = Kf(t, this._firestore), n = new Zl(this._firestore);
  20293. return this._transaction.lookup([ e._key ]).then((t => {
  20294. if (!t || 1 !== t.length) return B();
  20295. const s = t[0];
  20296. if (s.isFoundDocument()) return new El(this._firestore, n, s.key, s, e.converter);
  20297. if (s.isNoDocument()) return new El(this._firestore, n, e._key, null, e.converter);
  20298. throw B();
  20299. }));
  20300. }
  20301. set(t, e, n) {
  20302. const s = Kf(t, this._firestore), i = Xl(s.converter, e, n), r = sl(this._dataReader, "Transaction.set", s._key, i, null !== s.converter, n);
  20303. return this._transaction.set(s._key, r), this;
  20304. }
  20305. update(t, e, n, ...s) {
  20306. const i = Kf(t, this._firestore);
  20307. // For Compat types, we have to "extract" the underlying types before
  20308. // performing validation.
  20309. let r;
  20310. return r = "string" == typeof (e = _(e)) || e instanceof jh ? ll(this._dataReader, "Transaction.update", i._key, e, n, s) : hl(this._dataReader, "Transaction.update", i._key, e),
  20311. this._transaction.update(i._key, r), this;
  20312. }
  20313. /**
  20314. * Deletes the document referred to by the provided {@link DocumentReference}.
  20315. *
  20316. * @param documentRef - A reference to the document to be deleted.
  20317. * @returns This `Transaction` instance. Used for chaining method calls.
  20318. */ delete(t) {
  20319. const e = Kf(t, this._firestore);
  20320. return this._transaction.delete(e._key), this;
  20321. }
  20322. } {
  20323. // This class implements the same logic as the Transaction API in the Lite SDK
  20324. // but is subclassed in order to return its own DocumentSnapshot types.
  20325. /** @hideconstructor */
  20326. constructor(t, e) {
  20327. super(t, e), this._firestore = t;
  20328. }
  20329. /**
  20330. * Reads the document referenced by the provided {@link DocumentReference}.
  20331. *
  20332. * @param documentRef - A reference to the document to be read.
  20333. * @returns A `DocumentSnapshot` with the read data.
  20334. */ get(t) {
  20335. const e = Kf(t, this._firestore), n = new df(this._firestore);
  20336. return super.get(t).then((t => new uf(this._firestore, n, e._key, t._document, new of(
  20337. /* hasPendingWrites= */ !1,
  20338. /* fromCache= */ !1), e.converter)));
  20339. }
  20340. }
  20341. /**
  20342. * Executes the given `updateFunction` and then attempts to commit the changes
  20343. * applied within the transaction. If any document read within the transaction
  20344. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  20345. * commit after 5 attempts, the transaction fails.
  20346. *
  20347. * The maximum number of writes allowed in a single transaction is 500.
  20348. *
  20349. * @param firestore - A reference to the Firestore database to run this
  20350. * transaction against.
  20351. * @param updateFunction - The function to execute within the transaction
  20352. * context.
  20353. * @param options - An options object to configure maximum number of attempts to
  20354. * commit.
  20355. * @returns If the transaction completed successfully or was explicitly aborted
  20356. * (the `updateFunction` returned a failed promise), the promise returned by the
  20357. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  20358. * rejected promise with the corresponding failure error is returned.
  20359. */ function Qf(t, e, n) {
  20360. t = hh(t, bh);
  20361. const s = Object.assign(Object.assign({}, qf), n);
  20362. !function(t) {
  20363. if (t.maxAttempts < 1) throw new G(K.INVALID_ARGUMENT, "Max attempts must be at least 1");
  20364. }(s);
  20365. return function(t, e, n) {
  20366. const s = new Q;
  20367. return t.asyncQueue.enqueueAndForget((async () => {
  20368. const i = await Qa(t);
  20369. new ka(t.asyncQueue, i, n, e, s).run();
  20370. })), s.promise;
  20371. }(Dh(t), (n => e(new Gf(t, n))), s);
  20372. }
  20373. /**
  20374. * @license
  20375. * Copyright 2020 Google LLC
  20376. *
  20377. * Licensed under the Apache License, Version 2.0 (the "License");
  20378. * you may not use this file except in compliance with the License.
  20379. * You may obtain a copy of the License at
  20380. *
  20381. * http://www.apache.org/licenses/LICENSE-2.0
  20382. *
  20383. * Unless required by applicable law or agreed to in writing, software
  20384. * distributed under the License is distributed on an "AS IS" BASIS,
  20385. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20386. * See the License for the specific language governing permissions and
  20387. * limitations under the License.
  20388. */
  20389. /**
  20390. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  20391. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  20392. */ function jf() {
  20393. return new il("deleteField");
  20394. }
  20395. /**
  20396. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  20397. * include a server-generated timestamp in the written data.
  20398. */ function zf() {
  20399. return new ol("serverTimestamp");
  20400. }
  20401. /**
  20402. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  20403. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  20404. * value that already exists on the server. Each specified element that doesn't
  20405. * already exist in the array will be added to the end. If the field being
  20406. * modified is not already an array it will be overwritten with an array
  20407. * containing exactly the specified elements.
  20408. *
  20409. * @param elements - The elements to union into the array.
  20410. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20411. * `updateDoc()`.
  20412. */ function Wf(...t) {
  20413. // NOTE: We don't actually parse the data until it's used in set() or
  20414. // update() since we'd need the Firestore instance to do this.
  20415. return new ul("arrayUnion", t);
  20416. }
  20417. /**
  20418. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  20419. * updateDoc:1} that tells the server to remove the given elements from any
  20420. * array value that already exists on the server. All instances of each element
  20421. * specified will be removed from the array. If the field being modified is not
  20422. * already an array it will be overwritten with an empty array.
  20423. *
  20424. * @param elements - The elements to remove from the array.
  20425. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20426. * `updateDoc()`
  20427. */ function Hf(...t) {
  20428. // NOTE: We don't actually parse the data until it's used in set() or
  20429. // update() since we'd need the Firestore instance to do this.
  20430. return new cl("arrayRemove", t);
  20431. }
  20432. /**
  20433. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  20434. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  20435. * the given value.
  20436. *
  20437. * If either the operand or the current field value uses floating point
  20438. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  20439. * integers, values outside of JavaScript's safe number range
  20440. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  20441. * precision loss. Furthermore, once processed by the Firestore backend, all
  20442. * integer operations are capped between -2^63 and 2^63-1.
  20443. *
  20444. * If the current field value is not of type `number`, or if the field does not
  20445. * yet exist, the transformation sets the field to the given value.
  20446. *
  20447. * @param n - The value to increment by.
  20448. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  20449. * `updateDoc()`
  20450. */ function Jf(t) {
  20451. return new al("increment", t);
  20452. }
  20453. /**
  20454. * @license
  20455. * Copyright 2020 Google LLC
  20456. *
  20457. * Licensed under the Apache License, Version 2.0 (the "License");
  20458. * you may not use this file except in compliance with the License.
  20459. * You may obtain a copy of the License at
  20460. *
  20461. * http://www.apache.org/licenses/LICENSE-2.0
  20462. *
  20463. * Unless required by applicable law or agreed to in writing, software
  20464. * distributed under the License is distributed on an "AS IS" BASIS,
  20465. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20466. * See the License for the specific language governing permissions and
  20467. * limitations under the License.
  20468. */
  20469. /**
  20470. * Creates a write batch, used for performing multiple writes as a single
  20471. * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}
  20472. * is 500.
  20473. *
  20474. * Unlike transactions, write batches are persisted offline and therefore are
  20475. * preferable when you don't need to condition your writes on read data.
  20476. *
  20477. * @returns A {@link WriteBatch} that can be used to atomically execute multiple
  20478. * writes.
  20479. */ function Yf(t) {
  20480. return Dh(t = hh(t, bh)), new Uf(t, (e => Rf(t, e)));
  20481. }
  20482. /**
  20483. * @license
  20484. * Copyright 2021 Google LLC
  20485. *
  20486. * Licensed under the Apache License, Version 2.0 (the "License");
  20487. * you may not use this file except in compliance with the License.
  20488. * You may obtain a copy of the License at
  20489. *
  20490. * http://www.apache.org/licenses/LICENSE-2.0
  20491. *
  20492. * Unless required by applicable law or agreed to in writing, software
  20493. * distributed under the License is distributed on an "AS IS" BASIS,
  20494. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20495. * See the License for the specific language governing permissions and
  20496. * limitations under the License.
  20497. */ function Xf(t, e) {
  20498. var n;
  20499. const s = Dh(t = hh(t, bh));
  20500. if (!s._uninitializedComponentsProvider || "memory" === (null === (n = s._uninitializedComponentsProvider) || void 0 === n ? void 0 : n._offlineKind))
  20501. // PORTING NOTE: We don't return an error if the user has not enabled
  20502. // persistence since `enableIndexeddbPersistence()` can fail on the Web.
  20503. return O("Cannot enable indexes when persistence is disabled"), Promise.resolve();
  20504. const i = function(t) {
  20505. const e = "string" == typeof t ? function(t) {
  20506. try {
  20507. return JSON.parse(t);
  20508. } catch (t) {
  20509. throw new G(K.INVALID_ARGUMENT, "Failed to parse JSON: " + (null == t ? void 0 : t.message));
  20510. }
  20511. }(t) : t, n = [];
  20512. if (Array.isArray(e.indexes)) for (const t of e.indexes) {
  20513. const e = Zf(t, "collectionGroup"), s = [];
  20514. if (Array.isArray(t.fields)) for (const e of t.fields) {
  20515. const t = pl("setIndexConfiguration", Zf(e, "fieldPath"));
  20516. "CONTAINS" === e.arrayConfig ? s.push(new gt(t, 2 /* IndexKind.CONTAINS */)) : "ASCENDING" === e.order ? s.push(new gt(t, 0 /* IndexKind.ASCENDING */)) : "DESCENDING" === e.order && s.push(new gt(t, 1 /* IndexKind.DESCENDING */));
  20517. }
  20518. n.push(new dt(dt.UNKNOWN_ID, e, s, pt.empty()));
  20519. }
  20520. return n;
  20521. }(e);
  20522. return nh(s, i);
  20523. }
  20524. function Zf(t, e) {
  20525. if ("string" != typeof t[e]) throw new G(K.INVALID_ARGUMENT, "Missing string value for: " + e);
  20526. return t[e];
  20527. }
  20528. /**
  20529. * @license
  20530. * Copyright 2021 Google LLC
  20531. *
  20532. * Licensed under the Apache License, Version 2.0 (the "License");
  20533. * you may not use this file except in compliance with the License.
  20534. * You may obtain a copy of the License at
  20535. *
  20536. * http://www.apache.org/licenses/LICENSE-2.0
  20537. *
  20538. * Unless required by applicable law or agreed to in writing, software
  20539. * distributed under the License is distributed on an "AS IS" BASIS,
  20540. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20541. * See the License for the specific language governing permissions and
  20542. * limitations under the License.
  20543. */ !function(t, e = !0) {
  20544. !function(t) {
  20545. C = t;
  20546. }(i), n(new r("firestore", ((t, {instanceIdentifier: n, options: s}) => {
  20547. const i = t.getProvider("app").getImmediate(), r = new bh(new H(t.getProvider("auth-internal")), new Z(t.getProvider("app-check-internal")), function(t, e) {
  20548. if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new G(K.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
  20549. return new Le(t.options.projectId, e);
  20550. }(i, n), i);
  20551. return s = Object.assign({
  20552. useFetchStreams: e
  20553. }, s), r._setSettings(s), r;
  20554. }), "PUBLIC").setMultipleInstances(!0)), s(S, "3.13.0", t),
  20555. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  20556. s(S, "3.13.0", "esm2017");
  20557. }("rn", /* useFetchStreams= */ !1);
  20558. export { Yl as AbstractUserDataWriter, Kh as AggregateField, Gh as AggregateQuerySnapshot, Qh as Bytes, Ph as CACHE_SIZE_UNLIMITED, gh as CollectionReference, _h as DocumentReference, uf as DocumentSnapshot, jh as FieldPath, Wh as FieldValue, bh as Firestore, G as FirestoreError, Hh as GeoPoint, Rh as LoadBundleTask, mh as Query, Cl as QueryCompositeFilterConstraint, bl as QueryConstraint, cf as QueryDocumentSnapshot, Ul as QueryEndAtConstraint, Sl as QueryFieldFilterConstraint, Ml as QueryLimitConstraint, kl as QueryOrderByConstraint, af as QuerySnapshot, Bl as QueryStartAtConstraint, of as SnapshotMetadata, ot as Timestamp, Gf as Transaction, Uf as WriteBatch, Le as _DatabaseId, ft as _DocumentKey, tt as _EmptyAppCheckTokenProvider, z as _EmptyAuthCredentialsProvider, lt as _FieldPath, li as _TestingHooks, hh as _cast, q as _debugAssert, De as _isBase64Available, O as _logWarn, oh as _validateIsNotUsedTogether, Ef as addDoc, sf as aggregateFieldEqual, rf as aggregateQuerySnapshotEqual, Nl as and, Hf as arrayRemove, Wf as arrayUnion, ef as average, $h as clearIndexedDbPersistence, yh as collection, ph as collectionGroup, wh as connectFirestoreEmulator, nf as count, Tf as deleteDoc, jf as deleteField, Fh as disableNetwork, Ih as doc, zh as documentId, xh as enableIndexedDbPersistence, Nh as enableMultiTabIndexedDbPersistence, Oh as enableNetwork, Gl as endAt, Kl as endBefore, Dh as ensureFirestoreConfigured, Rf as executeWrite, Vf as getAggregateFromServer, bf as getCountFromServer, ff as getDoc, wf as getDocFromCache, _f as getDocFromServer, mf as getDocs, gf as getDocsFromCache, yf as getDocsFromServer, Sh as getFirestore, Jf as increment, Vh as initializeFirestore, Ol as limit, Fl as limitToLast, Lh as loadBundle, Nf as memoryEagerGarbageCollector, $f as memoryLocalCache, kf as memoryLruGarbageCollector, qh as namedQuery, Af as onSnapshot, vf as onSnapshotsInSync, xl as or, $l as orderBy, Mf as persistentLocalCache, Lf as persistentMultipleTabManager, Bf as persistentSingleTabManager, Vl as query, Eh as queryEqual, Th as refEqual, Qf as runTransaction, zf as serverTimestamp, pf as setDoc, Xf as setIndexConfiguration, k as setLogLevel, lf as snapshotEqual, ql as startAfter, Ll as startAt, tf as sum, Bh as terminate, If as updateDoc, Mh as waitForPendingWrites, Dl as where, Yf as writeBatch };
  20559. //# sourceMappingURL=index.rn.js.map