No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.rn.esm2017.js 256KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971
  1. import { _getProvider, getApp as t, _removeServiceInstance as e, _registerComponent as n, registerVersion as r, SDK_VERSION as s } from "@firebase/app";
  2. import { Component as i } from "@firebase/component";
  3. import { Logger as o, LogLevel as u } from "@firebase/logger";
  4. import { FirebaseError as c, base64 as a, getDefaultEmulatorHostnameAndPort as h, createMockUserToken as l, getModularInstance as f, deepEqual as d } from "@firebase/util";
  5. /**
  6. * @license
  7. * Copyright 2017 Google LLC
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License");
  10. * you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software
  16. * distributed under the License is distributed on an "AS IS" BASIS,
  17. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. * See the License for the specific language governing permissions and
  19. * limitations under the License.
  20. */
  21. /**
  22. * Simple wrapper around a nullable UID. Mostly exists to make code more
  23. * readable.
  24. */
  25. class w {
  26. constructor(t) {
  27. this.uid = t;
  28. }
  29. isAuthenticated() {
  30. return null != this.uid;
  31. }
  32. /**
  33. * Returns a key representing this user, suitable for inclusion in a
  34. * dictionary.
  35. */ toKey() {
  36. return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
  37. }
  38. isEqual(t) {
  39. return t.uid === this.uid;
  40. }
  41. }
  42. /** A user with a null UID. */ w.UNAUTHENTICATED = new w(null),
  43. // TODO(mikelehen): Look into getting a proper uid-equivalent for
  44. // non-FirebaseAuth providers.
  45. w.GOOGLE_CREDENTIALS = new w("google-credentials-uid"), w.FIRST_PARTY = new w("first-party-uid"),
  46. w.MOCK_USER = new w("mock-user");
  47. /**
  48. * @license
  49. * Copyright 2017 Google LLC
  50. *
  51. * Licensed under the Apache License, Version 2.0 (the "License");
  52. * you may not use this file except in compliance with the License.
  53. * You may obtain a copy of the License at
  54. *
  55. * http://www.apache.org/licenses/LICENSE-2.0
  56. *
  57. * Unless required by applicable law or agreed to in writing, software
  58. * distributed under the License is distributed on an "AS IS" BASIS,
  59. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  60. * See the License for the specific language governing permissions and
  61. * limitations under the License.
  62. */
  63. let m = "9.16.0";
  64. /**
  65. * @license
  66. * Copyright 2017 Google LLC
  67. *
  68. * Licensed under the Apache License, Version 2.0 (the "License");
  69. * you may not use this file except in compliance with the License.
  70. * You may obtain a copy of the License at
  71. *
  72. * http://www.apache.org/licenses/LICENSE-2.0
  73. *
  74. * Unless required by applicable law or agreed to in writing, software
  75. * distributed under the License is distributed on an "AS IS" BASIS,
  76. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  77. * See the License for the specific language governing permissions and
  78. * limitations under the License.
  79. */
  80. const p = new o("@firebase/firestore");
  81. /**
  82. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  83. *
  84. * @param logLevel - The verbosity you set for activity and error logging. Can
  85. * be any of the following values:
  86. *
  87. * <ul>
  88. * <li>`debug` for the most verbose logging level, primarily for
  89. * debugging.</li>
  90. * <li>`error` to log errors only.</li>
  91. * <li><code>`silent` to turn off logging.</li>
  92. * </ul>
  93. */ function y(t) {
  94. p.setLogLevel(t);
  95. }
  96. function g(t, ...e) {
  97. if (p.logLevel <= u.DEBUG) {
  98. const n = e.map(b);
  99. p.debug(`Firestore (${m}): ${t}`, ...n);
  100. }
  101. }
  102. function _(t, ...e) {
  103. if (p.logLevel <= u.ERROR) {
  104. const n = e.map(b);
  105. p.error(`Firestore (${m}): ${t}`, ...n);
  106. }
  107. }
  108. /**
  109. * @internal
  110. */ function v(t, ...e) {
  111. if (p.logLevel <= u.WARN) {
  112. const n = e.map(b);
  113. p.warn(`Firestore (${m}): ${t}`, ...n);
  114. }
  115. }
  116. /**
  117. * Converts an additional log parameter to a string representation.
  118. */ function b(t) {
  119. if ("string" == typeof t) return t;
  120. try {
  121. return e = t, JSON.stringify(e);
  122. } catch (e) {
  123. // Converting to JSON failed, just log the object directly
  124. return t;
  125. }
  126. /**
  127. * @license
  128. * Copyright 2020 Google LLC
  129. *
  130. * Licensed under the Apache License, Version 2.0 (the "License");
  131. * you may not use this file except in compliance with the License.
  132. * You may obtain a copy of the License at
  133. *
  134. * http://www.apache.org/licenses/LICENSE-2.0
  135. *
  136. * Unless required by applicable law or agreed to in writing, software
  137. * distributed under the License is distributed on an "AS IS" BASIS,
  138. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  139. * See the License for the specific language governing permissions and
  140. * limitations under the License.
  141. */
  142. /** Formats an object as a JSON string, suitable for logging. */
  143. var e;
  144. }
  145. /**
  146. * @license
  147. * Copyright 2017 Google LLC
  148. *
  149. * Licensed under the Apache License, Version 2.0 (the "License");
  150. * you may not use this file except in compliance with the License.
  151. * You may obtain a copy of the License at
  152. *
  153. * http://www.apache.org/licenses/LICENSE-2.0
  154. *
  155. * Unless required by applicable law or agreed to in writing, software
  156. * distributed under the License is distributed on an "AS IS" BASIS,
  157. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  158. * See the License for the specific language governing permissions and
  159. * limitations under the License.
  160. */
  161. /**
  162. * Unconditionally fails, throwing an Error with the given message.
  163. * Messages are stripped in production builds.
  164. *
  165. * Returns `never` and can be used in expressions:
  166. * @example
  167. * let futureVar = fail('not implemented yet');
  168. */ function E(t = "Unexpected state") {
  169. // Log the failure in addition to throw an exception, just in case the
  170. // exception is swallowed.
  171. const e = `FIRESTORE (${m}) INTERNAL ASSERTION FAILED: ` + t;
  172. // NOTE: We don't use FirestoreError here because these are internal failures
  173. // that cannot be handled by the user. (Also it would create a circular
  174. // dependency between the error and assert modules which doesn't work.)
  175. throw _(e), new Error(e);
  176. }
  177. /**
  178. * Fails if the given assertion condition is false, throwing an Error with the
  179. * given message if it did.
  180. *
  181. * Messages are stripped in production builds.
  182. */ function I(t, e) {
  183. t || E();
  184. }
  185. /**
  186. * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
  187. * instance of `T` before casting.
  188. */ function A(t,
  189. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  190. e) {
  191. return t;
  192. }
  193. /**
  194. * @license
  195. * Copyright 2017 Google LLC
  196. *
  197. * Licensed under the Apache License, Version 2.0 (the "License");
  198. * you may not use this file except in compliance with the License.
  199. * You may obtain a copy of the License at
  200. *
  201. * http://www.apache.org/licenses/LICENSE-2.0
  202. *
  203. * Unless required by applicable law or agreed to in writing, software
  204. * distributed under the License is distributed on an "AS IS" BASIS,
  205. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  206. * See the License for the specific language governing permissions and
  207. * limitations under the License.
  208. */ const T = "ok", R = "cancelled", P = "unknown", V = "invalid-argument", $ = "deadline-exceeded", N = "not-found", D = "already-exists", F = "permission-denied", x = "unauthenticated", S = "resource-exhausted", q = "failed-precondition", O = "aborted", k = "out-of-range", C = "unimplemented", L = "internal", M = "unavailable", U = "data-loss";
  209. /** An error returned by a Firestore operation. */ class j extends c {
  210. /** @hideconstructor */
  211. constructor(
  212. /**
  213. * The backend error code associated with this error.
  214. */
  215. t,
  216. /**
  217. * A custom error description.
  218. */
  219. e) {
  220. super(t, e), this.code = t, this.message = e,
  221. // HACK: We write a toString property directly because Error is not a real
  222. // class and so inheritance does not work correctly. We could alternatively
  223. // do the same "back-door inheritance" trick that FirebaseError does.
  224. this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
  225. }
  226. }
  227. /**
  228. * @license
  229. * Copyright 2017 Google LLC
  230. *
  231. * Licensed under the Apache License, Version 2.0 (the "License");
  232. * you may not use this file except in compliance with the License.
  233. * You may obtain a copy of the License at
  234. *
  235. * http://www.apache.org/licenses/LICENSE-2.0
  236. *
  237. * Unless required by applicable law or agreed to in writing, software
  238. * distributed under the License is distributed on an "AS IS" BASIS,
  239. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  240. * See the License for the specific language governing permissions and
  241. * limitations under the License.
  242. */ class B {
  243. constructor() {
  244. this.promise = new Promise(((t, e) => {
  245. this.resolve = t, this.reject = e;
  246. }));
  247. }
  248. }
  249. /**
  250. * @license
  251. * Copyright 2017 Google LLC
  252. *
  253. * Licensed under the Apache License, Version 2.0 (the "License");
  254. * you may not use this file except in compliance with the License.
  255. * You may obtain a copy of the License at
  256. *
  257. * http://www.apache.org/licenses/LICENSE-2.0
  258. *
  259. * Unless required by applicable law or agreed to in writing, software
  260. * distributed under the License is distributed on an "AS IS" BASIS,
  261. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  262. * See the License for the specific language governing permissions and
  263. * limitations under the License.
  264. */ class Q {
  265. constructor(t, e) {
  266. this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`);
  267. }
  268. }
  269. /**
  270. * A CredentialsProvider that always yields an empty token.
  271. * @internal
  272. */ class z {
  273. getToken() {
  274. return Promise.resolve(null);
  275. }
  276. invalidateToken() {}
  277. start(t, e) {
  278. // Fire with initial user.
  279. t.enqueueRetryable((() => e(w.UNAUTHENTICATED)));
  280. }
  281. shutdown() {}
  282. }
  283. /**
  284. * A CredentialsProvider that always returns a constant token. Used for
  285. * emulator token mocking.
  286. */ class W {
  287. constructor(t) {
  288. this.token = t,
  289. /**
  290. * Stores the listener registered with setChangeListener()
  291. * This isn't actually necessary since the UID never changes, but we use this
  292. * to verify the listen contract is adhered to in tests.
  293. */
  294. this.changeListener = null;
  295. }
  296. getToken() {
  297. return Promise.resolve(this.token);
  298. }
  299. invalidateToken() {}
  300. start(t, e) {
  301. this.changeListener = e,
  302. // Fire with initial user.
  303. t.enqueueRetryable((() => e(this.token.user)));
  304. }
  305. shutdown() {
  306. this.changeListener = null;
  307. }
  308. }
  309. /** Credential provider for the Lite SDK. */ class G {
  310. constructor(t) {
  311. this.auth = null, t.onInit((t => {
  312. this.auth = t;
  313. }));
  314. }
  315. getToken() {
  316. return this.auth ? this.auth.getToken().then((t => t ? (I("string" == typeof t.accessToken),
  317. new Q(t.accessToken, new w(this.auth.getUid()))) : null)) : Promise.resolve(null);
  318. }
  319. invalidateToken() {}
  320. start(t, e) {}
  321. shutdown() {}
  322. }
  323. /*
  324. * FirstPartyToken provides a fresh token each time its value
  325. * is requested, because if the token is too old, requests will be rejected.
  326. * Technically this may no longer be necessary since the SDK should gracefully
  327. * recover from unauthenticated errors (see b/33147818 for context), but it's
  328. * safer to keep the implementation as-is.
  329. */ class K {
  330. constructor(t, e, n, r) {
  331. this.t = t, this.i = e, this.o = n, this.u = r, this.type = "FirstParty", this.user = w.FIRST_PARTY,
  332. this.h = new Map;
  333. }
  334. /** Gets an authorization token, using a provided factory function, or falling back to First Party GAPI. */ l() {
  335. return this.u ? this.u() : (
  336. // Make sure this really is a Gapi client.
  337. I(!("object" != typeof this.t || null === this.t || !this.t.auth || !this.t.auth.getAuthHeaderValueForFirstParty)),
  338. this.t.auth.getAuthHeaderValueForFirstParty([]));
  339. }
  340. get headers() {
  341. this.h.set("X-Goog-AuthUser", this.i);
  342. // Use array notation to prevent minification
  343. const t = this.l();
  344. return t && this.h.set("Authorization", t), this.o && this.h.set("X-Goog-Iam-Authorization-Token", this.o),
  345. this.h;
  346. }
  347. }
  348. /*
  349. * Provides user credentials required for the Firestore JavaScript SDK
  350. * to authenticate the user, using technique that is only available
  351. * to applications hosted by Google.
  352. */ class Y {
  353. constructor(t, e, n, r) {
  354. this.t = t, this.i = e, this.o = n, this.u = r;
  355. }
  356. getToken() {
  357. return Promise.resolve(new K(this.t, this.i, this.o, this.u));
  358. }
  359. start(t, e) {
  360. // Fire with initial uid.
  361. t.enqueueRetryable((() => e(w.FIRST_PARTY)));
  362. }
  363. shutdown() {}
  364. invalidateToken() {}
  365. }
  366. class H {
  367. constructor(t) {
  368. this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
  369. }
  370. }
  371. /** AppCheck token provider for the Lite SDK. */ class J {
  372. constructor(t) {
  373. this.m = t, this.appCheck = null, t.onInit((t => {
  374. this.appCheck = t;
  375. }));
  376. }
  377. getToken() {
  378. return this.appCheck ? this.appCheck.getToken().then((t => t ? (I("string" == typeof t.token),
  379. new H(t.token)) : null)) : Promise.resolve(null);
  380. }
  381. invalidateToken() {}
  382. start(t, e) {}
  383. shutdown() {}
  384. }
  385. /**
  386. * Builds a CredentialsProvider depending on the type of
  387. * the credentials passed in.
  388. */
  389. /**
  390. * @license
  391. * Copyright 2017 Google LLC
  392. *
  393. * Licensed under the Apache License, Version 2.0 (the "License");
  394. * you may not use this file except in compliance with the License.
  395. * You may obtain a copy of the License at
  396. *
  397. * http://www.apache.org/licenses/LICENSE-2.0
  398. *
  399. * Unless required by applicable law or agreed to in writing, software
  400. * distributed under the License is distributed on an "AS IS" BASIS,
  401. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  402. * See the License for the specific language governing permissions and
  403. * limitations under the License.
  404. */
  405. class X {
  406. /**
  407. * Constructs a DatabaseInfo using the provided host, databaseId and
  408. * persistenceKey.
  409. *
  410. * @param databaseId - The database to use.
  411. * @param appId - The Firebase App Id.
  412. * @param persistenceKey - A unique identifier for this Firestore's local
  413. * storage (used in conjunction with the databaseId).
  414. * @param host - The Firestore backend host to connect to.
  415. * @param ssl - Whether to use SSL when connecting.
  416. * @param forceLongPolling - Whether to use the forceLongPolling option
  417. * when using WebChannel as the network transport.
  418. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  419. * option when using WebChannel as the network transport.
  420. * @param useFetchStreams Whether to use the Fetch API instead of
  421. * XMLHTTPRequest
  422. */
  423. constructor(t, e, n, r, s, i, o, u) {
  424. this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = r, this.ssl = s,
  425. this.forceLongPolling = i, this.autoDetectLongPolling = o, this.useFetchStreams = u;
  426. }
  427. }
  428. /** The default database name for a project. */
  429. /**
  430. * Represents the database ID a Firestore client is associated with.
  431. * @internal
  432. */
  433. class Z {
  434. constructor(t, e) {
  435. this.projectId = t, this.database = e || "(default)";
  436. }
  437. static empty() {
  438. return new Z("", "");
  439. }
  440. get isDefaultDatabase() {
  441. return "(default)" === this.database;
  442. }
  443. isEqual(t) {
  444. return t instanceof Z && t.projectId === this.projectId && t.database === this.database;
  445. }
  446. }
  447. /**
  448. * Path represents an ordered sequence of string segments.
  449. */
  450. class tt {
  451. constructor(t, e, n) {
  452. void 0 === e ? e = 0 : e > t.length && E(), void 0 === n ? n = t.length - e : n > t.length - e && E(),
  453. this.segments = t, this.offset = e, this.len = n;
  454. }
  455. get length() {
  456. return this.len;
  457. }
  458. isEqual(t) {
  459. return 0 === tt.comparator(this, t);
  460. }
  461. child(t) {
  462. const e = this.segments.slice(this.offset, this.limit());
  463. return t instanceof tt ? t.forEach((t => {
  464. e.push(t);
  465. })) : e.push(t), this.construct(e);
  466. }
  467. /** The index of one past the last segment of the path. */ limit() {
  468. return this.offset + this.length;
  469. }
  470. popFirst(t) {
  471. return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);
  472. }
  473. popLast() {
  474. return this.construct(this.segments, this.offset, this.length - 1);
  475. }
  476. firstSegment() {
  477. return this.segments[this.offset];
  478. }
  479. lastSegment() {
  480. return this.get(this.length - 1);
  481. }
  482. get(t) {
  483. return this.segments[this.offset + t];
  484. }
  485. isEmpty() {
  486. return 0 === this.length;
  487. }
  488. isPrefixOf(t) {
  489. if (t.length < this.length) return !1;
  490. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  491. return !0;
  492. }
  493. isImmediateParentOf(t) {
  494. if (this.length + 1 !== t.length) return !1;
  495. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  496. return !0;
  497. }
  498. forEach(t) {
  499. for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);
  500. }
  501. toArray() {
  502. return this.segments.slice(this.offset, this.limit());
  503. }
  504. static comparator(t, e) {
  505. const n = Math.min(t.length, e.length);
  506. for (let r = 0; r < n; r++) {
  507. const n = t.get(r), s = e.get(r);
  508. if (n < s) return -1;
  509. if (n > s) return 1;
  510. }
  511. return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
  512. }
  513. }
  514. /**
  515. * A slash-separated path for navigating resources (documents and collections)
  516. * within Firestore.
  517. *
  518. * @internal
  519. */ class et extends tt {
  520. construct(t, e, n) {
  521. return new et(t, e, n);
  522. }
  523. canonicalString() {
  524. // NOTE: The client is ignorant of any path segments containing escape
  525. // sequences (e.g. __id123__) and just passes them through raw (they exist
  526. // for legacy reasons and should not be used frequently).
  527. return this.toArray().join("/");
  528. }
  529. toString() {
  530. return this.canonicalString();
  531. }
  532. /**
  533. * Creates a resource path from the given slash-delimited string. If multiple
  534. * arguments are provided, all components are combined. Leading and trailing
  535. * slashes from all components are ignored.
  536. */ static fromString(...t) {
  537. // NOTE: The client is ignorant of any path segments containing escape
  538. // sequences (e.g. __id123__) and just passes them through raw (they exist
  539. // for legacy reasons and should not be used frequently).
  540. const e = [];
  541. for (const n of t) {
  542. if (n.indexOf("//") >= 0) throw new j(V, `Invalid segment (${n}). Paths must not contain // in them.`);
  543. // Strip leading and traling slashed.
  544. e.push(...n.split("/").filter((t => t.length > 0)));
  545. }
  546. return new et(e);
  547. }
  548. static emptyPath() {
  549. return new et([]);
  550. }
  551. }
  552. const nt = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
  553. /**
  554. * A dot-separated path for navigating sub-objects within a document.
  555. * @internal
  556. */ class rt extends tt {
  557. construct(t, e, n) {
  558. return new rt(t, e, n);
  559. }
  560. /**
  561. * Returns true if the string could be used as a segment in a field path
  562. * without escaping.
  563. */ static isValidIdentifier(t) {
  564. return nt.test(t);
  565. }
  566. canonicalString() {
  567. return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"),
  568. rt.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join(".");
  569. }
  570. toString() {
  571. return this.canonicalString();
  572. }
  573. /**
  574. * Returns true if this field references the key of a document.
  575. */ isKeyField() {
  576. return 1 === this.length && "__name__" === this.get(0);
  577. }
  578. /**
  579. * The field designating the key of a document.
  580. */ static keyField() {
  581. return new rt([ "__name__" ]);
  582. }
  583. /**
  584. * Parses a field string from the given server-formatted string.
  585. *
  586. * - Splitting the empty string is not allowed (for now at least).
  587. * - Empty segments within the string (e.g. if there are two consecutive
  588. * separators) are not allowed.
  589. *
  590. * TODO(b/37244157): we should make this more strict. Right now, it allows
  591. * non-identifier path components, even if they aren't escaped.
  592. */ static fromServerFormat(t) {
  593. const e = [];
  594. let n = "", r = 0;
  595. const s = () => {
  596. if (0 === n.length) throw new j(V, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
  597. e.push(n), n = "";
  598. };
  599. let i = !1;
  600. for (;r < t.length; ) {
  601. const e = t[r];
  602. if ("\\" === e) {
  603. if (r + 1 === t.length) throw new j(V, "Path has trailing escape character: " + t);
  604. const e = t[r + 1];
  605. if ("\\" !== e && "." !== e && "`" !== e) throw new j(V, "Path has invalid escape sequence: " + t);
  606. n += e, r += 2;
  607. } else "`" === e ? (i = !i, r++) : "." !== e || i ? (n += e, r++) : (s(), r++);
  608. }
  609. if (s(), i) throw new j(V, "Unterminated ` in path: " + t);
  610. return new rt(e);
  611. }
  612. static emptyPath() {
  613. return new rt([]);
  614. }
  615. }
  616. /**
  617. * @license
  618. * Copyright 2017 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. * @internal
  634. */ class st {
  635. constructor(t) {
  636. this.path = t;
  637. }
  638. static fromPath(t) {
  639. return new st(et.fromString(t));
  640. }
  641. static fromName(t) {
  642. return new st(et.fromString(t).popFirst(5));
  643. }
  644. static empty() {
  645. return new st(et.emptyPath());
  646. }
  647. get collectionGroup() {
  648. return this.path.popLast().lastSegment();
  649. }
  650. /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {
  651. return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
  652. }
  653. /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {
  654. return this.path.get(this.path.length - 2);
  655. }
  656. /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {
  657. return this.path.popLast();
  658. }
  659. isEqual(t) {
  660. return null !== t && 0 === et.comparator(this.path, t.path);
  661. }
  662. toString() {
  663. return this.path.toString();
  664. }
  665. static comparator(t, e) {
  666. return et.comparator(t.path, e.path);
  667. }
  668. static isDocumentKey(t) {
  669. return t.length % 2 == 0;
  670. }
  671. /**
  672. * Creates and returns a new document key with the given segments.
  673. *
  674. * @param segments - The segments of the path to the document
  675. * @returns A new instance of DocumentKey
  676. */ static fromSegments(t) {
  677. return new st(new et(t.slice()));
  678. }
  679. }
  680. /**
  681. * @license
  682. * Copyright 2017 Google LLC
  683. *
  684. * Licensed under the Apache License, Version 2.0 (the "License");
  685. * you may not use this file except in compliance with the License.
  686. * You may obtain a copy of the License at
  687. *
  688. * http://www.apache.org/licenses/LICENSE-2.0
  689. *
  690. * Unless required by applicable law or agreed to in writing, software
  691. * distributed under the License is distributed on an "AS IS" BASIS,
  692. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  693. * See the License for the specific language governing permissions and
  694. * limitations under the License.
  695. */ function it(t, e, n) {
  696. if (!n) throw new j(V, `Function ${t}() cannot be called with an empty ${e}.`);
  697. }
  698. /**
  699. * Validates that two boolean options are not set at the same time.
  700. * @internal
  701. */
  702. /**
  703. * Validates that `path` refers to a document (indicated by the fact it contains
  704. * an even numbers of segments).
  705. */
  706. function ot(t) {
  707. if (!st.isDocumentKey(t)) throw new j(V, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);
  708. }
  709. /**
  710. * Validates that `path` refers to a collection (indicated by the fact it
  711. * contains an odd numbers of segments).
  712. */ function ut(t) {
  713. if (st.isDocumentKey(t)) throw new j(V, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);
  714. }
  715. /**
  716. * Returns true if it's a non-null object without a custom prototype
  717. * (i.e. excludes Array, Date, etc.).
  718. */
  719. /** Returns a string describing the type / value of the provided input. */
  720. function ct(t) {
  721. if (void 0 === t) return "undefined";
  722. if (null === t) return "null";
  723. if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`),
  724. JSON.stringify(t);
  725. if ("number" == typeof t || "boolean" == typeof t) return "" + t;
  726. if ("object" == typeof t) {
  727. if (t instanceof Array) return "an array";
  728. {
  729. const e =
  730. /** try to get the constructor name for an object. */
  731. function(t) {
  732. if (t.constructor) return t.constructor.name;
  733. return null;
  734. }
  735. /**
  736. * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
  737. * underlying instance. Throws if `obj` is not an instance of `T`.
  738. *
  739. * This cast is used in the Lite and Full SDK to verify instance types for
  740. * arguments passed to the public API.
  741. * @internal
  742. */ (t);
  743. return e ? `a custom ${e} object` : "an object";
  744. }
  745. }
  746. return "function" == typeof t ? "a function" : E();
  747. }
  748. function at(t,
  749. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  750. e) {
  751. if ("_delegate" in t && (
  752. // Unwrap Compat types
  753. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  754. t = t._delegate), !(t instanceof e)) {
  755. if (e.name === t.constructor.name) throw new j(V, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
  756. {
  757. const n = ct(t);
  758. throw new j(V, `Expected type '${e.name}', but it was: ${n}`);
  759. }
  760. }
  761. return t;
  762. }
  763. function ht(t, e) {
  764. if (e <= 0) throw new j(V, `Function ${t}() requires a positive number, but it was: ${e}.`);
  765. }
  766. /**
  767. * @license
  768. * Copyright 2017 Google LLC
  769. *
  770. * Licensed under the Apache License, Version 2.0 (the "License");
  771. * you may not use this file except in compliance with the License.
  772. * You may obtain a copy of the License at
  773. *
  774. * http://www.apache.org/licenses/LICENSE-2.0
  775. *
  776. * Unless required by applicable law or agreed to in writing, software
  777. * distributed under the License is distributed on an "AS IS" BASIS,
  778. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  779. * See the License for the specific language governing permissions and
  780. * limitations under the License.
  781. */
  782. /**
  783. * Returns whether a variable is either undefined or null.
  784. */ function lt(t) {
  785. return null == t;
  786. }
  787. /** Returns whether the value represents -0. */ function ft(t) {
  788. // Detect if the value is -0.0. Based on polyfill from
  789. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  790. return 0 === t && 1 / t == -1 / 0;
  791. }
  792. /**
  793. * Returns whether a value is an integer and in the safe integer range
  794. * @param value - The value to test for being an integer and in the safe range
  795. */
  796. /**
  797. * @license
  798. * Copyright 2020 Google LLC
  799. *
  800. * Licensed under the Apache License, Version 2.0 (the "License");
  801. * you may not use this file except in compliance with the License.
  802. * You may obtain a copy of the License at
  803. *
  804. * http://www.apache.org/licenses/LICENSE-2.0
  805. *
  806. * Unless required by applicable law or agreed to in writing, software
  807. * distributed under the License is distributed on an "AS IS" BASIS,
  808. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  809. * See the License for the specific language governing permissions and
  810. * limitations under the License.
  811. */
  812. const dt = {
  813. BatchGetDocuments: "batchGet",
  814. Commit: "commit",
  815. RunQuery: "runQuery",
  816. RunAggregationQuery: "runAggregationQuery"
  817. };
  818. /**
  819. * Maps RPC names to the corresponding REST endpoint name.
  820. *
  821. * We use array notation to avoid mangling.
  822. */
  823. /**
  824. * @license
  825. * Copyright 2017 Google LLC
  826. *
  827. * Licensed under the Apache License, Version 2.0 (the "License");
  828. * you may not use this file except in compliance with the License.
  829. * You may obtain a copy of the License at
  830. *
  831. * http://www.apache.org/licenses/LICENSE-2.0
  832. *
  833. * Unless required by applicable law or agreed to in writing, software
  834. * distributed under the License is distributed on an "AS IS" BASIS,
  835. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  836. * See the License for the specific language governing permissions and
  837. * limitations under the License.
  838. */
  839. /**
  840. * Error Codes describing the different ways GRPC can fail. These are copied
  841. * directly from GRPC's sources here:
  842. *
  843. * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  844. *
  845. * Important! The names of these identifiers matter because the string forms
  846. * are used for reverse lookups from the webchannel stream. Do NOT change the
  847. * names of these identifiers or change this into a const enum.
  848. */
  849. var wt, mt;
  850. /**
  851. * Converts an HTTP Status Code to the equivalent error code.
  852. *
  853. * @param status - An HTTP Status Code, like 200, 404, 503, etc.
  854. * @returns The equivalent Code. Unknown status codes are mapped to
  855. * Code.UNKNOWN.
  856. */
  857. function pt(t) {
  858. if (void 0 === t) return _("RPC_ERROR", "HTTP error has no status"), P;
  859. // The canonical error codes for Google APIs [1] specify mapping onto HTTP
  860. // status codes but the mapping is not bijective. In each case of ambiguity
  861. // this function chooses a primary error.
  862. // [1]
  863. // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  864. switch (t) {
  865. case 200:
  866. // OK
  867. return T;
  868. case 400:
  869. // Bad Request
  870. return q;
  871. // Other possibilities based on the forward mapping
  872. // return Code.INVALID_ARGUMENT;
  873. // return Code.OUT_OF_RANGE;
  874. case 401:
  875. // Unauthorized
  876. return x;
  877. case 403:
  878. // Forbidden
  879. return F;
  880. case 404:
  881. // Not Found
  882. return N;
  883. case 409:
  884. // Conflict
  885. return O;
  886. // Other possibilities:
  887. // return Code.ALREADY_EXISTS;
  888. case 416:
  889. // Range Not Satisfiable
  890. return k;
  891. case 429:
  892. // Too Many Requests
  893. return S;
  894. case 499:
  895. // Client Closed Request
  896. return R;
  897. case 500:
  898. // Internal Server Error
  899. return P;
  900. // Other possibilities:
  901. // return Code.INTERNAL;
  902. // return Code.DATA_LOSS;
  903. case 501:
  904. // Unimplemented
  905. return C;
  906. case 503:
  907. // Service Unavailable
  908. return M;
  909. case 504:
  910. // Gateway Timeout
  911. return $;
  912. default:
  913. return t >= 200 && t < 300 ? T : t >= 400 && t < 500 ? q : t >= 500 && t < 600 ? L : P;
  914. }
  915. }
  916. /**
  917. * @license
  918. * Copyright 2020 Google LLC
  919. *
  920. * Licensed under the Apache License, Version 2.0 (the "License");
  921. * you may not use this file except in compliance with the License.
  922. * You may obtain a copy of the License at
  923. *
  924. * http://www.apache.org/licenses/LICENSE-2.0
  925. *
  926. * Unless required by applicable law or agreed to in writing, software
  927. * distributed under the License is distributed on an "AS IS" BASIS,
  928. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  929. * See the License for the specific language governing permissions and
  930. * limitations under the License.
  931. */
  932. /**
  933. * A Rest-based connection that relies on the native HTTP stack
  934. * (e.g. `fetch` or a polyfill).
  935. */ (mt = wt || (wt = {}))[mt.OK = 0] = "OK", mt[mt.CANCELLED = 1] = "CANCELLED",
  936. mt[mt.UNKNOWN = 2] = "UNKNOWN", mt[mt.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT",
  937. mt[mt.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", mt[mt.NOT_FOUND = 5] = "NOT_FOUND",
  938. mt[mt.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", mt[mt.PERMISSION_DENIED = 7] = "PERMISSION_DENIED",
  939. mt[mt.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", mt[mt.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED",
  940. mt[mt.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", mt[mt.ABORTED = 10] = "ABORTED",
  941. mt[mt.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", mt[mt.UNIMPLEMENTED = 12] = "UNIMPLEMENTED",
  942. mt[mt.INTERNAL = 13] = "INTERNAL", mt[mt.UNAVAILABLE = 14] = "UNAVAILABLE", mt[mt.DATA_LOSS = 15] = "DATA_LOSS";
  943. class yt extends
  944. /**
  945. * Base class for all Rest-based connections to the backend (WebChannel and
  946. * HTTP).
  947. */
  948. class {
  949. constructor(t) {
  950. this.databaseInfo = t, this.databaseId = t.databaseId;
  951. const e = t.ssl ? "https" : "http";
  952. this.p = e + "://" + t.host, this.g = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents";
  953. }
  954. get v() {
  955. // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
  956. // where to run the query, and expect the `request` to NOT specify the "path".
  957. return !1;
  958. }
  959. I(t, e, n, r, s) {
  960. const i = this.A(t, e);
  961. g("RestConnection", "Sending: ", i, n);
  962. const o = {};
  963. return this.T(o, r, s), this.R(t, i, o, n).then((t => (g("RestConnection", "Received: ", t),
  964. t)), (e => {
  965. throw v("RestConnection", `${t} failed with error: `, e, "url: ", i, "request:", n),
  966. e;
  967. }));
  968. }
  969. P(t, e, n, r, s, i) {
  970. // The REST API automatically aggregates all of the streamed results, so we
  971. // can just use the normal invoke() method.
  972. return this.I(t, e, n, r, s);
  973. }
  974. /**
  975. * Modifies the headers for a request, adding any authorization token if
  976. * present and any additional headers for the request.
  977. */ T(t, e, n) {
  978. t["X-Goog-Api-Client"] = "gl-js/ fire/" + m,
  979. // Content-Type: text/plain will avoid preflight requests which might
  980. // mess with CORS and redirects by proxies. If we add custom headers
  981. // we will need to change this code to potentially use the $httpOverwrite
  982. // parameter supported by ESF to avoid triggering preflight requests.
  983. t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId),
  984. e && e.headers.forEach(((e, n) => t[n] = e)), n && n.headers.forEach(((e, n) => t[n] = e));
  985. }
  986. A(t, e) {
  987. const n = dt[t];
  988. return `${this.p}/v1/${e}:${n}`;
  989. }
  990. } {
  991. /**
  992. * @param databaseInfo - The connection info.
  993. * @param fetchImpl - `fetch` or a Polyfill that implements the fetch API.
  994. */
  995. constructor(t, e) {
  996. super(t), this.V = e;
  997. }
  998. $(t, e) {
  999. throw new Error("Not supported by FetchConnection");
  1000. }
  1001. async R(t, e, n, r) {
  1002. var s;
  1003. const i = JSON.stringify(r);
  1004. let o;
  1005. try {
  1006. o = await this.V(e, {
  1007. method: "POST",
  1008. headers: n,
  1009. body: i
  1010. });
  1011. } catch (t) {
  1012. const e = t;
  1013. throw new j(pt(e.status), "Request failed with error: " + e.statusText);
  1014. }
  1015. if (!o.ok) {
  1016. let t = await o.json();
  1017. Array.isArray(t) && (t = t[0]);
  1018. const e = null === (s = null == t ? void 0 : t.error) || void 0 === s ? void 0 : s.message;
  1019. throw new j(pt(o.status), `Request failed with error: ${null != e ? e : o.statusText}`);
  1020. }
  1021. return o.json();
  1022. }
  1023. }
  1024. /**
  1025. * @license
  1026. * Copyright 2020 Google LLC
  1027. *
  1028. * Licensed under the Apache License, Version 2.0 (the "License");
  1029. * you may not use this file except in compliance with the License.
  1030. * You may obtain a copy of the License at
  1031. *
  1032. * http://www.apache.org/licenses/LICENSE-2.0
  1033. *
  1034. * Unless required by applicable law or agreed to in writing, software
  1035. * distributed under the License is distributed on an "AS IS" BASIS,
  1036. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1037. * See the License for the specific language governing permissions and
  1038. * limitations under the License.
  1039. */
  1040. /** Initializes the HTTP connection for the REST API. */
  1041. /**
  1042. * @license
  1043. * Copyright 2020 Google LLC
  1044. *
  1045. * Licensed under the Apache License, Version 2.0 (the "License");
  1046. * you may not use this file except in compliance with the License.
  1047. * You may obtain a copy of the License at
  1048. *
  1049. * http://www.apache.org/licenses/LICENSE-2.0
  1050. *
  1051. * Unless required by applicable law or agreed to in writing, software
  1052. * distributed under the License is distributed on an "AS IS" BASIS,
  1053. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1054. * See the License for the specific language governing permissions and
  1055. * limitations under the License.
  1056. */
  1057. /**
  1058. * Generates `nBytes` of random bytes.
  1059. *
  1060. * If `nBytes < 0` , an error will be thrown.
  1061. */
  1062. function gt(t) {
  1063. // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
  1064. const e =
  1065. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1066. "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);
  1067. if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else
  1068. // Falls back to Math.random
  1069. for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());
  1070. return n;
  1071. }
  1072. /**
  1073. * @license
  1074. * Copyright 2017 Google LLC
  1075. *
  1076. * Licensed under the Apache License, Version 2.0 (the "License");
  1077. * you may not use this file except in compliance with the License.
  1078. * You may obtain a copy of the License at
  1079. *
  1080. * http://www.apache.org/licenses/LICENSE-2.0
  1081. *
  1082. * Unless required by applicable law or agreed to in writing, software
  1083. * distributed under the License is distributed on an "AS IS" BASIS,
  1084. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1085. * See the License for the specific language governing permissions and
  1086. * limitations under the License.
  1087. */ class _t {
  1088. static N() {
  1089. // Alphanumeric characters
  1090. const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length;
  1091. // The largest byte value that is a multiple of `char.length`.
  1092. let n = "";
  1093. for (;n.length < 20; ) {
  1094. const r = gt(40);
  1095. for (let s = 0; s < r.length; ++s)
  1096. // Only accept values that are [0, maxMultiple), this ensures they can
  1097. // be evenly mapped to indices of `chars` via a modulo operation.
  1098. n.length < 20 && r[s] < e && (n += t.charAt(r[s] % t.length));
  1099. }
  1100. return n;
  1101. }
  1102. }
  1103. function vt(t, e) {
  1104. return t < e ? -1 : t > e ? 1 : 0;
  1105. }
  1106. /** Helper to compare arrays using isEqual(). */ function bt(t, e, n) {
  1107. return t.length === e.length && t.every(((t, r) => n(t, e[r])));
  1108. }
  1109. /**
  1110. * @license
  1111. * Copyright 2017 Google LLC
  1112. *
  1113. * Licensed under the Apache License, Version 2.0 (the "License");
  1114. * you may not use this file except in compliance with the License.
  1115. * You may obtain a copy of the License at
  1116. *
  1117. * http://www.apache.org/licenses/LICENSE-2.0
  1118. *
  1119. * Unless required by applicable law or agreed to in writing, software
  1120. * distributed under the License is distributed on an "AS IS" BASIS,
  1121. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1122. * See the License for the specific language governing permissions and
  1123. * limitations under the License.
  1124. */ function Et(t) {
  1125. let e = 0;
  1126. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;
  1127. return e;
  1128. }
  1129. function It(t, e) {
  1130. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);
  1131. }
  1132. /** Converts a Base64 encoded string to a binary string. */
  1133. function At(t) {
  1134. return String.fromCharCode.apply(null,
  1135. // We use `decodeStringToByteArray()` instead of `decodeString()` since
  1136. // `decodeString()` returns Unicode strings, which doesn't match the values
  1137. // returned by `atob()`'s Latin1 representation.
  1138. a.decodeStringToByteArray(t, false));
  1139. }
  1140. /** Converts a binary string to a Base64 encoded string. */
  1141. /**
  1142. * @license
  1143. * Copyright 2020 Google LLC
  1144. *
  1145. * Licensed under the Apache License, Version 2.0 (the "License");
  1146. * you may not use this file except in compliance with the License.
  1147. * You may obtain a copy of the License at
  1148. *
  1149. * http://www.apache.org/licenses/LICENSE-2.0
  1150. *
  1151. * Unless required by applicable law or agreed to in writing, software
  1152. * distributed under the License is distributed on an "AS IS" BASIS,
  1153. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1154. * See the License for the specific language governing permissions and
  1155. * limitations under the License.
  1156. */
  1157. /**
  1158. * Immutable class that represents a "proto" byte string.
  1159. *
  1160. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  1161. * sent on the wire. This class abstracts away this differentiation by holding
  1162. * the proto byte string in a common class that must be converted into a string
  1163. * before being sent as a proto.
  1164. * @internal
  1165. */
  1166. class Tt {
  1167. constructor(t) {
  1168. this.binaryString = t;
  1169. }
  1170. static fromBase64String(t) {
  1171. const e = At(t);
  1172. return new Tt(e);
  1173. }
  1174. static fromUint8Array(t) {
  1175. // TODO(indexing); Remove the copy of the byte string here as this method
  1176. // is frequently called during indexing.
  1177. const e =
  1178. /**
  1179. * Helper function to convert an Uint8array to a binary string.
  1180. */
  1181. function(t) {
  1182. let e = "";
  1183. for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);
  1184. return e;
  1185. }
  1186. /**
  1187. * Helper function to convert a binary string to an Uint8Array.
  1188. */ (t);
  1189. return new Tt(e);
  1190. }
  1191. [Symbol.iterator]() {
  1192. let t = 0;
  1193. return {
  1194. next: () => t < this.binaryString.length ? {
  1195. value: this.binaryString.charCodeAt(t++),
  1196. done: !1
  1197. } : {
  1198. value: void 0,
  1199. done: !0
  1200. }
  1201. };
  1202. }
  1203. toBase64() {
  1204. return function(t) {
  1205. const e = [];
  1206. for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  1207. return a.encodeByteArray(e, !1);
  1208. }(this.binaryString);
  1209. }
  1210. toUint8Array() {
  1211. return function(t) {
  1212. const e = new Uint8Array(t.length);
  1213. for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  1214. return e;
  1215. }
  1216. /**
  1217. * @license
  1218. * Copyright 2020 Google LLC
  1219. *
  1220. * Licensed under the Apache License, Version 2.0 (the "License");
  1221. * you may not use this file except in compliance with the License.
  1222. * You may obtain a copy of the License at
  1223. *
  1224. * http://www.apache.org/licenses/LICENSE-2.0
  1225. *
  1226. * Unless required by applicable law or agreed to in writing, software
  1227. * distributed under the License is distributed on an "AS IS" BASIS,
  1228. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1229. * See the License for the specific language governing permissions and
  1230. * limitations under the License.
  1231. */
  1232. // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
  1233. (this.binaryString);
  1234. }
  1235. approximateByteSize() {
  1236. return 2 * this.binaryString.length;
  1237. }
  1238. compareTo(t) {
  1239. return vt(this.binaryString, t.binaryString);
  1240. }
  1241. isEqual(t) {
  1242. return this.binaryString === t.binaryString;
  1243. }
  1244. }
  1245. Tt.EMPTY_BYTE_STRING = new Tt("");
  1246. const Rt = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  1247. /**
  1248. * Converts the possible Proto values for a timestamp value into a "seconds and
  1249. * nanos" representation.
  1250. */ function Pt(t) {
  1251. // The json interface (for the browser) will return an iso timestamp string,
  1252. // while the proto js library (for node) will return a
  1253. // google.protobuf.Timestamp instance.
  1254. if (I(!!t), "string" == typeof t) {
  1255. // The date string can have higher precision (nanos) than the Date class
  1256. // (millis), so we do some custom parsing here.
  1257. // Parse the nanos right out of the string.
  1258. let e = 0;
  1259. const n = Rt.exec(t);
  1260. if (I(!!n), n[1]) {
  1261. // Pad the fraction out to 9 digits (nanos).
  1262. let t = n[1];
  1263. t = (t + "000000000").substr(0, 9), e = Number(t);
  1264. }
  1265. // Parse the date to get the seconds.
  1266. const r = new Date(t);
  1267. return {
  1268. seconds: Math.floor(r.getTime() / 1e3),
  1269. nanos: e
  1270. };
  1271. }
  1272. return {
  1273. seconds: Vt(t.seconds),
  1274. nanos: Vt(t.nanos)
  1275. };
  1276. }
  1277. /**
  1278. * Converts the possible Proto types for numbers into a JavaScript number.
  1279. * Returns 0 if the value is not numeric.
  1280. */ function Vt(t) {
  1281. // TODO(bjornick): Handle int64 greater than 53 bits.
  1282. return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0;
  1283. }
  1284. /** Converts the possible Proto types for Blobs into a ByteString. */ function $t(t) {
  1285. return "string" == typeof t ? Tt.fromBase64String(t) : Tt.fromUint8Array(t);
  1286. }
  1287. /**
  1288. * @license
  1289. * Copyright 2017 Google LLC
  1290. *
  1291. * Licensed under the Apache License, Version 2.0 (the "License");
  1292. * you may not use this file except in compliance with the License.
  1293. * You may obtain a copy of the License at
  1294. *
  1295. * http://www.apache.org/licenses/LICENSE-2.0
  1296. *
  1297. * Unless required by applicable law or agreed to in writing, software
  1298. * distributed under the License is distributed on an "AS IS" BASIS,
  1299. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1300. * See the License for the specific language governing permissions and
  1301. * limitations under the License.
  1302. */
  1303. // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
  1304. /**
  1305. * A `Timestamp` represents a point in time independent of any time zone or
  1306. * calendar, represented as seconds and fractions of seconds at nanosecond
  1307. * resolution in UTC Epoch time.
  1308. *
  1309. * It is encoded using the Proleptic Gregorian Calendar which extends the
  1310. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  1311. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  1312. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  1313. * 9999-12-31T23:59:59.999999999Z.
  1314. *
  1315. * For examples and further specifications, refer to the
  1316. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  1317. */
  1318. class Nt {
  1319. /**
  1320. * Creates a new timestamp.
  1321. *
  1322. * @param seconds - The number of seconds of UTC time since Unix epoch
  1323. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  1324. * 9999-12-31T23:59:59Z inclusive.
  1325. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  1326. * resolution. Negative second values with fractions must still have
  1327. * non-negative nanoseconds values that count forward in time. Must be
  1328. * from 0 to 999,999,999 inclusive.
  1329. */
  1330. constructor(
  1331. /**
  1332. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  1333. */
  1334. t,
  1335. /**
  1336. * The fractions of a second at nanosecond resolution.*
  1337. */
  1338. e) {
  1339. if (this.seconds = t, this.nanoseconds = e, e < 0) throw new j(V, "Timestamp nanoseconds out of range: " + e);
  1340. if (e >= 1e9) throw new j(V, "Timestamp nanoseconds out of range: " + e);
  1341. if (t < -62135596800) throw new j(V, "Timestamp seconds out of range: " + t);
  1342. // This will break in the year 10,000.
  1343. if (t >= 253402300800) throw new j(V, "Timestamp seconds out of range: " + t);
  1344. }
  1345. /**
  1346. * Creates a new timestamp with the current date, with millisecond precision.
  1347. *
  1348. * @returns a new timestamp representing the current date.
  1349. */ static now() {
  1350. return Nt.fromMillis(Date.now());
  1351. }
  1352. /**
  1353. * Creates a new timestamp from the given date.
  1354. *
  1355. * @param date - The date to initialize the `Timestamp` from.
  1356. * @returns A new `Timestamp` representing the same point in time as the given
  1357. * date.
  1358. */ static fromDate(t) {
  1359. return Nt.fromMillis(t.getTime());
  1360. }
  1361. /**
  1362. * Creates a new timestamp from the given number of milliseconds.
  1363. *
  1364. * @param milliseconds - Number of milliseconds since Unix epoch
  1365. * 1970-01-01T00:00:00Z.
  1366. * @returns A new `Timestamp` representing the same point in time as the given
  1367. * number of milliseconds.
  1368. */ static fromMillis(t) {
  1369. const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));
  1370. return new Nt(e, n);
  1371. }
  1372. /**
  1373. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  1374. * causes a loss of precision since `Date` objects only support millisecond
  1375. * precision.
  1376. *
  1377. * @returns JavaScript `Date` object representing the same point in time as
  1378. * this `Timestamp`, with millisecond precision.
  1379. */ toDate() {
  1380. return new Date(this.toMillis());
  1381. }
  1382. /**
  1383. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  1384. * epoch). This operation causes a loss of precision.
  1385. *
  1386. * @returns The point in time corresponding to this timestamp, represented as
  1387. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  1388. */ toMillis() {
  1389. return 1e3 * this.seconds + this.nanoseconds / 1e6;
  1390. }
  1391. _compareTo(t) {
  1392. return this.seconds === t.seconds ? vt(this.nanoseconds, t.nanoseconds) : vt(this.seconds, t.seconds);
  1393. }
  1394. /**
  1395. * Returns true if this `Timestamp` is equal to the provided one.
  1396. *
  1397. * @param other - The `Timestamp` to compare against.
  1398. * @returns true if this `Timestamp` is equal to the provided one.
  1399. */ isEqual(t) {
  1400. return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
  1401. }
  1402. /** Returns a textual representation of this `Timestamp`. */ toString() {
  1403. return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
  1404. }
  1405. /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {
  1406. return {
  1407. seconds: this.seconds,
  1408. nanoseconds: this.nanoseconds
  1409. };
  1410. }
  1411. /**
  1412. * Converts this object to a primitive string, which allows `Timestamp` objects
  1413. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  1414. */ valueOf() {
  1415. // This method returns a string of the form <seconds>.<nanoseconds> where
  1416. // <seconds> is translated to have a non-negative value and both <seconds>
  1417. // and <nanoseconds> are left-padded with zeroes to be a consistent length.
  1418. // Strings with this format then have a lexiographical ordering that matches
  1419. // the expected ordering. The <seconds> translation is done to avoid having
  1420. // a leading negative sign (i.e. a leading '-' character) in its string
  1421. // representation, which would affect its lexiographical ordering.
  1422. const t = this.seconds - -62135596800;
  1423. // Note: Up to 12 decimal digits are required to represent all valid
  1424. // 'seconds' values.
  1425. return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
  1426. }
  1427. }
  1428. /**
  1429. * @license
  1430. * Copyright 2020 Google LLC
  1431. *
  1432. * Licensed under the Apache License, Version 2.0 (the "License");
  1433. * you may not use this file except in compliance with the License.
  1434. * You may obtain a copy of the License at
  1435. *
  1436. * http://www.apache.org/licenses/LICENSE-2.0
  1437. *
  1438. * Unless required by applicable law or agreed to in writing, software
  1439. * distributed under the License is distributed on an "AS IS" BASIS,
  1440. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1441. * See the License for the specific language governing permissions and
  1442. * limitations under the License.
  1443. */
  1444. /**
  1445. * Represents a locally-applied ServerTimestamp.
  1446. *
  1447. * Server Timestamps are backed by MapValues that contain an internal field
  1448. * `__type__` with a value of `server_timestamp`. The previous value and local
  1449. * write time are stored in its `__previous_value__` and `__local_write_time__`
  1450. * fields respectively.
  1451. *
  1452. * Notes:
  1453. * - ServerTimestampValue instances are created as the result of applying a
  1454. * transform. They can only exist in the local view of a document. Therefore
  1455. * they do not need to be parsed or serialized.
  1456. * - When evaluated locally (e.g. for snapshot.data()), they by default
  1457. * evaluate to `null`. This behavior can be configured by passing custom
  1458. * FieldValueOptions to value().
  1459. * - With respect to other ServerTimestampValues, they sort by their
  1460. * localWriteTime.
  1461. */ function Dt(t) {
  1462. var e, n;
  1463. 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);
  1464. }
  1465. /**
  1466. * Returns the value of the field before this ServerTimestamp was set.
  1467. *
  1468. * Preserving the previous values allows the user to display the last resoled
  1469. * value until the backend responds with the timestamp.
  1470. */ function Ft(t) {
  1471. const e = t.mapValue.fields.__previous_value__;
  1472. return Dt(e) ? Ft(e) : e;
  1473. }
  1474. /**
  1475. * Returns the local time at which this timestamp was first set.
  1476. */ function xt(t) {
  1477. const e = Pt(t.mapValue.fields.__local_write_time__.timestampValue);
  1478. return new Nt(e.seconds, e.nanos);
  1479. }
  1480. /**
  1481. * @license
  1482. * Copyright 2020 Google LLC
  1483. *
  1484. * Licensed under the Apache License, Version 2.0 (the "License");
  1485. * you may not use this file except in compliance with the License.
  1486. * You may obtain a copy of the License at
  1487. *
  1488. * http://www.apache.org/licenses/LICENSE-2.0
  1489. *
  1490. * Unless required by applicable law or agreed to in writing, software
  1491. * distributed under the License is distributed on an "AS IS" BASIS,
  1492. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1493. * See the License for the specific language governing permissions and
  1494. * limitations under the License.
  1495. */ const St = {
  1496. fields: {
  1497. __type__: {
  1498. stringValue: "__max__"
  1499. }
  1500. }
  1501. };
  1502. /** Extracts the backend's type order for the provided value. */
  1503. function qt(t) {
  1504. 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 ? Dt(t) ? 4 /* TypeOrder.ServerTimestampValue */ :
  1505. /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */
  1506. function(t) {
  1507. return "__max__" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;
  1508. }
  1509. /**
  1510. * @license
  1511. * Copyright 2022 Google LLC
  1512. *
  1513. * Licensed under the Apache License, Version 2.0 (the "License");
  1514. * you may not use this file except in compliance with the License.
  1515. * You may obtain a copy of the License at
  1516. *
  1517. * http://www.apache.org/licenses/LICENSE-2.0
  1518. *
  1519. * Unless required by applicable law or agreed to in writing, software
  1520. * distributed under the License is distributed on an "AS IS" BASIS,
  1521. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1522. * See the License for the specific language governing permissions and
  1523. * limitations under the License.
  1524. */
  1525. /**
  1526. * Represents a bound of a query.
  1527. *
  1528. * The bound is specified with the given components representing a position and
  1529. * whether it's just before or just after the position (relative to whatever the
  1530. * query order is).
  1531. *
  1532. * The position represents a logical index position for a query. It's a prefix
  1533. * of values for the (potentially implicit) order by clauses of a query.
  1534. *
  1535. * Bound provides a function to determine whether a document comes before or
  1536. * after a bound. This is influenced by whether the position is just before or
  1537. * just after the provided values.
  1538. */ (t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : E();
  1539. }
  1540. /** Tests `left` and `right` for equality based on the backend semantics. */ function Ot(t, e) {
  1541. if (t === e) return !0;
  1542. const n = qt(t);
  1543. if (n !== qt(e)) return !1;
  1544. switch (n) {
  1545. case 0 /* TypeOrder.NullValue */ :
  1546. case 9007199254740991 /* TypeOrder.MaxValue */ :
  1547. return !0;
  1548. case 1 /* TypeOrder.BooleanValue */ :
  1549. return t.booleanValue === e.booleanValue;
  1550. case 4 /* TypeOrder.ServerTimestampValue */ :
  1551. return xt(t).isEqual(xt(e));
  1552. case 3 /* TypeOrder.TimestampValue */ :
  1553. return function(t, e) {
  1554. if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length)
  1555. // Use string equality for ISO 8601 timestamps
  1556. return t.timestampValue === e.timestampValue;
  1557. const n = Pt(t.timestampValue), r = Pt(e.timestampValue);
  1558. return n.seconds === r.seconds && n.nanos === r.nanos;
  1559. }(t, e);
  1560. case 5 /* TypeOrder.StringValue */ :
  1561. return t.stringValue === e.stringValue;
  1562. case 6 /* TypeOrder.BlobValue */ :
  1563. return function(t, e) {
  1564. return $t(t.bytesValue).isEqual($t(e.bytesValue));
  1565. }(t, e);
  1566. case 7 /* TypeOrder.RefValue */ :
  1567. return t.referenceValue === e.referenceValue;
  1568. case 8 /* TypeOrder.GeoPointValue */ :
  1569. return function(t, e) {
  1570. return Vt(t.geoPointValue.latitude) === Vt(e.geoPointValue.latitude) && Vt(t.geoPointValue.longitude) === Vt(e.geoPointValue.longitude);
  1571. }(t, e);
  1572. case 2 /* TypeOrder.NumberValue */ :
  1573. return function(t, e) {
  1574. if ("integerValue" in t && "integerValue" in e) return Vt(t.integerValue) === Vt(e.integerValue);
  1575. if ("doubleValue" in t && "doubleValue" in e) {
  1576. const n = Vt(t.doubleValue), r = Vt(e.doubleValue);
  1577. return n === r ? ft(n) === ft(r) : isNaN(n) && isNaN(r);
  1578. }
  1579. return !1;
  1580. }(t, e);
  1581. case 9 /* TypeOrder.ArrayValue */ :
  1582. return bt(t.arrayValue.values || [], e.arrayValue.values || [], Ot);
  1583. case 10 /* TypeOrder.ObjectValue */ :
  1584. return function(t, e) {
  1585. const n = t.mapValue.fields || {}, r = e.mapValue.fields || {};
  1586. if (Et(n) !== Et(r)) return !1;
  1587. for (const t in n) if (n.hasOwnProperty(t) && (void 0 === r[t] || !Ot(n[t], r[t]))) return !1;
  1588. return !0;
  1589. }
  1590. /** Returns true if the ArrayValue contains the specified element. */ (t, e);
  1591. default:
  1592. return E();
  1593. }
  1594. }
  1595. function kt(t, e) {
  1596. return void 0 !== (t.values || []).find((t => Ot(t, e)));
  1597. }
  1598. function Ct(t, e) {
  1599. if (t === e) return 0;
  1600. const n = qt(t), r = qt(e);
  1601. if (n !== r) return vt(n, r);
  1602. switch (n) {
  1603. case 0 /* TypeOrder.NullValue */ :
  1604. case 9007199254740991 /* TypeOrder.MaxValue */ :
  1605. return 0;
  1606. case 1 /* TypeOrder.BooleanValue */ :
  1607. return vt(t.booleanValue, e.booleanValue);
  1608. case 2 /* TypeOrder.NumberValue */ :
  1609. return function(t, e) {
  1610. const n = Vt(t.integerValue || t.doubleValue), r = Vt(e.integerValue || e.doubleValue);
  1611. return n < r ? -1 : n > r ? 1 : n === r ? 0 :
  1612. // one or both are NaN.
  1613. isNaN(n) ? isNaN(r) ? 0 : -1 : 1;
  1614. }(t, e);
  1615. case 3 /* TypeOrder.TimestampValue */ :
  1616. return Lt(t.timestampValue, e.timestampValue);
  1617. case 4 /* TypeOrder.ServerTimestampValue */ :
  1618. return Lt(xt(t), xt(e));
  1619. case 5 /* TypeOrder.StringValue */ :
  1620. return vt(t.stringValue, e.stringValue);
  1621. case 6 /* TypeOrder.BlobValue */ :
  1622. return function(t, e) {
  1623. const n = $t(t), r = $t(e);
  1624. return n.compareTo(r);
  1625. }(t.bytesValue, e.bytesValue);
  1626. case 7 /* TypeOrder.RefValue */ :
  1627. return function(t, e) {
  1628. const n = t.split("/"), r = e.split("/");
  1629. for (let t = 0; t < n.length && t < r.length; t++) {
  1630. const e = vt(n[t], r[t]);
  1631. if (0 !== e) return e;
  1632. }
  1633. return vt(n.length, r.length);
  1634. }(t.referenceValue, e.referenceValue);
  1635. case 8 /* TypeOrder.GeoPointValue */ :
  1636. return function(t, e) {
  1637. const n = vt(Vt(t.latitude), Vt(e.latitude));
  1638. if (0 !== n) return n;
  1639. return vt(Vt(t.longitude), Vt(e.longitude));
  1640. }(t.geoPointValue, e.geoPointValue);
  1641. case 9 /* TypeOrder.ArrayValue */ :
  1642. return function(t, e) {
  1643. const n = t.values || [], r = e.values || [];
  1644. for (let t = 0; t < n.length && t < r.length; ++t) {
  1645. const e = Ct(n[t], r[t]);
  1646. if (e) return e;
  1647. }
  1648. return vt(n.length, r.length);
  1649. }(t.arrayValue, e.arrayValue);
  1650. case 10 /* TypeOrder.ObjectValue */ :
  1651. return function(t, e) {
  1652. if (t === St && e === St) return 0;
  1653. if (t === St) return 1;
  1654. if (e === St) return -1;
  1655. const n = t.fields || {}, r = Object.keys(n), s = e.fields || {}, i = Object.keys(s);
  1656. // Even though MapValues are likely sorted correctly based on their insertion
  1657. // order (e.g. when received from the backend), local modifications can bring
  1658. // elements out of order. We need to re-sort the elements to ensure that
  1659. // canonical IDs are independent of insertion order.
  1660. r.sort(), i.sort();
  1661. for (let t = 0; t < r.length && t < i.length; ++t) {
  1662. const e = vt(r[t], i[t]);
  1663. if (0 !== e) return e;
  1664. const o = Ct(n[r[t]], s[i[t]]);
  1665. if (0 !== o) return o;
  1666. }
  1667. return vt(r.length, i.length);
  1668. }
  1669. /** Returns a reference value for the provided database and key. */ (t.mapValue, e.mapValue);
  1670. default:
  1671. throw E();
  1672. }
  1673. }
  1674. function Lt(t, e) {
  1675. if ("string" == typeof t && "string" == typeof e && t.length === e.length) return vt(t, e);
  1676. const n = Pt(t), r = Pt(e), s = vt(n.seconds, r.seconds);
  1677. return 0 !== s ? s : vt(n.nanos, r.nanos);
  1678. }
  1679. function Mt(t, e) {
  1680. return {
  1681. referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`
  1682. };
  1683. }
  1684. /** Returns true if `value` is an ArrayValue. */ function Ut(t) {
  1685. return !!t && "arrayValue" in t;
  1686. }
  1687. /** Returns true if `value` is a NullValue. */ function jt(t) {
  1688. return !!t && "nullValue" in t;
  1689. }
  1690. /** Returns true if `value` is NaN. */ function Bt(t) {
  1691. return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
  1692. }
  1693. /** Returns true if `value` is a MapValue. */ function Qt(t) {
  1694. return !!t && "mapValue" in t;
  1695. }
  1696. /** Creates a deep copy of `source`. */ function zt(t) {
  1697. if (t.geoPointValue) return {
  1698. geoPointValue: Object.assign({}, t.geoPointValue)
  1699. };
  1700. if (t.timestampValue && "object" == typeof t.timestampValue) return {
  1701. timestampValue: Object.assign({}, t.timestampValue)
  1702. };
  1703. if (t.mapValue) {
  1704. const e = {
  1705. mapValue: {
  1706. fields: {}
  1707. }
  1708. };
  1709. return It(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = zt(n))), e;
  1710. }
  1711. if (t.arrayValue) {
  1712. const e = {
  1713. arrayValue: {
  1714. values: []
  1715. }
  1716. };
  1717. for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = zt(t.arrayValue.values[n]);
  1718. return e;
  1719. }
  1720. return Object.assign({}, t);
  1721. }
  1722. class Wt {
  1723. constructor(t, e) {
  1724. this.position = t, this.inclusive = e;
  1725. }
  1726. }
  1727. function Gt(t, e) {
  1728. if (null === t) return null === e;
  1729. if (null === e) return !1;
  1730. if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;
  1731. for (let n = 0; n < t.position.length; n++) {
  1732. if (!Ot(t.position[n], e.position[n])) return !1;
  1733. }
  1734. return !0;
  1735. }
  1736. /**
  1737. * @license
  1738. * Copyright 2022 Google LLC
  1739. *
  1740. * Licensed under the Apache License, Version 2.0 (the "License");
  1741. * you may not use this file except in compliance with the License.
  1742. * You may obtain a copy of the License at
  1743. *
  1744. * http://www.apache.org/licenses/LICENSE-2.0
  1745. *
  1746. * Unless required by applicable law or agreed to in writing, software
  1747. * distributed under the License is distributed on an "AS IS" BASIS,
  1748. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1749. * See the License for the specific language governing permissions and
  1750. * limitations under the License.
  1751. */ class Kt {}
  1752. class Yt extends Kt {
  1753. constructor(t, e, n) {
  1754. super(), this.field = t, this.op = e, this.value = n;
  1755. }
  1756. /**
  1757. * Creates a filter based on the provided arguments.
  1758. */ static create(t, e, n) {
  1759. return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, n) : new Xt(t, e, n) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new ne(t, n) : "in" /* Operator.IN */ === e ? new re(t, n) : "not-in" /* Operator.NOT_IN */ === e ? new se(t, n) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new ie(t, n) : new Yt(t, e, n);
  1760. }
  1761. static createKeyFieldInFilter(t, e, n) {
  1762. return "in" /* Operator.IN */ === e ? new Zt(t, n) : new te(t, n);
  1763. }
  1764. matches(t) {
  1765. const e = t.data.field(this.field);
  1766. // Types do not have to match in NOT_EQUAL filters.
  1767. return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(Ct(e, this.value)) : null !== e && qt(this.value) === qt(e) && this.matchesComparison(Ct(e, this.value));
  1768. // Only compare types with matching backend order (such as double and int).
  1769. }
  1770. matchesComparison(t) {
  1771. switch (this.op) {
  1772. case "<" /* Operator.LESS_THAN */ :
  1773. return t < 0;
  1774. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  1775. return t <= 0;
  1776. case "==" /* Operator.EQUAL */ :
  1777. return 0 === t;
  1778. case "!=" /* Operator.NOT_EQUAL */ :
  1779. return 0 !== t;
  1780. case ">" /* Operator.GREATER_THAN */ :
  1781. return t > 0;
  1782. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  1783. return t >= 0;
  1784. default:
  1785. return E();
  1786. }
  1787. }
  1788. isInequality() {
  1789. 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;
  1790. }
  1791. getFlattenedFilters() {
  1792. return [ this ];
  1793. }
  1794. getFilters() {
  1795. return [ this ];
  1796. }
  1797. getFirstInequalityField() {
  1798. return this.isInequality() ? this.field : null;
  1799. }
  1800. }
  1801. class Ht extends Kt {
  1802. constructor(t, e) {
  1803. super(), this.filters = t, this.op = e, this.D = null;
  1804. }
  1805. /**
  1806. * Creates a filter based on the provided arguments.
  1807. */ static create(t, e) {
  1808. return new Ht(t, e);
  1809. }
  1810. matches(t) {
  1811. return "and" /* CompositeOperator.AND */ === this.op ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t)));
  1812. }
  1813. getFlattenedFilters() {
  1814. return null !== this.D || (this.D = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])),
  1815. this.D;
  1816. }
  1817. // Returns a mutable copy of `this.filters`
  1818. getFilters() {
  1819. return Object.assign([], this.filters);
  1820. }
  1821. getFirstInequalityField() {
  1822. const t = this.F((t => t.isInequality()));
  1823. return null !== t ? t.field : null;
  1824. }
  1825. // Performs a depth-first search to find and return the first FieldFilter in the composite filter
  1826. // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
  1827. // predicate.
  1828. F(t) {
  1829. for (const e of this.getFlattenedFilters()) if (t(e)) return e;
  1830. return null;
  1831. }
  1832. }
  1833. function Jt(t, e) {
  1834. return t instanceof Yt ? function(t, e) {
  1835. return e instanceof Yt && t.op === e.op && t.field.isEqual(e.field) && Ot(t.value, e.value);
  1836. }(t, e) : t instanceof Ht ? function(t, e) {
  1837. if (e instanceof Ht && t.op === e.op && t.filters.length === e.filters.length) {
  1838. return t.filters.reduce(((t, n, r) => t && Jt(n, e.filters[r])), !0);
  1839. }
  1840. return !1;
  1841. }
  1842. /** Filter that matches on key fields (i.e. '__name__'). */ (t, e) : void E();
  1843. }
  1844. class Xt extends Yt {
  1845. constructor(t, e, n) {
  1846. super(t, e, n), this.key = st.fromName(n.referenceValue);
  1847. }
  1848. matches(t) {
  1849. const e = st.comparator(t.key, this.key);
  1850. return this.matchesComparison(e);
  1851. }
  1852. }
  1853. /** Filter that matches on key fields within an array. */ class Zt extends Yt {
  1854. constructor(t, e) {
  1855. super(t, "in" /* Operator.IN */ , e), this.keys = ee("in" /* Operator.IN */ , e);
  1856. }
  1857. matches(t) {
  1858. return this.keys.some((e => e.isEqual(t.key)));
  1859. }
  1860. }
  1861. /** Filter that matches on key fields not present within an array. */ class te extends Yt {
  1862. constructor(t, e) {
  1863. super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = ee("not-in" /* Operator.NOT_IN */ , e);
  1864. }
  1865. matches(t) {
  1866. return !this.keys.some((e => e.isEqual(t.key)));
  1867. }
  1868. }
  1869. function ee(t, e) {
  1870. var n;
  1871. return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => st.fromName(t.referenceValue)));
  1872. }
  1873. /** A Filter that implements the array-contains operator. */ class ne extends Yt {
  1874. constructor(t, e) {
  1875. super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e);
  1876. }
  1877. matches(t) {
  1878. const e = t.data.field(this.field);
  1879. return Ut(e) && kt(e.arrayValue, this.value);
  1880. }
  1881. }
  1882. /** A Filter that implements the IN operator. */ class re extends Yt {
  1883. constructor(t, e) {
  1884. super(t, "in" /* Operator.IN */ , e);
  1885. }
  1886. matches(t) {
  1887. const e = t.data.field(this.field);
  1888. return null !== e && kt(this.value.arrayValue, e);
  1889. }
  1890. }
  1891. /** A Filter that implements the not-in operator. */ class se extends Yt {
  1892. constructor(t, e) {
  1893. super(t, "not-in" /* Operator.NOT_IN */ , e);
  1894. }
  1895. matches(t) {
  1896. if (kt(this.value.arrayValue, {
  1897. nullValue: "NULL_VALUE"
  1898. })) return !1;
  1899. const e = t.data.field(this.field);
  1900. return null !== e && !kt(this.value.arrayValue, e);
  1901. }
  1902. }
  1903. /** A Filter that implements the array-contains-any operator. */ class ie extends Yt {
  1904. constructor(t, e) {
  1905. super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e);
  1906. }
  1907. matches(t) {
  1908. const e = t.data.field(this.field);
  1909. return !(!Ut(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => kt(this.value.arrayValue, t)));
  1910. }
  1911. }
  1912. /**
  1913. * @license
  1914. * Copyright 2022 Google LLC
  1915. *
  1916. * Licensed under the Apache License, Version 2.0 (the "License");
  1917. * you may not use this file except in compliance with the License.
  1918. * You may obtain a copy of the License at
  1919. *
  1920. * http://www.apache.org/licenses/LICENSE-2.0
  1921. *
  1922. * Unless required by applicable law or agreed to in writing, software
  1923. * distributed under the License is distributed on an "AS IS" BASIS,
  1924. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1925. * See the License for the specific language governing permissions and
  1926. * limitations under the License.
  1927. */
  1928. /**
  1929. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  1930. */ class oe {
  1931. constructor(t, e = "asc" /* Direction.ASCENDING */) {
  1932. this.field = t, this.dir = e;
  1933. }
  1934. }
  1935. function ue(t, e) {
  1936. return t.dir === e.dir && t.field.isEqual(e.field);
  1937. }
  1938. /**
  1939. * @license
  1940. * Copyright 2017 Google LLC
  1941. *
  1942. * Licensed under the Apache License, Version 2.0 (the "License");
  1943. * you may not use this file except in compliance with the License.
  1944. * You may obtain a copy of the License at
  1945. *
  1946. * http://www.apache.org/licenses/LICENSE-2.0
  1947. *
  1948. * Unless required by applicable law or agreed to in writing, software
  1949. * distributed under the License is distributed on an "AS IS" BASIS,
  1950. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1951. * See the License for the specific language governing permissions and
  1952. * limitations under the License.
  1953. */
  1954. /**
  1955. * A version of a document in Firestore. This corresponds to the version
  1956. * timestamp, such as update_time or read_time.
  1957. */ class ce {
  1958. constructor(t) {
  1959. this.timestamp = t;
  1960. }
  1961. static fromTimestamp(t) {
  1962. return new ce(t);
  1963. }
  1964. static min() {
  1965. return new ce(new Nt(0, 0));
  1966. }
  1967. static max() {
  1968. return new ce(new Nt(253402300799, 999999999));
  1969. }
  1970. compareTo(t) {
  1971. return this.timestamp._compareTo(t.timestamp);
  1972. }
  1973. isEqual(t) {
  1974. return this.timestamp.isEqual(t.timestamp);
  1975. }
  1976. /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {
  1977. // Convert to microseconds.
  1978. return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
  1979. }
  1980. toString() {
  1981. return "SnapshotVersion(" + this.timestamp.toString() + ")";
  1982. }
  1983. toTimestamp() {
  1984. return this.timestamp;
  1985. }
  1986. }
  1987. /**
  1988. * @license
  1989. * Copyright 2017 Google LLC
  1990. *
  1991. * Licensed under the Apache License, Version 2.0 (the "License");
  1992. * you may not use this file except in compliance with the License.
  1993. * You may obtain a copy of the License at
  1994. *
  1995. * http://www.apache.org/licenses/LICENSE-2.0
  1996. *
  1997. * Unless required by applicable law or agreed to in writing, software
  1998. * distributed under the License is distributed on an "AS IS" BASIS,
  1999. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2000. * See the License for the specific language governing permissions and
  2001. * limitations under the License.
  2002. */
  2003. // An immutable sorted map implementation, based on a Left-leaning Red-Black
  2004. // tree.
  2005. class ae {
  2006. constructor(t, e) {
  2007. this.comparator = t, this.root = e || le.EMPTY;
  2008. }
  2009. // Returns a copy of the map, with the specified key/value added or replaced.
  2010. insert(t, e) {
  2011. return new ae(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, le.BLACK, null, null));
  2012. }
  2013. // Returns a copy of the map, with the specified key removed.
  2014. remove(t) {
  2015. return new ae(this.comparator, this.root.remove(t, this.comparator).copy(null, null, le.BLACK, null, null));
  2016. }
  2017. // Returns the value of the node with the given key, or null.
  2018. get(t) {
  2019. let e = this.root;
  2020. for (;!e.isEmpty(); ) {
  2021. const n = this.comparator(t, e.key);
  2022. if (0 === n) return e.value;
  2023. n < 0 ? e = e.left : n > 0 && (e = e.right);
  2024. }
  2025. return null;
  2026. }
  2027. // Returns the index of the element in this sorted map, or -1 if it doesn't
  2028. // exist.
  2029. indexOf(t) {
  2030. // Number of nodes that were pruned when descending right
  2031. let e = 0, n = this.root;
  2032. for (;!n.isEmpty(); ) {
  2033. const r = this.comparator(t, n.key);
  2034. if (0 === r) return e + n.left.size;
  2035. r < 0 ? n = n.left : (
  2036. // Count all nodes left of the node plus the node itself
  2037. e += n.left.size + 1, n = n.right);
  2038. }
  2039. // Node not found
  2040. return -1;
  2041. }
  2042. isEmpty() {
  2043. return this.root.isEmpty();
  2044. }
  2045. // Returns the total number of nodes in the map.
  2046. get size() {
  2047. return this.root.size;
  2048. }
  2049. // Returns the minimum key in the map.
  2050. minKey() {
  2051. return this.root.minKey();
  2052. }
  2053. // Returns the maximum key in the map.
  2054. maxKey() {
  2055. return this.root.maxKey();
  2056. }
  2057. // Traverses the map in key order and calls the specified action function
  2058. // for each key/value pair. If action returns true, traversal is aborted.
  2059. // Returns the first truthy value returned by action, or the last falsey
  2060. // value returned by action.
  2061. inorderTraversal(t) {
  2062. return this.root.inorderTraversal(t);
  2063. }
  2064. forEach(t) {
  2065. this.inorderTraversal(((e, n) => (t(e, n), !1)));
  2066. }
  2067. toString() {
  2068. const t = [];
  2069. return this.inorderTraversal(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(", ")}}`;
  2070. }
  2071. // Traverses the map in reverse key order and calls the specified action
  2072. // function for each key/value pair. If action returns true, traversal is
  2073. // aborted.
  2074. // Returns the first truthy value returned by action, or the last falsey
  2075. // value returned by action.
  2076. reverseTraversal(t) {
  2077. return this.root.reverseTraversal(t);
  2078. }
  2079. // Returns an iterator over the SortedMap.
  2080. getIterator() {
  2081. return new he(this.root, null, this.comparator, !1);
  2082. }
  2083. getIteratorFrom(t) {
  2084. return new he(this.root, t, this.comparator, !1);
  2085. }
  2086. getReverseIterator() {
  2087. return new he(this.root, null, this.comparator, !0);
  2088. }
  2089. getReverseIteratorFrom(t) {
  2090. return new he(this.root, t, this.comparator, !0);
  2091. }
  2092. }
  2093. // end SortedMap
  2094. // An iterator over an LLRBNode.
  2095. class he {
  2096. constructor(t, e, n, r) {
  2097. this.isReverse = r, this.nodeStack = [];
  2098. let s = 1;
  2099. for (;!t.isEmpty(); ) if (s = e ? n(t.key, e) : 1,
  2100. // flip the comparison if we're going in reverse
  2101. e && r && (s *= -1), s < 0)
  2102. // This node is less than our start key. ignore it
  2103. t = this.isReverse ? t.left : t.right; else {
  2104. if (0 === s) {
  2105. // This node is exactly equal to our start key. Push it on the stack,
  2106. // but stop iterating;
  2107. this.nodeStack.push(t);
  2108. break;
  2109. }
  2110. // This node is greater than our start key, add it to the stack and move
  2111. // to the next one
  2112. this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;
  2113. }
  2114. }
  2115. getNext() {
  2116. let t = this.nodeStack.pop();
  2117. const e = {
  2118. key: t.key,
  2119. value: t.value
  2120. };
  2121. 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),
  2122. t = t.left;
  2123. return e;
  2124. }
  2125. hasNext() {
  2126. return this.nodeStack.length > 0;
  2127. }
  2128. peek() {
  2129. if (0 === this.nodeStack.length) return null;
  2130. const t = this.nodeStack[this.nodeStack.length - 1];
  2131. return {
  2132. key: t.key,
  2133. value: t.value
  2134. };
  2135. }
  2136. }
  2137. // end SortedMapIterator
  2138. // Represents a node in a Left-leaning Red-Black tree.
  2139. class le {
  2140. constructor(t, e, n, r, s) {
  2141. this.key = t, this.value = e, this.color = null != n ? n : le.RED, this.left = null != r ? r : le.EMPTY,
  2142. this.right = null != s ? s : le.EMPTY, this.size = this.left.size + 1 + this.right.size;
  2143. }
  2144. // Returns a copy of the current node, optionally replacing pieces of it.
  2145. copy(t, e, n, r, s) {
  2146. return new le(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != r ? r : this.left, null != s ? s : this.right);
  2147. }
  2148. isEmpty() {
  2149. return !1;
  2150. }
  2151. // Traverses the tree in key order and calls the specified action function
  2152. // for each node. If action returns true, traversal is aborted.
  2153. // Returns the first truthy value returned by action, or the last falsey
  2154. // value returned by action.
  2155. inorderTraversal(t) {
  2156. return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);
  2157. }
  2158. // Traverses the tree in reverse key order and calls the specified action
  2159. // function for each node. If action returns true, traversal is aborted.
  2160. // Returns the first truthy value returned by action, or the last falsey
  2161. // value returned by action.
  2162. reverseTraversal(t) {
  2163. return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);
  2164. }
  2165. // Returns the minimum node in the tree.
  2166. min() {
  2167. return this.left.isEmpty() ? this : this.left.min();
  2168. }
  2169. // Returns the maximum key in the tree.
  2170. minKey() {
  2171. return this.min().key;
  2172. }
  2173. // Returns the maximum key in the tree.
  2174. maxKey() {
  2175. return this.right.isEmpty() ? this.key : this.right.maxKey();
  2176. }
  2177. // Returns new tree, with the key/value added.
  2178. insert(t, e, n) {
  2179. let r = this;
  2180. const s = n(t, r.key);
  2181. return r = s < 0 ? r.copy(null, null, null, r.left.insert(t, e, n), null) : 0 === s ? r.copy(null, e, null, null, null) : r.copy(null, null, null, null, r.right.insert(t, e, n)),
  2182. r.fixUp();
  2183. }
  2184. removeMin() {
  2185. if (this.left.isEmpty()) return le.EMPTY;
  2186. let t = this;
  2187. return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null),
  2188. t.fixUp();
  2189. }
  2190. // Returns new tree, with the specified item removed.
  2191. remove(t, e) {
  2192. let n, r = this;
  2193. if (e(t, r.key) < 0) r.left.isEmpty() || r.left.isRed() || r.left.left.isRed() || (r = r.moveRedLeft()),
  2194. r = r.copy(null, null, null, r.left.remove(t, e), null); else {
  2195. if (r.left.isRed() && (r = r.rotateRight()), r.right.isEmpty() || r.right.isRed() || r.right.left.isRed() || (r = r.moveRedRight()),
  2196. 0 === e(t, r.key)) {
  2197. if (r.right.isEmpty()) return le.EMPTY;
  2198. n = r.right.min(), r = r.copy(n.key, n.value, null, null, r.right.removeMin());
  2199. }
  2200. r = r.copy(null, null, null, null, r.right.remove(t, e));
  2201. }
  2202. return r.fixUp();
  2203. }
  2204. isRed() {
  2205. return this.color;
  2206. }
  2207. // Returns new tree after performing any needed rotations.
  2208. fixUp() {
  2209. let t = this;
  2210. return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()),
  2211. t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;
  2212. }
  2213. moveRedLeft() {
  2214. let t = this.colorFlip();
  2215. return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()),
  2216. t = t.rotateLeft(), t = t.colorFlip()), t;
  2217. }
  2218. moveRedRight() {
  2219. let t = this.colorFlip();
  2220. return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t;
  2221. }
  2222. rotateLeft() {
  2223. const t = this.copy(null, null, le.RED, null, this.right.left);
  2224. return this.right.copy(null, null, this.color, t, null);
  2225. }
  2226. rotateRight() {
  2227. const t = this.copy(null, null, le.RED, this.left.right, null);
  2228. return this.left.copy(null, null, this.color, null, t);
  2229. }
  2230. colorFlip() {
  2231. const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);
  2232. return this.copy(null, null, !this.color, t, e);
  2233. }
  2234. // For testing.
  2235. checkMaxDepth() {
  2236. const t = this.check();
  2237. return Math.pow(2, t) <= this.size + 1;
  2238. }
  2239. // In a balanced RB tree, the black-depth (number of black nodes) from root to
  2240. // leaves is equal on both sides. This function verifies that or asserts.
  2241. check() {
  2242. if (this.isRed() && this.left.isRed()) throw E();
  2243. if (this.right.isRed()) throw E();
  2244. const t = this.left.check();
  2245. if (t !== this.right.check()) throw E();
  2246. return t + (this.isRed() ? 0 : 1);
  2247. }
  2248. }
  2249. // end LLRBNode
  2250. // Empty node is shared between all LLRB trees.
  2251. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2252. le.EMPTY = null, le.RED = !0, le.BLACK = !1;
  2253. // end LLRBEmptyNode
  2254. le.EMPTY = new
  2255. // Represents an empty node (a leaf node in the Red-Black Tree).
  2256. class {
  2257. constructor() {
  2258. this.size = 0;
  2259. }
  2260. get key() {
  2261. throw E();
  2262. }
  2263. get value() {
  2264. throw E();
  2265. }
  2266. get color() {
  2267. throw E();
  2268. }
  2269. get left() {
  2270. throw E();
  2271. }
  2272. get right() {
  2273. throw E();
  2274. }
  2275. // Returns a copy of the current node.
  2276. copy(t, e, n, r, s) {
  2277. return this;
  2278. }
  2279. // Returns a copy of the tree, with the specified key/value added.
  2280. insert(t, e, n) {
  2281. return new le(t, e);
  2282. }
  2283. // Returns a copy of the tree, with the specified key removed.
  2284. remove(t, e) {
  2285. return this;
  2286. }
  2287. isEmpty() {
  2288. return !0;
  2289. }
  2290. inorderTraversal(t) {
  2291. return !1;
  2292. }
  2293. reverseTraversal(t) {
  2294. return !1;
  2295. }
  2296. minKey() {
  2297. return null;
  2298. }
  2299. maxKey() {
  2300. return null;
  2301. }
  2302. isRed() {
  2303. return !1;
  2304. }
  2305. // For testing.
  2306. checkMaxDepth() {
  2307. return !0;
  2308. }
  2309. check() {
  2310. return 0;
  2311. }
  2312. };
  2313. /**
  2314. * @license
  2315. * Copyright 2017 Google LLC
  2316. *
  2317. * Licensed under the Apache License, Version 2.0 (the "License");
  2318. * you may not use this file except in compliance with the License.
  2319. * You may obtain a copy of the License at
  2320. *
  2321. * http://www.apache.org/licenses/LICENSE-2.0
  2322. *
  2323. * Unless required by applicable law or agreed to in writing, software
  2324. * distributed under the License is distributed on an "AS IS" BASIS,
  2325. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2326. * See the License for the specific language governing permissions and
  2327. * limitations under the License.
  2328. */
  2329. /**
  2330. * SortedSet is an immutable (copy-on-write) collection that holds elements
  2331. * in order specified by the provided comparator.
  2332. *
  2333. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  2334. * be equal!
  2335. */
  2336. class fe {
  2337. constructor(t) {
  2338. this.comparator = t, this.data = new ae(this.comparator);
  2339. }
  2340. has(t) {
  2341. return null !== this.data.get(t);
  2342. }
  2343. first() {
  2344. return this.data.minKey();
  2345. }
  2346. last() {
  2347. return this.data.maxKey();
  2348. }
  2349. get size() {
  2350. return this.data.size;
  2351. }
  2352. indexOf(t) {
  2353. return this.data.indexOf(t);
  2354. }
  2355. /** Iterates elements in order defined by "comparator" */ forEach(t) {
  2356. this.data.inorderTraversal(((e, n) => (t(e), !1)));
  2357. }
  2358. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */ forEachInRange(t, e) {
  2359. const n = this.data.getIteratorFrom(t[0]);
  2360. for (;n.hasNext(); ) {
  2361. const r = n.getNext();
  2362. if (this.comparator(r.key, t[1]) >= 0) return;
  2363. e(r.key);
  2364. }
  2365. }
  2366. /**
  2367. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  2368. */ forEachWhile(t, e) {
  2369. let n;
  2370. for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) {
  2371. if (!t(n.getNext().key)) return;
  2372. }
  2373. }
  2374. /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {
  2375. const e = this.data.getIteratorFrom(t);
  2376. return e.hasNext() ? e.getNext().key : null;
  2377. }
  2378. getIterator() {
  2379. return new de(this.data.getIterator());
  2380. }
  2381. getIteratorFrom(t) {
  2382. return new de(this.data.getIteratorFrom(t));
  2383. }
  2384. /** Inserts or updates an element */ add(t) {
  2385. return this.copy(this.data.remove(t).insert(t, !0));
  2386. }
  2387. /** Deletes an element */ delete(t) {
  2388. return this.has(t) ? this.copy(this.data.remove(t)) : this;
  2389. }
  2390. isEmpty() {
  2391. return this.data.isEmpty();
  2392. }
  2393. unionWith(t) {
  2394. let e = this;
  2395. // Make sure `result` always refers to the larger one of the two sets.
  2396. return e.size < t.size && (e = t, t = this), t.forEach((t => {
  2397. e = e.add(t);
  2398. })), e;
  2399. }
  2400. isEqual(t) {
  2401. if (!(t instanceof fe)) return !1;
  2402. if (this.size !== t.size) return !1;
  2403. const e = this.data.getIterator(), n = t.data.getIterator();
  2404. for (;e.hasNext(); ) {
  2405. const t = e.getNext().key, r = n.getNext().key;
  2406. if (0 !== this.comparator(t, r)) return !1;
  2407. }
  2408. return !0;
  2409. }
  2410. toArray() {
  2411. const t = [];
  2412. return this.forEach((e => {
  2413. t.push(e);
  2414. })), t;
  2415. }
  2416. toString() {
  2417. const t = [];
  2418. return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")";
  2419. }
  2420. copy(t) {
  2421. const e = new fe(this.comparator);
  2422. return e.data = t, e;
  2423. }
  2424. }
  2425. class de {
  2426. constructor(t) {
  2427. this.iter = t;
  2428. }
  2429. getNext() {
  2430. return this.iter.getNext().key;
  2431. }
  2432. hasNext() {
  2433. return this.iter.hasNext();
  2434. }
  2435. }
  2436. /**
  2437. * @license
  2438. * Copyright 2020 Google LLC
  2439. *
  2440. * Licensed under the Apache License, Version 2.0 (the "License");
  2441. * you may not use this file except in compliance with the License.
  2442. * You may obtain a copy of the License at
  2443. *
  2444. * http://www.apache.org/licenses/LICENSE-2.0
  2445. *
  2446. * Unless required by applicable law or agreed to in writing, software
  2447. * distributed under the License is distributed on an "AS IS" BASIS,
  2448. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2449. * See the License for the specific language governing permissions and
  2450. * limitations under the License.
  2451. */
  2452. /**
  2453. * Provides a set of fields that can be used to partially patch a document.
  2454. * FieldMask is used in conjunction with ObjectValue.
  2455. * Examples:
  2456. * foo - Overwrites foo entirely with the provided value. If foo is not
  2457. * present in the companion ObjectValue, the field is deleted.
  2458. * foo.bar - Overwrites only the field bar of the object foo.
  2459. * If foo is not an object, foo is replaced with an object
  2460. * containing foo
  2461. */ class we {
  2462. constructor(t) {
  2463. this.fields = t,
  2464. // TODO(dimond): validation of FieldMask
  2465. // Sort the field mask to support `FieldMask.isEqual()` and assert below.
  2466. t.sort(rt.comparator);
  2467. }
  2468. static empty() {
  2469. return new we([]);
  2470. }
  2471. /**
  2472. * Returns a new FieldMask object that is the result of adding all the given
  2473. * fields paths to this field mask.
  2474. */ unionWith(t) {
  2475. let e = new fe(rt.comparator);
  2476. for (const t of this.fields) e = e.add(t);
  2477. for (const n of t) e = e.add(n);
  2478. return new we(e.toArray());
  2479. }
  2480. /**
  2481. * Verifies that `fieldPath` is included by at least one field in this field
  2482. * mask.
  2483. *
  2484. * This is an O(n) operation, where `n` is the size of the field mask.
  2485. */ covers(t) {
  2486. for (const e of this.fields) if (e.isPrefixOf(t)) return !0;
  2487. return !1;
  2488. }
  2489. isEqual(t) {
  2490. return bt(this.fields, t.fields, ((t, e) => t.isEqual(e)));
  2491. }
  2492. }
  2493. /**
  2494. * @license
  2495. * Copyright 2017 Google LLC
  2496. *
  2497. * Licensed under the Apache License, Version 2.0 (the "License");
  2498. * you may not use this file except in compliance with the License.
  2499. * You may obtain a copy of the License at
  2500. *
  2501. * http://www.apache.org/licenses/LICENSE-2.0
  2502. *
  2503. * Unless required by applicable law or agreed to in writing, software
  2504. * distributed under the License is distributed on an "AS IS" BASIS,
  2505. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2506. * See the License for the specific language governing permissions and
  2507. * limitations under the License.
  2508. */
  2509. /**
  2510. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  2511. * ability to add and remove fields (via the ObjectValueBuilder).
  2512. */ class me {
  2513. constructor(t) {
  2514. this.value = t;
  2515. }
  2516. static empty() {
  2517. return new me({
  2518. mapValue: {}
  2519. });
  2520. }
  2521. /**
  2522. * Returns the value at the given path or null.
  2523. *
  2524. * @param path - the path to search
  2525. * @returns The value at the path or null if the path is not set.
  2526. */ field(t) {
  2527. if (t.isEmpty()) return this.value;
  2528. {
  2529. let e = this.value;
  2530. for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)],
  2531. !Qt(e)) return null;
  2532. return e = (e.mapValue.fields || {})[t.lastSegment()], e || null;
  2533. }
  2534. }
  2535. /**
  2536. * Sets the field to the provided value.
  2537. *
  2538. * @param path - The field path to set.
  2539. * @param value - The value to set.
  2540. */ set(t, e) {
  2541. this.getFieldsMap(t.popLast())[t.lastSegment()] = zt(e);
  2542. }
  2543. /**
  2544. * Sets the provided fields to the provided values.
  2545. *
  2546. * @param data - A map of fields to values (or null for deletes).
  2547. */ setAll(t) {
  2548. let e = rt.emptyPath(), n = {}, r = [];
  2549. t.forEach(((t, s) => {
  2550. if (!e.isImmediateParentOf(s)) {
  2551. // Insert the accumulated changes at this parent location
  2552. const t = this.getFieldsMap(e);
  2553. this.applyChanges(t, n, r), n = {}, r = [], e = s.popLast();
  2554. }
  2555. t ? n[s.lastSegment()] = zt(t) : r.push(s.lastSegment());
  2556. }));
  2557. const s = this.getFieldsMap(e);
  2558. this.applyChanges(s, n, r);
  2559. }
  2560. /**
  2561. * Removes the field at the specified path. If there is no field at the
  2562. * specified path, nothing is changed.
  2563. *
  2564. * @param path - The field path to remove.
  2565. */ delete(t) {
  2566. const e = this.field(t.popLast());
  2567. Qt(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];
  2568. }
  2569. isEqual(t) {
  2570. return Ot(this.value, t.value);
  2571. }
  2572. /**
  2573. * Returns the map that contains the leaf element of `path`. If the parent
  2574. * entry does not yet exist, or if it is not a map, a new map will be created.
  2575. */ getFieldsMap(t) {
  2576. let e = this.value;
  2577. e.mapValue.fields || (e.mapValue = {
  2578. fields: {}
  2579. });
  2580. for (let n = 0; n < t.length; ++n) {
  2581. let r = e.mapValue.fields[t.get(n)];
  2582. Qt(r) && r.mapValue.fields || (r = {
  2583. mapValue: {
  2584. fields: {}
  2585. }
  2586. }, e.mapValue.fields[t.get(n)] = r), e = r;
  2587. }
  2588. return e.mapValue.fields;
  2589. }
  2590. /**
  2591. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  2592. * entries.
  2593. */ applyChanges(t, e, n) {
  2594. It(e, ((e, n) => t[e] = n));
  2595. for (const e of n) delete t[e];
  2596. }
  2597. clone() {
  2598. return new me(zt(this.value));
  2599. }
  2600. }
  2601. /**
  2602. * @license
  2603. * Copyright 2017 Google LLC
  2604. *
  2605. * Licensed under the Apache License, Version 2.0 (the "License");
  2606. * you may not use this file except in compliance with the License.
  2607. * You may obtain a copy of the License at
  2608. *
  2609. * http://www.apache.org/licenses/LICENSE-2.0
  2610. *
  2611. * Unless required by applicable law or agreed to in writing, software
  2612. * distributed under the License is distributed on an "AS IS" BASIS,
  2613. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2614. * See the License for the specific language governing permissions and
  2615. * limitations under the License.
  2616. */
  2617. /**
  2618. * Represents a document in Firestore with a key, version, data and whether it
  2619. * has local mutations applied to it.
  2620. *
  2621. * Documents can transition between states via `convertToFoundDocument()`,
  2622. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  2623. * not transition to one of these states even after all mutations have been
  2624. * applied, `isValidDocument()` returns false and the document should be removed
  2625. * from all views.
  2626. */ class pe {
  2627. constructor(t, e, n, r, s, i, o) {
  2628. this.key = t, this.documentType = e, this.version = n, this.readTime = r, this.createTime = s,
  2629. this.data = i, this.documentState = o;
  2630. }
  2631. /**
  2632. * Creates a document with no known version or data, but which can serve as
  2633. * base document for mutations.
  2634. */ static newInvalidDocument(t) {
  2635. return new pe(t, 0 /* DocumentType.INVALID */ ,
  2636. /* version */ ce.min(),
  2637. /* readTime */ ce.min(),
  2638. /* createTime */ ce.min(), me.empty(), 0 /* DocumentState.SYNCED */);
  2639. }
  2640. /**
  2641. * Creates a new document that is known to exist with the given data at the
  2642. * given version.
  2643. */ static newFoundDocument(t, e, n, r) {
  2644. return new pe(t, 1 /* DocumentType.FOUND_DOCUMENT */ ,
  2645. /* version */ e,
  2646. /* readTime */ ce.min(),
  2647. /* createTime */ n, r, 0 /* DocumentState.SYNCED */);
  2648. }
  2649. /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {
  2650. return new pe(t, 2 /* DocumentType.NO_DOCUMENT */ ,
  2651. /* version */ e,
  2652. /* readTime */ ce.min(),
  2653. /* createTime */ ce.min(), me.empty(), 0 /* DocumentState.SYNCED */);
  2654. }
  2655. /**
  2656. * Creates a new document that is known to exist at the given version but
  2657. * whose data is not known (e.g. a document that was updated without a known
  2658. * base document).
  2659. */ static newUnknownDocument(t, e) {
  2660. return new pe(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  2661. /* version */ e,
  2662. /* readTime */ ce.min(),
  2663. /* createTime */ ce.min(), me.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
  2664. }
  2665. /**
  2666. * Changes the document type to indicate that it exists and that its version
  2667. * and data are known.
  2668. */ convertToFoundDocument(t, e) {
  2669. // If a document is switching state from being an invalid or deleted
  2670. // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
  2671. // update from Watch or due to applying a local set mutation on top
  2672. // of a deleted document, our best guess about its createTime would be the
  2673. // version at which the document transitioned to a FOUND_DOCUMENT.
  2674. return !this.createTime.isEqual(ce.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t),
  2675. this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e,
  2676. this.documentState = 0 /* DocumentState.SYNCED */ , this;
  2677. }
  2678. /**
  2679. * Changes the document type to indicate that it doesn't exist at the given
  2680. * version.
  2681. */ convertToNoDocument(t) {
  2682. return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ ,
  2683. this.data = me.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;
  2684. }
  2685. /**
  2686. * Changes the document type to indicate that it exists at a given version but
  2687. * that its data is not known (e.g. a document that was updated without a known
  2688. * base document).
  2689. */ convertToUnknownDocument(t) {
  2690. return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  2691. this.data = me.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ ,
  2692. this;
  2693. }
  2694. setHasCommittedMutations() {
  2695. return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;
  2696. }
  2697. setHasLocalMutations() {
  2698. return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = ce.min(),
  2699. this;
  2700. }
  2701. setReadTime(t) {
  2702. return this.readTime = t, this;
  2703. }
  2704. get hasLocalMutations() {
  2705. return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;
  2706. }
  2707. get hasCommittedMutations() {
  2708. return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;
  2709. }
  2710. get hasPendingWrites() {
  2711. return this.hasLocalMutations || this.hasCommittedMutations;
  2712. }
  2713. isValidDocument() {
  2714. return 0 /* DocumentType.INVALID */ !== this.documentType;
  2715. }
  2716. isFoundDocument() {
  2717. return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;
  2718. }
  2719. isNoDocument() {
  2720. return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;
  2721. }
  2722. isUnknownDocument() {
  2723. return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;
  2724. }
  2725. isEqual(t) {
  2726. return t instanceof pe && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);
  2727. }
  2728. mutableCopy() {
  2729. return new pe(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  2730. }
  2731. toString() {
  2732. return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;
  2733. }
  2734. }
  2735. /**
  2736. * @license
  2737. * Copyright 2019 Google LLC
  2738. *
  2739. * Licensed under the Apache License, Version 2.0 (the "License");
  2740. * you may not use this file except in compliance with the License.
  2741. * You may obtain a copy of the License at
  2742. *
  2743. * http://www.apache.org/licenses/LICENSE-2.0
  2744. *
  2745. * Unless required by applicable law or agreed to in writing, software
  2746. * distributed under the License is distributed on an "AS IS" BASIS,
  2747. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2748. * See the License for the specific language governing permissions and
  2749. * limitations under the License.
  2750. */
  2751. // Visible for testing
  2752. class ye {
  2753. constructor(t, e = null, n = [], r = [], s = null, i = null, o = null) {
  2754. this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = r, this.limit = s,
  2755. this.startAt = i, this.endAt = o, this.S = null;
  2756. }
  2757. }
  2758. /**
  2759. * Initializes a Target with a path and optional additional query constraints.
  2760. * Path must currently be empty if this is a collection group query.
  2761. *
  2762. * NOTE: you should always construct `Target` from `Query.toTarget` instead of
  2763. * using this factory method, because `Query` provides an implicit `orderBy`
  2764. * property.
  2765. */ function ge(t, e = null, n = [], r = [], s = null, i = null, o = null) {
  2766. return new ye(t, e, n, r, s, i, o);
  2767. }
  2768. /**
  2769. * @license
  2770. * Copyright 2017 Google LLC
  2771. *
  2772. * Licensed under the Apache License, Version 2.0 (the "License");
  2773. * you may not use this file except in compliance with the License.
  2774. * You may obtain a copy of the License at
  2775. *
  2776. * http://www.apache.org/licenses/LICENSE-2.0
  2777. *
  2778. * Unless required by applicable law or agreed to in writing, software
  2779. * distributed under the License is distributed on an "AS IS" BASIS,
  2780. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2781. * See the License for the specific language governing permissions and
  2782. * limitations under the License.
  2783. */
  2784. /**
  2785. * Query encapsulates all the query attributes we support in the SDK. It can
  2786. * be run against the LocalStore, as well as be converted to a `Target` to
  2787. * query the RemoteStore results.
  2788. *
  2789. * Visible for testing.
  2790. */
  2791. class _e {
  2792. /**
  2793. * Initializes a Query with a path and optional additional query constraints.
  2794. * Path must currently be empty if this is a collection group query.
  2795. */
  2796. constructor(t, e = null, n = [], r = [], s = null, i = "F" /* LimitType.First */ , o = null, u = null) {
  2797. this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = r,
  2798. this.limit = s, this.limitType = i, this.startAt = o, this.endAt = u, this.q = null,
  2799. // The corresponding `Target` of this `Query` instance.
  2800. this.O = null, this.startAt, this.endAt;
  2801. }
  2802. }
  2803. /** Creates a new Query for a query that matches all documents at `path` */ function ve(t) {
  2804. return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;
  2805. }
  2806. function be(t) {
  2807. for (const e of t.filters) {
  2808. const t = e.getFirstInequalityField();
  2809. if (null !== t) return t;
  2810. }
  2811. return null;
  2812. }
  2813. /**
  2814. * Creates a new Query for a collection group query that matches all documents
  2815. * within the provided collection group.
  2816. */
  2817. /**
  2818. * Returns whether the query matches a collection group rather than a specific
  2819. * collection.
  2820. */
  2821. function Ee(t) {
  2822. return null !== t.collectionGroup;
  2823. }
  2824. /**
  2825. * Returns the implicit order by constraint that is used to execute the Query,
  2826. * which can be different from the order by constraints the user provided (e.g.
  2827. * the SDK and backend always orders by `__name__`).
  2828. */ function Ie(t) {
  2829. const e = A(t);
  2830. if (null === e.q) {
  2831. e.q = [];
  2832. const t = be(e), n = ve(e);
  2833. if (null !== t && null === n)
  2834. // In order to implicitly add key ordering, we must also add the
  2835. // inequality filter field for it to be a valid query.
  2836. // Note that the default inequality field and key ordering is ascending.
  2837. t.isKeyField() || e.q.push(new oe(t)), e.q.push(new oe(rt.keyField(), "asc" /* Direction.ASCENDING */)); else {
  2838. let t = !1;
  2839. for (const n of e.explicitOrderBy) e.q.push(n), n.field.isKeyField() && (t = !0);
  2840. if (!t) {
  2841. // The order of the implicit key ordering always matches the last
  2842. // explicit order by
  2843. const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */;
  2844. e.q.push(new oe(rt.keyField(), t));
  2845. }
  2846. }
  2847. }
  2848. return e.q;
  2849. }
  2850. /**
  2851. * Converts this `Query` instance to it's corresponding `Target` representation.
  2852. */ function Ae(t) {
  2853. const e = A(t);
  2854. if (!e.O) if ("F" /* LimitType.First */ === e.limitType) e.O = ge(e.path, e.collectionGroup, Ie(e), e.filters, e.limit, e.startAt, e.endAt); else {
  2855. // Flip the orderBy directions since we want the last results
  2856. const t = [];
  2857. for (const n of Ie(e)) {
  2858. const e = "desc" /* Direction.DESCENDING */ === n.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */;
  2859. t.push(new oe(n.field, e));
  2860. }
  2861. // We need to swap the cursors to match the now-flipped query ordering.
  2862. const n = e.endAt ? new Wt(e.endAt.position, e.endAt.inclusive) : null, r = e.startAt ? new Wt(e.startAt.position, e.startAt.inclusive) : null;
  2863. // Now return as a LimitType.First query.
  2864. e.O = ge(e.path, e.collectionGroup, t, e.filters, e.limit, n, r);
  2865. }
  2866. return e.O;
  2867. }
  2868. function Te(t, e) {
  2869. e.getFirstInequalityField(), be(t);
  2870. const n = t.filters.concat([ e ]);
  2871. return new _e(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);
  2872. }
  2873. function Re(t, e) {
  2874. return function(t, e) {
  2875. if (t.limit !== e.limit) return !1;
  2876. if (t.orderBy.length !== e.orderBy.length) return !1;
  2877. for (let n = 0; n < t.orderBy.length; n++) if (!ue(t.orderBy[n], e.orderBy[n])) return !1;
  2878. if (t.filters.length !== e.filters.length) return !1;
  2879. for (let n = 0; n < t.filters.length; n++) if (!Jt(t.filters[n], e.filters[n])) return !1;
  2880. return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!Gt(t.startAt, e.startAt) && Gt(t.endAt, e.endAt);
  2881. }(Ae(t), Ae(e)) && t.limitType === e.limitType;
  2882. }
  2883. /**
  2884. * @license
  2885. * Copyright 2020 Google LLC
  2886. *
  2887. * Licensed under the Apache License, Version 2.0 (the "License");
  2888. * you may not use this file except in compliance with the License.
  2889. * You may obtain a copy of the License at
  2890. *
  2891. * http://www.apache.org/licenses/LICENSE-2.0
  2892. *
  2893. * Unless required by applicable law or agreed to in writing, software
  2894. * distributed under the License is distributed on an "AS IS" BASIS,
  2895. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2896. * See the License for the specific language governing permissions and
  2897. * limitations under the License.
  2898. */
  2899. /**
  2900. * Returns an DoubleValue for `value` that is encoded based the serializer's
  2901. * `useProto3Json` setting.
  2902. */
  2903. /**
  2904. * Returns a value for a number that's appropriate to put into a proto.
  2905. * The return value is an IntegerValue if it can safely represent the value,
  2906. * otherwise a DoubleValue is returned.
  2907. */
  2908. function Pe(t, e) {
  2909. return function(t) {
  2910. return "number" == typeof t && Number.isInteger(t) && !ft(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;
  2911. }(e) ?
  2912. /**
  2913. * Returns an IntegerValue for `value`.
  2914. */
  2915. function(t) {
  2916. return {
  2917. integerValue: "" + t
  2918. };
  2919. }(e) : function(t, e) {
  2920. if (t.k) {
  2921. if (isNaN(e)) return {
  2922. doubleValue: "NaN"
  2923. };
  2924. if (e === 1 / 0) return {
  2925. doubleValue: "Infinity"
  2926. };
  2927. if (e === -1 / 0) return {
  2928. doubleValue: "-Infinity"
  2929. };
  2930. }
  2931. return {
  2932. doubleValue: ft(e) ? "-0" : e
  2933. };
  2934. }(t, e);
  2935. }
  2936. /**
  2937. * @license
  2938. * Copyright 2018 Google LLC
  2939. *
  2940. * Licensed under the Apache License, Version 2.0 (the "License");
  2941. * you may not use this file except in compliance with the License.
  2942. * You may obtain a copy of the License at
  2943. *
  2944. * http://www.apache.org/licenses/LICENSE-2.0
  2945. *
  2946. * Unless required by applicable law or agreed to in writing, software
  2947. * distributed under the License is distributed on an "AS IS" BASIS,
  2948. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2949. * See the License for the specific language governing permissions and
  2950. * limitations under the License.
  2951. */
  2952. /** Used to represent a field transform on a mutation. */ class Ve {
  2953. constructor() {
  2954. // Make sure that the structural type of `TransformOperation` is unique.
  2955. // See https://github.com/microsoft/TypeScript/issues/5451
  2956. this._ = void 0;
  2957. }
  2958. }
  2959. /** Transforms a value into a server-generated timestamp. */ class $e extends Ve {}
  2960. /** Transforms an array value via a union operation. */ class Ne extends Ve {
  2961. constructor(t) {
  2962. super(), this.elements = t;
  2963. }
  2964. }
  2965. /** Transforms an array value via a remove operation. */ class De extends Ve {
  2966. constructor(t) {
  2967. super(), this.elements = t;
  2968. }
  2969. }
  2970. /**
  2971. * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
  2972. * transforms. Converts all field values to integers or doubles, but unlike the
  2973. * backend does not cap integer values at 2^63. Instead, JavaScript number
  2974. * arithmetic is used and precision loss can occur for values greater than 2^53.
  2975. */ class Fe extends Ve {
  2976. constructor(t, e) {
  2977. super(), this.C = t, this.L = e;
  2978. }
  2979. }
  2980. /**
  2981. * @license
  2982. * Copyright 2017 Google LLC
  2983. *
  2984. * Licensed under the Apache License, Version 2.0 (the "License");
  2985. * you may not use this file except in compliance with the License.
  2986. * You may obtain a copy of the License at
  2987. *
  2988. * http://www.apache.org/licenses/LICENSE-2.0
  2989. *
  2990. * Unless required by applicable law or agreed to in writing, software
  2991. * distributed under the License is distributed on an "AS IS" BASIS,
  2992. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2993. * See the License for the specific language governing permissions and
  2994. * limitations under the License.
  2995. */
  2996. /** A field path and the TransformOperation to perform upon it. */ class xe {
  2997. constructor(t, e) {
  2998. this.field = t, this.transform = e;
  2999. }
  3000. }
  3001. /**
  3002. * Encodes a precondition for a mutation. This follows the model that the
  3003. * backend accepts with the special case of an explicit "empty" precondition
  3004. * (meaning no precondition).
  3005. */ class Se {
  3006. constructor(t, e) {
  3007. this.updateTime = t, this.exists = e;
  3008. }
  3009. /** Creates a new empty Precondition. */ static none() {
  3010. return new Se;
  3011. }
  3012. /** Creates a new Precondition with an exists flag. */ static exists(t) {
  3013. return new Se(void 0, t);
  3014. }
  3015. /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) {
  3016. return new Se(t);
  3017. }
  3018. /** Returns whether this Precondition is empty. */ get isNone() {
  3019. return void 0 === this.updateTime && void 0 === this.exists;
  3020. }
  3021. isEqual(t) {
  3022. return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
  3023. }
  3024. }
  3025. /**
  3026. * A mutation describes a self-contained change to a document. Mutations can
  3027. * create, replace, delete, and update subsets of documents.
  3028. *
  3029. * Mutations not only act on the value of the document but also its version.
  3030. *
  3031. * For local mutations (mutations that haven't been committed yet), we preserve
  3032. * the existing version for Set and Patch mutations. For Delete mutations, we
  3033. * reset the version to 0.
  3034. *
  3035. * Here's the expected transition table.
  3036. *
  3037. * MUTATION APPLIED TO RESULTS IN
  3038. *
  3039. * SetMutation Document(v3) Document(v3)
  3040. * SetMutation NoDocument(v3) Document(v0)
  3041. * SetMutation InvalidDocument(v0) Document(v0)
  3042. * PatchMutation Document(v3) Document(v3)
  3043. * PatchMutation NoDocument(v3) NoDocument(v3)
  3044. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  3045. * DeleteMutation Document(v3) NoDocument(v0)
  3046. * DeleteMutation NoDocument(v3) NoDocument(v0)
  3047. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  3048. *
  3049. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  3050. * the resulting version for Set and Patch mutations. As deletes have no
  3051. * explicit update time, we use the commitTime of the WriteResponse for
  3052. * Delete mutations.
  3053. *
  3054. * If a mutation is acknowledged by the backend but fails the precondition check
  3055. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  3056. * the updated version.
  3057. *
  3058. * Field transforms are used only with Patch and Set Mutations. We use the
  3059. * `updateTransforms` message to store transforms, rather than the `transforms`s
  3060. * messages.
  3061. *
  3062. * ## Subclassing Notes
  3063. *
  3064. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  3065. * applyToLocalView() to implement the actual behavior of applying the mutation
  3066. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  3067. * example).
  3068. */ class qe {}
  3069. /**
  3070. * A mutation that creates or replaces the document at the given key with the
  3071. * object value contents.
  3072. */ class Oe extends qe {
  3073. constructor(t, e, n, r = []) {
  3074. super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = r,
  3075. this.type = 0 /* MutationType.Set */;
  3076. }
  3077. getFieldMask() {
  3078. return null;
  3079. }
  3080. }
  3081. /**
  3082. * A mutation that modifies fields of the document at the given key with the
  3083. * given values. The values are applied through a field mask:
  3084. *
  3085. * * When a field is in both the mask and the values, the corresponding field
  3086. * is updated.
  3087. * * When a field is in neither the mask nor the values, the corresponding
  3088. * field is unmodified.
  3089. * * When a field is in the mask but not in the values, the corresponding field
  3090. * is deleted.
  3091. * * When a field is not in the mask but is in the values, the values map is
  3092. * ignored.
  3093. */ class ke extends qe {
  3094. constructor(t, e, n, r, s = []) {
  3095. super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = r,
  3096. this.fieldTransforms = s, this.type = 1 /* MutationType.Patch */;
  3097. }
  3098. getFieldMask() {
  3099. return this.fieldMask;
  3100. }
  3101. }
  3102. /** A mutation that deletes the document at the given key. */ class Ce extends qe {
  3103. constructor(t, e) {
  3104. super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ ,
  3105. this.fieldTransforms = [];
  3106. }
  3107. getFieldMask() {
  3108. return null;
  3109. }
  3110. }
  3111. /**
  3112. * A mutation that verifies the existence of the document at the given key with
  3113. * the provided precondition.
  3114. *
  3115. * The `verify` operation is only used in Transactions, and this class serves
  3116. * primarily to facilitate serialization into protos.
  3117. */ class Le extends qe {
  3118. constructor(t, e) {
  3119. super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ ,
  3120. this.fieldTransforms = [];
  3121. }
  3122. getFieldMask() {
  3123. return null;
  3124. }
  3125. }
  3126. /**
  3127. * @license
  3128. * Copyright 2017 Google LLC
  3129. *
  3130. * Licensed under the Apache License, Version 2.0 (the "License");
  3131. * you may not use this file except in compliance with the License.
  3132. * You may obtain a copy of the License at
  3133. *
  3134. * http://www.apache.org/licenses/LICENSE-2.0
  3135. *
  3136. * Unless required by applicable law or agreed to in writing, software
  3137. * distributed under the License is distributed on an "AS IS" BASIS,
  3138. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3139. * See the License for the specific language governing permissions and
  3140. * limitations under the License.
  3141. */ const Me = (() => {
  3142. const t = {
  3143. asc: "ASCENDING",
  3144. desc: "DESCENDING"
  3145. };
  3146. return t;
  3147. })(), Ue = (() => {
  3148. const t = {
  3149. "<": "LESS_THAN",
  3150. "<=": "LESS_THAN_OR_EQUAL",
  3151. ">": "GREATER_THAN",
  3152. ">=": "GREATER_THAN_OR_EQUAL",
  3153. "==": "EQUAL",
  3154. "!=": "NOT_EQUAL",
  3155. "array-contains": "ARRAY_CONTAINS",
  3156. in: "IN",
  3157. "not-in": "NOT_IN",
  3158. "array-contains-any": "ARRAY_CONTAINS_ANY"
  3159. };
  3160. return t;
  3161. })(), je = (() => {
  3162. const t = {
  3163. and: "AND",
  3164. or: "OR"
  3165. };
  3166. return t;
  3167. })();
  3168. /**
  3169. * This class generates JsonObject values for the Datastore API suitable for
  3170. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  3171. *
  3172. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  3173. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  3174. * format.
  3175. *
  3176. * For a description of the Proto3 JSON format check
  3177. * https://developers.google.com/protocol-buffers/docs/proto3#json
  3178. *
  3179. * TODO(klimt): We can remove the databaseId argument if we keep the full
  3180. * resource name in documents.
  3181. */
  3182. class Be {
  3183. constructor(t, e) {
  3184. this.databaseId = t, this.k = e;
  3185. }
  3186. }
  3187. /**
  3188. * Returns a value for a number (or null) that's appropriate to put into
  3189. * a google.protobuf.Int32Value proto.
  3190. * DO NOT USE THIS FOR ANYTHING ELSE.
  3191. * This method cheats. It's typed as returning "number" because that's what
  3192. * our generated proto interfaces say Int32Value must be. But GRPC actually
  3193. * expects a { value: <number> } struct.
  3194. */
  3195. /**
  3196. * Returns a value for a Date that's appropriate to put into a proto.
  3197. */
  3198. function Qe(t, e) {
  3199. if (t.k) {
  3200. return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`;
  3201. }
  3202. return {
  3203. seconds: "" + e.seconds,
  3204. nanos: e.nanoseconds
  3205. };
  3206. }
  3207. /**
  3208. * Returns a value for bytes that's appropriate to put in a proto.
  3209. *
  3210. * Visible for testing.
  3211. */
  3212. function ze(t, e) {
  3213. return t.k ? e.toBase64() : e.toUint8Array();
  3214. }
  3215. function We(t, e) {
  3216. return Qe(t, e.toTimestamp());
  3217. }
  3218. function Ge(t) {
  3219. return I(!!t), ce.fromTimestamp(function(t) {
  3220. const e = Pt(t);
  3221. return new Nt(e.seconds, e.nanos);
  3222. }(t));
  3223. }
  3224. function Ke(t, e) {
  3225. return function(t) {
  3226. return new et([ "projects", t.projectId, "databases", t.database ]);
  3227. }(t).child("documents").child(e).canonicalString();
  3228. }
  3229. function Ye(t, e) {
  3230. return Ke(t.databaseId, e.path);
  3231. }
  3232. function He(t, e) {
  3233. const n = function(t) {
  3234. const e = et.fromString(t);
  3235. return I(hn(e)), e;
  3236. }(e);
  3237. if (n.get(1) !== t.databaseId.projectId) throw new j(V, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.databaseId.projectId);
  3238. if (n.get(3) !== t.databaseId.database) throw new j(V, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.databaseId.database);
  3239. return new st((I((r = n).length > 4 && "documents" === r.get(4)), r.popFirst(5)));
  3240. var r;
  3241. /** Creates a Document proto from key and fields (but no create/update time) */}
  3242. function Je(t, e) {
  3243. return Ke(t.databaseId, e);
  3244. }
  3245. function Xe(t) {
  3246. return new et([ "projects", t.databaseId.projectId, "databases", t.databaseId.database ]).canonicalString();
  3247. }
  3248. function Ze(t, e, n) {
  3249. return {
  3250. name: Ye(t, e),
  3251. fields: n.value.mapValue.fields
  3252. };
  3253. }
  3254. function tn(t, e) {
  3255. return "found" in e ? function(t, e) {
  3256. I(!!e.found), e.found.name, e.found.updateTime;
  3257. const n = He(t, e.found.name), r = Ge(e.found.updateTime), s = e.found.createTime ? Ge(e.found.createTime) : ce.min(), i = new me({
  3258. mapValue: {
  3259. fields: e.found.fields
  3260. }
  3261. });
  3262. return pe.newFoundDocument(n, r, s, i);
  3263. }(t, e) : "missing" in e ? function(t, e) {
  3264. I(!!e.missing), I(!!e.readTime);
  3265. const n = He(t, e.missing), r = Ge(e.readTime);
  3266. return pe.newNoDocument(n, r);
  3267. }(t, e) : E();
  3268. }
  3269. function en(t, e) {
  3270. let n;
  3271. if (e instanceof Oe) n = {
  3272. update: Ze(t, e.key, e.value)
  3273. }; else if (e instanceof Ce) n = {
  3274. delete: Ye(t, e.key)
  3275. }; else if (e instanceof ke) n = {
  3276. update: Ze(t, e.key, e.data),
  3277. updateMask: an(e.fieldMask)
  3278. }; else {
  3279. if (!(e instanceof Le)) return E();
  3280. n = {
  3281. verify: Ye(t, e.key)
  3282. };
  3283. }
  3284. return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {
  3285. const n = e.transform;
  3286. if (n instanceof $e) return {
  3287. fieldPath: e.field.canonicalString(),
  3288. setToServerValue: "REQUEST_TIME"
  3289. };
  3290. if (n instanceof Ne) return {
  3291. fieldPath: e.field.canonicalString(),
  3292. appendMissingElements: {
  3293. values: n.elements
  3294. }
  3295. };
  3296. if (n instanceof De) return {
  3297. fieldPath: e.field.canonicalString(),
  3298. removeAllFromArray: {
  3299. values: n.elements
  3300. }
  3301. };
  3302. if (n instanceof Fe) return {
  3303. fieldPath: e.field.canonicalString(),
  3304. increment: n.L
  3305. };
  3306. throw E();
  3307. }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) {
  3308. return void 0 !== e.updateTime ? {
  3309. updateTime: We(t, e.updateTime)
  3310. } : void 0 !== e.exists ? {
  3311. exists: e.exists
  3312. } : E();
  3313. }(t, e.precondition)), n;
  3314. }
  3315. function nn(t, e) {
  3316. // Dissect the path into parent, collectionId, and optional key filter.
  3317. const n = {
  3318. structuredQuery: {}
  3319. }, r = e.path;
  3320. null !== e.collectionGroup ? (n.parent = Je(t, r), n.structuredQuery.from = [ {
  3321. collectionId: e.collectionGroup,
  3322. allDescendants: !0
  3323. } ]) : (n.parent = Je(t, r.popLast()), n.structuredQuery.from = [ {
  3324. collectionId: r.lastSegment()
  3325. } ]);
  3326. const s = function(t) {
  3327. if (0 === t.length) return;
  3328. return cn(Ht.create(t, "and" /* CompositeOperator.AND */));
  3329. }(e.filters);
  3330. s && (n.structuredQuery.where = s);
  3331. const i = function(t) {
  3332. if (0 === t.length) return;
  3333. return t.map((t =>
  3334. // visible for testing
  3335. function(t) {
  3336. return {
  3337. field: un(t.field),
  3338. direction: rn(t.dir)
  3339. };
  3340. }
  3341. // visible for testing
  3342. (t)));
  3343. }(e.orderBy);
  3344. i && (n.structuredQuery.orderBy = i);
  3345. const o = function(t, e) {
  3346. return t.k || lt(e) ? e : {
  3347. value: e
  3348. };
  3349. }(t, e.limit);
  3350. var u;
  3351. return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = {
  3352. before: (u = e.startAt).inclusive,
  3353. values: u.position
  3354. }), e.endAt && (n.structuredQuery.endAt = function(t) {
  3355. return {
  3356. before: !t.inclusive,
  3357. values: t.position
  3358. };
  3359. }
  3360. // visible for testing
  3361. (e.endAt)), n;
  3362. }
  3363. function rn(t) {
  3364. return Me[t];
  3365. }
  3366. // visible for testing
  3367. function sn(t) {
  3368. return Ue[t];
  3369. }
  3370. function on(t) {
  3371. return je[t];
  3372. }
  3373. function un(t) {
  3374. return {
  3375. fieldPath: t.canonicalString()
  3376. };
  3377. }
  3378. function cn(t) {
  3379. return t instanceof Yt ? function(t) {
  3380. if ("==" /* Operator.EQUAL */ === t.op) {
  3381. if (Bt(t.value)) return {
  3382. unaryFilter: {
  3383. field: un(t.field),
  3384. op: "IS_NAN"
  3385. }
  3386. };
  3387. if (jt(t.value)) return {
  3388. unaryFilter: {
  3389. field: un(t.field),
  3390. op: "IS_NULL"
  3391. }
  3392. };
  3393. } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) {
  3394. if (Bt(t.value)) return {
  3395. unaryFilter: {
  3396. field: un(t.field),
  3397. op: "IS_NOT_NAN"
  3398. }
  3399. };
  3400. if (jt(t.value)) return {
  3401. unaryFilter: {
  3402. field: un(t.field),
  3403. op: "IS_NOT_NULL"
  3404. }
  3405. };
  3406. }
  3407. return {
  3408. fieldFilter: {
  3409. field: un(t.field),
  3410. op: sn(t.op),
  3411. value: t.value
  3412. }
  3413. };
  3414. }(t) : t instanceof Ht ? function(t) {
  3415. const e = t.getFilters().map((t => cn(t)));
  3416. if (1 === e.length) return e[0];
  3417. return {
  3418. compositeFilter: {
  3419. op: on(t.op),
  3420. filters: e
  3421. }
  3422. };
  3423. }(t) : E();
  3424. }
  3425. function an(t) {
  3426. const e = [];
  3427. return t.fields.forEach((t => e.push(t.canonicalString()))), {
  3428. fieldPaths: e
  3429. };
  3430. }
  3431. function hn(t) {
  3432. // Resource names have at least 4 components (project ID, database ID)
  3433. return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2);
  3434. }
  3435. /**
  3436. * @license
  3437. * Copyright 2020 Google LLC
  3438. *
  3439. * Licensed under the Apache License, Version 2.0 (the "License");
  3440. * you may not use this file except in compliance with the License.
  3441. * You may obtain a copy of the License at
  3442. *
  3443. * http://www.apache.org/licenses/LICENSE-2.0
  3444. *
  3445. * Unless required by applicable law or agreed to in writing, software
  3446. * distributed under the License is distributed on an "AS IS" BASIS,
  3447. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3448. * See the License for the specific language governing permissions and
  3449. * limitations under the License.
  3450. */ function ln(t) {
  3451. return new Be(t, /* useProto3Json= */ !0);
  3452. }
  3453. /**
  3454. * @license
  3455. * Copyright 2017 Google LLC
  3456. *
  3457. * Licensed under the Apache License, Version 2.0 (the "License");
  3458. * you may not use this file except in compliance with the License.
  3459. * You may obtain a copy of the License at
  3460. *
  3461. * http://www.apache.org/licenses/LICENSE-2.0
  3462. *
  3463. * Unless required by applicable law or agreed to in writing, software
  3464. * distributed under the License is distributed on an "AS IS" BASIS,
  3465. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3466. * See the License for the specific language governing permissions and
  3467. * limitations under the License.
  3468. */
  3469. /**
  3470. * A helper for running delayed tasks following an exponential backoff curve
  3471. * between attempts.
  3472. *
  3473. * Each delay is made up of a "base" delay which follows the exponential
  3474. * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
  3475. * base delay. This prevents clients from accidentally synchronizing their
  3476. * delays causing spikes of load to the backend.
  3477. */
  3478. class fn {
  3479. constructor(
  3480. /**
  3481. * The AsyncQueue to run backoff operations on.
  3482. */
  3483. t,
  3484. /**
  3485. * The ID to use when scheduling backoff operations on the AsyncQueue.
  3486. */
  3487. e,
  3488. /**
  3489. * The initial delay (used as the base delay on the first retry attempt).
  3490. * Note that jitter will still be applied, so the actual delay could be as
  3491. * little as 0.5*initialDelayMs.
  3492. */
  3493. n = 1e3
  3494. /**
  3495. * The multiplier to use to determine the extended base delay after each
  3496. * attempt.
  3497. */ , r = 1.5
  3498. /**
  3499. * The maximum base delay after which no further backoff is performed.
  3500. * Note that jitter will still be applied, so the actual delay could be as
  3501. * much as 1.5*maxDelayMs.
  3502. */ , s = 6e4) {
  3503. this.M = t, this.timerId = e, this.U = n, this.j = r, this.B = s, this.W = 0, this.G = null,
  3504. /** The last backoff attempt, as epoch milliseconds. */
  3505. this.K = Date.now(), this.reset();
  3506. }
  3507. /**
  3508. * Resets the backoff delay.
  3509. *
  3510. * The very next backoffAndWait() will have no delay. If it is called again
  3511. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  3512. * subsequent ones will increase according to the backoffFactor.
  3513. */ reset() {
  3514. this.W = 0;
  3515. }
  3516. /**
  3517. * Resets the backoff delay to the maximum delay (e.g. for use after a
  3518. * RESOURCE_EXHAUSTED error).
  3519. */ Y() {
  3520. this.W = this.B;
  3521. }
  3522. /**
  3523. * Returns a promise that resolves after currentDelayMs, and increases the
  3524. * delay for any subsequent attempts. If there was a pending backoff operation
  3525. * already, it will be canceled.
  3526. */ H(t) {
  3527. // Cancel any pending backoff operation.
  3528. this.cancel();
  3529. // First schedule using the current base (which may be 0 and should be
  3530. // honored as such).
  3531. const e = Math.floor(this.W + this.J()), n = Math.max(0, Date.now() - this.K), r = Math.max(0, e - n);
  3532. // Guard against lastAttemptTime being in the future due to a clock change.
  3533. r > 0 && g("ExponentialBackoff", `Backing off for ${r} ms (base delay: ${this.W} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`),
  3534. this.G = this.M.enqueueAfterDelay(this.timerId, r, (() => (this.K = Date.now(),
  3535. t()))),
  3536. // Apply backoff factor to determine next delay and ensure it is within
  3537. // bounds.
  3538. this.W *= this.j, this.W < this.U && (this.W = this.U), this.W > this.B && (this.W = this.B);
  3539. }
  3540. X() {
  3541. null !== this.G && (this.G.skipDelay(), this.G = null);
  3542. }
  3543. cancel() {
  3544. null !== this.G && (this.G.cancel(), this.G = null);
  3545. }
  3546. /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ J() {
  3547. return (Math.random() - .5) * this.W;
  3548. }
  3549. }
  3550. /**
  3551. * @license
  3552. * Copyright 2017 Google LLC
  3553. *
  3554. * Licensed under the Apache License, Version 2.0 (the "License");
  3555. * you may not use this file except in compliance with the License.
  3556. * You may obtain a copy of the License at
  3557. *
  3558. * http://www.apache.org/licenses/LICENSE-2.0
  3559. *
  3560. * Unless required by applicable law or agreed to in writing, software
  3561. * distributed under the License is distributed on an "AS IS" BASIS,
  3562. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3563. * See the License for the specific language governing permissions and
  3564. * limitations under the License.
  3565. */
  3566. /**
  3567. * Datastore and its related methods are a wrapper around the external Google
  3568. * Cloud Datastore grpc API, which provides an interface that is more convenient
  3569. * for the rest of the client SDK architecture to consume.
  3570. */
  3571. /**
  3572. * An implementation of Datastore that exposes additional state for internal
  3573. * consumption.
  3574. */
  3575. class dn extends class {} {
  3576. constructor(t, e, n, r) {
  3577. super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = n,
  3578. this.C = r, this.Z = !1;
  3579. }
  3580. tt() {
  3581. if (this.Z) throw new j(q, "The client has already been terminated.");
  3582. }
  3583. /** Invokes the provided RPC with auth and AppCheck tokens. */ I(t, e, n) {
  3584. return this.tt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([r, s]) => this.connection.I(t, e, n, r, s))).catch((t => {
  3585. throw "FirebaseError" === t.name ? (t.code === x && (this.authCredentials.invalidateToken(),
  3586. this.appCheckCredentials.invalidateToken()), t) : new j(P, t.toString());
  3587. }));
  3588. }
  3589. /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ P(t, e, n, r) {
  3590. return this.tt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.connection.P(t, e, n, s, i, r))).catch((t => {
  3591. throw "FirebaseError" === t.name ? (t.code === x && (this.authCredentials.invalidateToken(),
  3592. this.appCheckCredentials.invalidateToken()), t) : new j(P, t.toString());
  3593. }));
  3594. }
  3595. terminate() {
  3596. this.Z = !0;
  3597. }
  3598. }
  3599. // TODO(firestorexp): Make sure there is only one Datastore instance per
  3600. // firestore-exp client.
  3601. async function wn(t, e) {
  3602. const n = A(t), r = Xe(n.C) + "/documents", s = {
  3603. writes: e.map((t => en(n.C, t)))
  3604. };
  3605. await n.I("Commit", r, s);
  3606. }
  3607. async function mn(t, e) {
  3608. const n = A(t), r = Xe(n.C) + "/documents", s = {
  3609. documents: e.map((t => Ye(n.C, t)))
  3610. }, i = await n.P("BatchGetDocuments", r, s, e.length), o = new Map;
  3611. i.forEach((t => {
  3612. const e = tn(n.C, t);
  3613. o.set(e.key.toString(), e);
  3614. }));
  3615. const u = [];
  3616. return e.forEach((t => {
  3617. const e = o.get(t.toString());
  3618. I(!!e), u.push(e);
  3619. })), u;
  3620. }
  3621. async function pn(t, e) {
  3622. const n = A(t), r = nn(n.C, Ae(e));
  3623. return (await n.P("RunQuery", r.parent, {
  3624. structuredQuery: r.structuredQuery
  3625. })).filter((t => !!t.document)).map((t => function(t, e, n) {
  3626. const r = He(t, e.name), s = Ge(e.updateTime), i = e.createTime ? Ge(e.createTime) : ce.min(), o = new me({
  3627. mapValue: {
  3628. fields: e.fields
  3629. }
  3630. }), u = pe.newFoundDocument(r, s, i, o);
  3631. return n && u.setHasCommittedMutations(), n ? u.setHasCommittedMutations() : u;
  3632. }(n.C, t.document, void 0)));
  3633. }
  3634. async function yn(t, e) {
  3635. const n = A(t), r = function(t, e) {
  3636. const n = nn(t, e);
  3637. return {
  3638. structuredAggregationQuery: {
  3639. aggregations: [ {
  3640. count: {},
  3641. alias: "count_alias"
  3642. } ],
  3643. structuredQuery: n.structuredQuery
  3644. },
  3645. parent: n.parent
  3646. };
  3647. }(n.C, Ae(e)), s = r.parent;
  3648. n.connection.v || delete r.parent;
  3649. return (await n.P("RunAggregationQuery", s, r, /*expectedResponseCount=*/ 1)).filter((t => !!t.result)).map((t => t.result.aggregateFields));
  3650. }
  3651. /**
  3652. * @license
  3653. * Copyright 2020 Google LLC
  3654. *
  3655. * Licensed under the Apache License, Version 2.0 (the "License");
  3656. * you may not use this file except in compliance with the License.
  3657. * You may obtain a copy of the License at
  3658. *
  3659. * http://www.apache.org/licenses/LICENSE-2.0
  3660. *
  3661. * Unless required by applicable law or agreed to in writing, software
  3662. * distributed under the License is distributed on an "AS IS" BASIS,
  3663. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3664. * See the License for the specific language governing permissions and
  3665. * limitations under the License.
  3666. */ const gn = new Map;
  3667. /**
  3668. * An instance map that ensures only one Datastore exists per Firestore
  3669. * instance.
  3670. */
  3671. /**
  3672. * Returns an initialized and started Datastore for the given Firestore
  3673. * instance. Callers must invoke removeComponents() when the Firestore
  3674. * instance is terminated.
  3675. */
  3676. function _n(t) {
  3677. if (t._terminated) throw new j(q, "The client has already been terminated.");
  3678. if (!gn.has(t)) {
  3679. g("ComponentProvider", "Initializing Datastore");
  3680. const i = function(t) {
  3681. return new yt(t, fetch.bind(null));
  3682. }((e = t._databaseId, n = t.app.options.appId || "", r = t._persistenceKey, s = t._freezeSettings(),
  3683. new X(e, n, r, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, s.useFetchStreams))), o = ln(t._databaseId), u = function(t, e, n, r) {
  3684. return new dn(t, e, n, r);
  3685. }(t._authCredentials, t._appCheckCredentials, i, o);
  3686. gn.set(t, u);
  3687. }
  3688. var e, n, r, s;
  3689. /**
  3690. * @license
  3691. * Copyright 2018 Google LLC
  3692. *
  3693. * Licensed under the Apache License, Version 2.0 (the "License");
  3694. * you may not use this file except in compliance with the License.
  3695. * You may obtain a copy of the License at
  3696. *
  3697. * http://www.apache.org/licenses/LICENSE-2.0
  3698. *
  3699. * Unless required by applicable law or agreed to in writing, software
  3700. * distributed under the License is distributed on an "AS IS" BASIS,
  3701. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3702. * See the License for the specific language governing permissions and
  3703. * limitations under the License.
  3704. */ return gn.get(t);
  3705. }
  3706. /**
  3707. * Removes all components associated with the provided instance. Must be called
  3708. * when the `Firestore` instance is terminated.
  3709. */
  3710. /**
  3711. * A concrete type describing all the values that can be applied via a
  3712. * user-supplied `FirestoreSettings` object. This is a separate type so that
  3713. * defaults can be supplied and the value can be checked for equality.
  3714. */
  3715. class vn {
  3716. constructor(t) {
  3717. var e;
  3718. if (void 0 === t.host) {
  3719. if (void 0 !== t.ssl) throw new j(V, "Can't provide ssl option if host option is not set");
  3720. this.host = "firestore.googleapis.com", this.ssl = true;
  3721. } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;
  3722. if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties,
  3723. void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {
  3724. if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new j(V, "cacheSizeBytes must be at least 1048576");
  3725. this.cacheSizeBytes = t.cacheSizeBytes;
  3726. }
  3727. this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling,
  3728. this.useFetchStreams = !!t.useFetchStreams, function(t, e, n, r) {
  3729. if (!0 === e && !0 === r) throw new j(V, `${t} and ${n} cannot be used together.`);
  3730. }("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling);
  3731. }
  3732. isEqual(t) {
  3733. 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 && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;
  3734. }
  3735. }
  3736. /**
  3737. * @license
  3738. * Copyright 2020 Google LLC
  3739. *
  3740. * Licensed under the Apache License, Version 2.0 (the "License");
  3741. * you may not use this file except in compliance with the License.
  3742. * You may obtain a copy of the License at
  3743. *
  3744. * http://www.apache.org/licenses/LICENSE-2.0
  3745. *
  3746. * Unless required by applicable law or agreed to in writing, software
  3747. * distributed under the License is distributed on an "AS IS" BASIS,
  3748. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3749. * See the License for the specific language governing permissions and
  3750. * limitations under the License.
  3751. */
  3752. /**
  3753. * The Cloud Firestore service interface.
  3754. *
  3755. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  3756. */ class bn {
  3757. /** @hideconstructor */
  3758. constructor(t, e, n, r) {
  3759. this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n,
  3760. this._app = r,
  3761. /**
  3762. * Whether it's a Firestore or Firestore Lite instance.
  3763. */
  3764. this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new vn({}),
  3765. this._settingsFrozen = !1;
  3766. }
  3767. /**
  3768. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  3769. * instance.
  3770. */ get app() {
  3771. if (!this._app) throw new j(q, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
  3772. return this._app;
  3773. }
  3774. get _initialized() {
  3775. return this._settingsFrozen;
  3776. }
  3777. get _terminated() {
  3778. return void 0 !== this._terminateTask;
  3779. }
  3780. _setSettings(t) {
  3781. if (this._settingsFrozen) throw new j(q, "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.");
  3782. this._settings = new vn(t), void 0 !== t.credentials && (this._authCredentials = function(t) {
  3783. if (!t) return new z;
  3784. switch (t.type) {
  3785. case "gapi":
  3786. const e = t.client;
  3787. return new Y(e, t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null);
  3788. case "provider":
  3789. return t.client;
  3790. default:
  3791. throw new j(V, "makeAuthCredentialsProvider failed due to invalid credential type");
  3792. }
  3793. }(t.credentials));
  3794. }
  3795. _getSettings() {
  3796. return this._settings;
  3797. }
  3798. _freezeSettings() {
  3799. return this._settingsFrozen = !0, this._settings;
  3800. }
  3801. _delete() {
  3802. return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;
  3803. }
  3804. /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {
  3805. return {
  3806. app: this._app,
  3807. databaseId: this._databaseId,
  3808. settings: this._settings
  3809. };
  3810. }
  3811. /**
  3812. * Terminates all components used by this client. Subclasses can override
  3813. * this method to clean up their own dependencies, but must also call this
  3814. * method.
  3815. *
  3816. * Only ever called once.
  3817. */ _terminate() {
  3818. return function(t) {
  3819. const e = gn.get(t);
  3820. e && (g("ComponentProvider", "Removing Datastore"), gn.delete(t), e.terminate());
  3821. }(this), Promise.resolve();
  3822. }
  3823. }
  3824. function En(t, e, n) {
  3825. n || (n = "(default)");
  3826. const r = _getProvider(t, "firestore/lite");
  3827. if (r.isInitialized(n)) throw new j(q, "Firestore can only be initialized once per app.");
  3828. return r.initialize({
  3829. options: e,
  3830. instanceIdentifier: n
  3831. });
  3832. }
  3833. function In(e, n) {
  3834. const r = "object" == typeof e ? e : t(), s = "string" == typeof e ? e : n || "(default)", i = _getProvider(r, "firestore/lite").getImmediate({
  3835. identifier: s
  3836. });
  3837. if (!i._initialized) {
  3838. const t = h("firestore");
  3839. t && An(i, ...t);
  3840. }
  3841. return i;
  3842. }
  3843. /**
  3844. * Modify this instance to communicate with the Cloud Firestore emulator.
  3845. *
  3846. * Note: This must be called before this instance has been used to do any
  3847. * operations.
  3848. *
  3849. * @param firestore - The `Firestore` instance to configure to connect to the
  3850. * emulator.
  3851. * @param host - the emulator host (ex: localhost).
  3852. * @param port - the emulator port (ex: 9000).
  3853. * @param options.mockUserToken - the mock auth token to use for unit testing
  3854. * Security Rules.
  3855. */ function An(t, e, n, r = {}) {
  3856. var s;
  3857. const i = (t = at(t, bn))._getSettings();
  3858. if ("firestore.googleapis.com" !== i.host && i.host !== e && v("Host has been set in both settings() and useEmulator(), emulator host will be used"),
  3859. t._setSettings(Object.assign(Object.assign({}, i), {
  3860. host: `${e}:${n}`,
  3861. ssl: !1
  3862. })), r.mockUserToken) {
  3863. let e, n;
  3864. if ("string" == typeof r.mockUserToken) e = r.mockUserToken, n = w.MOCK_USER; else {
  3865. // Let createMockUserToken validate first (catches common mistakes like
  3866. // invalid field "uid" and missing field "sub" / "user_id".)
  3867. e = l(r.mockUserToken, null === (s = t._app) || void 0 === s ? void 0 : s.options.projectId);
  3868. const i = r.mockUserToken.sub || r.mockUserToken.user_id;
  3869. if (!i) throw new j(V, "mockUserToken must contain 'sub' or 'user_id' field!");
  3870. n = new w(i);
  3871. }
  3872. t._authCredentials = new W(new Q(e, n));
  3873. }
  3874. }
  3875. /**
  3876. * Terminates the provided `Firestore` instance.
  3877. *
  3878. * After calling `terminate()` only the `clearIndexedDbPersistence()` functions
  3879. * may be used. Any other function will throw a `FirestoreError`. Termination
  3880. * does not cancel any pending writes, and any promises that are awaiting a
  3881. * response from the server will not be resolved.
  3882. *
  3883. * To restart after termination, create a new instance of `Firestore` with
  3884. * {@link (getFirestore:1)}.
  3885. *
  3886. * Note: Under normal circumstances, calling `terminate()` is not required. This
  3887. * function is useful only when you want to force this instance to release all of
  3888. * its resources or in combination with {@link clearIndexedDbPersistence} to
  3889. * ensure that all local state is destroyed between test runs.
  3890. *
  3891. * @param firestore - The `Firestore` instance to terminate.
  3892. * @returns A `Promise` that is resolved when the instance has been successfully
  3893. * terminated.
  3894. */ function Tn(t) {
  3895. return t = at(t, bn), e(t.app, "firestore/lite"), t._delete();
  3896. }
  3897. /**
  3898. * @license
  3899. * Copyright 2020 Google LLC
  3900. *
  3901. * Licensed under the Apache License, Version 2.0 (the "License");
  3902. * you may not use this file except in compliance with the License.
  3903. * You may obtain a copy of the License at
  3904. *
  3905. * http://www.apache.org/licenses/LICENSE-2.0
  3906. *
  3907. * Unless required by applicable law or agreed to in writing, software
  3908. * distributed under the License is distributed on an "AS IS" BASIS,
  3909. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3910. * See the License for the specific language governing permissions and
  3911. * limitations under the License.
  3912. */
  3913. /**
  3914. * @license
  3915. * Copyright 2022 Google LLC
  3916. *
  3917. * Licensed under the Apache License, Version 2.0 (the "License");
  3918. * you may not use this file except in compliance with the License.
  3919. * You may obtain a copy of the License at
  3920. *
  3921. * http://www.apache.org/licenses/LICENSE-2.0
  3922. *
  3923. * Unless required by applicable law or agreed to in writing, software
  3924. * distributed under the License is distributed on an "AS IS" BASIS,
  3925. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3926. * See the License for the specific language governing permissions and
  3927. * limitations under the License.
  3928. */
  3929. /**
  3930. * Represents an aggregation that can be performed by Firestore.
  3931. */
  3932. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  3933. class Rn {
  3934. constructor() {
  3935. /** A type string to uniquely identify instances of this class. */
  3936. this.type = "AggregateField";
  3937. }
  3938. }
  3939. /**
  3940. * The results of executing an aggregation query.
  3941. */ class Pn {
  3942. /** @hideconstructor */
  3943. constructor(t, e) {
  3944. this._data = e,
  3945. /** A type string to uniquely identify instances of this class. */
  3946. this.type = "AggregateQuerySnapshot", this.query = t;
  3947. }
  3948. /**
  3949. * Returns the results of the aggregations performed over the underlying
  3950. * query.
  3951. *
  3952. * The keys of the returned object will be the same as those of the
  3953. * `AggregateSpec` object specified to the aggregation method, and the values
  3954. * will be the corresponding aggregation result.
  3955. *
  3956. * @returns The results of the aggregations performed over the underlying
  3957. * query.
  3958. */ data() {
  3959. return this._data;
  3960. }
  3961. }
  3962. /**
  3963. * @license
  3964. * Copyright 2022 Google LLC
  3965. *
  3966. * Licensed under the Apache License, Version 2.0 (the "License");
  3967. * you may not use this file except in compliance with the License.
  3968. * You may obtain a copy of the License at
  3969. *
  3970. * http://www.apache.org/licenses/LICENSE-2.0
  3971. *
  3972. * Unless required by applicable law or agreed to in writing, software
  3973. * distributed under the License is distributed on an "AS IS" BASIS,
  3974. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3975. * See the License for the specific language governing permissions and
  3976. * limitations under the License.
  3977. */
  3978. /**
  3979. * CountQueryRunner encapsulates the logic needed to run the count aggregation
  3980. * queries.
  3981. */ class Vn {
  3982. constructor(t, e, n) {
  3983. this.query = t, this.datastore = e, this.userDataWriter = n;
  3984. }
  3985. run() {
  3986. return yn(this.datastore, this.query._query).then((t => {
  3987. I(void 0 !== t[0]);
  3988. const e = Object.entries(t[0]).filter((([t, e]) => "count_alias" === t)).map((([t, e]) => this.userDataWriter.convertValue(e)))[0];
  3989. return I("number" == typeof e), Promise.resolve(new Pn(this.query, {
  3990. count: e
  3991. }));
  3992. }));
  3993. }
  3994. }
  3995. /**
  3996. * @license
  3997. * Copyright 2020 Google LLC
  3998. *
  3999. * Licensed under the Apache License, Version 2.0 (the "License");
  4000. * you may not use this file except in compliance with the License.
  4001. * You may obtain a copy of the License at
  4002. *
  4003. * http://www.apache.org/licenses/LICENSE-2.0
  4004. *
  4005. * Unless required by applicable law or agreed to in writing, software
  4006. * distributed under the License is distributed on an "AS IS" BASIS,
  4007. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4008. * See the License for the specific language governing permissions and
  4009. * limitations under the License.
  4010. */
  4011. /**
  4012. * A `DocumentReference` refers to a document location in a Firestore database
  4013. * and can be used to write, read, or listen to the location. The document at
  4014. * the referenced location may or may not exist.
  4015. */ class $n {
  4016. /** @hideconstructor */
  4017. constructor(t,
  4018. /**
  4019. * If provided, the `FirestoreDataConverter` associated with this instance.
  4020. */
  4021. e, n) {
  4022. this.converter = e, this._key = n,
  4023. /** The type of this Firestore reference. */
  4024. this.type = "document", this.firestore = t;
  4025. }
  4026. get _path() {
  4027. return this._key.path;
  4028. }
  4029. /**
  4030. * The document's identifier within its collection.
  4031. */ get id() {
  4032. return this._key.path.lastSegment();
  4033. }
  4034. /**
  4035. * A string representing the path of the referenced document (relative
  4036. * to the root of the database).
  4037. */ get path() {
  4038. return this._key.path.canonicalString();
  4039. }
  4040. /**
  4041. * The collection this `DocumentReference` belongs to.
  4042. */ get parent() {
  4043. return new Dn(this.firestore, this.converter, this._key.path.popLast());
  4044. }
  4045. withConverter(t) {
  4046. return new $n(this.firestore, t, this._key);
  4047. }
  4048. }
  4049. /**
  4050. * A `Query` refers to a query which you can read or listen to. You can also
  4051. * construct refined `Query` objects by adding filters and ordering.
  4052. */ class Nn {
  4053. // This is the lite version of the Query class in the main SDK.
  4054. /** @hideconstructor protected */
  4055. constructor(t,
  4056. /**
  4057. * If provided, the `FirestoreDataConverter` associated with this instance.
  4058. */
  4059. e, n) {
  4060. this.converter = e, this._query = n,
  4061. /** The type of this Firestore reference. */
  4062. this.type = "query", this.firestore = t;
  4063. }
  4064. withConverter(t) {
  4065. return new Nn(this.firestore, t, this._query);
  4066. }
  4067. }
  4068. /**
  4069. * A `CollectionReference` object can be used for adding documents, getting
  4070. * document references, and querying for documents (using {@link query}).
  4071. */ class Dn extends Nn {
  4072. /** @hideconstructor */
  4073. constructor(t, e, n) {
  4074. super(t, e, new _e(n)), this._path = n,
  4075. /** The type of this Firestore reference. */
  4076. this.type = "collection";
  4077. }
  4078. /** The collection's identifier. */ get id() {
  4079. return this._query.path.lastSegment();
  4080. }
  4081. /**
  4082. * A string representing the path of the referenced collection (relative
  4083. * to the root of the database).
  4084. */ get path() {
  4085. return this._query.path.canonicalString();
  4086. }
  4087. /**
  4088. * A reference to the containing `DocumentReference` if this is a
  4089. * subcollection. If this isn't a subcollection, the reference is null.
  4090. */ get parent() {
  4091. const t = this._path.popLast();
  4092. return t.isEmpty() ? null : new $n(this.firestore,
  4093. /* converter= */ null, new st(t));
  4094. }
  4095. withConverter(t) {
  4096. return new Dn(this.firestore, t, this._path);
  4097. }
  4098. }
  4099. function Fn(t, e, ...n) {
  4100. if (t = f(t), it("collection", "path", e), t instanceof bn) {
  4101. const r = et.fromString(e, ...n);
  4102. return ut(r), new Dn(t, /* converter= */ null, r);
  4103. }
  4104. {
  4105. if (!(t instanceof $n || t instanceof Dn)) throw new j(V, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  4106. const r = t._path.child(et.fromString(e, ...n));
  4107. return ut(r), new Dn(t.firestore,
  4108. /* converter= */ null, r);
  4109. }
  4110. }
  4111. // TODO(firestorelite): Consider using ErrorFactory -
  4112. // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
  4113. /**
  4114. * Creates and returns a new `Query` instance that includes all documents in the
  4115. * database that are contained in a collection or subcollection with the
  4116. * given `collectionId`.
  4117. *
  4118. * @param firestore - A reference to the root `Firestore` instance.
  4119. * @param collectionId - Identifies the collections to query over. Every
  4120. * collection or subcollection with this ID as the last segment of its path
  4121. * will be included. Cannot contain a slash.
  4122. * @returns The created `Query`.
  4123. */ function xn(t, e) {
  4124. if (t = at(t, bn), it("collectionGroup", "collection id", e), e.indexOf("/") >= 0) throw new j(V, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);
  4125. return new Nn(t,
  4126. /* converter= */ null, function(t) {
  4127. return new _e(et.emptyPath(), t);
  4128. }(e));
  4129. }
  4130. function Sn(t, e, ...n) {
  4131. if (t = f(t),
  4132. // We allow omission of 'pathString' but explicitly prohibit passing in both
  4133. // 'undefined' and 'null'.
  4134. 1 === arguments.length && (e = _t.N()), it("doc", "path", e), t instanceof bn) {
  4135. const r = et.fromString(e, ...n);
  4136. return ot(r), new $n(t,
  4137. /* converter= */ null, new st(r));
  4138. }
  4139. {
  4140. if (!(t instanceof $n || t instanceof Dn)) throw new j(V, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  4141. const r = t._path.child(et.fromString(e, ...n));
  4142. return ot(r), new $n(t.firestore, t instanceof Dn ? t.converter : null, new st(r));
  4143. }
  4144. }
  4145. /**
  4146. * Returns true if the provided references are equal.
  4147. *
  4148. * @param left - A reference to compare.
  4149. * @param right - A reference to compare.
  4150. * @returns true if the references point to the same location in the same
  4151. * Firestore database.
  4152. */ function qn(t, e) {
  4153. return t = f(t), e = f(e), (t instanceof $n || t instanceof Dn) && (e instanceof $n || e instanceof Dn) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter);
  4154. }
  4155. /**
  4156. * Returns true if the provided queries point to the same collection and apply
  4157. * the same constraints.
  4158. *
  4159. * @param left - A `Query` to compare.
  4160. * @param right - A `Query` to compare.
  4161. * @returns true if the references point to the same location in the same
  4162. * Firestore database.
  4163. */ function On(t, e) {
  4164. return t = f(t), e = f(e), t instanceof Nn && e instanceof Nn && (t.firestore === e.firestore && Re(t._query, e._query) && t.converter === e.converter);
  4165. }
  4166. /**
  4167. * @license
  4168. * Copyright 2020 Google LLC
  4169. *
  4170. * Licensed under the Apache License, Version 2.0 (the "License");
  4171. * you may not use this file except in compliance with the License.
  4172. * You may obtain a copy of the License at
  4173. *
  4174. * http://www.apache.org/licenses/LICENSE-2.0
  4175. *
  4176. * Unless required by applicable law or agreed to in writing, software
  4177. * distributed under the License is distributed on an "AS IS" BASIS,
  4178. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4179. * See the License for the specific language governing permissions and
  4180. * limitations under the License.
  4181. */
  4182. /**
  4183. * An immutable object representing an array of bytes.
  4184. */ class kn {
  4185. /** @hideconstructor */
  4186. constructor(t) {
  4187. this._byteString = t;
  4188. }
  4189. /**
  4190. * Creates a new `Bytes` object from the given Base64 string, converting it to
  4191. * bytes.
  4192. *
  4193. * @param base64 - The Base64 string used to create the `Bytes` object.
  4194. */ static fromBase64String(t) {
  4195. try {
  4196. return new kn(Tt.fromBase64String(t));
  4197. } catch (t) {
  4198. throw new j(V, "Failed to construct data from Base64 string: " + t);
  4199. }
  4200. }
  4201. /**
  4202. * Creates a new `Bytes` object from the given Uint8Array.
  4203. *
  4204. * @param array - The Uint8Array used to create the `Bytes` object.
  4205. */ static fromUint8Array(t) {
  4206. return new kn(Tt.fromUint8Array(t));
  4207. }
  4208. /**
  4209. * Returns the underlying bytes as a Base64-encoded string.
  4210. *
  4211. * @returns The Base64-encoded string created from the `Bytes` object.
  4212. */ toBase64() {
  4213. return this._byteString.toBase64();
  4214. }
  4215. /**
  4216. * Returns the underlying bytes in a new `Uint8Array`.
  4217. *
  4218. * @returns The Uint8Array created from the `Bytes` object.
  4219. */ toUint8Array() {
  4220. return this._byteString.toUint8Array();
  4221. }
  4222. /**
  4223. * Returns a string representation of the `Bytes` object.
  4224. *
  4225. * @returns A string representation of the `Bytes` object.
  4226. */ toString() {
  4227. return "Bytes(base64: " + this.toBase64() + ")";
  4228. }
  4229. /**
  4230. * Returns true if this `Bytes` object is equal to the provided one.
  4231. *
  4232. * @param other - The `Bytes` object to compare against.
  4233. * @returns true if this `Bytes` object is equal to the provided one.
  4234. */ isEqual(t) {
  4235. return this._byteString.isEqual(t._byteString);
  4236. }
  4237. }
  4238. /**
  4239. * @license
  4240. * Copyright 2020 Google LLC
  4241. *
  4242. * Licensed under the Apache License, Version 2.0 (the "License");
  4243. * you may not use this file except in compliance with the License.
  4244. * You may obtain a copy of the License at
  4245. *
  4246. * http://www.apache.org/licenses/LICENSE-2.0
  4247. *
  4248. * Unless required by applicable law or agreed to in writing, software
  4249. * distributed under the License is distributed on an "AS IS" BASIS,
  4250. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4251. * See the License for the specific language governing permissions and
  4252. * limitations under the License.
  4253. */
  4254. /**
  4255. * A `FieldPath` refers to a field in a document. The path may consist of a
  4256. * single field name (referring to a top-level field in the document), or a
  4257. * list of field names (referring to a nested field in the document).
  4258. *
  4259. * Create a `FieldPath` by providing field names. If more than one field
  4260. * name is provided, the path will point to a nested field in a document.
  4261. */ class Cn {
  4262. /**
  4263. * Creates a `FieldPath` from the provided field names. If more than one field
  4264. * name is provided, the path will point to a nested field in a document.
  4265. *
  4266. * @param fieldNames - A list of field names.
  4267. */
  4268. constructor(...t) {
  4269. for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new j(V, "Invalid field name at argument $(i + 1). Field names must not be empty.");
  4270. this._internalPath = new rt(t);
  4271. }
  4272. /**
  4273. * Returns true if this `FieldPath` is equal to the provided one.
  4274. *
  4275. * @param other - The `FieldPath` to compare against.
  4276. * @returns true if this `FieldPath` is equal to the provided one.
  4277. */ isEqual(t) {
  4278. return this._internalPath.isEqual(t._internalPath);
  4279. }
  4280. }
  4281. /**
  4282. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  4283. * It can be used in queries to sort or filter by the document ID.
  4284. */ function Ln() {
  4285. return new Cn("__name__");
  4286. }
  4287. /**
  4288. * @license
  4289. * Copyright 2020 Google LLC
  4290. *
  4291. * Licensed under the Apache License, Version 2.0 (the "License");
  4292. * you may not use this file except in compliance with the License.
  4293. * You may obtain a copy of the License at
  4294. *
  4295. * http://www.apache.org/licenses/LICENSE-2.0
  4296. *
  4297. * Unless required by applicable law or agreed to in writing, software
  4298. * distributed under the License is distributed on an "AS IS" BASIS,
  4299. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4300. * See the License for the specific language governing permissions and
  4301. * limitations under the License.
  4302. */
  4303. /**
  4304. * Sentinel values that can be used when writing document fields with `set()`
  4305. * or `update()`.
  4306. */ class Mn {
  4307. /**
  4308. * @param _methodName - The public API endpoint that returns this class.
  4309. * @hideconstructor
  4310. */
  4311. constructor(t) {
  4312. this._methodName = t;
  4313. }
  4314. }
  4315. /**
  4316. * @license
  4317. * Copyright 2017 Google LLC
  4318. *
  4319. * Licensed under the Apache License, Version 2.0 (the "License");
  4320. * you may not use this file except in compliance with the License.
  4321. * You may obtain a copy of the License at
  4322. *
  4323. * http://www.apache.org/licenses/LICENSE-2.0
  4324. *
  4325. * Unless required by applicable law or agreed to in writing, software
  4326. * distributed under the License is distributed on an "AS IS" BASIS,
  4327. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4328. * See the License for the specific language governing permissions and
  4329. * limitations under the License.
  4330. */
  4331. /**
  4332. * An immutable object representing a geographic location in Firestore. The
  4333. * location is represented as latitude/longitude pair.
  4334. *
  4335. * Latitude values are in the range of [-90, 90].
  4336. * Longitude values are in the range of [-180, 180].
  4337. */ class Un {
  4338. /**
  4339. * Creates a new immutable `GeoPoint` object with the provided latitude and
  4340. * longitude values.
  4341. * @param latitude - The latitude as number between -90 and 90.
  4342. * @param longitude - The longitude as number between -180 and 180.
  4343. */
  4344. constructor(t, e) {
  4345. if (!isFinite(t) || t < -90 || t > 90) throw new j(V, "Latitude must be a number between -90 and 90, but was: " + t);
  4346. if (!isFinite(e) || e < -180 || e > 180) throw new j(V, "Longitude must be a number between -180 and 180, but was: " + e);
  4347. this._lat = t, this._long = e;
  4348. }
  4349. /**
  4350. * The latitude of this `GeoPoint` instance.
  4351. */ get latitude() {
  4352. return this._lat;
  4353. }
  4354. /**
  4355. * The longitude of this `GeoPoint` instance.
  4356. */ get longitude() {
  4357. return this._long;
  4358. }
  4359. /**
  4360. * Returns true if this `GeoPoint` is equal to the provided one.
  4361. *
  4362. * @param other - The `GeoPoint` to compare against.
  4363. * @returns true if this `GeoPoint` is equal to the provided one.
  4364. */ isEqual(t) {
  4365. return this._lat === t._lat && this._long === t._long;
  4366. }
  4367. /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {
  4368. return {
  4369. latitude: this._lat,
  4370. longitude: this._long
  4371. };
  4372. }
  4373. /**
  4374. * Actually private to JS consumers of our API, so this function is prefixed
  4375. * with an underscore.
  4376. */ _compareTo(t) {
  4377. return vt(this._lat, t._lat) || vt(this._long, t._long);
  4378. }
  4379. }
  4380. /**
  4381. * @license
  4382. * Copyright 2017 Google LLC
  4383. *
  4384. * Licensed under the Apache License, Version 2.0 (the "License");
  4385. * you may not use this file except in compliance with the License.
  4386. * You may obtain a copy of the License at
  4387. *
  4388. * http://www.apache.org/licenses/LICENSE-2.0
  4389. *
  4390. * Unless required by applicable law or agreed to in writing, software
  4391. * distributed under the License is distributed on an "AS IS" BASIS,
  4392. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4393. * See the License for the specific language governing permissions and
  4394. * limitations under the License.
  4395. */ const jn = /^__.*__$/;
  4396. /** The result of parsing document data (e.g. for a setData call). */ class Bn {
  4397. constructor(t, e, n) {
  4398. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  4399. }
  4400. toMutation(t, e) {
  4401. return null !== this.fieldMask ? new ke(t, this.data, this.fieldMask, e, this.fieldTransforms) : new Oe(t, this.data, e, this.fieldTransforms);
  4402. }
  4403. }
  4404. /** The result of parsing "update" data (i.e. for an updateData call). */ class Qn {
  4405. constructor(t,
  4406. // The fieldMask does not include document transforms.
  4407. e, n) {
  4408. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  4409. }
  4410. toMutation(t, e) {
  4411. return new ke(t, this.data, this.fieldMask, e, this.fieldTransforms);
  4412. }
  4413. }
  4414. function zn(t) {
  4415. switch (t) {
  4416. case 0 /* UserDataSource.Set */ :
  4417. // fall through
  4418. case 2 /* UserDataSource.MergeSet */ :
  4419. // fall through
  4420. case 1 /* UserDataSource.Update */ :
  4421. return !0;
  4422. case 3 /* UserDataSource.Argument */ :
  4423. case 4 /* UserDataSource.ArrayArgument */ :
  4424. return !1;
  4425. default:
  4426. throw E();
  4427. }
  4428. }
  4429. /** A "context" object passed around while parsing user data. */ class Wn {
  4430. /**
  4431. * Initializes a ParseContext with the given source and path.
  4432. *
  4433. * @param settings - The settings for the parser.
  4434. * @param databaseId - The database ID of the Firestore instance.
  4435. * @param serializer - The serializer to use to generate the Value proto.
  4436. * @param ignoreUndefinedProperties - Whether to ignore undefined properties
  4437. * rather than throw.
  4438. * @param fieldTransforms - A mutable list of field transforms encountered
  4439. * while parsing the data.
  4440. * @param fieldMask - A mutable list of field paths encountered while parsing
  4441. * the data.
  4442. *
  4443. * TODO(b/34871131): We don't support array paths right now, so path can be
  4444. * null to indicate the context represents any location within an array (in
  4445. * which case certain features will not work and errors will be somewhat
  4446. * compromised).
  4447. */
  4448. constructor(t, e, n, r, s, i) {
  4449. this.settings = t, this.databaseId = e, this.C = n, this.ignoreUndefinedProperties = r,
  4450. // Minor hack: If fieldTransforms is undefined, we assume this is an
  4451. // external call and we need to validate the entire path.
  4452. void 0 === s && this.et(), this.fieldTransforms = s || [], this.fieldMask = i || [];
  4453. }
  4454. get path() {
  4455. return this.settings.path;
  4456. }
  4457. get nt() {
  4458. return this.settings.nt;
  4459. }
  4460. /** Returns a new context with the specified settings overwritten. */ rt(t) {
  4461. return new Wn(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.C, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  4462. }
  4463. st(t) {
  4464. var e;
  4465. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), r = this.rt({
  4466. path: n,
  4467. it: !1
  4468. });
  4469. return r.ot(t), r;
  4470. }
  4471. ut(t) {
  4472. var e;
  4473. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), r = this.rt({
  4474. path: n,
  4475. it: !1
  4476. });
  4477. return r.et(), r;
  4478. }
  4479. ct(t) {
  4480. // TODO(b/34871131): We don't support array paths right now; so make path
  4481. // undefined.
  4482. return this.rt({
  4483. path: void 0,
  4484. it: !0
  4485. });
  4486. }
  4487. at(t) {
  4488. return fr(t, this.settings.methodName, this.settings.ht || !1, this.path, this.settings.lt);
  4489. }
  4490. /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) {
  4491. return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field)));
  4492. }
  4493. et() {
  4494. // TODO(b/34871131): Remove null check once we have proper paths for fields
  4495. // within arrays.
  4496. if (this.path) for (let t = 0; t < this.path.length; t++) this.ot(this.path.get(t));
  4497. }
  4498. ot(t) {
  4499. if (0 === t.length) throw this.at("Document fields must not be empty");
  4500. if (zn(this.nt) && jn.test(t)) throw this.at('Document fields cannot begin and end with "__"');
  4501. }
  4502. }
  4503. /**
  4504. * Helper for parsing raw user input (provided via the API) into internal model
  4505. * classes.
  4506. */ class Gn {
  4507. constructor(t, e, n) {
  4508. this.databaseId = t, this.ignoreUndefinedProperties = e, this.C = n || ln(t);
  4509. }
  4510. /** Creates a new top-level parse context. */ ft(t, e, n, r = !1) {
  4511. return new Wn({
  4512. nt: t,
  4513. methodName: e,
  4514. lt: n,
  4515. path: rt.emptyPath(),
  4516. it: !1,
  4517. ht: r
  4518. }, this.databaseId, this.C, this.ignoreUndefinedProperties);
  4519. }
  4520. }
  4521. function Kn(t) {
  4522. const e = t._freezeSettings(), n = ln(t._databaseId);
  4523. return new Gn(t._databaseId, !!e.ignoreUndefinedProperties, n);
  4524. }
  4525. /** Parse document data from a set() call. */ function Yn(t, e, n, r, s, i = {}) {
  4526. const o = t.ft(i.merge || i.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, s);
  4527. cr("Data must be an object, but it was:", o, r);
  4528. const u = or(r, o);
  4529. let c, a;
  4530. if (i.merge) c = new we(o.fieldMask), a = o.fieldTransforms; else if (i.mergeFields) {
  4531. const t = [];
  4532. for (const r of i.mergeFields) {
  4533. const s = ar(e, r, n);
  4534. if (!o.contains(s)) throw new j(V, `Field '${s}' is specified in your field mask but missing from your input data.`);
  4535. dr(t, s) || t.push(s);
  4536. }
  4537. c = new we(t), a = o.fieldTransforms.filter((t => c.covers(t.field)));
  4538. } else c = null, a = o.fieldTransforms;
  4539. return new Bn(new me(u), c, a);
  4540. }
  4541. class Hn extends Mn {
  4542. _toFieldTransform(t) {
  4543. if (2 /* UserDataSource.MergeSet */ !== t.nt) throw 1 /* UserDataSource.Update */ === t.nt ? t.at(`${this._methodName}() can only appear at the top level of your update data`) : t.at(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);
  4544. // No transform to add for a delete, but we need to add it to our
  4545. // fieldMask so it gets deleted.
  4546. return t.fieldMask.push(t.path), null;
  4547. }
  4548. isEqual(t) {
  4549. return t instanceof Hn;
  4550. }
  4551. }
  4552. /**
  4553. * Creates a child context for parsing SerializableFieldValues.
  4554. *
  4555. * This is different than calling `ParseContext.contextWith` because it keeps
  4556. * the fieldTransforms and fieldMask separate.
  4557. *
  4558. * The created context has its `dataSource` set to `UserDataSource.Argument`.
  4559. * Although these values are used with writes, any elements in these FieldValues
  4560. * are not considered writes since they cannot contain any FieldValue sentinels,
  4561. * etc.
  4562. *
  4563. * @param fieldValue - The sentinel FieldValue for which to create a child
  4564. * context.
  4565. * @param context - The parent context.
  4566. * @param arrayElement - Whether or not the FieldValue has an array.
  4567. */ function Jn(t, e, n) {
  4568. return new Wn({
  4569. nt: 3 /* UserDataSource.Argument */ ,
  4570. lt: e.settings.lt,
  4571. methodName: t._methodName,
  4572. it: n
  4573. }, e.databaseId, e.C, e.ignoreUndefinedProperties);
  4574. }
  4575. class Xn extends Mn {
  4576. _toFieldTransform(t) {
  4577. return new xe(t.path, new $e);
  4578. }
  4579. isEqual(t) {
  4580. return t instanceof Xn;
  4581. }
  4582. }
  4583. class Zn extends Mn {
  4584. constructor(t, e) {
  4585. super(t), this.dt = e;
  4586. }
  4587. _toFieldTransform(t) {
  4588. const e = Jn(this, t,
  4589. /*array=*/ !0), n = this.dt.map((t => ir(t, e))), r = new Ne(n);
  4590. return new xe(t.path, r);
  4591. }
  4592. isEqual(t) {
  4593. // TODO(mrschmidt): Implement isEquals
  4594. return this === t;
  4595. }
  4596. }
  4597. class tr extends Mn {
  4598. constructor(t, e) {
  4599. super(t), this.dt = e;
  4600. }
  4601. _toFieldTransform(t) {
  4602. const e = Jn(this, t,
  4603. /*array=*/ !0), n = this.dt.map((t => ir(t, e))), r = new De(n);
  4604. return new xe(t.path, r);
  4605. }
  4606. isEqual(t) {
  4607. // TODO(mrschmidt): Implement isEquals
  4608. return this === t;
  4609. }
  4610. }
  4611. class er extends Mn {
  4612. constructor(t, e) {
  4613. super(t), this.wt = e;
  4614. }
  4615. _toFieldTransform(t) {
  4616. const e = new Fe(t.C, Pe(t.C, this.wt));
  4617. return new xe(t.path, e);
  4618. }
  4619. isEqual(t) {
  4620. // TODO(mrschmidt): Implement isEquals
  4621. return this === t;
  4622. }
  4623. }
  4624. /** Parse update data from an update() call. */ function nr(t, e, n, r) {
  4625. const s = t.ft(1 /* UserDataSource.Update */ , e, n);
  4626. cr("Data must be an object, but it was:", s, r);
  4627. const i = [], o = me.empty();
  4628. It(r, ((t, r) => {
  4629. const u = lr(e, t, n);
  4630. // For Compat types, we have to "extract" the underlying types before
  4631. // performing validation.
  4632. r = f(r);
  4633. const c = s.ut(u);
  4634. if (r instanceof Hn)
  4635. // Add it to the field mask, but don't add anything to updateData.
  4636. i.push(u); else {
  4637. const t = ir(r, c);
  4638. null != t && (i.push(u), o.set(u, t));
  4639. }
  4640. }));
  4641. const u = new we(i);
  4642. return new Qn(o, u, s.fieldTransforms);
  4643. }
  4644. /** Parse update data from a list of field/value arguments. */ function rr(t, e, n, r, s, i) {
  4645. const o = t.ft(1 /* UserDataSource.Update */ , e, n), u = [ ar(e, r, n) ], c = [ s ];
  4646. if (i.length % 2 != 0) throw new j(V, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);
  4647. for (let t = 0; t < i.length; t += 2) u.push(ar(e, i[t])), c.push(i[t + 1]);
  4648. const a = [], h = me.empty();
  4649. // We iterate in reverse order to pick the last value for a field if the
  4650. // user specified the field multiple times.
  4651. for (let t = u.length - 1; t >= 0; --t) if (!dr(a, u[t])) {
  4652. const e = u[t];
  4653. let n = c[t];
  4654. // For Compat types, we have to "extract" the underlying types before
  4655. // performing validation.
  4656. n = f(n);
  4657. const r = o.ut(e);
  4658. if (n instanceof Hn)
  4659. // Add it to the field mask, but don't add anything to updateData.
  4660. a.push(e); else {
  4661. const t = ir(n, r);
  4662. null != t && (a.push(e), h.set(e, t));
  4663. }
  4664. }
  4665. const l = new we(a);
  4666. return new Qn(h, l, o.fieldTransforms);
  4667. }
  4668. /**
  4669. * Parse a "query value" (e.g. value in a where filter or a value in a cursor
  4670. * bound).
  4671. *
  4672. * @param allowArrays - Whether the query value is an array that may directly
  4673. * contain additional arrays (e.g. the operand of an `in` query).
  4674. */ function sr(t, e, n, r = !1) {
  4675. return ir(n, t.ft(r ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));
  4676. }
  4677. /**
  4678. * Parses user data to Protobuf Values.
  4679. *
  4680. * @param input - Data to be parsed.
  4681. * @param context - A context object representing the current path being parsed,
  4682. * the source of the data being parsed, etc.
  4683. * @returns The parsed value, or null if the value was a FieldValue sentinel
  4684. * that should not be included in the resulting parsed data.
  4685. */ function ir(t, e) {
  4686. if (ur(
  4687. // Unwrap the API type from the Compat SDK. This will return the API type
  4688. // from firestore-exp.
  4689. t = f(t))) return cr("Unsupported field value:", e, t), or(t, e);
  4690. if (t instanceof Mn)
  4691. // FieldValues usually parse into transforms (except deleteField())
  4692. // in which case we do not want to include this field in our parsed data
  4693. // (as doing so will overwrite the field directly prior to the transform
  4694. // trying to transform it). So we don't add this location to
  4695. // context.fieldMask and we return null as our parsing result.
  4696. /**
  4697. * "Parses" the provided FieldValueImpl, adding any necessary transforms to
  4698. * context.fieldTransforms.
  4699. */
  4700. return function(t, e) {
  4701. // Sentinels are only supported with writes, and not within arrays.
  4702. if (!zn(e.nt)) throw e.at(`${t._methodName}() can only be used with update() and set()`);
  4703. if (!e.path) throw e.at(`${t._methodName}() is not currently supported inside arrays`);
  4704. const n = t._toFieldTransform(e);
  4705. n && e.fieldTransforms.push(n);
  4706. }
  4707. /**
  4708. * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
  4709. *
  4710. * @returns The parsed value
  4711. */ (t, e), null;
  4712. if (void 0 === t && e.ignoreUndefinedProperties)
  4713. // If the input is undefined it can never participate in the fieldMask, so
  4714. // don't handle this below. If `ignoreUndefinedProperties` is false,
  4715. // `parseScalarValue` will reject an undefined value.
  4716. return null;
  4717. if (
  4718. // If context.path is null we are inside an array and we don't support
  4719. // field mask paths more granular than the top-level array.
  4720. e.path && e.fieldMask.push(e.path), t instanceof Array) {
  4721. // TODO(b/34871131): Include the path containing the array in the error
  4722. // message.
  4723. // In the case of IN queries, the parsed data is an array (representing
  4724. // the set of values to be included for the IN query) that may directly
  4725. // contain additional arrays (each representing an individual field
  4726. // value), so we disable this validation.
  4727. if (e.settings.it && 4 /* UserDataSource.ArrayArgument */ !== e.nt) throw e.at("Nested arrays are not supported");
  4728. return function(t, e) {
  4729. const n = [];
  4730. let r = 0;
  4731. for (const s of t) {
  4732. let t = ir(s, e.ct(r));
  4733. null == t && (
  4734. // Just include nulls in the array for fields being replaced with a
  4735. // sentinel.
  4736. t = {
  4737. nullValue: "NULL_VALUE"
  4738. }), n.push(t), r++;
  4739. }
  4740. return {
  4741. arrayValue: {
  4742. values: n
  4743. }
  4744. };
  4745. }(t, e);
  4746. }
  4747. return function(t, e) {
  4748. if (null === (t = f(t))) return {
  4749. nullValue: "NULL_VALUE"
  4750. };
  4751. if ("number" == typeof t) return Pe(e.C, t);
  4752. if ("boolean" == typeof t) return {
  4753. booleanValue: t
  4754. };
  4755. if ("string" == typeof t) return {
  4756. stringValue: t
  4757. };
  4758. if (t instanceof Date) {
  4759. const n = Nt.fromDate(t);
  4760. return {
  4761. timestampValue: Qe(e.C, n)
  4762. };
  4763. }
  4764. if (t instanceof Nt) {
  4765. // Firestore backend truncates precision down to microseconds. To ensure
  4766. // offline mode works the same with regards to truncation, perform the
  4767. // truncation immediately without waiting for the backend to do that.
  4768. const n = new Nt(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
  4769. return {
  4770. timestampValue: Qe(e.C, n)
  4771. };
  4772. }
  4773. if (t instanceof Un) return {
  4774. geoPointValue: {
  4775. latitude: t.latitude,
  4776. longitude: t.longitude
  4777. }
  4778. };
  4779. if (t instanceof kn) return {
  4780. bytesValue: ze(e.C, t._byteString)
  4781. };
  4782. if (t instanceof $n) {
  4783. const n = e.databaseId, r = t.firestore._databaseId;
  4784. if (!r.isEqual(n)) throw e.at(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);
  4785. return {
  4786. referenceValue: Ke(t.firestore._databaseId || e.databaseId, t._key.path)
  4787. };
  4788. }
  4789. throw e.at(`Unsupported field value: ${ct(t)}`);
  4790. }
  4791. /**
  4792. * Checks whether an object looks like a JSON object that should be converted
  4793. * into a struct. Normal class/prototype instances are considered to look like
  4794. * JSON objects since they should be converted to a struct value. Arrays, Dates,
  4795. * GeoPoints, etc. are not considered to look like JSON objects since they map
  4796. * to specific FieldValue types other than ObjectValue.
  4797. */ (t, e);
  4798. }
  4799. function or(t, e) {
  4800. const n = {};
  4801. return !function(t) {
  4802. for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
  4803. return !0;
  4804. }
  4805. /**
  4806. * @license
  4807. * Copyright 2020 Google LLC
  4808. *
  4809. * Licensed under the Apache License, Version 2.0 (the "License");
  4810. * you may not use this file except in compliance with the License.
  4811. * You may obtain a copy of the License at
  4812. *
  4813. * http://www.apache.org/licenses/LICENSE-2.0
  4814. *
  4815. * Unless required by applicable law or agreed to in writing, software
  4816. * distributed under the License is distributed on an "AS IS" BASIS,
  4817. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4818. * See the License for the specific language governing permissions and
  4819. * limitations under the License.
  4820. */
  4821. // WebSafe uses a different URL-encoding safe alphabet that doesn't match
  4822. // the encoding used on the backend.
  4823. (t) ? It(t, ((t, r) => {
  4824. const s = ir(r, e.st(t));
  4825. null != s && (n[t] = s);
  4826. })) :
  4827. // If we encounter an empty object, we explicitly add it to the update
  4828. // mask to ensure that the server creates a map entry.
  4829. e.path && e.path.length > 0 && e.fieldMask.push(e.path), {
  4830. mapValue: {
  4831. fields: n
  4832. }
  4833. };
  4834. }
  4835. function ur(t) {
  4836. return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof Nt || t instanceof Un || t instanceof kn || t instanceof $n || t instanceof Mn);
  4837. }
  4838. function cr(t, e, n) {
  4839. if (!ur(n) || !function(t) {
  4840. return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));
  4841. }(n)) {
  4842. const r = ct(n);
  4843. throw "an object" === r ? e.at(t + " a custom object") : e.at(t + " " + r);
  4844. }
  4845. }
  4846. /**
  4847. * Helper that calls fromDotSeparatedString() but wraps any error thrown.
  4848. */ function ar(t, e, n) {
  4849. if ((
  4850. // If required, replace the FieldPath Compat class with with the firestore-exp
  4851. // FieldPath.
  4852. e = f(e)) instanceof Cn) return e._internalPath;
  4853. if ("string" == typeof e) return lr(t, e);
  4854. throw fr("Field path arguments must be of type string or ", t,
  4855. /* hasConverter= */ !1,
  4856. /* path= */ void 0, n);
  4857. }
  4858. /**
  4859. * Matches any characters in a field path string that are reserved.
  4860. */ const hr = new RegExp("[~\\*/\\[\\]]");
  4861. /**
  4862. * Wraps fromDotSeparatedString with an error message about the method that
  4863. * was thrown.
  4864. * @param methodName - The publicly visible method name
  4865. * @param path - The dot-separated string form of a field path which will be
  4866. * split on dots.
  4867. * @param targetDoc - The document against which the field path will be
  4868. * evaluated.
  4869. */ function lr(t, e, n) {
  4870. if (e.search(hr) >= 0) throw fr(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t,
  4871. /* hasConverter= */ !1,
  4872. /* path= */ void 0, n);
  4873. try {
  4874. return new Cn(...e.split("."))._internalPath;
  4875. } catch (r) {
  4876. throw fr(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t,
  4877. /* hasConverter= */ !1,
  4878. /* path= */ void 0, n);
  4879. }
  4880. }
  4881. function fr(t, e, n, r, s) {
  4882. const i = r && !r.isEmpty(), o = void 0 !== s;
  4883. let u = `Function ${e}() called with invalid data`;
  4884. n && (u += " (via `toFirestore()`)"), u += ". ";
  4885. let c = "";
  4886. return (i || o) && (c += " (found", i && (c += ` in field ${r}`), o && (c += ` in document ${s}`),
  4887. c += ")"), new j(V, u + t + c);
  4888. }
  4889. /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function dr(t, e) {
  4890. return t.some((t => t.isEqual(e)));
  4891. }
  4892. /**
  4893. * @license
  4894. * Copyright 2020 Google LLC
  4895. *
  4896. * Licensed under the Apache License, Version 2.0 (the "License");
  4897. * you may not use this file except in compliance with the License.
  4898. * You may obtain a copy of the License at
  4899. *
  4900. * http://www.apache.org/licenses/LICENSE-2.0
  4901. *
  4902. * Unless required by applicable law or agreed to in writing, software
  4903. * distributed under the License is distributed on an "AS IS" BASIS,
  4904. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4905. * See the License for the specific language governing permissions and
  4906. * limitations under the License.
  4907. */
  4908. /**
  4909. * A `DocumentSnapshot` contains data read from a document in your Firestore
  4910. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  4911. * get a specific field.
  4912. *
  4913. * For a `DocumentSnapshot` that points to a non-existing document, any data
  4914. * access will return 'undefined'. You can use the `exists()` method to
  4915. * explicitly verify a document's existence.
  4916. */ class wr {
  4917. // Note: This class is stripped down version of the DocumentSnapshot in
  4918. // the legacy SDK. The changes are:
  4919. // - No support for SnapshotMetadata.
  4920. // - No support for SnapshotOptions.
  4921. /** @hideconstructor protected */
  4922. constructor(t, e, n, r, s) {
  4923. this._firestore = t, this._userDataWriter = e, this._key = n, this._document = r,
  4924. this._converter = s;
  4925. }
  4926. /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {
  4927. return this._key.path.lastSegment();
  4928. }
  4929. /**
  4930. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  4931. */ get ref() {
  4932. return new $n(this._firestore, this._converter, this._key);
  4933. }
  4934. /**
  4935. * Signals whether or not the document at the snapshot's location exists.
  4936. *
  4937. * @returns true if the document exists.
  4938. */ exists() {
  4939. return null !== this._document;
  4940. }
  4941. /**
  4942. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  4943. * the document doesn't exist.
  4944. *
  4945. * @returns An `Object` containing all fields in the document or `undefined`
  4946. * if the document doesn't exist.
  4947. */ data() {
  4948. if (this._document) {
  4949. if (this._converter) {
  4950. // We only want to use the converter and create a new DocumentSnapshot
  4951. // if a converter has been provided.
  4952. const t = new mr(this._firestore, this._userDataWriter, this._key, this._document,
  4953. /* converter= */ null);
  4954. return this._converter.fromFirestore(t);
  4955. }
  4956. return this._userDataWriter.convertValue(this._document.data.value);
  4957. }
  4958. }
  4959. /**
  4960. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  4961. * document or field doesn't exist.
  4962. *
  4963. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  4964. * field.
  4965. * @returns The data at the specified field location or undefined if no such
  4966. * field exists in the document.
  4967. */
  4968. // We are using `any` here to avoid an explicit cast by our users.
  4969. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4970. get(t) {
  4971. if (this._document) {
  4972. const e = this._document.data.field(gr("DocumentSnapshot.get", t));
  4973. if (null !== e) return this._userDataWriter.convertValue(e);
  4974. }
  4975. }
  4976. }
  4977. /**
  4978. * A `QueryDocumentSnapshot` contains data read from a document in your
  4979. * Firestore database as part of a query. The document is guaranteed to exist
  4980. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  4981. * specific field.
  4982. *
  4983. * A `QueryDocumentSnapshot` offers the same API surface as a
  4984. * `DocumentSnapshot`. Since query results contain only existing documents, the
  4985. * `exists` property will always be true and `data()` will never return
  4986. * 'undefined'.
  4987. */ class mr extends wr {
  4988. /**
  4989. * Retrieves all fields in the document as an `Object`.
  4990. *
  4991. * @override
  4992. * @returns An `Object` containing all fields in the document.
  4993. */
  4994. data() {
  4995. return super.data();
  4996. }
  4997. }
  4998. /**
  4999. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  5000. * representing the results of a query. The documents can be accessed as an
  5001. * array via the `docs` property or enumerated using the `forEach` method. The
  5002. * number of documents can be determined via the `empty` and `size`
  5003. * properties.
  5004. */ class pr {
  5005. /** @hideconstructor */
  5006. constructor(t, e) {
  5007. this._docs = e, this.query = t;
  5008. }
  5009. /** An array of all the documents in the `QuerySnapshot`. */ get docs() {
  5010. return [ ...this._docs ];
  5011. }
  5012. /** The number of documents in the `QuerySnapshot`. */ get size() {
  5013. return this.docs.length;
  5014. }
  5015. /** True if there are no documents in the `QuerySnapshot`. */ get empty() {
  5016. return 0 === this.docs.length;
  5017. }
  5018. /**
  5019. * Enumerates all of the documents in the `QuerySnapshot`.
  5020. *
  5021. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  5022. * each document in the snapshot.
  5023. * @param thisArg - The `this` binding for the callback.
  5024. */ forEach(t, e) {
  5025. this._docs.forEach(t, e);
  5026. }
  5027. }
  5028. /**
  5029. * Returns true if the provided snapshots are equal.
  5030. *
  5031. * @param left - A snapshot to compare.
  5032. * @param right - A snapshot to compare.
  5033. * @returns true if the snapshots are equal.
  5034. */ function yr(t, e) {
  5035. return t = f(t), e = f(e), t instanceof wr && e instanceof wr ? 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 pr && e instanceof pr && (On(t.query, e.query) && bt(t.docs, e.docs, yr));
  5036. }
  5037. /**
  5038. * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
  5039. */ function gr(t, e) {
  5040. return "string" == typeof e ? lr(t, e) : e instanceof Cn ? e._internalPath : e._delegate._internalPath;
  5041. }
  5042. /**
  5043. * @license
  5044. * Copyright 2020 Google LLC
  5045. *
  5046. * Licensed under the Apache License, Version 2.0 (the "License");
  5047. * you may not use this file except in compliance with the License.
  5048. * You may obtain a copy of the License at
  5049. *
  5050. * http://www.apache.org/licenses/LICENSE-2.0
  5051. *
  5052. * Unless required by applicable law or agreed to in writing, software
  5053. * distributed under the License is distributed on an "AS IS" BASIS,
  5054. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5055. * See the License for the specific language governing permissions and
  5056. * limitations under the License.
  5057. */
  5058. /**
  5059. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  5060. * to a Firestore query.
  5061. */
  5062. class _r {}
  5063. /**
  5064. * A `QueryConstraint` is used to narrow the set of documents returned by a
  5065. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  5066. * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link
  5067. * endBefore}, {@link endAt}, {@link limit}, {@link limitToLast} and
  5068. * can then be passed to {@link query} to create a new query instance that
  5069. * also contains this `QueryConstraint`.
  5070. */ class vr extends _r {}
  5071. function br(t, e, ...n) {
  5072. let r = [];
  5073. e instanceof _r && r.push(e), r = r.concat(n), function(t) {
  5074. const e = t.filter((t => t instanceof Ar)).length, n = t.filter((t => t instanceof Er)).length;
  5075. if (e > 1 || e > 0 && n > 0) throw new j(V, "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(...)))`.");
  5076. }
  5077. /**
  5078. * @license
  5079. * Copyright 2020 Google LLC
  5080. *
  5081. * Licensed under the Apache License, Version 2.0 (the "License");
  5082. * you may not use this file except in compliance with the License.
  5083. * You may obtain a copy of the License at
  5084. *
  5085. * http://www.apache.org/licenses/LICENSE-2.0
  5086. *
  5087. * Unless required by applicable law or agreed to in writing, software
  5088. * distributed under the License is distributed on an "AS IS" BASIS,
  5089. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5090. * See the License for the specific language governing permissions and
  5091. * limitations under the License.
  5092. */
  5093. /**
  5094. * Converts Firestore's internal types to the JavaScript types that we expose
  5095. * to the user.
  5096. *
  5097. * @internal
  5098. */ (r);
  5099. for (const e of r) t = e._apply(t);
  5100. return t;
  5101. }
  5102. /**
  5103. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  5104. * a Firestore query by filtering on one or more document fields.
  5105. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  5106. * be passed to {@link query} to create a new query instance that also contains
  5107. * this `QueryFieldFilterConstraint`.
  5108. */ class Er extends vr {
  5109. /**
  5110. * @internal
  5111. */
  5112. constructor(t, e, n) {
  5113. super(), this._field = t, this._op = e, this._value = n,
  5114. /** The type of this query constraint */
  5115. this.type = "where";
  5116. }
  5117. static _create(t, e, n) {
  5118. return new Er(t, e, n);
  5119. }
  5120. _apply(t) {
  5121. const e = this._parse(t);
  5122. return Ur(t._query, e), new Nn(t.firestore, t.converter, Te(t._query, e));
  5123. }
  5124. _parse(t) {
  5125. const e = Kn(t.firestore), n = function(t, e, n, r, s, i, o) {
  5126. let u;
  5127. if (s.isKeyField()) {
  5128. if ("array-contains" /* Operator.ARRAY_CONTAINS */ === i || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === i) throw new j(V, `Invalid Query. You can't perform '${i}' queries on documentId().`);
  5129. if ("in" /* Operator.IN */ === i || "not-in" /* Operator.NOT_IN */ === i) {
  5130. Mr(o, i);
  5131. const e = [];
  5132. for (const n of o) e.push(Lr(r, t, n));
  5133. u = {
  5134. arrayValue: {
  5135. values: e
  5136. }
  5137. };
  5138. } else u = Lr(r, t, o);
  5139. } else "in" /* Operator.IN */ !== i && "not-in" /* Operator.NOT_IN */ !== i && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== i || Mr(o, i),
  5140. u = sr(n, e, o,
  5141. /* allowArrays= */ "in" /* Operator.IN */ === i || "not-in" /* Operator.NOT_IN */ === i);
  5142. return Yt.create(s, i, u);
  5143. }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value);
  5144. return n;
  5145. }
  5146. }
  5147. /**
  5148. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  5149. * must contain the specified field and that the value should satisfy the
  5150. * relation constraint provided.
  5151. *
  5152. * @param fieldPath - The path to compare
  5153. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  5154. * "&lt;=", "!=").
  5155. * @param value - The value for comparison
  5156. * @returns The created {@link QueryFieldFilterConstraint}.
  5157. */ function Ir(t, e, n) {
  5158. const r = e, s = gr("where", t);
  5159. return Er._create(s, r, n);
  5160. }
  5161. /**
  5162. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  5163. * returned by a Firestore query by performing the logical OR or AND of multiple
  5164. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  5165. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  5166. * {@link and} and can then be passed to {@link query} to create a new query
  5167. * instance that also contains the `QueryCompositeFilterConstraint`.
  5168. * @internal TODO remove this internal tag with OR Query support in the server
  5169. */ class Ar extends _r {
  5170. /**
  5171. * @internal
  5172. */
  5173. constructor(
  5174. /** The type of this query constraint */
  5175. t, e) {
  5176. super(), this.type = t, this._queryConstraints = e;
  5177. }
  5178. static _create(t, e) {
  5179. return new Ar(t, e);
  5180. }
  5181. _parse(t) {
  5182. const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0));
  5183. return 1 === e.length ? e[0] : Ht.create(e, this._getOperator());
  5184. }
  5185. _apply(t) {
  5186. const e = this._parse(t);
  5187. return 0 === e.getFilters().length ? t : (function(t, e) {
  5188. let n = t;
  5189. const r = e.getFlattenedFilters();
  5190. for (const t of r) Ur(n, t), n = Te(n, t);
  5191. }
  5192. // Checks if any of the provided filter operators are included in the given list of filters and
  5193. // returns the first one that is, or null if none are.
  5194. (t._query, e), new Nn(t.firestore, t.converter, Te(t._query, e)));
  5195. }
  5196. _getQueryConstraints() {
  5197. return this._queryConstraints;
  5198. }
  5199. _getOperator() {
  5200. return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
  5201. }
  5202. }
  5203. /**
  5204. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  5205. * the given filter constraints. A disjunction filter includes a document if it
  5206. * satisfies any of the given filters.
  5207. *
  5208. * @param queryConstraints - Optional. The list of
  5209. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  5210. * created with calls to {@link where}, {@link or}, or {@link and}.
  5211. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  5212. * @internal TODO remove this internal tag with OR Query support in the server
  5213. */ function Tr(...t) {
  5214. // Only support QueryFilterConstraints
  5215. return t.forEach((t => Br("or", t))), Ar._create("or" /* CompositeOperator.OR */ , t);
  5216. }
  5217. /**
  5218. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  5219. * the given filter constraints. A conjunction filter includes a document if it
  5220. * satisfies all of the given filters.
  5221. *
  5222. * @param queryConstraints - Optional. The list of
  5223. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  5224. * created with calls to {@link where}, {@link or}, or {@link and}.
  5225. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  5226. * @internal TODO remove this internal tag with OR Query support in the server
  5227. */ function Rr(...t) {
  5228. // Only support QueryFilterConstraints
  5229. return t.forEach((t => Br("and", t))), Ar._create("and" /* CompositeOperator.AND */ , t);
  5230. }
  5231. /**
  5232. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  5233. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  5234. * {@link orderBy} and can then be passed to {@link query} to create a new query
  5235. * instance that also contains this `QueryOrderByConstraint`.
  5236. *
  5237. * Note: Documents that do not contain the orderBy field will not be present in
  5238. * the query result.
  5239. */ class Pr extends vr {
  5240. /**
  5241. * @internal
  5242. */
  5243. constructor(t, e) {
  5244. super(), this._field = t, this._direction = e,
  5245. /** The type of this query constraint */
  5246. this.type = "orderBy";
  5247. }
  5248. static _create(t, e) {
  5249. return new Pr(t, e);
  5250. }
  5251. _apply(t) {
  5252. const e = function(t, e, n) {
  5253. if (null !== t.startAt) throw new j(V, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
  5254. if (null !== t.endAt) throw new j(V, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
  5255. const r = new oe(e, n);
  5256. return function(t, e) {
  5257. if (null === ve(t)) {
  5258. // This is the first order by. It must match any inequality.
  5259. const n = be(t);
  5260. null !== n && jr(t, n, e.field);
  5261. }
  5262. }(t, r), r;
  5263. }
  5264. /**
  5265. * Create a `Bound` from a query and a document.
  5266. *
  5267. * Note that the `Bound` will always include the key of the document
  5268. * and so only the provided document will compare equal to the returned
  5269. * position.
  5270. *
  5271. * Will throw if the document does not contain all fields of the order by
  5272. * of the query or if any of the fields in the order by are an uncommitted
  5273. * server timestamp.
  5274. */ (t._query, this._field, this._direction);
  5275. return new Nn(t.firestore, t.converter, function(t, e) {
  5276. // TODO(dimond): validate that orderBy does not list the same key twice.
  5277. const n = t.explicitOrderBy.concat([ e ]);
  5278. return new _e(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  5279. }(t._query, e));
  5280. }
  5281. }
  5282. /**
  5283. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  5284. * specified field, optionally in descending order instead of ascending.
  5285. *
  5286. * Note: Documents that do not contain the specified field will not be present
  5287. * in the query result.
  5288. *
  5289. * @param fieldPath - The field to sort by.
  5290. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  5291. * not specified, order will be ascending.
  5292. * @returns The created {@link QueryOrderByConstraint}.
  5293. */ function Vr(t, e = "asc") {
  5294. const n = e, r = gr("orderBy", t);
  5295. return Pr._create(r, n);
  5296. }
  5297. /**
  5298. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  5299. * a Firestore query.
  5300. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  5301. * {@link limitToLast} and can then be passed to {@link query} to create a new
  5302. * query instance that also contains this `QueryLimitConstraint`.
  5303. */ class $r extends vr {
  5304. /**
  5305. * @internal
  5306. */
  5307. constructor(
  5308. /** The type of this query constraint */
  5309. t, e, n) {
  5310. super(), this.type = t, this._limit = e, this._limitType = n;
  5311. }
  5312. static _create(t, e, n) {
  5313. return new $r(t, e, n);
  5314. }
  5315. _apply(t) {
  5316. return new Nn(t.firestore, t.converter, function(t, e, n) {
  5317. return new _e(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);
  5318. }(t._query, this._limit, this._limitType));
  5319. }
  5320. }
  5321. /**
  5322. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  5323. * documents.
  5324. *
  5325. * @param limit - The maximum number of items to return.
  5326. * @returns The created {@link QueryLimitConstraint}.
  5327. */ function Nr(t) {
  5328. return ht("limit", t), $r._create("limit", t, "F" /* LimitType.First */);
  5329. }
  5330. /**
  5331. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  5332. * documents.
  5333. *
  5334. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  5335. * otherwise an exception will be thrown during execution.
  5336. *
  5337. * @param limit - The maximum number of items to return.
  5338. * @returns The created {@link QueryLimitConstraint}.
  5339. */ function Dr(t) {
  5340. return ht("limitToLast", t), $r._create("limitToLast", t, "L" /* LimitType.Last */);
  5341. }
  5342. /**
  5343. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  5344. * result set returned by a Firestore query.
  5345. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  5346. * {@link (startAfter:1)} and can then be passed to {@link query} to create a
  5347. * new query instance that also contains this `QueryStartAtConstraint`.
  5348. */ class Fr extends vr {
  5349. /**
  5350. * @internal
  5351. */
  5352. constructor(
  5353. /** The type of this query constraint */
  5354. t, e, n) {
  5355. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  5356. }
  5357. static _create(t, e, n) {
  5358. return new Fr(t, e, n);
  5359. }
  5360. _apply(t) {
  5361. const e = Cr(t, this.type, this._docOrFields, this._inclusive);
  5362. return new Nn(t.firestore, t.converter, function(t, e) {
  5363. return new _e(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);
  5364. }(t._query, e));
  5365. }
  5366. }
  5367. function xr(...t) {
  5368. return Fr._create("startAt", t,
  5369. /*inclusive=*/ !0);
  5370. }
  5371. function Sr(...t) {
  5372. return Fr._create("startAfter", t,
  5373. /*inclusive=*/ !1);
  5374. }
  5375. /**
  5376. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  5377. * result set returned by a Firestore query.
  5378. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  5379. * {@link (endBefore:1)} and can then be passed to {@link query} to create a new
  5380. * query instance that also contains this `QueryEndAtConstraint`.
  5381. */ class qr extends vr {
  5382. /**
  5383. * @internal
  5384. */
  5385. constructor(
  5386. /** The type of this query constraint */
  5387. t, e, n) {
  5388. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  5389. }
  5390. static _create(t, e, n) {
  5391. return new qr(t, e, n);
  5392. }
  5393. _apply(t) {
  5394. const e = Cr(t, this.type, this._docOrFields, this._inclusive);
  5395. return new Nn(t.firestore, t.converter, function(t, e) {
  5396. return new _e(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);
  5397. }(t._query, e));
  5398. }
  5399. }
  5400. function Or(...t) {
  5401. return qr._create("endBefore", t,
  5402. /*inclusive=*/ !1);
  5403. }
  5404. function kr(...t) {
  5405. return qr._create("endAt", t,
  5406. /*inclusive=*/ !0);
  5407. }
  5408. /** Helper function to create a bound from a document or fields */ function Cr(t, e, n, r) {
  5409. if (n[0] = f(n[0]), n[0] instanceof wr) return function(t, e, n, r, s) {
  5410. if (!r) throw new j(N, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);
  5411. const i = [];
  5412. // Because people expect to continue/end a query at the exact document
  5413. // provided, we need to use the implicit sort order rather than the explicit
  5414. // sort order, because it's guaranteed to contain the document key. That way
  5415. // the position becomes unambiguous and the query continues/ends exactly at
  5416. // the provided document. Without the key (by using the explicit sort
  5417. // orders), multiple documents could match the position, yielding duplicate
  5418. // results.
  5419. for (const n of Ie(t)) if (n.field.isKeyField()) i.push(Mt(e, r.key)); else {
  5420. const t = r.data.field(n.field);
  5421. if (Dt(t)) throw new j(V, '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.)');
  5422. if (null === t) {
  5423. const t = n.field.canonicalString();
  5424. throw new j(V, `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.`);
  5425. }
  5426. i.push(t);
  5427. }
  5428. return new Wt(i, s);
  5429. }
  5430. /**
  5431. * Converts a list of field values to a `Bound` for the given query.
  5432. */ (t._query, t.firestore._databaseId, e, n[0]._document, r);
  5433. {
  5434. const s = Kn(t.firestore);
  5435. return function(t, e, n, r, s, i) {
  5436. // Use explicit order by's because it has to match the query the user made
  5437. const o = t.explicitOrderBy;
  5438. if (s.length > o.length) throw new j(V, `Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);
  5439. const u = [];
  5440. for (let i = 0; i < s.length; i++) {
  5441. const c = s[i];
  5442. if (o[i].field.isKeyField()) {
  5443. if ("string" != typeof c) throw new j(V, `Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);
  5444. if (!Ee(t) && -1 !== c.indexOf("/")) throw new j(V, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${c}' contains a slash.`);
  5445. const n = t.path.child(et.fromString(c));
  5446. if (!st.isDocumentKey(n)) throw new j(V, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);
  5447. const s = new st(n);
  5448. u.push(Mt(e, s));
  5449. } else {
  5450. const t = sr(n, r, c);
  5451. u.push(t);
  5452. }
  5453. }
  5454. return new Wt(u, i);
  5455. }
  5456. /**
  5457. * Parses the given `documentIdValue` into a `ReferenceValue`, throwing
  5458. * appropriate errors if the value is anything other than a `DocumentReference`
  5459. * or `string`, or if the string is malformed.
  5460. */ (t._query, t.firestore._databaseId, s, e, n, r);
  5461. }
  5462. }
  5463. function Lr(t, e, n) {
  5464. if ("string" == typeof (n = f(n))) {
  5465. if ("" === n) throw new j(V, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");
  5466. if (!Ee(e) && -1 !== n.indexOf("/")) throw new j(V, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);
  5467. const r = e.path.child(et.fromString(n));
  5468. if (!st.isDocumentKey(r)) throw new j(V, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);
  5469. return Mt(t, new st(r));
  5470. }
  5471. if (n instanceof $n) return Mt(t, n._key);
  5472. throw new j(V, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${ct(n)}.`);
  5473. }
  5474. /**
  5475. * Validates that the value passed into a disjunctive filter satisfies all
  5476. * array requirements.
  5477. */ function Mr(t, e) {
  5478. if (!Array.isArray(t) || 0 === t.length) throw new j(V, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);
  5479. if (t.length > 10) throw new j(V, `Invalid Query. '${e.toString()}' filters support a maximum of 10 elements in the value array.`);
  5480. }
  5481. /**
  5482. * Given an operator, returns the set of operators that cannot be used with it.
  5483. *
  5484. * Operators in a query must adhere to the following set of rules:
  5485. * 1. Only one array operator is allowed.
  5486. * 2. Only one disjunctive operator is allowed.
  5487. * 3. `NOT_EQUAL` cannot be used with another `NOT_EQUAL` operator.
  5488. * 4. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.
  5489. *
  5490. * Array operators: `ARRAY_CONTAINS`, `ARRAY_CONTAINS_ANY`
  5491. * Disjunctive operators: `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`
  5492. */ function Ur(t, e) {
  5493. if (e.isInequality()) {
  5494. const n = be(t), r = e.field;
  5495. if (null !== n && !n.isEqual(r)) throw new j(V, `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 '${r.toString()}'`);
  5496. const s = ve(t);
  5497. null !== s && jr(t, r, s);
  5498. }
  5499. const n = function(t, e) {
  5500. for (const n of t) for (const t of n.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op;
  5501. return null;
  5502. }(t.filters, function(t) {
  5503. switch (t) {
  5504. case "!=" /* Operator.NOT_EQUAL */ :
  5505. return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ];
  5506. case "array-contains" /* Operator.ARRAY_CONTAINS */ :
  5507. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "not-in" /* Operator.NOT_IN */ ];
  5508. case "in" /* Operator.IN */ :
  5509. return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ ];
  5510. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  5511. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ ];
  5512. case "not-in" /* Operator.NOT_IN */ :
  5513. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ];
  5514. default:
  5515. return [];
  5516. }
  5517. }(e.op));
  5518. if (null !== n)
  5519. // Special case when it's a duplicate op to give a slightly clearer error message.
  5520. throw n === e.op ? new j(V, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new j(V, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);
  5521. }
  5522. function jr(t, e, n) {
  5523. if (!n.isEqual(e)) throw new j(V, `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.`);
  5524. }
  5525. function Br(t, e) {
  5526. if (!(e instanceof Er || e instanceof Ar)) throw new j(V, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
  5527. }
  5528. /**
  5529. * @license
  5530. * Copyright 2020 Google LLC
  5531. *
  5532. * Licensed under the Apache License, Version 2.0 (the "License");
  5533. * you may not use this file except in compliance with the License.
  5534. * You may obtain a copy of the License at
  5535. *
  5536. * http://www.apache.org/licenses/LICENSE-2.0
  5537. *
  5538. * Unless required by applicable law or agreed to in writing, software
  5539. * distributed under the License is distributed on an "AS IS" BASIS,
  5540. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5541. * See the License for the specific language governing permissions and
  5542. * limitations under the License.
  5543. */
  5544. /**
  5545. * Converts custom model object of type T into `DocumentData` by applying the
  5546. * converter if it exists.
  5547. *
  5548. * This function is used when converting user objects to `DocumentData`
  5549. * because we want to provide the user with a more specific error message if
  5550. * their `set()` or fails due to invalid data originating from a `toFirestore()`
  5551. * call.
  5552. */
  5553. function Qr(t, e, n) {
  5554. let r;
  5555. // Cast to `any` in order to satisfy the union type constraint on
  5556. // toFirestore().
  5557. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5558. return r = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e,
  5559. r;
  5560. }
  5561. class zr extends class {
  5562. convertValue(t, e = "none") {
  5563. switch (qt(t)) {
  5564. case 0 /* TypeOrder.NullValue */ :
  5565. return null;
  5566. case 1 /* TypeOrder.BooleanValue */ :
  5567. return t.booleanValue;
  5568. case 2 /* TypeOrder.NumberValue */ :
  5569. return Vt(t.integerValue || t.doubleValue);
  5570. case 3 /* TypeOrder.TimestampValue */ :
  5571. return this.convertTimestamp(t.timestampValue);
  5572. case 4 /* TypeOrder.ServerTimestampValue */ :
  5573. return this.convertServerTimestamp(t, e);
  5574. case 5 /* TypeOrder.StringValue */ :
  5575. return t.stringValue;
  5576. case 6 /* TypeOrder.BlobValue */ :
  5577. return this.convertBytes($t(t.bytesValue));
  5578. case 7 /* TypeOrder.RefValue */ :
  5579. return this.convertReference(t.referenceValue);
  5580. case 8 /* TypeOrder.GeoPointValue */ :
  5581. return this.convertGeoPoint(t.geoPointValue);
  5582. case 9 /* TypeOrder.ArrayValue */ :
  5583. return this.convertArray(t.arrayValue, e);
  5584. case 10 /* TypeOrder.ObjectValue */ :
  5585. return this.convertObject(t.mapValue, e);
  5586. default:
  5587. throw E();
  5588. }
  5589. }
  5590. convertObject(t, e) {
  5591. const n = {};
  5592. return It(t.fields, ((t, r) => {
  5593. n[t] = this.convertValue(r, e);
  5594. })), n;
  5595. }
  5596. convertGeoPoint(t) {
  5597. return new Un(Vt(t.latitude), Vt(t.longitude));
  5598. }
  5599. convertArray(t, e) {
  5600. return (t.values || []).map((t => this.convertValue(t, e)));
  5601. }
  5602. convertServerTimestamp(t, e) {
  5603. switch (e) {
  5604. case "previous":
  5605. const n = Ft(t);
  5606. return null == n ? null : this.convertValue(n, e);
  5607. case "estimate":
  5608. return this.convertTimestamp(xt(t));
  5609. default:
  5610. return null;
  5611. }
  5612. }
  5613. convertTimestamp(t) {
  5614. const e = Pt(t);
  5615. return new Nt(e.seconds, e.nanos);
  5616. }
  5617. convertDocumentKey(t, e) {
  5618. const n = et.fromString(t);
  5619. I(hn(n));
  5620. const r = new Z(n.get(1), n.get(3)), s = new st(n.popFirst(5));
  5621. return r.isEqual(e) ||
  5622. // TODO(b/64130202): Somehow support foreign references.
  5623. _(`Document ${s} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`),
  5624. s;
  5625. }
  5626. } {
  5627. constructor(t) {
  5628. super(), this.firestore = t;
  5629. }
  5630. convertBytes(t) {
  5631. return new kn(t);
  5632. }
  5633. convertReference(t) {
  5634. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  5635. return new $n(this.firestore, /* converter= */ null, e);
  5636. }
  5637. }
  5638. /**
  5639. * Reads the document referred to by the specified document reference.
  5640. *
  5641. * All documents are directly fetched from the server, even if the document was
  5642. * previously read or modified. Recent modifications are only reflected in the
  5643. * retrieved `DocumentSnapshot` if they have already been applied by the
  5644. * backend. If the client is offline, the read fails. If you like to use
  5645. * caching or see local modifications, please use the full Firestore SDK.
  5646. *
  5647. * @param reference - The reference of the document to fetch.
  5648. * @returns A Promise resolved with a `DocumentSnapshot` containing the current
  5649. * document contents.
  5650. */ function Wr(t) {
  5651. const e = _n((t = at(t, $n)).firestore), n = new zr(t.firestore);
  5652. return mn(e, [ t._key ]).then((e => {
  5653. I(1 === e.length);
  5654. const r = e[0];
  5655. return new wr(t.firestore, n, t._key, r.isFoundDocument() ? r : null, t.converter);
  5656. }));
  5657. }
  5658. /**
  5659. * Executes the query and returns the results as a {@link QuerySnapshot}.
  5660. *
  5661. * All queries are executed directly by the server, even if the the query was
  5662. * previously executed. Recent modifications are only reflected in the retrieved
  5663. * results if they have already been applied by the backend. If the client is
  5664. * offline, the operation fails. To see previously cached result and local
  5665. * modifications, use the full Firestore SDK.
  5666. *
  5667. * @param query - The `Query` to execute.
  5668. * @returns A Promise that will be resolved with the results of the query.
  5669. */ function Gr(t) {
  5670. !function(t) {
  5671. if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new j(C, "limitToLast() queries require specifying at least one orderBy() clause");
  5672. }((t = at(t, Nn))._query);
  5673. const e = _n(t.firestore), n = new zr(t.firestore);
  5674. return pn(e, t._query).then((e => {
  5675. const r = e.map((e => new mr(t.firestore, n, e.key, e, t.converter)));
  5676. return "L" /* LimitType.Last */ === t._query.limitType &&
  5677. // Limit to last queries reverse the orderBy constraint that was
  5678. // specified by the user. As such, we need to reverse the order of the
  5679. // results to return the documents in the expected order.
  5680. r.reverse(), new pr(t, r);
  5681. }));
  5682. }
  5683. function Kr(t, e, n) {
  5684. const r = Qr((t = at(t, $n)).converter, e, n), s = Yn(Kn(t.firestore), "setDoc", t._key, r, null !== t.converter, n);
  5685. return wn(_n(t.firestore), [ s.toMutation(t._key, Se.none()) ]);
  5686. }
  5687. function Yr(t, e, n, ...r) {
  5688. const s = Kn((t = at(t, $n)).firestore);
  5689. // For Compat types, we have to "extract" the underlying types before
  5690. // performing validation.
  5691. let i;
  5692. i = "string" == typeof (e = f(e)) || e instanceof Cn ? rr(s, "updateDoc", t._key, e, n, r) : nr(s, "updateDoc", t._key, e);
  5693. return wn(_n(t.firestore), [ i.toMutation(t._key, Se.exists(!0)) ]);
  5694. }
  5695. /**
  5696. * Deletes the document referred to by the specified `DocumentReference`.
  5697. *
  5698. * The deletion will only be reflected in document reads that occur after the
  5699. * returned promise resolves. If the client is offline, the
  5700. * delete fails. If you would like to see local modifications or buffer writes
  5701. * until the client is online, use the full Firestore SDK.
  5702. *
  5703. * @param reference - A reference to the document to delete.
  5704. * @returns A `Promise` resolved once the document has been successfully
  5705. * deleted from the backend.
  5706. */ function Hr(t) {
  5707. return wn(_n((t = at(t, $n)).firestore), [ new Ce(t._key, Se.none()) ]);
  5708. }
  5709. /**
  5710. * Add a new document to specified `CollectionReference` with the given data,
  5711. * assigning it a document ID automatically.
  5712. *
  5713. * The result of this write will only be reflected in document reads that occur
  5714. * after the returned promise resolves. If the client is offline, the
  5715. * write fails. If you would like to see local modifications or buffer writes
  5716. * until the client is online, use the full Firestore SDK.
  5717. *
  5718. * @param reference - A reference to the collection to add this document to.
  5719. * @param data - An Object containing the data for the new document.
  5720. * @throws Error - If the provided input is not a valid Firestore document.
  5721. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  5722. * newly created document after it has been written to the backend.
  5723. */ function Jr(t, e) {
  5724. const n = Sn(t = at(t, Dn)), r = Qr(t.converter, e), s = Yn(Kn(t.firestore), "addDoc", n._key, r, null !== n.converter, {});
  5725. return wn(_n(t.firestore), [ s.toMutation(n._key, Se.exists(!1)) ]).then((() => n));
  5726. }
  5727. /**
  5728. * @license
  5729. * Copyright 2022 Google LLC
  5730. *
  5731. * Licensed under the Apache License, Version 2.0 (the "License");
  5732. * you may not use this file except in compliance with the License.
  5733. * You may obtain a copy of the License at
  5734. *
  5735. * http://www.apache.org/licenses/LICENSE-2.0
  5736. *
  5737. * Unless required by applicable law or agreed to in writing, software
  5738. * distributed under the License is distributed on an "AS IS" BASIS,
  5739. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5740. * See the License for the specific language governing permissions and
  5741. * limitations under the License.
  5742. */
  5743. /**
  5744. * Calculates the number of documents in the result set of the given query,
  5745. * without actually downloading the documents.
  5746. *
  5747. * Using this function to count the documents is efficient because only the
  5748. * final count, not the documents' data, is downloaded. This function can even
  5749. * count the documents if the result set would be prohibitively large to
  5750. * download entirely (e.g. thousands of documents).
  5751. *
  5752. * @param query - The query whose result set size to calculate.
  5753. * @returns A Promise that will be resolved with the count; the count can be
  5754. * retrieved from `snapshot.data().count`, where `snapshot` is the
  5755. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  5756. */ function Xr(t) {
  5757. const e = at(t.firestore, bn), n = _n(e), r = new zr(e);
  5758. return new Vn(t, n, r).run();
  5759. }
  5760. /**
  5761. * Compares two `AggregateQuerySnapshot` instances for equality.
  5762. *
  5763. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  5764. * underlying queries that compare equal, and the same data.
  5765. *
  5766. * @param left - The first `AggregateQuerySnapshot` to compare.
  5767. * @param right - The second `AggregateQuerySnapshot` to compare.
  5768. *
  5769. * @returns `true` if the objects are "equal", as defined above, or `false`
  5770. * otherwise.
  5771. */ function Zr(t, e) {
  5772. return On(t.query, e.query) && d(t.data(), e.data());
  5773. }
  5774. /**
  5775. * @license
  5776. * Copyright 2020 Google LLC
  5777. *
  5778. * Licensed under the Apache License, Version 2.0 (the "License");
  5779. * you may not use this file except in compliance with the License.
  5780. * You may obtain a copy of the License at
  5781. *
  5782. * http://www.apache.org/licenses/LICENSE-2.0
  5783. *
  5784. * Unless required by applicable law or agreed to in writing, software
  5785. * distributed under the License is distributed on an "AS IS" BASIS,
  5786. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5787. * See the License for the specific language governing permissions and
  5788. * limitations under the License.
  5789. */
  5790. /**
  5791. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  5792. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  5793. */ function ts() {
  5794. return new Hn("deleteField");
  5795. }
  5796. /**
  5797. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  5798. * include a server-generated timestamp in the written data.
  5799. */ function es() {
  5800. return new Xn("serverTimestamp");
  5801. }
  5802. /**
  5803. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  5804. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  5805. * value that already exists on the server. Each specified element that doesn't
  5806. * already exist in the array will be added to the end. If the field being
  5807. * modified is not already an array it will be overwritten with an array
  5808. * containing exactly the specified elements.
  5809. *
  5810. * @param elements - The elements to union into the array.
  5811. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  5812. * `updateDoc()`.
  5813. */ function ns(...t) {
  5814. // NOTE: We don't actually parse the data until it's used in set() or
  5815. // update() since we'd need the Firestore instance to do this.
  5816. return new Zn("arrayUnion", t);
  5817. }
  5818. /**
  5819. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  5820. * updateDoc:1} that tells the server to remove the given elements from any
  5821. * array value that already exists on the server. All instances of each element
  5822. * specified will be removed from the array. If the field being modified is not
  5823. * already an array it will be overwritten with an empty array.
  5824. *
  5825. * @param elements - The elements to remove from the array.
  5826. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  5827. * `updateDoc()`
  5828. */ function rs(...t) {
  5829. // NOTE: We don't actually parse the data until it's used in set() or
  5830. // update() since we'd need the Firestore instance to do this.
  5831. return new tr("arrayRemove", t);
  5832. }
  5833. /**
  5834. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  5835. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  5836. * the given value.
  5837. *
  5838. * If either the operand or the current field value uses floating point
  5839. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  5840. * integers, values outside of JavaScript's safe number range
  5841. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  5842. * precision loss. Furthermore, once processed by the Firestore backend, all
  5843. * integer operations are capped between -2^63 and 2^63-1.
  5844. *
  5845. * If the current field value is not of type `number`, or if the field does not
  5846. * yet exist, the transformation sets the field to the given value.
  5847. *
  5848. * @param n - The value to increment by.
  5849. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  5850. * `updateDoc()`
  5851. */ function ss(t) {
  5852. return new er("increment", t);
  5853. }
  5854. /**
  5855. * @license
  5856. * Copyright 2020 Google LLC
  5857. *
  5858. * Licensed under the Apache License, Version 2.0 (the "License");
  5859. * you may not use this file except in compliance with the License.
  5860. * You may obtain a copy of the License at
  5861. *
  5862. * http://www.apache.org/licenses/LICENSE-2.0
  5863. *
  5864. * Unless required by applicable law or agreed to in writing, software
  5865. * distributed under the License is distributed on an "AS IS" BASIS,
  5866. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5867. * See the License for the specific language governing permissions and
  5868. * limitations under the License.
  5869. */
  5870. /**
  5871. * A write batch, used to perform multiple writes as a single atomic unit.
  5872. *
  5873. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  5874. * provides methods for adding writes to the write batch. None of the writes
  5875. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  5876. * called.
  5877. */ class is {
  5878. /** @hideconstructor */
  5879. constructor(t, e) {
  5880. this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1,
  5881. this._dataReader = Kn(t);
  5882. }
  5883. set(t, e, n) {
  5884. this._verifyNotCommitted();
  5885. const r = os(t, this._firestore), s = Qr(r.converter, e, n), i = Yn(this._dataReader, "WriteBatch.set", r._key, s, null !== r.converter, n);
  5886. return this._mutations.push(i.toMutation(r._key, Se.none())), this;
  5887. }
  5888. update(t, e, n, ...r) {
  5889. this._verifyNotCommitted();
  5890. const s = os(t, this._firestore);
  5891. // For Compat types, we have to "extract" the underlying types before
  5892. // performing validation.
  5893. let i;
  5894. return i = "string" == typeof (e = f(e)) || e instanceof Cn ? rr(this._dataReader, "WriteBatch.update", s._key, e, n, r) : nr(this._dataReader, "WriteBatch.update", s._key, e),
  5895. this._mutations.push(i.toMutation(s._key, Se.exists(!0))), this;
  5896. }
  5897. /**
  5898. * Deletes the document referred to by the provided {@link DocumentReference}.
  5899. *
  5900. * @param documentRef - A reference to the document to be deleted.
  5901. * @returns This `WriteBatch` instance. Used for chaining method calls.
  5902. */ delete(t) {
  5903. this._verifyNotCommitted();
  5904. const e = os(t, this._firestore);
  5905. return this._mutations = this._mutations.concat(new Ce(e._key, Se.none())), this;
  5906. }
  5907. /**
  5908. * Commits all of the writes in this write batch as a single atomic unit.
  5909. *
  5910. * The result of these writes will only be reflected in document reads that
  5911. * occur after the returned promise resolves. If the client is offline, the
  5912. * write fails. If you would like to see local modifications or buffer writes
  5913. * until the client is online, use the full Firestore SDK.
  5914. *
  5915. * @returns A `Promise` resolved once all of the writes in the batch have been
  5916. * successfully written to the backend as an atomic unit (note that it won't
  5917. * resolve while you're offline).
  5918. */ commit() {
  5919. return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();
  5920. }
  5921. _verifyNotCommitted() {
  5922. if (this._committed) throw new j(q, "A write batch can no longer be used after commit() has been called.");
  5923. }
  5924. }
  5925. function os(t, e) {
  5926. if ((t = f(t)).firestore !== e) throw new j(V, "Provided document reference is from a different Firestore instance.");
  5927. return t;
  5928. }
  5929. /**
  5930. * Creates a write batch, used for performing multiple writes as a single
  5931. * atomic operation. The maximum number of writes allowed in a single WriteBatch
  5932. * is 500.
  5933. *
  5934. * The result of these writes will only be reflected in document reads that
  5935. * occur after the returned promise resolves. If the client is offline, the
  5936. * write fails. If you would like to see local modifications or buffer writes
  5937. * until the client is online, use the full Firestore SDK.
  5938. *
  5939. * @returns A `WriteBatch` that can be used to atomically execute multiple
  5940. * writes.
  5941. */ function us(t) {
  5942. const e = _n(t = at(t, bn));
  5943. return new is(t, (t => wn(e, t)));
  5944. }
  5945. /**
  5946. * @license
  5947. * Copyright 2017 Google LLC
  5948. *
  5949. * Licensed under the Apache License, Version 2.0 (the "License");
  5950. * you may not use this file except in compliance with the License.
  5951. * You may obtain a copy of the License at
  5952. *
  5953. * http://www.apache.org/licenses/LICENSE-2.0
  5954. *
  5955. * Unless required by applicable law or agreed to in writing, software
  5956. * distributed under the License is distributed on an "AS IS" BASIS,
  5957. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5958. * See the License for the specific language governing permissions and
  5959. * limitations under the License.
  5960. */
  5961. /**
  5962. * Internal transaction object responsible for accumulating the mutations to
  5963. * perform and the base versions for any documents read.
  5964. */ class cs {
  5965. constructor(t) {
  5966. this.datastore = t,
  5967. // The version of each document that was read during this transaction.
  5968. this.readVersions = new Map, this.mutations = [], this.committed = !1,
  5969. /**
  5970. * A deferred usage error that occurred previously in this transaction that
  5971. * will cause the transaction to fail once it actually commits.
  5972. */
  5973. this.lastWriteError = null,
  5974. /**
  5975. * Set of documents that have been written in the transaction.
  5976. *
  5977. * When there's more than one write to the same key in a transaction, any
  5978. * writes after the first are handled differently.
  5979. */
  5980. this.writtenDocs = new Set;
  5981. }
  5982. async lookup(t) {
  5983. if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new j(V, "Firestore transactions require all reads to be executed before all writes.");
  5984. const e = await mn(this.datastore, t);
  5985. return e.forEach((t => this.recordVersion(t))), e;
  5986. }
  5987. set(t, e) {
  5988. this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  5989. }
  5990. update(t, e) {
  5991. try {
  5992. this.write(e.toMutation(t, this.preconditionForUpdate(t)));
  5993. } catch (t) {
  5994. this.lastWriteError = t;
  5995. }
  5996. this.writtenDocs.add(t.toString());
  5997. }
  5998. delete(t) {
  5999. this.write(new Ce(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  6000. }
  6001. async commit() {
  6002. if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;
  6003. const t = this.readVersions;
  6004. // For each mutation, note that the doc was written.
  6005. this.mutations.forEach((e => {
  6006. t.delete(e.key.toString());
  6007. })),
  6008. // For each document that was read but not written to, we want to perform
  6009. // a `verify` operation.
  6010. t.forEach(((t, e) => {
  6011. const n = st.fromPath(e);
  6012. this.mutations.push(new Le(n, this.precondition(n)));
  6013. })), await wn(this.datastore, this.mutations), this.committed = !0;
  6014. }
  6015. recordVersion(t) {
  6016. let e;
  6017. if (t.isFoundDocument()) e = t.version; else {
  6018. if (!t.isNoDocument()) throw E();
  6019. // Represent a deleted doc using SnapshotVersion.min().
  6020. e = ce.min();
  6021. }
  6022. const n = this.readVersions.get(t.key.toString());
  6023. if (n) {
  6024. if (!e.isEqual(n))
  6025. // This transaction will fail no matter what.
  6026. throw new j(O, "Document version changed between two reads.");
  6027. } else this.readVersions.set(t.key.toString(), e);
  6028. }
  6029. /**
  6030. * Returns the version of this document when it was read in this transaction,
  6031. * as a precondition, or no precondition if it was not read.
  6032. */ precondition(t) {
  6033. const e = this.readVersions.get(t.toString());
  6034. return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(ce.min()) ? Se.exists(!1) : Se.updateTime(e) : Se.none();
  6035. }
  6036. /**
  6037. * Returns the precondition for a document if the operation is an update.
  6038. */ preconditionForUpdate(t) {
  6039. const e = this.readVersions.get(t.toString());
  6040. // The first time a document is written, we want to take into account the
  6041. // read time and existence
  6042. if (!this.writtenDocs.has(t.toString()) && e) {
  6043. if (e.isEqual(ce.min()))
  6044. // The document doesn't exist, so fail the transaction.
  6045. // This has to be validated locally because you can't send a
  6046. // precondition that a document does not exist without changing the
  6047. // semantics of the backend write to be an insert. This is the reverse
  6048. // of what we want, since we want to assert that the document doesn't
  6049. // exist but then send the update and have it fail. Since we can't
  6050. // express that to the backend, we have to validate locally.
  6051. // Note: this can change once we can send separate verify writes in the
  6052. // transaction.
  6053. throw new j(V, "Can't update a document that doesn't exist.");
  6054. // Document exists, base precondition on document update time.
  6055. return Se.updateTime(e);
  6056. }
  6057. // Document was not read, so we just use the preconditions for a blind
  6058. // update.
  6059. return Se.exists(!0);
  6060. }
  6061. write(t) {
  6062. this.ensureCommitNotCalled(), this.mutations.push(t);
  6063. }
  6064. ensureCommitNotCalled() {}
  6065. }
  6066. /**
  6067. * @license
  6068. * Copyright 2022 Google LLC
  6069. *
  6070. * Licensed under the Apache License, Version 2.0 (the "License");
  6071. * you may not use this file except in compliance with the License.
  6072. * You may obtain a copy of the License at
  6073. *
  6074. * http://www.apache.org/licenses/LICENSE-2.0
  6075. *
  6076. * Unless required by applicable law or agreed to in writing, software
  6077. * distributed under the License is distributed on an "AS IS" BASIS,
  6078. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6079. * See the License for the specific language governing permissions and
  6080. * limitations under the License.
  6081. */ const as = {
  6082. maxAttempts: 5
  6083. };
  6084. /**
  6085. * @license
  6086. * Copyright 2019 Google LLC
  6087. *
  6088. * Licensed under the Apache License, Version 2.0 (the "License");
  6089. * you may not use this file except in compliance with the License.
  6090. * You may obtain a copy of the License at
  6091. *
  6092. * http://www.apache.org/licenses/LICENSE-2.0
  6093. *
  6094. * Unless required by applicable law or agreed to in writing, software
  6095. * distributed under the License is distributed on an "AS IS" BASIS,
  6096. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6097. * See the License for the specific language governing permissions and
  6098. * limitations under the License.
  6099. */
  6100. /**
  6101. * TransactionRunner encapsulates the logic needed to run and retry transactions
  6102. * with backoff.
  6103. */
  6104. class hs {
  6105. constructor(t, e, n, r, s) {
  6106. this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = r,
  6107. this.deferred = s, this.yt = n.maxAttempts, this.gt = new fn(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */);
  6108. }
  6109. /** Runs the transaction and sets the result on deferred. */ run() {
  6110. this.yt -= 1, this._t();
  6111. }
  6112. _t() {
  6113. this.gt.H((async () => {
  6114. const t = new cs(this.datastore), e = this.vt(t);
  6115. e && e.then((e => {
  6116. this.asyncQueue.enqueueAndForget((() => t.commit().then((() => {
  6117. this.deferred.resolve(e);
  6118. })).catch((t => {
  6119. this.bt(t);
  6120. }))));
  6121. })).catch((t => {
  6122. this.bt(t);
  6123. }));
  6124. }));
  6125. }
  6126. vt(t) {
  6127. try {
  6128. const e = this.updateFunction(t);
  6129. return !lt(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")),
  6130. null);
  6131. } catch (t) {
  6132. // Do not retry errors thrown by user provided updateFunction.
  6133. return this.deferred.reject(t), null;
  6134. }
  6135. }
  6136. bt(t) {
  6137. this.yt > 0 && this.Et(t) ? (this.yt -= 1, this.asyncQueue.enqueueAndForget((() => (this._t(),
  6138. Promise.resolve())))) : this.deferred.reject(t);
  6139. }
  6140. Et(t) {
  6141. if ("FirebaseError" === t.name) {
  6142. // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
  6143. // non-matching document versions with ABORTED. These errors should be retried.
  6144. const e = t.code;
  6145. return "aborted" === e || "failed-precondition" === e || "already-exists" === e || !
  6146. /**
  6147. * Determines whether an error code represents a permanent error when received
  6148. * in response to a non-write operation.
  6149. *
  6150. * See isPermanentWriteError for classifying write errors.
  6151. */
  6152. function(t) {
  6153. switch (t) {
  6154. default:
  6155. return E();
  6156. case R:
  6157. case P:
  6158. case $:
  6159. case S:
  6160. case L:
  6161. case M:
  6162. // Unauthenticated means something went wrong with our token and we need
  6163. // to retry with new credentials which will happen automatically.
  6164. case x:
  6165. return !1;
  6166. case V:
  6167. case N:
  6168. case D:
  6169. case F:
  6170. case q:
  6171. // Aborted might be retried in some scenarios, but that is dependant on
  6172. // the context and should handled individually by the calling code.
  6173. // See https://cloud.google.com/apis/design/errors.
  6174. case O:
  6175. case k:
  6176. case C:
  6177. case U:
  6178. return !0;
  6179. }
  6180. }(e);
  6181. }
  6182. return !1;
  6183. }
  6184. }
  6185. /**
  6186. * @license
  6187. * Copyright 2020 Google LLC
  6188. *
  6189. * Licensed under the Apache License, Version 2.0 (the "License");
  6190. * you may not use this file except in compliance with the License.
  6191. * You may obtain a copy of the License at
  6192. *
  6193. * http://www.apache.org/licenses/LICENSE-2.0
  6194. *
  6195. * Unless required by applicable law or agreed to in writing, software
  6196. * distributed under the License is distributed on an "AS IS" BASIS,
  6197. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6198. * See the License for the specific language governing permissions and
  6199. * limitations under the License.
  6200. */
  6201. /** The Platform's 'document' implementation or null if not available. */ function ls() {
  6202. // `document` is not always available, e.g. in ReactNative and WebWorkers.
  6203. // eslint-disable-next-line no-restricted-globals
  6204. return "undefined" != typeof document ? document : null;
  6205. }
  6206. /**
  6207. * @license
  6208. * Copyright 2017 Google LLC
  6209. *
  6210. * Licensed under the Apache License, Version 2.0 (the "License");
  6211. * you may not use this file except in compliance with the License.
  6212. * You may obtain a copy of the License at
  6213. *
  6214. * http://www.apache.org/licenses/LICENSE-2.0
  6215. *
  6216. * Unless required by applicable law or agreed to in writing, software
  6217. * distributed under the License is distributed on an "AS IS" BASIS,
  6218. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6219. * See the License for the specific language governing permissions and
  6220. * limitations under the License.
  6221. */
  6222. /**
  6223. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  6224. *
  6225. * It is created via DelayedOperation.createAndSchedule().
  6226. *
  6227. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  6228. *
  6229. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  6230. * in newer versions of TypeScript defines `finally`, which is not available in
  6231. * IE.
  6232. */ class fs {
  6233. constructor(t, e, n, r, s) {
  6234. this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = r, this.removalCallback = s,
  6235. this.deferred = new B, this.then = this.deferred.promise.then.bind(this.deferred.promise),
  6236. // It's normal for the deferred promise to be canceled (due to cancellation)
  6237. // and so we attach a dummy catch callback to avoid
  6238. // 'UnhandledPromiseRejectionWarning' log spam.
  6239. this.deferred.promise.catch((t => {}));
  6240. }
  6241. /**
  6242. * Creates and returns a DelayedOperation that has been scheduled to be
  6243. * executed on the provided asyncQueue after the provided delayMs.
  6244. *
  6245. * @param asyncQueue - The queue to schedule the operation on.
  6246. * @param id - A Timer ID identifying the type of operation this is.
  6247. * @param delayMs - The delay (ms) before the operation should be scheduled.
  6248. * @param op - The operation to run.
  6249. * @param removalCallback - A callback to be called synchronously once the
  6250. * operation is executed or canceled, notifying the AsyncQueue to remove it
  6251. * from its delayedOperations list.
  6252. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  6253. * the DelayedOperation class public.
  6254. */ static createAndSchedule(t, e, n, r, s) {
  6255. const i = Date.now() + n, o = new fs(t, e, i, r, s);
  6256. return o.start(n), o;
  6257. }
  6258. /**
  6259. * Starts the timer. This is called immediately after construction by
  6260. * createAndSchedule().
  6261. */ start(t) {
  6262. this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t);
  6263. }
  6264. /**
  6265. * Queues the operation to run immediately (if it hasn't already been run or
  6266. * canceled).
  6267. */ skipDelay() {
  6268. return this.handleDelayElapsed();
  6269. }
  6270. /**
  6271. * Cancels the operation if it hasn't already been executed or canceled. The
  6272. * promise will be rejected.
  6273. *
  6274. * As long as the operation has not yet been run, calling cancel() provides a
  6275. * guarantee that the operation will not be run.
  6276. */ cancel(t) {
  6277. null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new j(R, "Operation cancelled" + (t ? ": " + t : ""))));
  6278. }
  6279. handleDelayElapsed() {
  6280. this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(),
  6281. this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve()));
  6282. }
  6283. clearTimeout() {
  6284. null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle),
  6285. this.timerHandle = null);
  6286. }
  6287. }
  6288. /**
  6289. * @license
  6290. * Copyright 2020 Google LLC
  6291. *
  6292. * Licensed under the Apache License, Version 2.0 (the "License");
  6293. * you may not use this file except in compliance with the License.
  6294. * You may obtain a copy of the License at
  6295. *
  6296. * http://www.apache.org/licenses/LICENSE-2.0
  6297. *
  6298. * Unless required by applicable law or agreed to in writing, software
  6299. * distributed under the License is distributed on an "AS IS" BASIS,
  6300. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6301. * See the License for the specific language governing permissions and
  6302. * limitations under the License.
  6303. */ class ds {
  6304. constructor() {
  6305. // The last promise in the queue.
  6306. this.It = Promise.resolve(),
  6307. // A list of retryable operations. Retryable operations are run in order and
  6308. // retried with backoff.
  6309. this.At = [],
  6310. // Is this AsyncQueue being shut down? Once it is set to true, it will not
  6311. // be changed again.
  6312. this.Tt = !1,
  6313. // Operations scheduled to be queued in the future. Operations are
  6314. // automatically removed after they are run or canceled.
  6315. this.Rt = [],
  6316. // visible for testing
  6317. this.Pt = null,
  6318. // Flag set while there's an outstanding AsyncQueue operation, used for
  6319. // assertion sanity-checks.
  6320. this.Vt = !1,
  6321. // Enabled during shutdown on Safari to prevent future access to IndexedDB.
  6322. this.$t = !1,
  6323. // List of TimerIds to fast-forward delays for.
  6324. this.Nt = [],
  6325. // Backoff timer used to schedule retries for retryable operations
  6326. this.gt = new fn(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */),
  6327. // Visibility handler that triggers an immediate retry of all retryable
  6328. // operations. Meant to speed up recovery when we regain file system access
  6329. // after page comes into foreground.
  6330. this.Dt = () => {
  6331. const t = ls();
  6332. t && g("AsyncQueue", "Visibility state changed to " + t.visibilityState), this.gt.X();
  6333. };
  6334. const t = ls();
  6335. t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.Dt);
  6336. }
  6337. get isShuttingDown() {
  6338. return this.Tt;
  6339. }
  6340. /**
  6341. * Adds a new operation to the queue without waiting for it to complete (i.e.
  6342. * we ignore the Promise result).
  6343. */ enqueueAndForget(t) {
  6344. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  6345. this.enqueue(t);
  6346. }
  6347. enqueueAndForgetEvenWhileRestricted(t) {
  6348. this.Ft(),
  6349. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  6350. this.xt(t);
  6351. }
  6352. enterRestrictedMode(t) {
  6353. if (!this.Tt) {
  6354. this.Tt = !0, this.$t = t || !1;
  6355. const e = ls();
  6356. e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Dt);
  6357. }
  6358. }
  6359. enqueue(t) {
  6360. if (this.Ft(), this.Tt)
  6361. // Return a Promise which never resolves.
  6362. return new Promise((() => {}));
  6363. // Create a deferred Promise that we can return to the callee. This
  6364. // allows us to return a "hanging Promise" only to the callee and still
  6365. // advance the queue even when the operation is not run.
  6366. const e = new B;
  6367. return this.xt((() => this.Tt && this.$t ? Promise.resolve() : (t().then(e.resolve, e.reject),
  6368. e.promise))).then((() => e.promise));
  6369. }
  6370. enqueueRetryable(t) {
  6371. this.enqueueAndForget((() => (this.At.push(t), this.St())));
  6372. }
  6373. /**
  6374. * Runs the next operation from the retryable queue. If the operation fails,
  6375. * reschedules with backoff.
  6376. */ async St() {
  6377. if (0 !== this.At.length) {
  6378. try {
  6379. await this.At[0](), this.At.shift(), this.gt.reset();
  6380. } catch (t) {
  6381. if (!
  6382. /**
  6383. * @license
  6384. * Copyright 2017 Google LLC
  6385. *
  6386. * Licensed under the Apache License, Version 2.0 (the "License");
  6387. * you may not use this file except in compliance with the License.
  6388. * You may obtain a copy of the License at
  6389. *
  6390. * http://www.apache.org/licenses/LICENSE-2.0
  6391. *
  6392. * Unless required by applicable law or agreed to in writing, software
  6393. * distributed under the License is distributed on an "AS IS" BASIS,
  6394. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6395. * See the License for the specific language governing permissions and
  6396. * limitations under the License.
  6397. */
  6398. /** Verifies whether `e` is an IndexedDbTransactionError. */
  6399. function(t) {
  6400. // Use name equality, as instanceof checks on errors don't work with errors
  6401. // that wrap other errors.
  6402. return "IndexedDbTransactionError" === t.name;
  6403. }
  6404. /**
  6405. * @license
  6406. * Copyright 2020 Google LLC
  6407. *
  6408. * Licensed under the Apache License, Version 2.0 (the "License");
  6409. * you may not use this file except in compliance with the License.
  6410. * You may obtain a copy of the License at
  6411. *
  6412. * http://www.apache.org/licenses/LICENSE-2.0
  6413. *
  6414. * Unless required by applicable law or agreed to in writing, software
  6415. * distributed under the License is distributed on an "AS IS" BASIS,
  6416. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6417. * See the License for the specific language governing permissions and
  6418. * limitations under the License.
  6419. */ (t)) throw t;
  6420. // Failure will be handled by AsyncQueue
  6421. g("AsyncQueue", "Operation failed with retryable error: " + t);
  6422. }
  6423. this.At.length > 0 &&
  6424. // If there are additional operations, we re-schedule `retryNextOp()`.
  6425. // This is necessary to run retryable operations that failed during
  6426. // their initial attempt since we don't know whether they are already
  6427. // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
  6428. // needs to be re-run, we will run `op1`, `op1`, `op2` using the
  6429. // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
  6430. // call scheduled here.
  6431. // Since `backoffAndRun()` cancels an existing backoff and schedules a
  6432. // new backoff on every call, there is only ever a single additional
  6433. // operation in the queue.
  6434. this.gt.H((() => this.St()));
  6435. }
  6436. }
  6437. xt(t) {
  6438. const e = this.It.then((() => (this.Vt = !0, t().catch((t => {
  6439. this.Pt = t, this.Vt = !1;
  6440. const e =
  6441. /**
  6442. * Chrome includes Error.message in Error.stack. Other browsers do not.
  6443. * This returns expected output of message + stack when available.
  6444. * @param error - Error or FirestoreError
  6445. */
  6446. function(t) {
  6447. let e = t.message || "";
  6448. t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack);
  6449. return e;
  6450. }
  6451. /**
  6452. * @license
  6453. * Copyright 2020 Google LLC
  6454. *
  6455. * Licensed under the Apache License, Version 2.0 (the "License");
  6456. * you may not use this file except in compliance with the License.
  6457. * You may obtain a copy of the License at
  6458. *
  6459. * http://www.apache.org/licenses/LICENSE-2.0
  6460. *
  6461. * Unless required by applicable law or agreed to in writing, software
  6462. * distributed under the License is distributed on an "AS IS" BASIS,
  6463. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6464. * See the License for the specific language governing permissions and
  6465. * limitations under the License.
  6466. */
  6467. // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
  6468. // legacy SDK.
  6469. /**
  6470. * A reference to a transaction.
  6471. *
  6472. * The `Transaction` object passed to a transaction's `updateFunction` provides
  6473. * the methods to read and write data within the transaction context. See
  6474. * {@link runTransaction}.
  6475. */ (t);
  6476. // Re-throw the error so that this.tail becomes a rejected Promise and
  6477. // all further attempts to chain (via .then) will just short-circuit
  6478. // and return the rejected Promise.
  6479. throw _("INTERNAL UNHANDLED ERROR: ", e), t;
  6480. })).then((t => (this.Vt = !1, t))))));
  6481. return this.It = e, e;
  6482. }
  6483. enqueueAfterDelay(t, e, n) {
  6484. this.Ft(),
  6485. // Fast-forward delays for timerIds that have been overriden.
  6486. this.Nt.indexOf(t) > -1 && (e = 0);
  6487. const r = fs.createAndSchedule(this, t, e, n, (t => this.qt(t)));
  6488. return this.Rt.push(r), r;
  6489. }
  6490. Ft() {
  6491. this.Pt && E();
  6492. }
  6493. verifyOperationInProgress() {}
  6494. /**
  6495. * Waits until all currently queued tasks are finished executing. Delayed
  6496. * operations are not run.
  6497. */ async Ot() {
  6498. // Operations in the queue prior to draining may have enqueued additional
  6499. // operations. Keep draining the queue until the tail is no longer advanced,
  6500. // which indicates that no more new operations were enqueued and that all
  6501. // operations were executed.
  6502. let t;
  6503. do {
  6504. t = this.It, await t;
  6505. } while (t !== this.It);
  6506. }
  6507. /**
  6508. * For Tests: Determine if a delayed operation with a particular TimerId
  6509. * exists.
  6510. */ kt(t) {
  6511. for (const e of this.Rt) if (e.timerId === t) return !0;
  6512. return !1;
  6513. }
  6514. /**
  6515. * For Tests: Runs some or all delayed operations early.
  6516. *
  6517. * @param lastTimerId - Delayed operations up to and including this TimerId
  6518. * will be drained. Pass TimerId.All to run all delayed operations.
  6519. * @returns a Promise that resolves once all operations have been run.
  6520. */ Ct(t) {
  6521. // Note that draining may generate more delayed ops, so we do that first.
  6522. return this.Ot().then((() => {
  6523. // Run ops in the same order they'd run if they ran naturally.
  6524. this.Rt.sort(((t, e) => t.targetTimeMs - e.targetTimeMs));
  6525. for (const e of this.Rt) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break;
  6526. return this.Ot();
  6527. }));
  6528. }
  6529. /**
  6530. * For Tests: Skip all subsequent delays for a timer id.
  6531. */ Lt(t) {
  6532. this.Nt.push(t);
  6533. }
  6534. /** Called once a DelayedOperation is run or canceled. */ qt(t) {
  6535. // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
  6536. const e = this.Rt.indexOf(t);
  6537. this.Rt.splice(e, 1);
  6538. }
  6539. }
  6540. class ws {
  6541. /** @hideconstructor */
  6542. constructor(t, e) {
  6543. this._firestore = t, this._transaction = e, this._dataReader = Kn(t);
  6544. }
  6545. /**
  6546. * Reads the document referenced by the provided {@link DocumentReference}.
  6547. *
  6548. * @param documentRef - A reference to the document to be read.
  6549. * @returns A `DocumentSnapshot` with the read data.
  6550. */ get(t) {
  6551. const e = os(t, this._firestore), n = new zr(this._firestore);
  6552. return this._transaction.lookup([ e._key ]).then((t => {
  6553. if (!t || 1 !== t.length) return E();
  6554. const r = t[0];
  6555. if (r.isFoundDocument()) return new wr(this._firestore, n, r.key, r, e.converter);
  6556. if (r.isNoDocument()) return new wr(this._firestore, n, e._key, null, e.converter);
  6557. throw E();
  6558. }));
  6559. }
  6560. set(t, e, n) {
  6561. const r = os(t, this._firestore), s = Qr(r.converter, e, n), i = Yn(this._dataReader, "Transaction.set", r._key, s, null !== r.converter, n);
  6562. return this._transaction.set(r._key, i), this;
  6563. }
  6564. update(t, e, n, ...r) {
  6565. const s = os(t, this._firestore);
  6566. // For Compat types, we have to "extract" the underlying types before
  6567. // performing validation.
  6568. let i;
  6569. return i = "string" == typeof (e = f(e)) || e instanceof Cn ? rr(this._dataReader, "Transaction.update", s._key, e, n, r) : nr(this._dataReader, "Transaction.update", s._key, e),
  6570. this._transaction.update(s._key, i), this;
  6571. }
  6572. /**
  6573. * Deletes the document referred to by the provided {@link DocumentReference}.
  6574. *
  6575. * @param documentRef - A reference to the document to be deleted.
  6576. * @returns This `Transaction` instance. Used for chaining method calls.
  6577. */ delete(t) {
  6578. const e = os(t, this._firestore);
  6579. return this._transaction.delete(e._key), this;
  6580. }
  6581. }
  6582. /**
  6583. * Executes the given `updateFunction` and then attempts to commit the changes
  6584. * applied within the transaction. If any document read within the transaction
  6585. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  6586. * commit after 5 attempts, the transaction fails.
  6587. *
  6588. * The maximum number of writes allowed in a single transaction is 500.
  6589. *
  6590. * @param firestore - A reference to the Firestore database to run this
  6591. * transaction against.
  6592. * @param updateFunction - The function to execute within the transaction
  6593. * context.
  6594. * @param options - An options object to configure maximum number of attempts to
  6595. * commit.
  6596. * @returns If the transaction completed successfully or was explicitly aborted
  6597. * (the `updateFunction` returned a failed promise), the promise returned by the
  6598. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  6599. * rejected promise with the corresponding failure error is returned.
  6600. */ function ms(t, e, n) {
  6601. const r = _n(t = at(t, bn)), s = Object.assign(Object.assign({}, as), n);
  6602. !function(t) {
  6603. if (t.maxAttempts < 1) throw new j(V, "Max attempts must be at least 1");
  6604. }(s);
  6605. const i = new B;
  6606. return new hs(new ds, r, s, (n => e(new ws(t, n))), i).run(), i.promise;
  6607. }
  6608. /**
  6609. * Firestore Lite
  6610. *
  6611. * @remarks Firestore Lite is a small online-only SDK that allows read
  6612. * and write access to your Firestore database. All operations connect
  6613. * directly to the backend, and `onSnapshot()` APIs are not supported.
  6614. * @packageDocumentation
  6615. */ !function(t) {
  6616. m = t;
  6617. }(`${s}_lite`), n(new i("firestore/lite", ((t, {instanceIdentifier: e, options: n}) => {
  6618. const r = t.getProvider("app").getImmediate(), s = new bn(new G(t.getProvider("auth-internal")), new J(t.getProvider("app-check-internal")), function(t, e) {
  6619. if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new j(V, '"projectId" not provided in firebase.initializeApp.');
  6620. return new Z(t.options.projectId, e);
  6621. }
  6622. /**
  6623. * @license
  6624. * Copyright 2017 Google LLC
  6625. *
  6626. * Licensed under the Apache License, Version 2.0 (the "License");
  6627. * you may not use this file except in compliance with the License.
  6628. * You may obtain a copy of the License at
  6629. *
  6630. * http://www.apache.org/licenses/LICENSE-2.0
  6631. *
  6632. * Unless required by applicable law or agreed to in writing, software
  6633. * distributed under the License is distributed on an "AS IS" BASIS,
  6634. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6635. * See the License for the specific language governing permissions and
  6636. * limitations under the License.
  6637. */ (r, e), r);
  6638. return n && s._setSettings(n), s;
  6639. }), "PUBLIC").setMultipleInstances(!0)),
  6640. // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation
  6641. r("firestore-lite", "3.8.1", "rn"), r("firestore-lite", "3.8.1", "esm2017");
  6642. export { Rn as AggregateField, Pn as AggregateQuerySnapshot, kn as Bytes, Dn as CollectionReference, $n as DocumentReference, wr as DocumentSnapshot, Cn as FieldPath, Mn as FieldValue, bn as Firestore, j as FirestoreError, Un as GeoPoint, Nn as Query, Ar as QueryCompositeFilterConstraint, vr as QueryConstraint, mr as QueryDocumentSnapshot, qr as QueryEndAtConstraint, Er as QueryFieldFilterConstraint, $r as QueryLimitConstraint, Pr as QueryOrderByConstraint, pr as QuerySnapshot, Fr as QueryStartAtConstraint, Nt as Timestamp, ws as Transaction, is as WriteBatch, Jr as addDoc, Zr as aggregateQuerySnapshotEqual, Rr as and, rs as arrayRemove, ns as arrayUnion, Fn as collection, xn as collectionGroup, An as connectFirestoreEmulator, Hr as deleteDoc, ts as deleteField, Sn as doc, Ln as documentId, kr as endAt, Or as endBefore, Xr as getCount, Wr as getDoc, Gr as getDocs, In as getFirestore, ss as increment, En as initializeFirestore, Nr as limit, Dr as limitToLast, Tr as or, Vr as orderBy, br as query, On as queryEqual, qn as refEqual, ms as runTransaction, es as serverTimestamp, Kr as setDoc, y as setLogLevel, yr as snapshotEqual, Sr as startAfter, xr as startAt, Tn as terminate, Yr as updateDoc, Ir as where, us as writeBatch };
  6643. //# sourceMappingURL=index.rn.esm2017.js.map