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.node.cjs.js 334KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var app = require('@firebase/app');
  4. var component = require('@firebase/component');
  5. var logger = require('@firebase/logger');
  6. var util$1 = require('util');
  7. var util = require('@firebase/util');
  8. var nodeFetch = require('node-fetch');
  9. var crypto = require('crypto');
  10. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  11. var nodeFetch__default = /*#__PURE__*/_interopDefaultLegacy(nodeFetch);
  12. const version$1 = "3.8.1";
  13. /**
  14. * @license
  15. * Copyright 2017 Google LLC
  16. *
  17. * Licensed under the Apache License, Version 2.0 (the "License");
  18. * you may not use this file except in compliance with the License.
  19. * You may obtain a copy of the License at
  20. *
  21. * http://www.apache.org/licenses/LICENSE-2.0
  22. *
  23. * Unless required by applicable law or agreed to in writing, software
  24. * distributed under the License is distributed on an "AS IS" BASIS,
  25. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26. * See the License for the specific language governing permissions and
  27. * limitations under the License.
  28. */
  29. /**
  30. * Simple wrapper around a nullable UID. Mostly exists to make code more
  31. * readable.
  32. */
  33. class User {
  34. constructor(uid) {
  35. this.uid = uid;
  36. }
  37. isAuthenticated() {
  38. return this.uid != null;
  39. }
  40. /**
  41. * Returns a key representing this user, suitable for inclusion in a
  42. * dictionary.
  43. */
  44. toKey() {
  45. if (this.isAuthenticated()) {
  46. return 'uid:' + this.uid;
  47. }
  48. else {
  49. return 'anonymous-user';
  50. }
  51. }
  52. isEqual(otherUser) {
  53. return otherUser.uid === this.uid;
  54. }
  55. }
  56. /** A user with a null UID. */
  57. User.UNAUTHENTICATED = new User(null);
  58. // TODO(mikelehen): Look into getting a proper uid-equivalent for
  59. // non-FirebaseAuth providers.
  60. User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');
  61. User.FIRST_PARTY = new User('first-party-uid');
  62. User.MOCK_USER = new User('mock-user');
  63. const version = "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. let SDK_VERSION = version;
  81. function setSDKVersion(version) {
  82. SDK_VERSION = version;
  83. }
  84. /**
  85. * @license
  86. * Copyright 2020 Google LLC
  87. *
  88. * Licensed under the Apache License, Version 2.0 (the "License");
  89. * you may not use this file except in compliance with the License.
  90. * You may obtain a copy of the License at
  91. *
  92. * http://www.apache.org/licenses/LICENSE-2.0
  93. *
  94. * Unless required by applicable law or agreed to in writing, software
  95. * distributed under the License is distributed on an "AS IS" BASIS,
  96. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  97. * See the License for the specific language governing permissions and
  98. * limitations under the License.
  99. */
  100. /** Formats an object as a JSON string, suitable for logging. */
  101. function formatJSON(value) {
  102. // util.inspect() results in much more readable output than JSON.stringify()
  103. return util$1.inspect(value, { depth: 100 });
  104. }
  105. /**
  106. * @license
  107. * Copyright 2017 Google LLC
  108. *
  109. * Licensed under the Apache License, Version 2.0 (the "License");
  110. * you may not use this file except in compliance with the License.
  111. * You may obtain a copy of the License at
  112. *
  113. * http://www.apache.org/licenses/LICENSE-2.0
  114. *
  115. * Unless required by applicable law or agreed to in writing, software
  116. * distributed under the License is distributed on an "AS IS" BASIS,
  117. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  118. * See the License for the specific language governing permissions and
  119. * limitations under the License.
  120. */
  121. const logClient = new logger.Logger('@firebase/firestore');
  122. /**
  123. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  124. *
  125. * @param logLevel - The verbosity you set for activity and error logging. Can
  126. * be any of the following values:
  127. *
  128. * <ul>
  129. * <li>`debug` for the most verbose logging level, primarily for
  130. * debugging.</li>
  131. * <li>`error` to log errors only.</li>
  132. * <li><code>`silent` to turn off logging.</li>
  133. * </ul>
  134. */
  135. function setLogLevel(logLevel) {
  136. logClient.setLogLevel(logLevel);
  137. }
  138. function logDebug(msg, ...obj) {
  139. if (logClient.logLevel <= logger.LogLevel.DEBUG) {
  140. const args = obj.map(argToString);
  141. logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args);
  142. }
  143. }
  144. function logError(msg, ...obj) {
  145. if (logClient.logLevel <= logger.LogLevel.ERROR) {
  146. const args = obj.map(argToString);
  147. logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);
  148. }
  149. }
  150. /**
  151. * @internal
  152. */
  153. function logWarn(msg, ...obj) {
  154. if (logClient.logLevel <= logger.LogLevel.WARN) {
  155. const args = obj.map(argToString);
  156. logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args);
  157. }
  158. }
  159. /**
  160. * Converts an additional log parameter to a string representation.
  161. */
  162. function argToString(obj) {
  163. if (typeof obj === 'string') {
  164. return obj;
  165. }
  166. else {
  167. try {
  168. return formatJSON(obj);
  169. }
  170. catch (e) {
  171. // Converting to JSON failed, just log the object directly
  172. return obj;
  173. }
  174. }
  175. }
  176. /**
  177. * @license
  178. * Copyright 2017 Google LLC
  179. *
  180. * Licensed under the Apache License, Version 2.0 (the "License");
  181. * you may not use this file except in compliance with the License.
  182. * You may obtain a copy of the License at
  183. *
  184. * http://www.apache.org/licenses/LICENSE-2.0
  185. *
  186. * Unless required by applicable law or agreed to in writing, software
  187. * distributed under the License is distributed on an "AS IS" BASIS,
  188. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  189. * See the License for the specific language governing permissions and
  190. * limitations under the License.
  191. */
  192. /**
  193. * Unconditionally fails, throwing an Error with the given message.
  194. * Messages are stripped in production builds.
  195. *
  196. * Returns `never` and can be used in expressions:
  197. * @example
  198. * let futureVar = fail('not implemented yet');
  199. */
  200. function fail(failure = 'Unexpected state') {
  201. // Log the failure in addition to throw an exception, just in case the
  202. // exception is swallowed.
  203. const message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ` + failure;
  204. logError(message);
  205. // NOTE: We don't use FirestoreError here because these are internal failures
  206. // that cannot be handled by the user. (Also it would create a circular
  207. // dependency between the error and assert modules which doesn't work.)
  208. throw new Error(message);
  209. }
  210. /**
  211. * Fails if the given assertion condition is false, throwing an Error with the
  212. * given message if it did.
  213. *
  214. * Messages are stripped in production builds.
  215. */
  216. function hardAssert(assertion, message) {
  217. if (!assertion) {
  218. fail();
  219. }
  220. }
  221. /**
  222. * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
  223. * instance of `T` before casting.
  224. */
  225. function debugCast(obj,
  226. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  227. constructor) {
  228. return obj;
  229. }
  230. /**
  231. * @license
  232. * Copyright 2017 Google LLC
  233. *
  234. * Licensed under the Apache License, Version 2.0 (the "License");
  235. * you may not use this file except in compliance with the License.
  236. * You may obtain a copy of the License at
  237. *
  238. * http://www.apache.org/licenses/LICENSE-2.0
  239. *
  240. * Unless required by applicable law or agreed to in writing, software
  241. * distributed under the License is distributed on an "AS IS" BASIS,
  242. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  243. * See the License for the specific language governing permissions and
  244. * limitations under the License.
  245. */
  246. const Code = {
  247. // Causes are copied from:
  248. // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  249. /** Not an error; returned on success. */
  250. OK: 'ok',
  251. /** The operation was cancelled (typically by the caller). */
  252. CANCELLED: 'cancelled',
  253. /** Unknown error or an error from a different error domain. */
  254. UNKNOWN: 'unknown',
  255. /**
  256. * Client specified an invalid argument. Note that this differs from
  257. * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
  258. * problematic regardless of the state of the system (e.g., a malformed file
  259. * name).
  260. */
  261. INVALID_ARGUMENT: 'invalid-argument',
  262. /**
  263. * Deadline expired before operation could complete. For operations that
  264. * change the state of the system, this error may be returned even if the
  265. * operation has completed successfully. For example, a successful response
  266. * from a server could have been delayed long enough for the deadline to
  267. * expire.
  268. */
  269. DEADLINE_EXCEEDED: 'deadline-exceeded',
  270. /** Some requested entity (e.g., file or directory) was not found. */
  271. NOT_FOUND: 'not-found',
  272. /**
  273. * Some entity that we attempted to create (e.g., file or directory) already
  274. * exists.
  275. */
  276. ALREADY_EXISTS: 'already-exists',
  277. /**
  278. * The caller does not have permission to execute the specified operation.
  279. * PERMISSION_DENIED must not be used for rejections caused by exhausting
  280. * some resource (use RESOURCE_EXHAUSTED instead for those errors).
  281. * PERMISSION_DENIED must not be used if the caller can not be identified
  282. * (use UNAUTHENTICATED instead for those errors).
  283. */
  284. PERMISSION_DENIED: 'permission-denied',
  285. /**
  286. * The request does not have valid authentication credentials for the
  287. * operation.
  288. */
  289. UNAUTHENTICATED: 'unauthenticated',
  290. /**
  291. * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  292. * entire file system is out of space.
  293. */
  294. RESOURCE_EXHAUSTED: 'resource-exhausted',
  295. /**
  296. * Operation was rejected because the system is not in a state required for
  297. * the operation's execution. For example, directory to be deleted may be
  298. * non-empty, an rmdir operation is applied to a non-directory, etc.
  299. *
  300. * A litmus test that may help a service implementor in deciding
  301. * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  302. * (a) Use UNAVAILABLE if the client can retry just the failing call.
  303. * (b) Use ABORTED if the client should retry at a higher-level
  304. * (e.g., restarting a read-modify-write sequence).
  305. * (c) Use FAILED_PRECONDITION if the client should not retry until
  306. * the system state has been explicitly fixed. E.g., if an "rmdir"
  307. * fails because the directory is non-empty, FAILED_PRECONDITION
  308. * should be returned since the client should not retry unless
  309. * they have first fixed up the directory by deleting files from it.
  310. * (d) Use FAILED_PRECONDITION if the client performs conditional
  311. * REST Get/Update/Delete on a resource and the resource on the
  312. * server does not match the condition. E.g., conflicting
  313. * read-modify-write on the same resource.
  314. */
  315. FAILED_PRECONDITION: 'failed-precondition',
  316. /**
  317. * The operation was aborted, typically due to a concurrency issue like
  318. * sequencer check failures, transaction aborts, etc.
  319. *
  320. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  321. * and UNAVAILABLE.
  322. */
  323. ABORTED: 'aborted',
  324. /**
  325. * Operation was attempted past the valid range. E.g., seeking or reading
  326. * past end of file.
  327. *
  328. * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
  329. * if the system state changes. For example, a 32-bit file system will
  330. * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
  331. * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  332. * an offset past the current file size.
  333. *
  334. * There is a fair bit of overlap between FAILED_PRECONDITION and
  335. * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  336. * when it applies so that callers who are iterating through a space can
  337. * easily look for an OUT_OF_RANGE error to detect when they are done.
  338. */
  339. OUT_OF_RANGE: 'out-of-range',
  340. /** Operation is not implemented or not supported/enabled in this service. */
  341. UNIMPLEMENTED: 'unimplemented',
  342. /**
  343. * Internal errors. Means some invariants expected by underlying System has
  344. * been broken. If you see one of these errors, Something is very broken.
  345. */
  346. INTERNAL: 'internal',
  347. /**
  348. * The service is currently unavailable. This is a most likely a transient
  349. * condition and may be corrected by retrying with a backoff.
  350. *
  351. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  352. * and UNAVAILABLE.
  353. */
  354. UNAVAILABLE: 'unavailable',
  355. /** Unrecoverable data loss or corruption. */
  356. DATA_LOSS: 'data-loss'
  357. };
  358. /** An error returned by a Firestore operation. */
  359. class FirestoreError extends util.FirebaseError {
  360. /** @hideconstructor */
  361. constructor(
  362. /**
  363. * The backend error code associated with this error.
  364. */
  365. code,
  366. /**
  367. * A custom error description.
  368. */
  369. message) {
  370. super(code, message);
  371. this.code = code;
  372. this.message = message;
  373. // HACK: We write a toString property directly because Error is not a real
  374. // class and so inheritance does not work correctly. We could alternatively
  375. // do the same "back-door inheritance" trick that FirebaseError does.
  376. this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
  377. }
  378. }
  379. /**
  380. * @license
  381. * Copyright 2017 Google LLC
  382. *
  383. * Licensed under the Apache License, Version 2.0 (the "License");
  384. * you may not use this file except in compliance with the License.
  385. * You may obtain a copy of the License at
  386. *
  387. * http://www.apache.org/licenses/LICENSE-2.0
  388. *
  389. * Unless required by applicable law or agreed to in writing, software
  390. * distributed under the License is distributed on an "AS IS" BASIS,
  391. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  392. * See the License for the specific language governing permissions and
  393. * limitations under the License.
  394. */
  395. class Deferred {
  396. constructor() {
  397. this.promise = new Promise((resolve, reject) => {
  398. this.resolve = resolve;
  399. this.reject = reject;
  400. });
  401. }
  402. }
  403. /**
  404. * @license
  405. * Copyright 2017 Google LLC
  406. *
  407. * Licensed under the Apache License, Version 2.0 (the "License");
  408. * you may not use this file except in compliance with the License.
  409. * You may obtain a copy of the License at
  410. *
  411. * http://www.apache.org/licenses/LICENSE-2.0
  412. *
  413. * Unless required by applicable law or agreed to in writing, software
  414. * distributed under the License is distributed on an "AS IS" BASIS,
  415. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  416. * See the License for the specific language governing permissions and
  417. * limitations under the License.
  418. */
  419. class OAuthToken {
  420. constructor(value, user) {
  421. this.user = user;
  422. this.type = 'OAuth';
  423. this.headers = new Map();
  424. this.headers.set('Authorization', `Bearer ${value}`);
  425. }
  426. }
  427. /**
  428. * A CredentialsProvider that always yields an empty token.
  429. * @internal
  430. */
  431. class EmptyAuthCredentialsProvider {
  432. getToken() {
  433. return Promise.resolve(null);
  434. }
  435. invalidateToken() { }
  436. start(asyncQueue, changeListener) {
  437. // Fire with initial user.
  438. asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED));
  439. }
  440. shutdown() { }
  441. }
  442. /**
  443. * A CredentialsProvider that always returns a constant token. Used for
  444. * emulator token mocking.
  445. */
  446. class EmulatorAuthCredentialsProvider {
  447. constructor(token) {
  448. this.token = token;
  449. /**
  450. * Stores the listener registered with setChangeListener()
  451. * This isn't actually necessary since the UID never changes, but we use this
  452. * to verify the listen contract is adhered to in tests.
  453. */
  454. this.changeListener = null;
  455. }
  456. getToken() {
  457. return Promise.resolve(this.token);
  458. }
  459. invalidateToken() { }
  460. start(asyncQueue, changeListener) {
  461. this.changeListener = changeListener;
  462. // Fire with initial user.
  463. asyncQueue.enqueueRetryable(() => changeListener(this.token.user));
  464. }
  465. shutdown() {
  466. this.changeListener = null;
  467. }
  468. }
  469. /** Credential provider for the Lite SDK. */
  470. class LiteAuthCredentialsProvider {
  471. constructor(authProvider) {
  472. this.auth = null;
  473. authProvider.onInit(auth => {
  474. this.auth = auth;
  475. });
  476. }
  477. getToken() {
  478. if (!this.auth) {
  479. return Promise.resolve(null);
  480. }
  481. return this.auth.getToken().then(tokenData => {
  482. if (tokenData) {
  483. hardAssert(typeof tokenData.accessToken === 'string');
  484. return new OAuthToken(tokenData.accessToken, new User(this.auth.getUid()));
  485. }
  486. else {
  487. return null;
  488. }
  489. });
  490. }
  491. invalidateToken() { }
  492. start(asyncQueue, changeListener) { }
  493. shutdown() { }
  494. }
  495. /*
  496. * FirstPartyToken provides a fresh token each time its value
  497. * is requested, because if the token is too old, requests will be rejected.
  498. * Technically this may no longer be necessary since the SDK should gracefully
  499. * recover from unauthenticated errors (see b/33147818 for context), but it's
  500. * safer to keep the implementation as-is.
  501. */
  502. class FirstPartyToken {
  503. constructor(gapi, sessionIndex, iamToken, authTokenFactory) {
  504. this.gapi = gapi;
  505. this.sessionIndex = sessionIndex;
  506. this.iamToken = iamToken;
  507. this.authTokenFactory = authTokenFactory;
  508. this.type = 'FirstParty';
  509. this.user = User.FIRST_PARTY;
  510. this._headers = new Map();
  511. }
  512. /** Gets an authorization token, using a provided factory function, or falling back to First Party GAPI. */
  513. getAuthToken() {
  514. if (this.authTokenFactory) {
  515. return this.authTokenFactory();
  516. }
  517. else {
  518. // Make sure this really is a Gapi client.
  519. hardAssert(!!(typeof this.gapi === 'object' &&
  520. this.gapi !== null &&
  521. this.gapi['auth'] &&
  522. this.gapi['auth']['getAuthHeaderValueForFirstParty']));
  523. return this.gapi['auth']['getAuthHeaderValueForFirstParty']([]);
  524. }
  525. }
  526. get headers() {
  527. this._headers.set('X-Goog-AuthUser', this.sessionIndex);
  528. // Use array notation to prevent minification
  529. const authHeaderTokenValue = this.getAuthToken();
  530. if (authHeaderTokenValue) {
  531. this._headers.set('Authorization', authHeaderTokenValue);
  532. }
  533. if (this.iamToken) {
  534. this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken);
  535. }
  536. return this._headers;
  537. }
  538. }
  539. /*
  540. * Provides user credentials required for the Firestore JavaScript SDK
  541. * to authenticate the user, using technique that is only available
  542. * to applications hosted by Google.
  543. */
  544. class FirstPartyAuthCredentialsProvider {
  545. constructor(gapi, sessionIndex, iamToken, authTokenFactory) {
  546. this.gapi = gapi;
  547. this.sessionIndex = sessionIndex;
  548. this.iamToken = iamToken;
  549. this.authTokenFactory = authTokenFactory;
  550. }
  551. getToken() {
  552. return Promise.resolve(new FirstPartyToken(this.gapi, this.sessionIndex, this.iamToken, this.authTokenFactory));
  553. }
  554. start(asyncQueue, changeListener) {
  555. // Fire with initial uid.
  556. asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY));
  557. }
  558. shutdown() { }
  559. invalidateToken() { }
  560. }
  561. class AppCheckToken {
  562. constructor(value) {
  563. this.value = value;
  564. this.type = 'AppCheck';
  565. this.headers = new Map();
  566. if (value && value.length > 0) {
  567. this.headers.set('x-firebase-appcheck', this.value);
  568. }
  569. }
  570. }
  571. /** AppCheck token provider for the Lite SDK. */
  572. class LiteAppCheckTokenProvider {
  573. constructor(appCheckProvider) {
  574. this.appCheckProvider = appCheckProvider;
  575. this.appCheck = null;
  576. appCheckProvider.onInit(appCheck => {
  577. this.appCheck = appCheck;
  578. });
  579. }
  580. getToken() {
  581. if (!this.appCheck) {
  582. return Promise.resolve(null);
  583. }
  584. return this.appCheck.getToken().then(tokenResult => {
  585. if (tokenResult) {
  586. hardAssert(typeof tokenResult.token === 'string');
  587. return new AppCheckToken(tokenResult.token);
  588. }
  589. else {
  590. return null;
  591. }
  592. });
  593. }
  594. invalidateToken() { }
  595. start(asyncQueue, changeListener) { }
  596. shutdown() { }
  597. }
  598. /**
  599. * Builds a CredentialsProvider depending on the type of
  600. * the credentials passed in.
  601. */
  602. function makeAuthCredentialsProvider(credentials) {
  603. if (!credentials) {
  604. return new EmptyAuthCredentialsProvider();
  605. }
  606. switch (credentials['type']) {
  607. case 'gapi':
  608. const client = credentials['client'];
  609. return new FirstPartyAuthCredentialsProvider(client, credentials['sessionIndex'] || '0', credentials['iamToken'] || null, credentials['authTokenFactory'] || null);
  610. case 'provider':
  611. return credentials['client'];
  612. default:
  613. throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeAuthCredentialsProvider failed due to invalid credential type');
  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. class DatabaseInfo {
  633. /**
  634. * Constructs a DatabaseInfo using the provided host, databaseId and
  635. * persistenceKey.
  636. *
  637. * @param databaseId - The database to use.
  638. * @param appId - The Firebase App Id.
  639. * @param persistenceKey - A unique identifier for this Firestore's local
  640. * storage (used in conjunction with the databaseId).
  641. * @param host - The Firestore backend host to connect to.
  642. * @param ssl - Whether to use SSL when connecting.
  643. * @param forceLongPolling - Whether to use the forceLongPolling option
  644. * when using WebChannel as the network transport.
  645. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  646. * option when using WebChannel as the network transport.
  647. * @param useFetchStreams Whether to use the Fetch API instead of
  648. * XMLHTTPRequest
  649. */
  650. constructor(databaseId, appId, persistenceKey, host, ssl, forceLongPolling, autoDetectLongPolling, useFetchStreams) {
  651. this.databaseId = databaseId;
  652. this.appId = appId;
  653. this.persistenceKey = persistenceKey;
  654. this.host = host;
  655. this.ssl = ssl;
  656. this.forceLongPolling = forceLongPolling;
  657. this.autoDetectLongPolling = autoDetectLongPolling;
  658. this.useFetchStreams = useFetchStreams;
  659. }
  660. }
  661. /** The default database name for a project. */
  662. const DEFAULT_DATABASE_NAME = '(default)';
  663. /**
  664. * Represents the database ID a Firestore client is associated with.
  665. * @internal
  666. */
  667. class DatabaseId {
  668. constructor(projectId, database) {
  669. this.projectId = projectId;
  670. this.database = database ? database : DEFAULT_DATABASE_NAME;
  671. }
  672. static empty() {
  673. return new DatabaseId('', '');
  674. }
  675. get isDefaultDatabase() {
  676. return this.database === DEFAULT_DATABASE_NAME;
  677. }
  678. isEqual(other) {
  679. return (other instanceof DatabaseId &&
  680. other.projectId === this.projectId &&
  681. other.database === this.database);
  682. }
  683. }
  684. function databaseIdFromApp(app, database) {
  685. if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) {
  686. throw new FirestoreError(Code.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
  687. }
  688. return new DatabaseId(app.options.projectId, database);
  689. }
  690. /**
  691. * @license
  692. * Copyright 2017 Google LLC
  693. *
  694. * Licensed under the Apache License, Version 2.0 (the "License");
  695. * you may not use this file except in compliance with the License.
  696. * You may obtain a copy of the License at
  697. *
  698. * http://www.apache.org/licenses/LICENSE-2.0
  699. *
  700. * Unless required by applicable law or agreed to in writing, software
  701. * distributed under the License is distributed on an "AS IS" BASIS,
  702. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  703. * See the License for the specific language governing permissions and
  704. * limitations under the License.
  705. */
  706. const DOCUMENT_KEY_NAME = '__name__';
  707. /**
  708. * Path represents an ordered sequence of string segments.
  709. */
  710. class BasePath {
  711. constructor(segments, offset, length) {
  712. if (offset === undefined) {
  713. offset = 0;
  714. }
  715. else if (offset > segments.length) {
  716. fail();
  717. }
  718. if (length === undefined) {
  719. length = segments.length - offset;
  720. }
  721. else if (length > segments.length - offset) {
  722. fail();
  723. }
  724. this.segments = segments;
  725. this.offset = offset;
  726. this.len = length;
  727. }
  728. get length() {
  729. return this.len;
  730. }
  731. isEqual(other) {
  732. return BasePath.comparator(this, other) === 0;
  733. }
  734. child(nameOrPath) {
  735. const segments = this.segments.slice(this.offset, this.limit());
  736. if (nameOrPath instanceof BasePath) {
  737. nameOrPath.forEach(segment => {
  738. segments.push(segment);
  739. });
  740. }
  741. else {
  742. segments.push(nameOrPath);
  743. }
  744. return this.construct(segments);
  745. }
  746. /** The index of one past the last segment of the path. */
  747. limit() {
  748. return this.offset + this.length;
  749. }
  750. popFirst(size) {
  751. size = size === undefined ? 1 : size;
  752. return this.construct(this.segments, this.offset + size, this.length - size);
  753. }
  754. popLast() {
  755. return this.construct(this.segments, this.offset, this.length - 1);
  756. }
  757. firstSegment() {
  758. return this.segments[this.offset];
  759. }
  760. lastSegment() {
  761. return this.get(this.length - 1);
  762. }
  763. get(index) {
  764. return this.segments[this.offset + index];
  765. }
  766. isEmpty() {
  767. return this.length === 0;
  768. }
  769. isPrefixOf(other) {
  770. if (other.length < this.length) {
  771. return false;
  772. }
  773. for (let i = 0; i < this.length; i++) {
  774. if (this.get(i) !== other.get(i)) {
  775. return false;
  776. }
  777. }
  778. return true;
  779. }
  780. isImmediateParentOf(potentialChild) {
  781. if (this.length + 1 !== potentialChild.length) {
  782. return false;
  783. }
  784. for (let i = 0; i < this.length; i++) {
  785. if (this.get(i) !== potentialChild.get(i)) {
  786. return false;
  787. }
  788. }
  789. return true;
  790. }
  791. forEach(fn) {
  792. for (let i = this.offset, end = this.limit(); i < end; i++) {
  793. fn(this.segments[i]);
  794. }
  795. }
  796. toArray() {
  797. return this.segments.slice(this.offset, this.limit());
  798. }
  799. static comparator(p1, p2) {
  800. const len = Math.min(p1.length, p2.length);
  801. for (let i = 0; i < len; i++) {
  802. const left = p1.get(i);
  803. const right = p2.get(i);
  804. if (left < right) {
  805. return -1;
  806. }
  807. if (left > right) {
  808. return 1;
  809. }
  810. }
  811. if (p1.length < p2.length) {
  812. return -1;
  813. }
  814. if (p1.length > p2.length) {
  815. return 1;
  816. }
  817. return 0;
  818. }
  819. }
  820. /**
  821. * A slash-separated path for navigating resources (documents and collections)
  822. * within Firestore.
  823. *
  824. * @internal
  825. */
  826. class ResourcePath extends BasePath {
  827. construct(segments, offset, length) {
  828. return new ResourcePath(segments, offset, length);
  829. }
  830. canonicalString() {
  831. // NOTE: The client is ignorant of any path segments containing escape
  832. // sequences (e.g. __id123__) and just passes them through raw (they exist
  833. // for legacy reasons and should not be used frequently).
  834. return this.toArray().join('/');
  835. }
  836. toString() {
  837. return this.canonicalString();
  838. }
  839. /**
  840. * Creates a resource path from the given slash-delimited string. If multiple
  841. * arguments are provided, all components are combined. Leading and trailing
  842. * slashes from all components are ignored.
  843. */
  844. static fromString(...pathComponents) {
  845. // NOTE: The client is ignorant of any path segments containing escape
  846. // sequences (e.g. __id123__) and just passes them through raw (they exist
  847. // for legacy reasons and should not be used frequently).
  848. const segments = [];
  849. for (const path of pathComponents) {
  850. if (path.indexOf('//') >= 0) {
  851. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid segment (${path}). Paths must not contain // in them.`);
  852. }
  853. // Strip leading and traling slashed.
  854. segments.push(...path.split('/').filter(segment => segment.length > 0));
  855. }
  856. return new ResourcePath(segments);
  857. }
  858. static emptyPath() {
  859. return new ResourcePath([]);
  860. }
  861. }
  862. const identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
  863. /**
  864. * A dot-separated path for navigating sub-objects within a document.
  865. * @internal
  866. */
  867. class FieldPath$1 extends BasePath {
  868. construct(segments, offset, length) {
  869. return new FieldPath$1(segments, offset, length);
  870. }
  871. /**
  872. * Returns true if the string could be used as a segment in a field path
  873. * without escaping.
  874. */
  875. static isValidIdentifier(segment) {
  876. return identifierRegExp.test(segment);
  877. }
  878. canonicalString() {
  879. return this.toArray()
  880. .map(str => {
  881. str = str.replace(/\\/g, '\\\\').replace(/`/g, '\\`');
  882. if (!FieldPath$1.isValidIdentifier(str)) {
  883. str = '`' + str + '`';
  884. }
  885. return str;
  886. })
  887. .join('.');
  888. }
  889. toString() {
  890. return this.canonicalString();
  891. }
  892. /**
  893. * Returns true if this field references the key of a document.
  894. */
  895. isKeyField() {
  896. return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;
  897. }
  898. /**
  899. * The field designating the key of a document.
  900. */
  901. static keyField() {
  902. return new FieldPath$1([DOCUMENT_KEY_NAME]);
  903. }
  904. /**
  905. * Parses a field string from the given server-formatted string.
  906. *
  907. * - Splitting the empty string is not allowed (for now at least).
  908. * - Empty segments within the string (e.g. if there are two consecutive
  909. * separators) are not allowed.
  910. *
  911. * TODO(b/37244157): we should make this more strict. Right now, it allows
  912. * non-identifier path components, even if they aren't escaped.
  913. */
  914. static fromServerFormat(path) {
  915. const segments = [];
  916. let current = '';
  917. let i = 0;
  918. const addCurrentSegment = () => {
  919. if (current.length === 0) {
  920. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field path (${path}). Paths must not be empty, begin ` +
  921. `with '.', end with '.', or contain '..'`);
  922. }
  923. segments.push(current);
  924. current = '';
  925. };
  926. let inBackticks = false;
  927. while (i < path.length) {
  928. const c = path[i];
  929. if (c === '\\') {
  930. if (i + 1 === path.length) {
  931. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path);
  932. }
  933. const next = path[i + 1];
  934. if (!(next === '\\' || next === '.' || next === '`')) {
  935. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path);
  936. }
  937. current += next;
  938. i += 2;
  939. }
  940. else if (c === '`') {
  941. inBackticks = !inBackticks;
  942. i++;
  943. }
  944. else if (c === '.' && !inBackticks) {
  945. addCurrentSegment();
  946. i++;
  947. }
  948. else {
  949. current += c;
  950. i++;
  951. }
  952. }
  953. addCurrentSegment();
  954. if (inBackticks) {
  955. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path);
  956. }
  957. return new FieldPath$1(segments);
  958. }
  959. static emptyPath() {
  960. return new FieldPath$1([]);
  961. }
  962. }
  963. /**
  964. * @license
  965. * Copyright 2017 Google LLC
  966. *
  967. * Licensed under the Apache License, Version 2.0 (the "License");
  968. * you may not use this file except in compliance with the License.
  969. * You may obtain a copy of the License at
  970. *
  971. * http://www.apache.org/licenses/LICENSE-2.0
  972. *
  973. * Unless required by applicable law or agreed to in writing, software
  974. * distributed under the License is distributed on an "AS IS" BASIS,
  975. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  976. * See the License for the specific language governing permissions and
  977. * limitations under the License.
  978. */
  979. /**
  980. * @internal
  981. */
  982. class DocumentKey {
  983. constructor(path) {
  984. this.path = path;
  985. }
  986. static fromPath(path) {
  987. return new DocumentKey(ResourcePath.fromString(path));
  988. }
  989. static fromName(name) {
  990. return new DocumentKey(ResourcePath.fromString(name).popFirst(5));
  991. }
  992. static empty() {
  993. return new DocumentKey(ResourcePath.emptyPath());
  994. }
  995. get collectionGroup() {
  996. return this.path.popLast().lastSegment();
  997. }
  998. /** Returns true if the document is in the specified collectionId. */
  999. hasCollectionId(collectionId) {
  1000. return (this.path.length >= 2 &&
  1001. this.path.get(this.path.length - 2) === collectionId);
  1002. }
  1003. /** Returns the collection group (i.e. the name of the parent collection) for this key. */
  1004. getCollectionGroup() {
  1005. return this.path.get(this.path.length - 2);
  1006. }
  1007. /** Returns the fully qualified path to the parent collection. */
  1008. getCollectionPath() {
  1009. return this.path.popLast();
  1010. }
  1011. isEqual(other) {
  1012. return (other !== null && ResourcePath.comparator(this.path, other.path) === 0);
  1013. }
  1014. toString() {
  1015. return this.path.toString();
  1016. }
  1017. static comparator(k1, k2) {
  1018. return ResourcePath.comparator(k1.path, k2.path);
  1019. }
  1020. static isDocumentKey(path) {
  1021. return path.length % 2 === 0;
  1022. }
  1023. /**
  1024. * Creates and returns a new document key with the given segments.
  1025. *
  1026. * @param segments - The segments of the path to the document
  1027. * @returns A new instance of DocumentKey
  1028. */
  1029. static fromSegments(segments) {
  1030. return new DocumentKey(new ResourcePath(segments.slice()));
  1031. }
  1032. }
  1033. /**
  1034. * @license
  1035. * Copyright 2017 Google LLC
  1036. *
  1037. * Licensed under the Apache License, Version 2.0 (the "License");
  1038. * you may not use this file except in compliance with the License.
  1039. * You may obtain a copy of the License at
  1040. *
  1041. * http://www.apache.org/licenses/LICENSE-2.0
  1042. *
  1043. * Unless required by applicable law or agreed to in writing, software
  1044. * distributed under the License is distributed on an "AS IS" BASIS,
  1045. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1046. * See the License for the specific language governing permissions and
  1047. * limitations under the License.
  1048. */
  1049. function validateNonEmptyArgument(functionName, argumentName, argument) {
  1050. if (!argument) {
  1051. throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() cannot be called with an empty ${argumentName}.`);
  1052. }
  1053. }
  1054. /**
  1055. * Validates that two boolean options are not set at the same time.
  1056. * @internal
  1057. */
  1058. function validateIsNotUsedTogether(optionName1, argument1, optionName2, argument2) {
  1059. if (argument1 === true && argument2 === true) {
  1060. throw new FirestoreError(Code.INVALID_ARGUMENT, `${optionName1} and ${optionName2} cannot be used together.`);
  1061. }
  1062. }
  1063. /**
  1064. * Validates that `path` refers to a document (indicated by the fact it contains
  1065. * an even numbers of segments).
  1066. */
  1067. function validateDocumentPath(path) {
  1068. if (!DocumentKey.isDocumentKey(path)) {
  1069. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`);
  1070. }
  1071. }
  1072. /**
  1073. * Validates that `path` refers to a collection (indicated by the fact it
  1074. * contains an odd numbers of segments).
  1075. */
  1076. function validateCollectionPath(path) {
  1077. if (DocumentKey.isDocumentKey(path)) {
  1078. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`);
  1079. }
  1080. }
  1081. /**
  1082. * Returns true if it's a non-null object without a custom prototype
  1083. * (i.e. excludes Array, Date, etc.).
  1084. */
  1085. function isPlainObject(input) {
  1086. return (typeof input === 'object' &&
  1087. input !== null &&
  1088. (Object.getPrototypeOf(input) === Object.prototype ||
  1089. Object.getPrototypeOf(input) === null));
  1090. }
  1091. /** Returns a string describing the type / value of the provided input. */
  1092. function valueDescription(input) {
  1093. if (input === undefined) {
  1094. return 'undefined';
  1095. }
  1096. else if (input === null) {
  1097. return 'null';
  1098. }
  1099. else if (typeof input === 'string') {
  1100. if (input.length > 20) {
  1101. input = `${input.substring(0, 20)}...`;
  1102. }
  1103. return JSON.stringify(input);
  1104. }
  1105. else if (typeof input === 'number' || typeof input === 'boolean') {
  1106. return '' + input;
  1107. }
  1108. else if (typeof input === 'object') {
  1109. if (input instanceof Array) {
  1110. return 'an array';
  1111. }
  1112. else {
  1113. const customObjectName = tryGetCustomObjectType(input);
  1114. if (customObjectName) {
  1115. return `a custom ${customObjectName} object`;
  1116. }
  1117. else {
  1118. return 'an object';
  1119. }
  1120. }
  1121. }
  1122. else if (typeof input === 'function') {
  1123. return 'a function';
  1124. }
  1125. else {
  1126. return fail();
  1127. }
  1128. }
  1129. /** try to get the constructor name for an object. */
  1130. function tryGetCustomObjectType(input) {
  1131. if (input.constructor) {
  1132. return input.constructor.name;
  1133. }
  1134. return null;
  1135. }
  1136. /**
  1137. * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
  1138. * underlying instance. Throws if `obj` is not an instance of `T`.
  1139. *
  1140. * This cast is used in the Lite and Full SDK to verify instance types for
  1141. * arguments passed to the public API.
  1142. * @internal
  1143. */
  1144. function cast(obj,
  1145. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1146. constructor) {
  1147. if ('_delegate' in obj) {
  1148. // Unwrap Compat types
  1149. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1150. obj = obj._delegate;
  1151. }
  1152. if (!(obj instanceof constructor)) {
  1153. if (constructor.name === obj.constructor.name) {
  1154. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Type does not match the expected instance. Did you pass a ' +
  1155. `reference from a different Firestore SDK?`);
  1156. }
  1157. else {
  1158. const description = valueDescription(obj);
  1159. throw new FirestoreError(Code.INVALID_ARGUMENT, `Expected type '${constructor.name}', but it was: ${description}`);
  1160. }
  1161. }
  1162. return obj;
  1163. }
  1164. function validatePositiveNumber(functionName, n) {
  1165. if (n <= 0) {
  1166. throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires a positive number, but it was: ${n}.`);
  1167. }
  1168. }
  1169. /**
  1170. * @license
  1171. * Copyright 2020 Google LLC
  1172. *
  1173. * Licensed under the Apache License, Version 2.0 (the "License");
  1174. * you may not use this file except in compliance with the License.
  1175. * You may obtain a copy of the License at
  1176. *
  1177. * http://www.apache.org/licenses/LICENSE-2.0
  1178. *
  1179. * Unless required by applicable law or agreed to in writing, software
  1180. * distributed under the License is distributed on an "AS IS" BASIS,
  1181. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1182. * See the License for the specific language governing permissions and
  1183. * limitations under the License.
  1184. */
  1185. const LOG_TAG$3 = 'RestConnection';
  1186. /**
  1187. * Maps RPC names to the corresponding REST endpoint name.
  1188. *
  1189. * We use array notation to avoid mangling.
  1190. */
  1191. const RPC_NAME_URL_MAPPING = {};
  1192. RPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet';
  1193. RPC_NAME_URL_MAPPING['Commit'] = 'commit';
  1194. RPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery';
  1195. RPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery';
  1196. const RPC_URL_VERSION = 'v1';
  1197. // SDK_VERSION is updated to different value at runtime depending on the entry point,
  1198. // so we need to get its value when we need it in a function.
  1199. function getGoogApiClientValue() {
  1200. return 'gl-js/ fire/' + SDK_VERSION;
  1201. }
  1202. /**
  1203. * Base class for all Rest-based connections to the backend (WebChannel and
  1204. * HTTP).
  1205. */
  1206. class RestConnection {
  1207. constructor(databaseInfo) {
  1208. this.databaseInfo = databaseInfo;
  1209. this.databaseId = databaseInfo.databaseId;
  1210. const proto = databaseInfo.ssl ? 'https' : 'http';
  1211. this.baseUrl = proto + '://' + databaseInfo.host;
  1212. this.databaseRoot =
  1213. 'projects/' +
  1214. this.databaseId.projectId +
  1215. '/databases/' +
  1216. this.databaseId.database +
  1217. '/documents';
  1218. }
  1219. get shouldResourcePathBeIncludedInRequest() {
  1220. // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
  1221. // where to run the query, and expect the `request` to NOT specify the "path".
  1222. return false;
  1223. }
  1224. invokeRPC(rpcName, path, req, authToken, appCheckToken) {
  1225. const url = this.makeUrl(rpcName, path);
  1226. logDebug(LOG_TAG$3, 'Sending: ', url, req);
  1227. const headers = {};
  1228. this.modifyHeadersForRequest(headers, authToken, appCheckToken);
  1229. return this.performRPCRequest(rpcName, url, headers, req).then(response => {
  1230. logDebug(LOG_TAG$3, 'Received: ', response);
  1231. return response;
  1232. }, (err) => {
  1233. logWarn(LOG_TAG$3, `${rpcName} failed with error: `, err, 'url: ', url, 'request:', req);
  1234. throw err;
  1235. });
  1236. }
  1237. invokeStreamingRPC(rpcName, path, request, authToken, appCheckToken, expectedResponseCount) {
  1238. // The REST API automatically aggregates all of the streamed results, so we
  1239. // can just use the normal invoke() method.
  1240. return this.invokeRPC(rpcName, path, request, authToken, appCheckToken);
  1241. }
  1242. /**
  1243. * Modifies the headers for a request, adding any authorization token if
  1244. * present and any additional headers for the request.
  1245. */
  1246. modifyHeadersForRequest(headers, authToken, appCheckToken) {
  1247. headers['X-Goog-Api-Client'] = getGoogApiClientValue();
  1248. // Content-Type: text/plain will avoid preflight requests which might
  1249. // mess with CORS and redirects by proxies. If we add custom headers
  1250. // we will need to change this code to potentially use the $httpOverwrite
  1251. // parameter supported by ESF to avoid triggering preflight requests.
  1252. headers['Content-Type'] = 'text/plain';
  1253. if (this.databaseInfo.appId) {
  1254. headers['X-Firebase-GMPID'] = this.databaseInfo.appId;
  1255. }
  1256. if (authToken) {
  1257. authToken.headers.forEach((value, key) => (headers[key] = value));
  1258. }
  1259. if (appCheckToken) {
  1260. appCheckToken.headers.forEach((value, key) => (headers[key] = value));
  1261. }
  1262. }
  1263. makeUrl(rpcName, path) {
  1264. const urlRpcName = RPC_NAME_URL_MAPPING[rpcName];
  1265. return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`;
  1266. }
  1267. }
  1268. /**
  1269. * @license
  1270. * Copyright 2017 Google LLC
  1271. *
  1272. * Licensed under the Apache License, Version 2.0 (the "License");
  1273. * you may not use this file except in compliance with the License.
  1274. * You may obtain a copy of the License at
  1275. *
  1276. * http://www.apache.org/licenses/LICENSE-2.0
  1277. *
  1278. * Unless required by applicable law or agreed to in writing, software
  1279. * distributed under the License is distributed on an "AS IS" BASIS,
  1280. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1281. * See the License for the specific language governing permissions and
  1282. * limitations under the License.
  1283. */
  1284. /**
  1285. * Error Codes describing the different ways GRPC can fail. These are copied
  1286. * directly from GRPC's sources here:
  1287. *
  1288. * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  1289. *
  1290. * Important! The names of these identifiers matter because the string forms
  1291. * are used for reverse lookups from the webchannel stream. Do NOT change the
  1292. * names of these identifiers or change this into a const enum.
  1293. */
  1294. var RpcCode;
  1295. (function (RpcCode) {
  1296. RpcCode[RpcCode["OK"] = 0] = "OK";
  1297. RpcCode[RpcCode["CANCELLED"] = 1] = "CANCELLED";
  1298. RpcCode[RpcCode["UNKNOWN"] = 2] = "UNKNOWN";
  1299. RpcCode[RpcCode["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT";
  1300. RpcCode[RpcCode["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED";
  1301. RpcCode[RpcCode["NOT_FOUND"] = 5] = "NOT_FOUND";
  1302. RpcCode[RpcCode["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS";
  1303. RpcCode[RpcCode["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED";
  1304. RpcCode[RpcCode["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED";
  1305. RpcCode[RpcCode["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED";
  1306. RpcCode[RpcCode["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION";
  1307. RpcCode[RpcCode["ABORTED"] = 10] = "ABORTED";
  1308. RpcCode[RpcCode["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE";
  1309. RpcCode[RpcCode["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED";
  1310. RpcCode[RpcCode["INTERNAL"] = 13] = "INTERNAL";
  1311. RpcCode[RpcCode["UNAVAILABLE"] = 14] = "UNAVAILABLE";
  1312. RpcCode[RpcCode["DATA_LOSS"] = 15] = "DATA_LOSS";
  1313. })(RpcCode || (RpcCode = {}));
  1314. /**
  1315. * Determines whether an error code represents a permanent error when received
  1316. * in response to a non-write operation.
  1317. *
  1318. * See isPermanentWriteError for classifying write errors.
  1319. */
  1320. function isPermanentError(code) {
  1321. switch (code) {
  1322. case Code.OK:
  1323. return fail();
  1324. case Code.CANCELLED:
  1325. case Code.UNKNOWN:
  1326. case Code.DEADLINE_EXCEEDED:
  1327. case Code.RESOURCE_EXHAUSTED:
  1328. case Code.INTERNAL:
  1329. case Code.UNAVAILABLE:
  1330. // Unauthenticated means something went wrong with our token and we need
  1331. // to retry with new credentials which will happen automatically.
  1332. case Code.UNAUTHENTICATED:
  1333. return false;
  1334. case Code.INVALID_ARGUMENT:
  1335. case Code.NOT_FOUND:
  1336. case Code.ALREADY_EXISTS:
  1337. case Code.PERMISSION_DENIED:
  1338. case Code.FAILED_PRECONDITION:
  1339. // Aborted might be retried in some scenarios, but that is dependant on
  1340. // the context and should handled individually by the calling code.
  1341. // See https://cloud.google.com/apis/design/errors.
  1342. case Code.ABORTED:
  1343. case Code.OUT_OF_RANGE:
  1344. case Code.UNIMPLEMENTED:
  1345. case Code.DATA_LOSS:
  1346. return true;
  1347. default:
  1348. return fail();
  1349. }
  1350. }
  1351. /**
  1352. * Converts an HTTP Status Code to the equivalent error code.
  1353. *
  1354. * @param status - An HTTP Status Code, like 200, 404, 503, etc.
  1355. * @returns The equivalent Code. Unknown status codes are mapped to
  1356. * Code.UNKNOWN.
  1357. */
  1358. function mapCodeFromHttpStatus(status) {
  1359. if (status === undefined) {
  1360. logError('RPC_ERROR', 'HTTP error has no status');
  1361. return Code.UNKNOWN;
  1362. }
  1363. // The canonical error codes for Google APIs [1] specify mapping onto HTTP
  1364. // status codes but the mapping is not bijective. In each case of ambiguity
  1365. // this function chooses a primary error.
  1366. //
  1367. // [1]
  1368. // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  1369. switch (status) {
  1370. case 200: // OK
  1371. return Code.OK;
  1372. case 400: // Bad Request
  1373. return Code.FAILED_PRECONDITION;
  1374. // Other possibilities based on the forward mapping
  1375. // return Code.INVALID_ARGUMENT;
  1376. // return Code.OUT_OF_RANGE;
  1377. case 401: // Unauthorized
  1378. return Code.UNAUTHENTICATED;
  1379. case 403: // Forbidden
  1380. return Code.PERMISSION_DENIED;
  1381. case 404: // Not Found
  1382. return Code.NOT_FOUND;
  1383. case 409: // Conflict
  1384. return Code.ABORTED;
  1385. // Other possibilities:
  1386. // return Code.ALREADY_EXISTS;
  1387. case 416: // Range Not Satisfiable
  1388. return Code.OUT_OF_RANGE;
  1389. case 429: // Too Many Requests
  1390. return Code.RESOURCE_EXHAUSTED;
  1391. case 499: // Client Closed Request
  1392. return Code.CANCELLED;
  1393. case 500: // Internal Server Error
  1394. return Code.UNKNOWN;
  1395. // Other possibilities:
  1396. // return Code.INTERNAL;
  1397. // return Code.DATA_LOSS;
  1398. case 501: // Unimplemented
  1399. return Code.UNIMPLEMENTED;
  1400. case 503: // Service Unavailable
  1401. return Code.UNAVAILABLE;
  1402. case 504: // Gateway Timeout
  1403. return Code.DEADLINE_EXCEEDED;
  1404. default:
  1405. if (status >= 200 && status < 300) {
  1406. return Code.OK;
  1407. }
  1408. if (status >= 400 && status < 500) {
  1409. return Code.FAILED_PRECONDITION;
  1410. }
  1411. if (status >= 500 && status < 600) {
  1412. return Code.INTERNAL;
  1413. }
  1414. return Code.UNKNOWN;
  1415. }
  1416. }
  1417. /**
  1418. * @license
  1419. * Copyright 2020 Google LLC
  1420. *
  1421. * Licensed under the Apache License, Version 2.0 (the "License");
  1422. * you may not use this file except in compliance with the License.
  1423. * You may obtain a copy of the License at
  1424. *
  1425. * http://www.apache.org/licenses/LICENSE-2.0
  1426. *
  1427. * Unless required by applicable law or agreed to in writing, software
  1428. * distributed under the License is distributed on an "AS IS" BASIS,
  1429. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1430. * See the License for the specific language governing permissions and
  1431. * limitations under the License.
  1432. */
  1433. /**
  1434. * A Rest-based connection that relies on the native HTTP stack
  1435. * (e.g. `fetch` or a polyfill).
  1436. */
  1437. class FetchConnection extends RestConnection {
  1438. /**
  1439. * @param databaseInfo - The connection info.
  1440. * @param fetchImpl - `fetch` or a Polyfill that implements the fetch API.
  1441. */
  1442. constructor(databaseInfo, fetchImpl) {
  1443. super(databaseInfo);
  1444. this.fetchImpl = fetchImpl;
  1445. }
  1446. openStream(rpcName, token) {
  1447. throw new Error('Not supported by FetchConnection');
  1448. }
  1449. async performRPCRequest(rpcName, url, headers, body) {
  1450. var _a;
  1451. const requestJson = JSON.stringify(body);
  1452. let response;
  1453. try {
  1454. response = await this.fetchImpl(url, {
  1455. method: 'POST',
  1456. headers,
  1457. body: requestJson
  1458. });
  1459. }
  1460. catch (e) {
  1461. const err = e;
  1462. throw new FirestoreError(mapCodeFromHttpStatus(err.status), 'Request failed with error: ' + err.statusText);
  1463. }
  1464. if (!response.ok) {
  1465. let errorResponse = await response.json();
  1466. if (Array.isArray(errorResponse)) {
  1467. errorResponse = errorResponse[0];
  1468. }
  1469. const errorMessage = (_a = errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.error) === null || _a === void 0 ? void 0 : _a.message;
  1470. throw new FirestoreError(mapCodeFromHttpStatus(response.status), `Request failed with error: ${errorMessage !== null && errorMessage !== void 0 ? errorMessage : response.statusText}`);
  1471. }
  1472. return response.json();
  1473. }
  1474. }
  1475. /**
  1476. * @license
  1477. * Copyright 2020 Google LLC
  1478. *
  1479. * Licensed under the Apache License, Version 2.0 (the "License");
  1480. * you may not use this file except in compliance with the License.
  1481. * You may obtain a copy of the License at
  1482. *
  1483. * http://www.apache.org/licenses/LICENSE-2.0
  1484. *
  1485. * Unless required by applicable law or agreed to in writing, software
  1486. * distributed under the License is distributed on an "AS IS" BASIS,
  1487. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1488. * See the License for the specific language governing permissions and
  1489. * limitations under the License.
  1490. */
  1491. /** Initializes the HTTP connection for the REST API. */
  1492. function newConnection(databaseInfo) {
  1493. // node-fetch is meant to be API compatible with `fetch`, but its type doesn't
  1494. // match 100%.
  1495. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1496. return new FetchConnection(databaseInfo, nodeFetch__default["default"]);
  1497. }
  1498. /**
  1499. * @license
  1500. * Copyright 2020 Google LLC
  1501. *
  1502. * Licensed under the Apache License, Version 2.0 (the "License");
  1503. * you may not use this file except in compliance with the License.
  1504. * You may obtain a copy of the License at
  1505. *
  1506. * http://www.apache.org/licenses/LICENSE-2.0
  1507. *
  1508. * Unless required by applicable law or agreed to in writing, software
  1509. * distributed under the License is distributed on an "AS IS" BASIS,
  1510. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1511. * See the License for the specific language governing permissions and
  1512. * limitations under the License.
  1513. */
  1514. /**
  1515. * Generates `nBytes` of random bytes.
  1516. *
  1517. * If `nBytes < 0` , an error will be thrown.
  1518. */
  1519. function randomBytes(nBytes) {
  1520. return crypto.randomBytes(nBytes);
  1521. }
  1522. /**
  1523. * @license
  1524. * Copyright 2017 Google LLC
  1525. *
  1526. * Licensed under the Apache License, Version 2.0 (the "License");
  1527. * you may not use this file except in compliance with the License.
  1528. * You may obtain a copy of the License at
  1529. *
  1530. * http://www.apache.org/licenses/LICENSE-2.0
  1531. *
  1532. * Unless required by applicable law or agreed to in writing, software
  1533. * distributed under the License is distributed on an "AS IS" BASIS,
  1534. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1535. * See the License for the specific language governing permissions and
  1536. * limitations under the License.
  1537. */
  1538. class AutoId {
  1539. static newId() {
  1540. // Alphanumeric characters
  1541. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  1542. // The largest byte value that is a multiple of `char.length`.
  1543. const maxMultiple = Math.floor(256 / chars.length) * chars.length;
  1544. let autoId = '';
  1545. const targetLength = 20;
  1546. while (autoId.length < targetLength) {
  1547. const bytes = randomBytes(40);
  1548. for (let i = 0; i < bytes.length; ++i) {
  1549. // Only accept values that are [0, maxMultiple), this ensures they can
  1550. // be evenly mapped to indices of `chars` via a modulo operation.
  1551. if (autoId.length < targetLength && bytes[i] < maxMultiple) {
  1552. autoId += chars.charAt(bytes[i] % chars.length);
  1553. }
  1554. }
  1555. }
  1556. return autoId;
  1557. }
  1558. }
  1559. function primitiveComparator(left, right) {
  1560. if (left < right) {
  1561. return -1;
  1562. }
  1563. if (left > right) {
  1564. return 1;
  1565. }
  1566. return 0;
  1567. }
  1568. /** Helper to compare arrays using isEqual(). */
  1569. function arrayEquals(left, right, comparator) {
  1570. if (left.length !== right.length) {
  1571. return false;
  1572. }
  1573. return left.every((value, index) => comparator(value, right[index]));
  1574. }
  1575. /**
  1576. * @license
  1577. * Copyright 2017 Google LLC
  1578. *
  1579. * Licensed under the Apache License, Version 2.0 (the "License");
  1580. * you may not use this file except in compliance with the License.
  1581. * You may obtain a copy of the License at
  1582. *
  1583. * http://www.apache.org/licenses/LICENSE-2.0
  1584. *
  1585. * Unless required by applicable law or agreed to in writing, software
  1586. * distributed under the License is distributed on an "AS IS" BASIS,
  1587. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1588. * See the License for the specific language governing permissions and
  1589. * limitations under the License.
  1590. */
  1591. function objectSize(obj) {
  1592. let count = 0;
  1593. for (const key in obj) {
  1594. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1595. count++;
  1596. }
  1597. }
  1598. return count;
  1599. }
  1600. function forEach(obj, fn) {
  1601. for (const key in obj) {
  1602. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1603. fn(key, obj[key]);
  1604. }
  1605. }
  1606. }
  1607. function isEmpty(obj) {
  1608. for (const key in obj) {
  1609. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1610. return false;
  1611. }
  1612. }
  1613. return true;
  1614. }
  1615. /**
  1616. * @license
  1617. * Copyright 2017 Google LLC
  1618. *
  1619. * Licensed under the Apache License, Version 2.0 (the "License");
  1620. * you may not use this file except in compliance with the License.
  1621. * You may obtain a copy of the License at
  1622. *
  1623. * http://www.apache.org/licenses/LICENSE-2.0
  1624. *
  1625. * Unless required by applicable law or agreed to in writing, software
  1626. * distributed under the License is distributed on an "AS IS" BASIS,
  1627. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1628. * See the License for the specific language governing permissions and
  1629. * limitations under the License.
  1630. */
  1631. /**
  1632. * Returns whether a variable is either undefined or null.
  1633. */
  1634. function isNullOrUndefined(value) {
  1635. return value === null || value === undefined;
  1636. }
  1637. /** Returns whether the value represents -0. */
  1638. function isNegativeZero(value) {
  1639. // Detect if the value is -0.0. Based on polyfill from
  1640. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  1641. return value === 0 && 1 / value === 1 / -0;
  1642. }
  1643. /**
  1644. * Returns whether a value is an integer and in the safe integer range
  1645. * @param value - The value to test for being an integer and in the safe range
  1646. */
  1647. function isSafeInteger(value) {
  1648. return (typeof value === 'number' &&
  1649. Number.isInteger(value) &&
  1650. !isNegativeZero(value) &&
  1651. value <= Number.MAX_SAFE_INTEGER &&
  1652. value >= Number.MIN_SAFE_INTEGER);
  1653. }
  1654. /**
  1655. * @license
  1656. * Copyright 2020 Google LLC
  1657. *
  1658. * Licensed under the Apache License, Version 2.0 (the "License");
  1659. * you may not use this file except in compliance with the License.
  1660. * You may obtain a copy of the License at
  1661. *
  1662. * http://www.apache.org/licenses/LICENSE-2.0
  1663. *
  1664. * Unless required by applicable law or agreed to in writing, software
  1665. * distributed under the License is distributed on an "AS IS" BASIS,
  1666. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1667. * See the License for the specific language governing permissions and
  1668. * limitations under the License.
  1669. */
  1670. /** Converts a Base64 encoded string to a binary string. */
  1671. function decodeBase64(encoded) {
  1672. // Note: We used to validate the base64 string here via a regular expression.
  1673. // This was removed to improve the performance of indexing.
  1674. return Buffer.from(encoded, 'base64').toString('binary');
  1675. }
  1676. /** Converts a binary string to a Base64 encoded string. */
  1677. function encodeBase64(raw) {
  1678. return Buffer.from(raw, 'binary').toString('base64');
  1679. }
  1680. /**
  1681. * @license
  1682. * Copyright 2020 Google LLC
  1683. *
  1684. * Licensed under the Apache License, Version 2.0 (the "License");
  1685. * you may not use this file except in compliance with the License.
  1686. * You may obtain a copy of the License at
  1687. *
  1688. * http://www.apache.org/licenses/LICENSE-2.0
  1689. *
  1690. * Unless required by applicable law or agreed to in writing, software
  1691. * distributed under the License is distributed on an "AS IS" BASIS,
  1692. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1693. * See the License for the specific language governing permissions and
  1694. * limitations under the License.
  1695. */
  1696. /**
  1697. * Immutable class that represents a "proto" byte string.
  1698. *
  1699. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  1700. * sent on the wire. This class abstracts away this differentiation by holding
  1701. * the proto byte string in a common class that must be converted into a string
  1702. * before being sent as a proto.
  1703. * @internal
  1704. */
  1705. class ByteString {
  1706. constructor(binaryString) {
  1707. this.binaryString = binaryString;
  1708. }
  1709. static fromBase64String(base64) {
  1710. const binaryString = decodeBase64(base64);
  1711. return new ByteString(binaryString);
  1712. }
  1713. static fromUint8Array(array) {
  1714. // TODO(indexing); Remove the copy of the byte string here as this method
  1715. // is frequently called during indexing.
  1716. const binaryString = binaryStringFromUint8Array(array);
  1717. return new ByteString(binaryString);
  1718. }
  1719. [Symbol.iterator]() {
  1720. let i = 0;
  1721. return {
  1722. next: () => {
  1723. if (i < this.binaryString.length) {
  1724. return { value: this.binaryString.charCodeAt(i++), done: false };
  1725. }
  1726. else {
  1727. return { value: undefined, done: true };
  1728. }
  1729. }
  1730. };
  1731. }
  1732. toBase64() {
  1733. return encodeBase64(this.binaryString);
  1734. }
  1735. toUint8Array() {
  1736. return uint8ArrayFromBinaryString(this.binaryString);
  1737. }
  1738. approximateByteSize() {
  1739. return this.binaryString.length * 2;
  1740. }
  1741. compareTo(other) {
  1742. return primitiveComparator(this.binaryString, other.binaryString);
  1743. }
  1744. isEqual(other) {
  1745. return this.binaryString === other.binaryString;
  1746. }
  1747. }
  1748. ByteString.EMPTY_BYTE_STRING = new ByteString('');
  1749. /**
  1750. * Helper function to convert an Uint8array to a binary string.
  1751. */
  1752. function binaryStringFromUint8Array(array) {
  1753. let binaryString = '';
  1754. for (let i = 0; i < array.length; ++i) {
  1755. binaryString += String.fromCharCode(array[i]);
  1756. }
  1757. return binaryString;
  1758. }
  1759. /**
  1760. * Helper function to convert a binary string to an Uint8Array.
  1761. */
  1762. function uint8ArrayFromBinaryString(binaryString) {
  1763. const buffer = new Uint8Array(binaryString.length);
  1764. for (let i = 0; i < binaryString.length; i++) {
  1765. buffer[i] = binaryString.charCodeAt(i);
  1766. }
  1767. return buffer;
  1768. }
  1769. /**
  1770. * @license
  1771. * Copyright 2020 Google LLC
  1772. *
  1773. * Licensed under the Apache License, Version 2.0 (the "License");
  1774. * you may not use this file except in compliance with the License.
  1775. * You may obtain a copy of the License at
  1776. *
  1777. * http://www.apache.org/licenses/LICENSE-2.0
  1778. *
  1779. * Unless required by applicable law or agreed to in writing, software
  1780. * distributed under the License is distributed on an "AS IS" BASIS,
  1781. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1782. * See the License for the specific language governing permissions and
  1783. * limitations under the License.
  1784. */
  1785. // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
  1786. const ISO_TIMESTAMP_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  1787. /**
  1788. * Converts the possible Proto values for a timestamp value into a "seconds and
  1789. * nanos" representation.
  1790. */
  1791. function normalizeTimestamp(date) {
  1792. hardAssert(!!date);
  1793. // The json interface (for the browser) will return an iso timestamp string,
  1794. // while the proto js library (for node) will return a
  1795. // google.protobuf.Timestamp instance.
  1796. if (typeof date === 'string') {
  1797. // The date string can have higher precision (nanos) than the Date class
  1798. // (millis), so we do some custom parsing here.
  1799. // Parse the nanos right out of the string.
  1800. let nanos = 0;
  1801. const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);
  1802. hardAssert(!!fraction);
  1803. if (fraction[1]) {
  1804. // Pad the fraction out to 9 digits (nanos).
  1805. let nanoStr = fraction[1];
  1806. nanoStr = (nanoStr + '000000000').substr(0, 9);
  1807. nanos = Number(nanoStr);
  1808. }
  1809. // Parse the date to get the seconds.
  1810. const parsedDate = new Date(date);
  1811. const seconds = Math.floor(parsedDate.getTime() / 1000);
  1812. return { seconds, nanos };
  1813. }
  1814. else {
  1815. // TODO(b/37282237): Use strings for Proto3 timestamps
  1816. // assert(!this.options.useProto3Json,
  1817. // 'The timestamp instance format requires Proto JS.');
  1818. const seconds = normalizeNumber(date.seconds);
  1819. const nanos = normalizeNumber(date.nanos);
  1820. return { seconds, nanos };
  1821. }
  1822. }
  1823. /**
  1824. * Converts the possible Proto types for numbers into a JavaScript number.
  1825. * Returns 0 if the value is not numeric.
  1826. */
  1827. function normalizeNumber(value) {
  1828. // TODO(bjornick): Handle int64 greater than 53 bits.
  1829. if (typeof value === 'number') {
  1830. return value;
  1831. }
  1832. else if (typeof value === 'string') {
  1833. return Number(value);
  1834. }
  1835. else {
  1836. return 0;
  1837. }
  1838. }
  1839. /** Converts the possible Proto types for Blobs into a ByteString. */
  1840. function normalizeByteString(blob) {
  1841. if (typeof blob === 'string') {
  1842. return ByteString.fromBase64String(blob);
  1843. }
  1844. else {
  1845. return ByteString.fromUint8Array(blob);
  1846. }
  1847. }
  1848. /**
  1849. * @license
  1850. * Copyright 2017 Google LLC
  1851. *
  1852. * Licensed under the Apache License, Version 2.0 (the "License");
  1853. * you may not use this file except in compliance with the License.
  1854. * You may obtain a copy of the License at
  1855. *
  1856. * http://www.apache.org/licenses/LICENSE-2.0
  1857. *
  1858. * Unless required by applicable law or agreed to in writing, software
  1859. * distributed under the License is distributed on an "AS IS" BASIS,
  1860. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1861. * See the License for the specific language governing permissions and
  1862. * limitations under the License.
  1863. */
  1864. // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
  1865. const MIN_SECONDS = -62135596800;
  1866. // Number of nanoseconds in a millisecond.
  1867. const MS_TO_NANOS = 1e6;
  1868. /**
  1869. * A `Timestamp` represents a point in time independent of any time zone or
  1870. * calendar, represented as seconds and fractions of seconds at nanosecond
  1871. * resolution in UTC Epoch time.
  1872. *
  1873. * It is encoded using the Proleptic Gregorian Calendar which extends the
  1874. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  1875. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  1876. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  1877. * 9999-12-31T23:59:59.999999999Z.
  1878. *
  1879. * For examples and further specifications, refer to the
  1880. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  1881. */
  1882. class Timestamp {
  1883. /**
  1884. * Creates a new timestamp.
  1885. *
  1886. * @param seconds - The number of seconds of UTC time since Unix epoch
  1887. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  1888. * 9999-12-31T23:59:59Z inclusive.
  1889. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  1890. * resolution. Negative second values with fractions must still have
  1891. * non-negative nanoseconds values that count forward in time. Must be
  1892. * from 0 to 999,999,999 inclusive.
  1893. */
  1894. constructor(
  1895. /**
  1896. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  1897. */
  1898. seconds,
  1899. /**
  1900. * The fractions of a second at nanosecond resolution.*
  1901. */
  1902. nanoseconds) {
  1903. this.seconds = seconds;
  1904. this.nanoseconds = nanoseconds;
  1905. if (nanoseconds < 0) {
  1906. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);
  1907. }
  1908. if (nanoseconds >= 1e9) {
  1909. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);
  1910. }
  1911. if (seconds < MIN_SECONDS) {
  1912. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);
  1913. }
  1914. // This will break in the year 10,000.
  1915. if (seconds >= 253402300800) {
  1916. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);
  1917. }
  1918. }
  1919. /**
  1920. * Creates a new timestamp with the current date, with millisecond precision.
  1921. *
  1922. * @returns a new timestamp representing the current date.
  1923. */
  1924. static now() {
  1925. return Timestamp.fromMillis(Date.now());
  1926. }
  1927. /**
  1928. * Creates a new timestamp from the given date.
  1929. *
  1930. * @param date - The date to initialize the `Timestamp` from.
  1931. * @returns A new `Timestamp` representing the same point in time as the given
  1932. * date.
  1933. */
  1934. static fromDate(date) {
  1935. return Timestamp.fromMillis(date.getTime());
  1936. }
  1937. /**
  1938. * Creates a new timestamp from the given number of milliseconds.
  1939. *
  1940. * @param milliseconds - Number of milliseconds since Unix epoch
  1941. * 1970-01-01T00:00:00Z.
  1942. * @returns A new `Timestamp` representing the same point in time as the given
  1943. * number of milliseconds.
  1944. */
  1945. static fromMillis(milliseconds) {
  1946. const seconds = Math.floor(milliseconds / 1000);
  1947. const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);
  1948. return new Timestamp(seconds, nanos);
  1949. }
  1950. /**
  1951. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  1952. * causes a loss of precision since `Date` objects only support millisecond
  1953. * precision.
  1954. *
  1955. * @returns JavaScript `Date` object representing the same point in time as
  1956. * this `Timestamp`, with millisecond precision.
  1957. */
  1958. toDate() {
  1959. return new Date(this.toMillis());
  1960. }
  1961. /**
  1962. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  1963. * epoch). This operation causes a loss of precision.
  1964. *
  1965. * @returns The point in time corresponding to this timestamp, represented as
  1966. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  1967. */
  1968. toMillis() {
  1969. return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;
  1970. }
  1971. _compareTo(other) {
  1972. if (this.seconds === other.seconds) {
  1973. return primitiveComparator(this.nanoseconds, other.nanoseconds);
  1974. }
  1975. return primitiveComparator(this.seconds, other.seconds);
  1976. }
  1977. /**
  1978. * Returns true if this `Timestamp` is equal to the provided one.
  1979. *
  1980. * @param other - The `Timestamp` to compare against.
  1981. * @returns true if this `Timestamp` is equal to the provided one.
  1982. */
  1983. isEqual(other) {
  1984. return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds);
  1985. }
  1986. /** Returns a textual representation of this `Timestamp`. */
  1987. toString() {
  1988. return ('Timestamp(seconds=' +
  1989. this.seconds +
  1990. ', nanoseconds=' +
  1991. this.nanoseconds +
  1992. ')');
  1993. }
  1994. /** Returns a JSON-serializable representation of this `Timestamp`. */
  1995. toJSON() {
  1996. return { seconds: this.seconds, nanoseconds: this.nanoseconds };
  1997. }
  1998. /**
  1999. * Converts this object to a primitive string, which allows `Timestamp` objects
  2000. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  2001. */
  2002. valueOf() {
  2003. // This method returns a string of the form <seconds>.<nanoseconds> where
  2004. // <seconds> is translated to have a non-negative value and both <seconds>
  2005. // and <nanoseconds> are left-padded with zeroes to be a consistent length.
  2006. // Strings with this format then have a lexiographical ordering that matches
  2007. // the expected ordering. The <seconds> translation is done to avoid having
  2008. // a leading negative sign (i.e. a leading '-' character) in its string
  2009. // representation, which would affect its lexiographical ordering.
  2010. const adjustedSeconds = this.seconds - MIN_SECONDS;
  2011. // Note: Up to 12 decimal digits are required to represent all valid
  2012. // 'seconds' values.
  2013. const formattedSeconds = String(adjustedSeconds).padStart(12, '0');
  2014. const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');
  2015. return formattedSeconds + '.' + formattedNanoseconds;
  2016. }
  2017. }
  2018. /**
  2019. * @license
  2020. * Copyright 2020 Google LLC
  2021. *
  2022. * Licensed under the Apache License, Version 2.0 (the "License");
  2023. * you may not use this file except in compliance with the License.
  2024. * You may obtain a copy of the License at
  2025. *
  2026. * http://www.apache.org/licenses/LICENSE-2.0
  2027. *
  2028. * Unless required by applicable law or agreed to in writing, software
  2029. * distributed under the License is distributed on an "AS IS" BASIS,
  2030. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2031. * See the License for the specific language governing permissions and
  2032. * limitations under the License.
  2033. */
  2034. /**
  2035. * Represents a locally-applied ServerTimestamp.
  2036. *
  2037. * Server Timestamps are backed by MapValues that contain an internal field
  2038. * `__type__` with a value of `server_timestamp`. The previous value and local
  2039. * write time are stored in its `__previous_value__` and `__local_write_time__`
  2040. * fields respectively.
  2041. *
  2042. * Notes:
  2043. * - ServerTimestampValue instances are created as the result of applying a
  2044. * transform. They can only exist in the local view of a document. Therefore
  2045. * they do not need to be parsed or serialized.
  2046. * - When evaluated locally (e.g. for snapshot.data()), they by default
  2047. * evaluate to `null`. This behavior can be configured by passing custom
  2048. * FieldValueOptions to value().
  2049. * - With respect to other ServerTimestampValues, they sort by their
  2050. * localWriteTime.
  2051. */
  2052. const SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';
  2053. const TYPE_KEY = '__type__';
  2054. const PREVIOUS_VALUE_KEY = '__previous_value__';
  2055. const LOCAL_WRITE_TIME_KEY = '__local_write_time__';
  2056. function isServerTimestamp(value) {
  2057. var _a, _b;
  2058. const type = (_b = (((_a = value === null || value === void 0 ? void 0 : value.mapValue) === null || _a === void 0 ? void 0 : _a.fields) || {})[TYPE_KEY]) === null || _b === void 0 ? void 0 : _b.stringValue;
  2059. return type === SERVER_TIMESTAMP_SENTINEL;
  2060. }
  2061. /**
  2062. * Returns the value of the field before this ServerTimestamp was set.
  2063. *
  2064. * Preserving the previous values allows the user to display the last resoled
  2065. * value until the backend responds with the timestamp.
  2066. */
  2067. function getPreviousValue(value) {
  2068. const previousValue = value.mapValue.fields[PREVIOUS_VALUE_KEY];
  2069. if (isServerTimestamp(previousValue)) {
  2070. return getPreviousValue(previousValue);
  2071. }
  2072. return previousValue;
  2073. }
  2074. /**
  2075. * Returns the local time at which this timestamp was first set.
  2076. */
  2077. function getLocalWriteTime(value) {
  2078. const localWriteTime = normalizeTimestamp(value.mapValue.fields[LOCAL_WRITE_TIME_KEY].timestampValue);
  2079. return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);
  2080. }
  2081. /**
  2082. * @license
  2083. * Copyright 2020 Google LLC
  2084. *
  2085. * Licensed under the Apache License, Version 2.0 (the "License");
  2086. * you may not use this file except in compliance with the License.
  2087. * You may obtain a copy of the License at
  2088. *
  2089. * http://www.apache.org/licenses/LICENSE-2.0
  2090. *
  2091. * Unless required by applicable law or agreed to in writing, software
  2092. * distributed under the License is distributed on an "AS IS" BASIS,
  2093. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2094. * See the License for the specific language governing permissions and
  2095. * limitations under the License.
  2096. */
  2097. const MAX_VALUE_TYPE = '__max__';
  2098. const MAX_VALUE = {
  2099. mapValue: {
  2100. fields: {
  2101. '__type__': { stringValue: MAX_VALUE_TYPE }
  2102. }
  2103. }
  2104. };
  2105. /** Extracts the backend's type order for the provided value. */
  2106. function typeOrder(value) {
  2107. if ('nullValue' in value) {
  2108. return 0 /* TypeOrder.NullValue */;
  2109. }
  2110. else if ('booleanValue' in value) {
  2111. return 1 /* TypeOrder.BooleanValue */;
  2112. }
  2113. else if ('integerValue' in value || 'doubleValue' in value) {
  2114. return 2 /* TypeOrder.NumberValue */;
  2115. }
  2116. else if ('timestampValue' in value) {
  2117. return 3 /* TypeOrder.TimestampValue */;
  2118. }
  2119. else if ('stringValue' in value) {
  2120. return 5 /* TypeOrder.StringValue */;
  2121. }
  2122. else if ('bytesValue' in value) {
  2123. return 6 /* TypeOrder.BlobValue */;
  2124. }
  2125. else if ('referenceValue' in value) {
  2126. return 7 /* TypeOrder.RefValue */;
  2127. }
  2128. else if ('geoPointValue' in value) {
  2129. return 8 /* TypeOrder.GeoPointValue */;
  2130. }
  2131. else if ('arrayValue' in value) {
  2132. return 9 /* TypeOrder.ArrayValue */;
  2133. }
  2134. else if ('mapValue' in value) {
  2135. if (isServerTimestamp(value)) {
  2136. return 4 /* TypeOrder.ServerTimestampValue */;
  2137. }
  2138. else if (isMaxValue(value)) {
  2139. return 9007199254740991 /* TypeOrder.MaxValue */;
  2140. }
  2141. return 10 /* TypeOrder.ObjectValue */;
  2142. }
  2143. else {
  2144. return fail();
  2145. }
  2146. }
  2147. /** Tests `left` and `right` for equality based on the backend semantics. */
  2148. function valueEquals(left, right) {
  2149. if (left === right) {
  2150. return true;
  2151. }
  2152. const leftType = typeOrder(left);
  2153. const rightType = typeOrder(right);
  2154. if (leftType !== rightType) {
  2155. return false;
  2156. }
  2157. switch (leftType) {
  2158. case 0 /* TypeOrder.NullValue */:
  2159. return true;
  2160. case 1 /* TypeOrder.BooleanValue */:
  2161. return left.booleanValue === right.booleanValue;
  2162. case 4 /* TypeOrder.ServerTimestampValue */:
  2163. return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));
  2164. case 3 /* TypeOrder.TimestampValue */:
  2165. return timestampEquals(left, right);
  2166. case 5 /* TypeOrder.StringValue */:
  2167. return left.stringValue === right.stringValue;
  2168. case 6 /* TypeOrder.BlobValue */:
  2169. return blobEquals(left, right);
  2170. case 7 /* TypeOrder.RefValue */:
  2171. return left.referenceValue === right.referenceValue;
  2172. case 8 /* TypeOrder.GeoPointValue */:
  2173. return geoPointEquals(left, right);
  2174. case 2 /* TypeOrder.NumberValue */:
  2175. return numberEquals(left, right);
  2176. case 9 /* TypeOrder.ArrayValue */:
  2177. return arrayEquals(left.arrayValue.values || [], right.arrayValue.values || [], valueEquals);
  2178. case 10 /* TypeOrder.ObjectValue */:
  2179. return objectEquals(left, right);
  2180. case 9007199254740991 /* TypeOrder.MaxValue */:
  2181. return true;
  2182. default:
  2183. return fail();
  2184. }
  2185. }
  2186. function timestampEquals(left, right) {
  2187. if (typeof left.timestampValue === 'string' &&
  2188. typeof right.timestampValue === 'string' &&
  2189. left.timestampValue.length === right.timestampValue.length) {
  2190. // Use string equality for ISO 8601 timestamps
  2191. return left.timestampValue === right.timestampValue;
  2192. }
  2193. const leftTimestamp = normalizeTimestamp(left.timestampValue);
  2194. const rightTimestamp = normalizeTimestamp(right.timestampValue);
  2195. return (leftTimestamp.seconds === rightTimestamp.seconds &&
  2196. leftTimestamp.nanos === rightTimestamp.nanos);
  2197. }
  2198. function geoPointEquals(left, right) {
  2199. return (normalizeNumber(left.geoPointValue.latitude) ===
  2200. normalizeNumber(right.geoPointValue.latitude) &&
  2201. normalizeNumber(left.geoPointValue.longitude) ===
  2202. normalizeNumber(right.geoPointValue.longitude));
  2203. }
  2204. function blobEquals(left, right) {
  2205. return normalizeByteString(left.bytesValue).isEqual(normalizeByteString(right.bytesValue));
  2206. }
  2207. function numberEquals(left, right) {
  2208. if ('integerValue' in left && 'integerValue' in right) {
  2209. return (normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue));
  2210. }
  2211. else if ('doubleValue' in left && 'doubleValue' in right) {
  2212. const n1 = normalizeNumber(left.doubleValue);
  2213. const n2 = normalizeNumber(right.doubleValue);
  2214. if (n1 === n2) {
  2215. return isNegativeZero(n1) === isNegativeZero(n2);
  2216. }
  2217. else {
  2218. return isNaN(n1) && isNaN(n2);
  2219. }
  2220. }
  2221. return false;
  2222. }
  2223. function objectEquals(left, right) {
  2224. const leftMap = left.mapValue.fields || {};
  2225. const rightMap = right.mapValue.fields || {};
  2226. if (objectSize(leftMap) !== objectSize(rightMap)) {
  2227. return false;
  2228. }
  2229. for (const key in leftMap) {
  2230. if (leftMap.hasOwnProperty(key)) {
  2231. if (rightMap[key] === undefined ||
  2232. !valueEquals(leftMap[key], rightMap[key])) {
  2233. return false;
  2234. }
  2235. }
  2236. }
  2237. return true;
  2238. }
  2239. /** Returns true if the ArrayValue contains the specified element. */
  2240. function arrayValueContains(haystack, needle) {
  2241. return ((haystack.values || []).find(v => valueEquals(v, needle)) !== undefined);
  2242. }
  2243. function valueCompare(left, right) {
  2244. if (left === right) {
  2245. return 0;
  2246. }
  2247. const leftType = typeOrder(left);
  2248. const rightType = typeOrder(right);
  2249. if (leftType !== rightType) {
  2250. return primitiveComparator(leftType, rightType);
  2251. }
  2252. switch (leftType) {
  2253. case 0 /* TypeOrder.NullValue */:
  2254. case 9007199254740991 /* TypeOrder.MaxValue */:
  2255. return 0;
  2256. case 1 /* TypeOrder.BooleanValue */:
  2257. return primitiveComparator(left.booleanValue, right.booleanValue);
  2258. case 2 /* TypeOrder.NumberValue */:
  2259. return compareNumbers(left, right);
  2260. case 3 /* TypeOrder.TimestampValue */:
  2261. return compareTimestamps(left.timestampValue, right.timestampValue);
  2262. case 4 /* TypeOrder.ServerTimestampValue */:
  2263. return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right));
  2264. case 5 /* TypeOrder.StringValue */:
  2265. return primitiveComparator(left.stringValue, right.stringValue);
  2266. case 6 /* TypeOrder.BlobValue */:
  2267. return compareBlobs(left.bytesValue, right.bytesValue);
  2268. case 7 /* TypeOrder.RefValue */:
  2269. return compareReferences(left.referenceValue, right.referenceValue);
  2270. case 8 /* TypeOrder.GeoPointValue */:
  2271. return compareGeoPoints(left.geoPointValue, right.geoPointValue);
  2272. case 9 /* TypeOrder.ArrayValue */:
  2273. return compareArrays(left.arrayValue, right.arrayValue);
  2274. case 10 /* TypeOrder.ObjectValue */:
  2275. return compareMaps(left.mapValue, right.mapValue);
  2276. default:
  2277. throw fail();
  2278. }
  2279. }
  2280. function compareNumbers(left, right) {
  2281. const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);
  2282. const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);
  2283. if (leftNumber < rightNumber) {
  2284. return -1;
  2285. }
  2286. else if (leftNumber > rightNumber) {
  2287. return 1;
  2288. }
  2289. else if (leftNumber === rightNumber) {
  2290. return 0;
  2291. }
  2292. else {
  2293. // one or both are NaN.
  2294. if (isNaN(leftNumber)) {
  2295. return isNaN(rightNumber) ? 0 : -1;
  2296. }
  2297. else {
  2298. return 1;
  2299. }
  2300. }
  2301. }
  2302. function compareTimestamps(left, right) {
  2303. if (typeof left === 'string' &&
  2304. typeof right === 'string' &&
  2305. left.length === right.length) {
  2306. return primitiveComparator(left, right);
  2307. }
  2308. const leftTimestamp = normalizeTimestamp(left);
  2309. const rightTimestamp = normalizeTimestamp(right);
  2310. const comparison = primitiveComparator(leftTimestamp.seconds, rightTimestamp.seconds);
  2311. if (comparison !== 0) {
  2312. return comparison;
  2313. }
  2314. return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);
  2315. }
  2316. function compareReferences(leftPath, rightPath) {
  2317. const leftSegments = leftPath.split('/');
  2318. const rightSegments = rightPath.split('/');
  2319. for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {
  2320. const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);
  2321. if (comparison !== 0) {
  2322. return comparison;
  2323. }
  2324. }
  2325. return primitiveComparator(leftSegments.length, rightSegments.length);
  2326. }
  2327. function compareGeoPoints(left, right) {
  2328. const comparison = primitiveComparator(normalizeNumber(left.latitude), normalizeNumber(right.latitude));
  2329. if (comparison !== 0) {
  2330. return comparison;
  2331. }
  2332. return primitiveComparator(normalizeNumber(left.longitude), normalizeNumber(right.longitude));
  2333. }
  2334. function compareBlobs(left, right) {
  2335. const leftBytes = normalizeByteString(left);
  2336. const rightBytes = normalizeByteString(right);
  2337. return leftBytes.compareTo(rightBytes);
  2338. }
  2339. function compareArrays(left, right) {
  2340. const leftArray = left.values || [];
  2341. const rightArray = right.values || [];
  2342. for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {
  2343. const compare = valueCompare(leftArray[i], rightArray[i]);
  2344. if (compare) {
  2345. return compare;
  2346. }
  2347. }
  2348. return primitiveComparator(leftArray.length, rightArray.length);
  2349. }
  2350. function compareMaps(left, right) {
  2351. if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {
  2352. return 0;
  2353. }
  2354. else if (left === MAX_VALUE.mapValue) {
  2355. return 1;
  2356. }
  2357. else if (right === MAX_VALUE.mapValue) {
  2358. return -1;
  2359. }
  2360. const leftMap = left.fields || {};
  2361. const leftKeys = Object.keys(leftMap);
  2362. const rightMap = right.fields || {};
  2363. const rightKeys = Object.keys(rightMap);
  2364. // Even though MapValues are likely sorted correctly based on their insertion
  2365. // order (e.g. when received from the backend), local modifications can bring
  2366. // elements out of order. We need to re-sort the elements to ensure that
  2367. // canonical IDs are independent of insertion order.
  2368. leftKeys.sort();
  2369. rightKeys.sort();
  2370. for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {
  2371. const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]);
  2372. if (keyCompare !== 0) {
  2373. return keyCompare;
  2374. }
  2375. const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);
  2376. if (compare !== 0) {
  2377. return compare;
  2378. }
  2379. }
  2380. return primitiveComparator(leftKeys.length, rightKeys.length);
  2381. }
  2382. /** Returns a reference value for the provided database and key. */
  2383. function refValue(databaseId, key) {
  2384. return {
  2385. referenceValue: `projects/${databaseId.projectId}/databases/${databaseId.database}/documents/${key.path.canonicalString()}`
  2386. };
  2387. }
  2388. /** Returns true if `value` is an ArrayValue. */
  2389. function isArray(value) {
  2390. return !!value && 'arrayValue' in value;
  2391. }
  2392. /** Returns true if `value` is a NullValue. */
  2393. function isNullValue(value) {
  2394. return !!value && 'nullValue' in value;
  2395. }
  2396. /** Returns true if `value` is NaN. */
  2397. function isNanValue(value) {
  2398. return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));
  2399. }
  2400. /** Returns true if `value` is a MapValue. */
  2401. function isMapValue(value) {
  2402. return !!value && 'mapValue' in value;
  2403. }
  2404. /** Creates a deep copy of `source`. */
  2405. function deepClone(source) {
  2406. if (source.geoPointValue) {
  2407. return { geoPointValue: Object.assign({}, source.geoPointValue) };
  2408. }
  2409. else if (source.timestampValue &&
  2410. typeof source.timestampValue === 'object') {
  2411. return { timestampValue: Object.assign({}, source.timestampValue) };
  2412. }
  2413. else if (source.mapValue) {
  2414. const target = { mapValue: { fields: {} } };
  2415. forEach(source.mapValue.fields, (key, val) => (target.mapValue.fields[key] = deepClone(val)));
  2416. return target;
  2417. }
  2418. else if (source.arrayValue) {
  2419. const target = { arrayValue: { values: [] } };
  2420. for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {
  2421. target.arrayValue.values[i] = deepClone(source.arrayValue.values[i]);
  2422. }
  2423. return target;
  2424. }
  2425. else {
  2426. return Object.assign({}, source);
  2427. }
  2428. }
  2429. /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */
  2430. function isMaxValue(value) {
  2431. return ((((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===
  2432. MAX_VALUE_TYPE);
  2433. }
  2434. /**
  2435. * @license
  2436. * Copyright 2022 Google LLC
  2437. *
  2438. * Licensed under the Apache License, Version 2.0 (the "License");
  2439. * you may not use this file except in compliance with the License.
  2440. * You may obtain a copy of the License at
  2441. *
  2442. * http://www.apache.org/licenses/LICENSE-2.0
  2443. *
  2444. * Unless required by applicable law or agreed to in writing, software
  2445. * distributed under the License is distributed on an "AS IS" BASIS,
  2446. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2447. * See the License for the specific language governing permissions and
  2448. * limitations under the License.
  2449. */
  2450. /**
  2451. * Represents a bound of a query.
  2452. *
  2453. * The bound is specified with the given components representing a position and
  2454. * whether it's just before or just after the position (relative to whatever the
  2455. * query order is).
  2456. *
  2457. * The position represents a logical index position for a query. It's a prefix
  2458. * of values for the (potentially implicit) order by clauses of a query.
  2459. *
  2460. * Bound provides a function to determine whether a document comes before or
  2461. * after a bound. This is influenced by whether the position is just before or
  2462. * just after the provided values.
  2463. */
  2464. class Bound {
  2465. constructor(position, inclusive) {
  2466. this.position = position;
  2467. this.inclusive = inclusive;
  2468. }
  2469. }
  2470. function boundEquals(left, right) {
  2471. if (left === null) {
  2472. return right === null;
  2473. }
  2474. else if (right === null) {
  2475. return false;
  2476. }
  2477. if (left.inclusive !== right.inclusive ||
  2478. left.position.length !== right.position.length) {
  2479. return false;
  2480. }
  2481. for (let i = 0; i < left.position.length; i++) {
  2482. const leftPosition = left.position[i];
  2483. const rightPosition = right.position[i];
  2484. if (!valueEquals(leftPosition, rightPosition)) {
  2485. return false;
  2486. }
  2487. }
  2488. return true;
  2489. }
  2490. /**
  2491. * @license
  2492. * Copyright 2022 Google LLC
  2493. *
  2494. * Licensed under the Apache License, Version 2.0 (the "License");
  2495. * you may not use this file except in compliance with the License.
  2496. * You may obtain a copy of the License at
  2497. *
  2498. * http://www.apache.org/licenses/LICENSE-2.0
  2499. *
  2500. * Unless required by applicable law or agreed to in writing, software
  2501. * distributed under the License is distributed on an "AS IS" BASIS,
  2502. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2503. * See the License for the specific language governing permissions and
  2504. * limitations under the License.
  2505. */
  2506. class Filter {
  2507. }
  2508. class FieldFilter extends Filter {
  2509. constructor(field, op, value) {
  2510. super();
  2511. this.field = field;
  2512. this.op = op;
  2513. this.value = value;
  2514. }
  2515. /**
  2516. * Creates a filter based on the provided arguments.
  2517. */
  2518. static create(field, op, value) {
  2519. if (field.isKeyField()) {
  2520. if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) {
  2521. return this.createKeyFieldInFilter(field, op, value);
  2522. }
  2523. else {
  2524. return new KeyFieldFilter(field, op, value);
  2525. }
  2526. }
  2527. else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) {
  2528. return new ArrayContainsFilter(field, value);
  2529. }
  2530. else if (op === "in" /* Operator.IN */) {
  2531. return new InFilter(field, value);
  2532. }
  2533. else if (op === "not-in" /* Operator.NOT_IN */) {
  2534. return new NotInFilter(field, value);
  2535. }
  2536. else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
  2537. return new ArrayContainsAnyFilter(field, value);
  2538. }
  2539. else {
  2540. return new FieldFilter(field, op, value);
  2541. }
  2542. }
  2543. static createKeyFieldInFilter(field, op, value) {
  2544. return op === "in" /* Operator.IN */
  2545. ? new KeyFieldInFilter(field, value)
  2546. : new KeyFieldNotInFilter(field, value);
  2547. }
  2548. matches(doc) {
  2549. const other = doc.data.field(this.field);
  2550. // Types do not have to match in NOT_EQUAL filters.
  2551. if (this.op === "!=" /* Operator.NOT_EQUAL */) {
  2552. return (other !== null &&
  2553. this.matchesComparison(valueCompare(other, this.value)));
  2554. }
  2555. // Only compare types with matching backend order (such as double and int).
  2556. return (other !== null &&
  2557. typeOrder(this.value) === typeOrder(other) &&
  2558. this.matchesComparison(valueCompare(other, this.value)));
  2559. }
  2560. matchesComparison(comparison) {
  2561. switch (this.op) {
  2562. case "<" /* Operator.LESS_THAN */:
  2563. return comparison < 0;
  2564. case "<=" /* Operator.LESS_THAN_OR_EQUAL */:
  2565. return comparison <= 0;
  2566. case "==" /* Operator.EQUAL */:
  2567. return comparison === 0;
  2568. case "!=" /* Operator.NOT_EQUAL */:
  2569. return comparison !== 0;
  2570. case ">" /* Operator.GREATER_THAN */:
  2571. return comparison > 0;
  2572. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */:
  2573. return comparison >= 0;
  2574. default:
  2575. return fail();
  2576. }
  2577. }
  2578. isInequality() {
  2579. return ([
  2580. "<" /* Operator.LESS_THAN */,
  2581. "<=" /* Operator.LESS_THAN_OR_EQUAL */,
  2582. ">" /* Operator.GREATER_THAN */,
  2583. ">=" /* Operator.GREATER_THAN_OR_EQUAL */,
  2584. "!=" /* Operator.NOT_EQUAL */,
  2585. "not-in" /* Operator.NOT_IN */
  2586. ].indexOf(this.op) >= 0);
  2587. }
  2588. getFlattenedFilters() {
  2589. return [this];
  2590. }
  2591. getFilters() {
  2592. return [this];
  2593. }
  2594. getFirstInequalityField() {
  2595. if (this.isInequality()) {
  2596. return this.field;
  2597. }
  2598. return null;
  2599. }
  2600. }
  2601. class CompositeFilter extends Filter {
  2602. constructor(filters, op) {
  2603. super();
  2604. this.filters = filters;
  2605. this.op = op;
  2606. this.memoizedFlattenedFilters = null;
  2607. }
  2608. /**
  2609. * Creates a filter based on the provided arguments.
  2610. */
  2611. static create(filters, op) {
  2612. return new CompositeFilter(filters, op);
  2613. }
  2614. matches(doc) {
  2615. if (compositeFilterIsConjunction(this)) {
  2616. // For conjunctions, all filters must match, so return false if any filter doesn't match.
  2617. return this.filters.find(filter => !filter.matches(doc)) === undefined;
  2618. }
  2619. else {
  2620. // For disjunctions, at least one filter should match.
  2621. return this.filters.find(filter => filter.matches(doc)) !== undefined;
  2622. }
  2623. }
  2624. getFlattenedFilters() {
  2625. if (this.memoizedFlattenedFilters !== null) {
  2626. return this.memoizedFlattenedFilters;
  2627. }
  2628. this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {
  2629. return result.concat(subfilter.getFlattenedFilters());
  2630. }, []);
  2631. return this.memoizedFlattenedFilters;
  2632. }
  2633. // Returns a mutable copy of `this.filters`
  2634. getFilters() {
  2635. return Object.assign([], this.filters);
  2636. }
  2637. getFirstInequalityField() {
  2638. const found = this.findFirstMatchingFilter(filter => filter.isInequality());
  2639. if (found !== null) {
  2640. return found.field;
  2641. }
  2642. return null;
  2643. }
  2644. // Performs a depth-first search to find and return the first FieldFilter in the composite filter
  2645. // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
  2646. // predicate.
  2647. findFirstMatchingFilter(predicate) {
  2648. for (const fieldFilter of this.getFlattenedFilters()) {
  2649. if (predicate(fieldFilter)) {
  2650. return fieldFilter;
  2651. }
  2652. }
  2653. return null;
  2654. }
  2655. }
  2656. function compositeFilterIsConjunction(compositeFilter) {
  2657. return compositeFilter.op === "and" /* CompositeOperator.AND */;
  2658. }
  2659. function filterEquals(f1, f2) {
  2660. if (f1 instanceof FieldFilter) {
  2661. return fieldFilterEquals(f1, f2);
  2662. }
  2663. else if (f1 instanceof CompositeFilter) {
  2664. return compositeFilterEquals(f1, f2);
  2665. }
  2666. else {
  2667. fail();
  2668. }
  2669. }
  2670. function fieldFilterEquals(f1, f2) {
  2671. return (f2 instanceof FieldFilter &&
  2672. f1.op === f2.op &&
  2673. f1.field.isEqual(f2.field) &&
  2674. valueEquals(f1.value, f2.value));
  2675. }
  2676. function compositeFilterEquals(f1, f2) {
  2677. if (f2 instanceof CompositeFilter &&
  2678. f1.op === f2.op &&
  2679. f1.filters.length === f2.filters.length) {
  2680. const subFiltersMatch = f1.filters.reduce((result, f1Filter, index) => result && filterEquals(f1Filter, f2.filters[index]), true);
  2681. return subFiltersMatch;
  2682. }
  2683. return false;
  2684. }
  2685. /** Filter that matches on key fields (i.e. '__name__'). */
  2686. class KeyFieldFilter extends FieldFilter {
  2687. constructor(field, op, value) {
  2688. super(field, op, value);
  2689. this.key = DocumentKey.fromName(value.referenceValue);
  2690. }
  2691. matches(doc) {
  2692. const comparison = DocumentKey.comparator(doc.key, this.key);
  2693. return this.matchesComparison(comparison);
  2694. }
  2695. }
  2696. /** Filter that matches on key fields within an array. */
  2697. class KeyFieldInFilter extends FieldFilter {
  2698. constructor(field, value) {
  2699. super(field, "in" /* Operator.IN */, value);
  2700. this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value);
  2701. }
  2702. matches(doc) {
  2703. return this.keys.some(key => key.isEqual(doc.key));
  2704. }
  2705. }
  2706. /** Filter that matches on key fields not present within an array. */
  2707. class KeyFieldNotInFilter extends FieldFilter {
  2708. constructor(field, value) {
  2709. super(field, "not-in" /* Operator.NOT_IN */, value);
  2710. this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value);
  2711. }
  2712. matches(doc) {
  2713. return !this.keys.some(key => key.isEqual(doc.key));
  2714. }
  2715. }
  2716. function extractDocumentKeysFromArrayValue(op, value) {
  2717. var _a;
  2718. return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
  2719. return DocumentKey.fromName(v.referenceValue);
  2720. });
  2721. }
  2722. /** A Filter that implements the array-contains operator. */
  2723. class ArrayContainsFilter extends FieldFilter {
  2724. constructor(field, value) {
  2725. super(field, "array-contains" /* Operator.ARRAY_CONTAINS */, value);
  2726. }
  2727. matches(doc) {
  2728. const other = doc.data.field(this.field);
  2729. return isArray(other) && arrayValueContains(other.arrayValue, this.value);
  2730. }
  2731. }
  2732. /** A Filter that implements the IN operator. */
  2733. class InFilter extends FieldFilter {
  2734. constructor(field, value) {
  2735. super(field, "in" /* Operator.IN */, value);
  2736. }
  2737. matches(doc) {
  2738. const other = doc.data.field(this.field);
  2739. return other !== null && arrayValueContains(this.value.arrayValue, other);
  2740. }
  2741. }
  2742. /** A Filter that implements the not-in operator. */
  2743. class NotInFilter extends FieldFilter {
  2744. constructor(field, value) {
  2745. super(field, "not-in" /* Operator.NOT_IN */, value);
  2746. }
  2747. matches(doc) {
  2748. if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
  2749. return false;
  2750. }
  2751. const other = doc.data.field(this.field);
  2752. return other !== null && !arrayValueContains(this.value.arrayValue, other);
  2753. }
  2754. }
  2755. /** A Filter that implements the array-contains-any operator. */
  2756. class ArrayContainsAnyFilter extends FieldFilter {
  2757. constructor(field, value) {
  2758. super(field, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, value);
  2759. }
  2760. matches(doc) {
  2761. const other = doc.data.field(this.field);
  2762. if (!isArray(other) || !other.arrayValue.values) {
  2763. return false;
  2764. }
  2765. return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
  2766. }
  2767. }
  2768. /**
  2769. * @license
  2770. * Copyright 2022 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. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  2786. */
  2787. class OrderBy {
  2788. constructor(field, dir = "asc" /* Direction.ASCENDING */) {
  2789. this.field = field;
  2790. this.dir = dir;
  2791. }
  2792. }
  2793. function orderByEquals(left, right) {
  2794. return left.dir === right.dir && left.field.isEqual(right.field);
  2795. }
  2796. /**
  2797. * @license
  2798. * Copyright 2017 Google LLC
  2799. *
  2800. * Licensed under the Apache License, Version 2.0 (the "License");
  2801. * you may not use this file except in compliance with the License.
  2802. * You may obtain a copy of the License at
  2803. *
  2804. * http://www.apache.org/licenses/LICENSE-2.0
  2805. *
  2806. * Unless required by applicable law or agreed to in writing, software
  2807. * distributed under the License is distributed on an "AS IS" BASIS,
  2808. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2809. * See the License for the specific language governing permissions and
  2810. * limitations under the License.
  2811. */
  2812. /**
  2813. * A version of a document in Firestore. This corresponds to the version
  2814. * timestamp, such as update_time or read_time.
  2815. */
  2816. class SnapshotVersion {
  2817. constructor(timestamp) {
  2818. this.timestamp = timestamp;
  2819. }
  2820. static fromTimestamp(value) {
  2821. return new SnapshotVersion(value);
  2822. }
  2823. static min() {
  2824. return new SnapshotVersion(new Timestamp(0, 0));
  2825. }
  2826. static max() {
  2827. return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));
  2828. }
  2829. compareTo(other) {
  2830. return this.timestamp._compareTo(other.timestamp);
  2831. }
  2832. isEqual(other) {
  2833. return this.timestamp.isEqual(other.timestamp);
  2834. }
  2835. /** Returns a number representation of the version for use in spec tests. */
  2836. toMicroseconds() {
  2837. // Convert to microseconds.
  2838. return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;
  2839. }
  2840. toString() {
  2841. return 'SnapshotVersion(' + this.timestamp.toString() + ')';
  2842. }
  2843. toTimestamp() {
  2844. return this.timestamp;
  2845. }
  2846. }
  2847. /**
  2848. * @license
  2849. * Copyright 2017 Google LLC
  2850. *
  2851. * Licensed under the Apache License, Version 2.0 (the "License");
  2852. * you may not use this file except in compliance with the License.
  2853. * You may obtain a copy of the License at
  2854. *
  2855. * http://www.apache.org/licenses/LICENSE-2.0
  2856. *
  2857. * Unless required by applicable law or agreed to in writing, software
  2858. * distributed under the License is distributed on an "AS IS" BASIS,
  2859. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2860. * See the License for the specific language governing permissions and
  2861. * limitations under the License.
  2862. */
  2863. // An immutable sorted map implementation, based on a Left-leaning Red-Black
  2864. // tree.
  2865. class SortedMap {
  2866. constructor(comparator, root) {
  2867. this.comparator = comparator;
  2868. this.root = root ? root : LLRBNode.EMPTY;
  2869. }
  2870. // Returns a copy of the map, with the specified key/value added or replaced.
  2871. insert(key, value) {
  2872. return new SortedMap(this.comparator, this.root
  2873. .insert(key, value, this.comparator)
  2874. .copy(null, null, LLRBNode.BLACK, null, null));
  2875. }
  2876. // Returns a copy of the map, with the specified key removed.
  2877. remove(key) {
  2878. return new SortedMap(this.comparator, this.root
  2879. .remove(key, this.comparator)
  2880. .copy(null, null, LLRBNode.BLACK, null, null));
  2881. }
  2882. // Returns the value of the node with the given key, or null.
  2883. get(key) {
  2884. let node = this.root;
  2885. while (!node.isEmpty()) {
  2886. const cmp = this.comparator(key, node.key);
  2887. if (cmp === 0) {
  2888. return node.value;
  2889. }
  2890. else if (cmp < 0) {
  2891. node = node.left;
  2892. }
  2893. else if (cmp > 0) {
  2894. node = node.right;
  2895. }
  2896. }
  2897. return null;
  2898. }
  2899. // Returns the index of the element in this sorted map, or -1 if it doesn't
  2900. // exist.
  2901. indexOf(key) {
  2902. // Number of nodes that were pruned when descending right
  2903. let prunedNodes = 0;
  2904. let node = this.root;
  2905. while (!node.isEmpty()) {
  2906. const cmp = this.comparator(key, node.key);
  2907. if (cmp === 0) {
  2908. return prunedNodes + node.left.size;
  2909. }
  2910. else if (cmp < 0) {
  2911. node = node.left;
  2912. }
  2913. else {
  2914. // Count all nodes left of the node plus the node itself
  2915. prunedNodes += node.left.size + 1;
  2916. node = node.right;
  2917. }
  2918. }
  2919. // Node not found
  2920. return -1;
  2921. }
  2922. isEmpty() {
  2923. return this.root.isEmpty();
  2924. }
  2925. // Returns the total number of nodes in the map.
  2926. get size() {
  2927. return this.root.size;
  2928. }
  2929. // Returns the minimum key in the map.
  2930. minKey() {
  2931. return this.root.minKey();
  2932. }
  2933. // Returns the maximum key in the map.
  2934. maxKey() {
  2935. return this.root.maxKey();
  2936. }
  2937. // Traverses the map in key order and calls the specified action function
  2938. // for each key/value pair. If action returns true, traversal is aborted.
  2939. // Returns the first truthy value returned by action, or the last falsey
  2940. // value returned by action.
  2941. inorderTraversal(action) {
  2942. return this.root.inorderTraversal(action);
  2943. }
  2944. forEach(fn) {
  2945. this.inorderTraversal((k, v) => {
  2946. fn(k, v);
  2947. return false;
  2948. });
  2949. }
  2950. toString() {
  2951. const descriptions = [];
  2952. this.inorderTraversal((k, v) => {
  2953. descriptions.push(`${k}:${v}`);
  2954. return false;
  2955. });
  2956. return `{${descriptions.join(', ')}}`;
  2957. }
  2958. // Traverses the map in reverse key order and calls the specified action
  2959. // function for each key/value pair. If action returns true, traversal is
  2960. // aborted.
  2961. // Returns the first truthy value returned by action, or the last falsey
  2962. // value returned by action.
  2963. reverseTraversal(action) {
  2964. return this.root.reverseTraversal(action);
  2965. }
  2966. // Returns an iterator over the SortedMap.
  2967. getIterator() {
  2968. return new SortedMapIterator(this.root, null, this.comparator, false);
  2969. }
  2970. getIteratorFrom(key) {
  2971. return new SortedMapIterator(this.root, key, this.comparator, false);
  2972. }
  2973. getReverseIterator() {
  2974. return new SortedMapIterator(this.root, null, this.comparator, true);
  2975. }
  2976. getReverseIteratorFrom(key) {
  2977. return new SortedMapIterator(this.root, key, this.comparator, true);
  2978. }
  2979. } // end SortedMap
  2980. // An iterator over an LLRBNode.
  2981. class SortedMapIterator {
  2982. constructor(node, startKey, comparator, isReverse) {
  2983. this.isReverse = isReverse;
  2984. this.nodeStack = [];
  2985. let cmp = 1;
  2986. while (!node.isEmpty()) {
  2987. cmp = startKey ? comparator(node.key, startKey) : 1;
  2988. // flip the comparison if we're going in reverse
  2989. if (startKey && isReverse) {
  2990. cmp *= -1;
  2991. }
  2992. if (cmp < 0) {
  2993. // This node is less than our start key. ignore it
  2994. if (this.isReverse) {
  2995. node = node.left;
  2996. }
  2997. else {
  2998. node = node.right;
  2999. }
  3000. }
  3001. else if (cmp === 0) {
  3002. // This node is exactly equal to our start key. Push it on the stack,
  3003. // but stop iterating;
  3004. this.nodeStack.push(node);
  3005. break;
  3006. }
  3007. else {
  3008. // This node is greater than our start key, add it to the stack and move
  3009. // to the next one
  3010. this.nodeStack.push(node);
  3011. if (this.isReverse) {
  3012. node = node.right;
  3013. }
  3014. else {
  3015. node = node.left;
  3016. }
  3017. }
  3018. }
  3019. }
  3020. getNext() {
  3021. let node = this.nodeStack.pop();
  3022. const result = { key: node.key, value: node.value };
  3023. if (this.isReverse) {
  3024. node = node.left;
  3025. while (!node.isEmpty()) {
  3026. this.nodeStack.push(node);
  3027. node = node.right;
  3028. }
  3029. }
  3030. else {
  3031. node = node.right;
  3032. while (!node.isEmpty()) {
  3033. this.nodeStack.push(node);
  3034. node = node.left;
  3035. }
  3036. }
  3037. return result;
  3038. }
  3039. hasNext() {
  3040. return this.nodeStack.length > 0;
  3041. }
  3042. peek() {
  3043. if (this.nodeStack.length === 0) {
  3044. return null;
  3045. }
  3046. const node = this.nodeStack[this.nodeStack.length - 1];
  3047. return { key: node.key, value: node.value };
  3048. }
  3049. } // end SortedMapIterator
  3050. // Represents a node in a Left-leaning Red-Black tree.
  3051. class LLRBNode {
  3052. constructor(key, value, color, left, right) {
  3053. this.key = key;
  3054. this.value = value;
  3055. this.color = color != null ? color : LLRBNode.RED;
  3056. this.left = left != null ? left : LLRBNode.EMPTY;
  3057. this.right = right != null ? right : LLRBNode.EMPTY;
  3058. this.size = this.left.size + 1 + this.right.size;
  3059. }
  3060. // Returns a copy of the current node, optionally replacing pieces of it.
  3061. copy(key, value, color, left, right) {
  3062. return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
  3063. }
  3064. isEmpty() {
  3065. return false;
  3066. }
  3067. // Traverses the tree in key order and calls the specified action function
  3068. // for each node. If action returns true, traversal is aborted.
  3069. // Returns the first truthy value returned by action, or the last falsey
  3070. // value returned by action.
  3071. inorderTraversal(action) {
  3072. return (this.left.inorderTraversal(action) ||
  3073. action(this.key, this.value) ||
  3074. this.right.inorderTraversal(action));
  3075. }
  3076. // Traverses the tree in reverse key order and calls the specified action
  3077. // function for each node. If action returns true, traversal is aborted.
  3078. // Returns the first truthy value returned by action, or the last falsey
  3079. // value returned by action.
  3080. reverseTraversal(action) {
  3081. return (this.right.reverseTraversal(action) ||
  3082. action(this.key, this.value) ||
  3083. this.left.reverseTraversal(action));
  3084. }
  3085. // Returns the minimum node in the tree.
  3086. min() {
  3087. if (this.left.isEmpty()) {
  3088. return this;
  3089. }
  3090. else {
  3091. return this.left.min();
  3092. }
  3093. }
  3094. // Returns the maximum key in the tree.
  3095. minKey() {
  3096. return this.min().key;
  3097. }
  3098. // Returns the maximum key in the tree.
  3099. maxKey() {
  3100. if (this.right.isEmpty()) {
  3101. return this.key;
  3102. }
  3103. else {
  3104. return this.right.maxKey();
  3105. }
  3106. }
  3107. // Returns new tree, with the key/value added.
  3108. insert(key, value, comparator) {
  3109. let n = this;
  3110. const cmp = comparator(key, n.key);
  3111. if (cmp < 0) {
  3112. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  3113. }
  3114. else if (cmp === 0) {
  3115. n = n.copy(null, value, null, null, null);
  3116. }
  3117. else {
  3118. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  3119. }
  3120. return n.fixUp();
  3121. }
  3122. removeMin() {
  3123. if (this.left.isEmpty()) {
  3124. return LLRBNode.EMPTY;
  3125. }
  3126. let n = this;
  3127. if (!n.left.isRed() && !n.left.left.isRed()) {
  3128. n = n.moveRedLeft();
  3129. }
  3130. n = n.copy(null, null, null, n.left.removeMin(), null);
  3131. return n.fixUp();
  3132. }
  3133. // Returns new tree, with the specified item removed.
  3134. remove(key, comparator) {
  3135. let smallest;
  3136. let n = this;
  3137. if (comparator(key, n.key) < 0) {
  3138. if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
  3139. n = n.moveRedLeft();
  3140. }
  3141. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  3142. }
  3143. else {
  3144. if (n.left.isRed()) {
  3145. n = n.rotateRight();
  3146. }
  3147. if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
  3148. n = n.moveRedRight();
  3149. }
  3150. if (comparator(key, n.key) === 0) {
  3151. if (n.right.isEmpty()) {
  3152. return LLRBNode.EMPTY;
  3153. }
  3154. else {
  3155. smallest = n.right.min();
  3156. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
  3157. }
  3158. }
  3159. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  3160. }
  3161. return n.fixUp();
  3162. }
  3163. isRed() {
  3164. return this.color;
  3165. }
  3166. // Returns new tree after performing any needed rotations.
  3167. fixUp() {
  3168. let n = this;
  3169. if (n.right.isRed() && !n.left.isRed()) {
  3170. n = n.rotateLeft();
  3171. }
  3172. if (n.left.isRed() && n.left.left.isRed()) {
  3173. n = n.rotateRight();
  3174. }
  3175. if (n.left.isRed() && n.right.isRed()) {
  3176. n = n.colorFlip();
  3177. }
  3178. return n;
  3179. }
  3180. moveRedLeft() {
  3181. let n = this.colorFlip();
  3182. if (n.right.left.isRed()) {
  3183. n = n.copy(null, null, null, null, n.right.rotateRight());
  3184. n = n.rotateLeft();
  3185. n = n.colorFlip();
  3186. }
  3187. return n;
  3188. }
  3189. moveRedRight() {
  3190. let n = this.colorFlip();
  3191. if (n.left.left.isRed()) {
  3192. n = n.rotateRight();
  3193. n = n.colorFlip();
  3194. }
  3195. return n;
  3196. }
  3197. rotateLeft() {
  3198. const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  3199. return this.right.copy(null, null, this.color, nl, null);
  3200. }
  3201. rotateRight() {
  3202. const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  3203. return this.left.copy(null, null, this.color, null, nr);
  3204. }
  3205. colorFlip() {
  3206. const left = this.left.copy(null, null, !this.left.color, null, null);
  3207. const right = this.right.copy(null, null, !this.right.color, null, null);
  3208. return this.copy(null, null, !this.color, left, right);
  3209. }
  3210. // For testing.
  3211. checkMaxDepth() {
  3212. const blackDepth = this.check();
  3213. if (Math.pow(2.0, blackDepth) <= this.size + 1) {
  3214. return true;
  3215. }
  3216. else {
  3217. return false;
  3218. }
  3219. }
  3220. // In a balanced RB tree, the black-depth (number of black nodes) from root to
  3221. // leaves is equal on both sides. This function verifies that or asserts.
  3222. check() {
  3223. if (this.isRed() && this.left.isRed()) {
  3224. throw fail();
  3225. }
  3226. if (this.right.isRed()) {
  3227. throw fail();
  3228. }
  3229. const blackDepth = this.left.check();
  3230. if (blackDepth !== this.right.check()) {
  3231. throw fail();
  3232. }
  3233. else {
  3234. return blackDepth + (this.isRed() ? 0 : 1);
  3235. }
  3236. }
  3237. } // end LLRBNode
  3238. // Empty node is shared between all LLRB trees.
  3239. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3240. LLRBNode.EMPTY = null;
  3241. LLRBNode.RED = true;
  3242. LLRBNode.BLACK = false;
  3243. // Represents an empty node (a leaf node in the Red-Black Tree).
  3244. class LLRBEmptyNode {
  3245. constructor() {
  3246. this.size = 0;
  3247. }
  3248. get key() {
  3249. throw fail();
  3250. }
  3251. get value() {
  3252. throw fail();
  3253. }
  3254. get color() {
  3255. throw fail();
  3256. }
  3257. get left() {
  3258. throw fail();
  3259. }
  3260. get right() {
  3261. throw fail();
  3262. }
  3263. // Returns a copy of the current node.
  3264. copy(key, value, color, left, right) {
  3265. return this;
  3266. }
  3267. // Returns a copy of the tree, with the specified key/value added.
  3268. insert(key, value, comparator) {
  3269. return new LLRBNode(key, value);
  3270. }
  3271. // Returns a copy of the tree, with the specified key removed.
  3272. remove(key, comparator) {
  3273. return this;
  3274. }
  3275. isEmpty() {
  3276. return true;
  3277. }
  3278. inorderTraversal(action) {
  3279. return false;
  3280. }
  3281. reverseTraversal(action) {
  3282. return false;
  3283. }
  3284. minKey() {
  3285. return null;
  3286. }
  3287. maxKey() {
  3288. return null;
  3289. }
  3290. isRed() {
  3291. return false;
  3292. }
  3293. // For testing.
  3294. checkMaxDepth() {
  3295. return true;
  3296. }
  3297. check() {
  3298. return 0;
  3299. }
  3300. } // end LLRBEmptyNode
  3301. LLRBNode.EMPTY = new LLRBEmptyNode();
  3302. /**
  3303. * @license
  3304. * Copyright 2017 Google LLC
  3305. *
  3306. * Licensed under the Apache License, Version 2.0 (the "License");
  3307. * you may not use this file except in compliance with the License.
  3308. * You may obtain a copy of the License at
  3309. *
  3310. * http://www.apache.org/licenses/LICENSE-2.0
  3311. *
  3312. * Unless required by applicable law or agreed to in writing, software
  3313. * distributed under the License is distributed on an "AS IS" BASIS,
  3314. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3315. * See the License for the specific language governing permissions and
  3316. * limitations under the License.
  3317. */
  3318. /**
  3319. * SortedSet is an immutable (copy-on-write) collection that holds elements
  3320. * in order specified by the provided comparator.
  3321. *
  3322. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  3323. * be equal!
  3324. */
  3325. class SortedSet {
  3326. constructor(comparator) {
  3327. this.comparator = comparator;
  3328. this.data = new SortedMap(this.comparator);
  3329. }
  3330. has(elem) {
  3331. return this.data.get(elem) !== null;
  3332. }
  3333. first() {
  3334. return this.data.minKey();
  3335. }
  3336. last() {
  3337. return this.data.maxKey();
  3338. }
  3339. get size() {
  3340. return this.data.size;
  3341. }
  3342. indexOf(elem) {
  3343. return this.data.indexOf(elem);
  3344. }
  3345. /** Iterates elements in order defined by "comparator" */
  3346. forEach(cb) {
  3347. this.data.inorderTraversal((k, v) => {
  3348. cb(k);
  3349. return false;
  3350. });
  3351. }
  3352. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
  3353. forEachInRange(range, cb) {
  3354. const iter = this.data.getIteratorFrom(range[0]);
  3355. while (iter.hasNext()) {
  3356. const elem = iter.getNext();
  3357. if (this.comparator(elem.key, range[1]) >= 0) {
  3358. return;
  3359. }
  3360. cb(elem.key);
  3361. }
  3362. }
  3363. /**
  3364. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  3365. */
  3366. forEachWhile(cb, start) {
  3367. let iter;
  3368. if (start !== undefined) {
  3369. iter = this.data.getIteratorFrom(start);
  3370. }
  3371. else {
  3372. iter = this.data.getIterator();
  3373. }
  3374. while (iter.hasNext()) {
  3375. const elem = iter.getNext();
  3376. const result = cb(elem.key);
  3377. if (!result) {
  3378. return;
  3379. }
  3380. }
  3381. }
  3382. /** Finds the least element greater than or equal to `elem`. */
  3383. firstAfterOrEqual(elem) {
  3384. const iter = this.data.getIteratorFrom(elem);
  3385. return iter.hasNext() ? iter.getNext().key : null;
  3386. }
  3387. getIterator() {
  3388. return new SortedSetIterator(this.data.getIterator());
  3389. }
  3390. getIteratorFrom(key) {
  3391. return new SortedSetIterator(this.data.getIteratorFrom(key));
  3392. }
  3393. /** Inserts or updates an element */
  3394. add(elem) {
  3395. return this.copy(this.data.remove(elem).insert(elem, true));
  3396. }
  3397. /** Deletes an element */
  3398. delete(elem) {
  3399. if (!this.has(elem)) {
  3400. return this;
  3401. }
  3402. return this.copy(this.data.remove(elem));
  3403. }
  3404. isEmpty() {
  3405. return this.data.isEmpty();
  3406. }
  3407. unionWith(other) {
  3408. let result = this;
  3409. // Make sure `result` always refers to the larger one of the two sets.
  3410. if (result.size < other.size) {
  3411. result = other;
  3412. other = this;
  3413. }
  3414. other.forEach(elem => {
  3415. result = result.add(elem);
  3416. });
  3417. return result;
  3418. }
  3419. isEqual(other) {
  3420. if (!(other instanceof SortedSet)) {
  3421. return false;
  3422. }
  3423. if (this.size !== other.size) {
  3424. return false;
  3425. }
  3426. const thisIt = this.data.getIterator();
  3427. const otherIt = other.data.getIterator();
  3428. while (thisIt.hasNext()) {
  3429. const thisElem = thisIt.getNext().key;
  3430. const otherElem = otherIt.getNext().key;
  3431. if (this.comparator(thisElem, otherElem) !== 0) {
  3432. return false;
  3433. }
  3434. }
  3435. return true;
  3436. }
  3437. toArray() {
  3438. const res = [];
  3439. this.forEach(targetId => {
  3440. res.push(targetId);
  3441. });
  3442. return res;
  3443. }
  3444. toString() {
  3445. const result = [];
  3446. this.forEach(elem => result.push(elem));
  3447. return 'SortedSet(' + result.toString() + ')';
  3448. }
  3449. copy(data) {
  3450. const result = new SortedSet(this.comparator);
  3451. result.data = data;
  3452. return result;
  3453. }
  3454. }
  3455. class SortedSetIterator {
  3456. constructor(iter) {
  3457. this.iter = iter;
  3458. }
  3459. getNext() {
  3460. return this.iter.getNext().key;
  3461. }
  3462. hasNext() {
  3463. return this.iter.hasNext();
  3464. }
  3465. }
  3466. /**
  3467. * @license
  3468. * Copyright 2020 Google LLC
  3469. *
  3470. * Licensed under the Apache License, Version 2.0 (the "License");
  3471. * you may not use this file except in compliance with the License.
  3472. * You may obtain a copy of the License at
  3473. *
  3474. * http://www.apache.org/licenses/LICENSE-2.0
  3475. *
  3476. * Unless required by applicable law or agreed to in writing, software
  3477. * distributed under the License is distributed on an "AS IS" BASIS,
  3478. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3479. * See the License for the specific language governing permissions and
  3480. * limitations under the License.
  3481. */
  3482. /**
  3483. * Provides a set of fields that can be used to partially patch a document.
  3484. * FieldMask is used in conjunction with ObjectValue.
  3485. * Examples:
  3486. * foo - Overwrites foo entirely with the provided value. If foo is not
  3487. * present in the companion ObjectValue, the field is deleted.
  3488. * foo.bar - Overwrites only the field bar of the object foo.
  3489. * If foo is not an object, foo is replaced with an object
  3490. * containing foo
  3491. */
  3492. class FieldMask {
  3493. constructor(fields) {
  3494. this.fields = fields;
  3495. // TODO(dimond): validation of FieldMask
  3496. // Sort the field mask to support `FieldMask.isEqual()` and assert below.
  3497. fields.sort(FieldPath$1.comparator);
  3498. }
  3499. static empty() {
  3500. return new FieldMask([]);
  3501. }
  3502. /**
  3503. * Returns a new FieldMask object that is the result of adding all the given
  3504. * fields paths to this field mask.
  3505. */
  3506. unionWith(extraFields) {
  3507. let mergedMaskSet = new SortedSet(FieldPath$1.comparator);
  3508. for (const fieldPath of this.fields) {
  3509. mergedMaskSet = mergedMaskSet.add(fieldPath);
  3510. }
  3511. for (const fieldPath of extraFields) {
  3512. mergedMaskSet = mergedMaskSet.add(fieldPath);
  3513. }
  3514. return new FieldMask(mergedMaskSet.toArray());
  3515. }
  3516. /**
  3517. * Verifies that `fieldPath` is included by at least one field in this field
  3518. * mask.
  3519. *
  3520. * This is an O(n) operation, where `n` is the size of the field mask.
  3521. */
  3522. covers(fieldPath) {
  3523. for (const fieldMaskPath of this.fields) {
  3524. if (fieldMaskPath.isPrefixOf(fieldPath)) {
  3525. return true;
  3526. }
  3527. }
  3528. return false;
  3529. }
  3530. isEqual(other) {
  3531. return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));
  3532. }
  3533. }
  3534. /**
  3535. * @license
  3536. * Copyright 2017 Google LLC
  3537. *
  3538. * Licensed under the Apache License, Version 2.0 (the "License");
  3539. * you may not use this file except in compliance with the License.
  3540. * You may obtain a copy of the License at
  3541. *
  3542. * http://www.apache.org/licenses/LICENSE-2.0
  3543. *
  3544. * Unless required by applicable law or agreed to in writing, software
  3545. * distributed under the License is distributed on an "AS IS" BASIS,
  3546. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3547. * See the License for the specific language governing permissions and
  3548. * limitations under the License.
  3549. */
  3550. /**
  3551. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  3552. * ability to add and remove fields (via the ObjectValueBuilder).
  3553. */
  3554. class ObjectValue {
  3555. constructor(value) {
  3556. this.value = value;
  3557. }
  3558. static empty() {
  3559. return new ObjectValue({ mapValue: {} });
  3560. }
  3561. /**
  3562. * Returns the value at the given path or null.
  3563. *
  3564. * @param path - the path to search
  3565. * @returns The value at the path or null if the path is not set.
  3566. */
  3567. field(path) {
  3568. if (path.isEmpty()) {
  3569. return this.value;
  3570. }
  3571. else {
  3572. let currentLevel = this.value;
  3573. for (let i = 0; i < path.length - 1; ++i) {
  3574. currentLevel = (currentLevel.mapValue.fields || {})[path.get(i)];
  3575. if (!isMapValue(currentLevel)) {
  3576. return null;
  3577. }
  3578. }
  3579. currentLevel = (currentLevel.mapValue.fields || {})[path.lastSegment()];
  3580. return currentLevel || null;
  3581. }
  3582. }
  3583. /**
  3584. * Sets the field to the provided value.
  3585. *
  3586. * @param path - The field path to set.
  3587. * @param value - The value to set.
  3588. */
  3589. set(path, value) {
  3590. const fieldsMap = this.getFieldsMap(path.popLast());
  3591. fieldsMap[path.lastSegment()] = deepClone(value);
  3592. }
  3593. /**
  3594. * Sets the provided fields to the provided values.
  3595. *
  3596. * @param data - A map of fields to values (or null for deletes).
  3597. */
  3598. setAll(data) {
  3599. let parent = FieldPath$1.emptyPath();
  3600. let upserts = {};
  3601. let deletes = [];
  3602. data.forEach((value, path) => {
  3603. if (!parent.isImmediateParentOf(path)) {
  3604. // Insert the accumulated changes at this parent location
  3605. const fieldsMap = this.getFieldsMap(parent);
  3606. this.applyChanges(fieldsMap, upserts, deletes);
  3607. upserts = {};
  3608. deletes = [];
  3609. parent = path.popLast();
  3610. }
  3611. if (value) {
  3612. upserts[path.lastSegment()] = deepClone(value);
  3613. }
  3614. else {
  3615. deletes.push(path.lastSegment());
  3616. }
  3617. });
  3618. const fieldsMap = this.getFieldsMap(parent);
  3619. this.applyChanges(fieldsMap, upserts, deletes);
  3620. }
  3621. /**
  3622. * Removes the field at the specified path. If there is no field at the
  3623. * specified path, nothing is changed.
  3624. *
  3625. * @param path - The field path to remove.
  3626. */
  3627. delete(path) {
  3628. const nestedValue = this.field(path.popLast());
  3629. if (isMapValue(nestedValue) && nestedValue.mapValue.fields) {
  3630. delete nestedValue.mapValue.fields[path.lastSegment()];
  3631. }
  3632. }
  3633. isEqual(other) {
  3634. return valueEquals(this.value, other.value);
  3635. }
  3636. /**
  3637. * Returns the map that contains the leaf element of `path`. If the parent
  3638. * entry does not yet exist, or if it is not a map, a new map will be created.
  3639. */
  3640. getFieldsMap(path) {
  3641. let current = this.value;
  3642. if (!current.mapValue.fields) {
  3643. current.mapValue = { fields: {} };
  3644. }
  3645. for (let i = 0; i < path.length; ++i) {
  3646. let next = current.mapValue.fields[path.get(i)];
  3647. if (!isMapValue(next) || !next.mapValue.fields) {
  3648. next = { mapValue: { fields: {} } };
  3649. current.mapValue.fields[path.get(i)] = next;
  3650. }
  3651. current = next;
  3652. }
  3653. return current.mapValue.fields;
  3654. }
  3655. /**
  3656. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  3657. * entries.
  3658. */
  3659. applyChanges(fieldsMap, inserts, deletes) {
  3660. forEach(inserts, (key, val) => (fieldsMap[key] = val));
  3661. for (const field of deletes) {
  3662. delete fieldsMap[field];
  3663. }
  3664. }
  3665. clone() {
  3666. return new ObjectValue(deepClone(this.value));
  3667. }
  3668. }
  3669. /**
  3670. * @license
  3671. * Copyright 2017 Google LLC
  3672. *
  3673. * Licensed under the Apache License, Version 2.0 (the "License");
  3674. * you may not use this file except in compliance with the License.
  3675. * You may obtain a copy of the License at
  3676. *
  3677. * http://www.apache.org/licenses/LICENSE-2.0
  3678. *
  3679. * Unless required by applicable law or agreed to in writing, software
  3680. * distributed under the License is distributed on an "AS IS" BASIS,
  3681. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3682. * See the License for the specific language governing permissions and
  3683. * limitations under the License.
  3684. */
  3685. /**
  3686. * Represents a document in Firestore with a key, version, data and whether it
  3687. * has local mutations applied to it.
  3688. *
  3689. * Documents can transition between states via `convertToFoundDocument()`,
  3690. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  3691. * not transition to one of these states even after all mutations have been
  3692. * applied, `isValidDocument()` returns false and the document should be removed
  3693. * from all views.
  3694. */
  3695. class MutableDocument {
  3696. constructor(key, documentType, version, readTime, createTime, data, documentState) {
  3697. this.key = key;
  3698. this.documentType = documentType;
  3699. this.version = version;
  3700. this.readTime = readTime;
  3701. this.createTime = createTime;
  3702. this.data = data;
  3703. this.documentState = documentState;
  3704. }
  3705. /**
  3706. * Creates a document with no known version or data, but which can serve as
  3707. * base document for mutations.
  3708. */
  3709. static newInvalidDocument(documentKey) {
  3710. return new MutableDocument(documentKey, 0 /* DocumentType.INVALID */,
  3711. /* version */ SnapshotVersion.min(),
  3712. /* readTime */ SnapshotVersion.min(),
  3713. /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);
  3714. }
  3715. /**
  3716. * Creates a new document that is known to exist with the given data at the
  3717. * given version.
  3718. */
  3719. static newFoundDocument(documentKey, version, createTime, value) {
  3720. return new MutableDocument(documentKey, 1 /* DocumentType.FOUND_DOCUMENT */,
  3721. /* version */ version,
  3722. /* readTime */ SnapshotVersion.min(),
  3723. /* createTime */ createTime, value, 0 /* DocumentState.SYNCED */);
  3724. }
  3725. /** Creates a new document that is known to not exist at the given version. */
  3726. static newNoDocument(documentKey, version) {
  3727. return new MutableDocument(documentKey, 2 /* DocumentType.NO_DOCUMENT */,
  3728. /* version */ version,
  3729. /* readTime */ SnapshotVersion.min(),
  3730. /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);
  3731. }
  3732. /**
  3733. * Creates a new document that is known to exist at the given version but
  3734. * whose data is not known (e.g. a document that was updated without a known
  3735. * base document).
  3736. */
  3737. static newUnknownDocument(documentKey, version) {
  3738. return new MutableDocument(documentKey, 3 /* DocumentType.UNKNOWN_DOCUMENT */,
  3739. /* version */ version,
  3740. /* readTime */ SnapshotVersion.min(),
  3741. /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
  3742. }
  3743. /**
  3744. * Changes the document type to indicate that it exists and that its version
  3745. * and data are known.
  3746. */
  3747. convertToFoundDocument(version, value) {
  3748. // If a document is switching state from being an invalid or deleted
  3749. // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
  3750. // update from Watch or due to applying a local set mutation on top
  3751. // of a deleted document, our best guess about its createTime would be the
  3752. // version at which the document transitioned to a FOUND_DOCUMENT.
  3753. if (this.createTime.isEqual(SnapshotVersion.min()) &&
  3754. (this.documentType === 2 /* DocumentType.NO_DOCUMENT */ ||
  3755. this.documentType === 0 /* DocumentType.INVALID */)) {
  3756. this.createTime = version;
  3757. }
  3758. this.version = version;
  3759. this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */;
  3760. this.data = value;
  3761. this.documentState = 0 /* DocumentState.SYNCED */;
  3762. return this;
  3763. }
  3764. /**
  3765. * Changes the document type to indicate that it doesn't exist at the given
  3766. * version.
  3767. */
  3768. convertToNoDocument(version) {
  3769. this.version = version;
  3770. this.documentType = 2 /* DocumentType.NO_DOCUMENT */;
  3771. this.data = ObjectValue.empty();
  3772. this.documentState = 0 /* DocumentState.SYNCED */;
  3773. return this;
  3774. }
  3775. /**
  3776. * Changes the document type to indicate that it exists at a given version but
  3777. * that its data is not known (e.g. a document that was updated without a known
  3778. * base document).
  3779. */
  3780. convertToUnknownDocument(version) {
  3781. this.version = version;
  3782. this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */;
  3783. this.data = ObjectValue.empty();
  3784. this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */;
  3785. return this;
  3786. }
  3787. setHasCommittedMutations() {
  3788. this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */;
  3789. return this;
  3790. }
  3791. setHasLocalMutations() {
  3792. this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */;
  3793. this.version = SnapshotVersion.min();
  3794. return this;
  3795. }
  3796. setReadTime(readTime) {
  3797. this.readTime = readTime;
  3798. return this;
  3799. }
  3800. get hasLocalMutations() {
  3801. return this.documentState === 1 /* DocumentState.HAS_LOCAL_MUTATIONS */;
  3802. }
  3803. get hasCommittedMutations() {
  3804. return this.documentState === 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */;
  3805. }
  3806. get hasPendingWrites() {
  3807. return this.hasLocalMutations || this.hasCommittedMutations;
  3808. }
  3809. isValidDocument() {
  3810. return this.documentType !== 0 /* DocumentType.INVALID */;
  3811. }
  3812. isFoundDocument() {
  3813. return this.documentType === 1 /* DocumentType.FOUND_DOCUMENT */;
  3814. }
  3815. isNoDocument() {
  3816. return this.documentType === 2 /* DocumentType.NO_DOCUMENT */;
  3817. }
  3818. isUnknownDocument() {
  3819. return this.documentType === 3 /* DocumentType.UNKNOWN_DOCUMENT */;
  3820. }
  3821. isEqual(other) {
  3822. return (other instanceof MutableDocument &&
  3823. this.key.isEqual(other.key) &&
  3824. this.version.isEqual(other.version) &&
  3825. this.documentType === other.documentType &&
  3826. this.documentState === other.documentState &&
  3827. this.data.isEqual(other.data));
  3828. }
  3829. mutableCopy() {
  3830. return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  3831. }
  3832. toString() {
  3833. return (`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, ` +
  3834. `{createTime: ${this.createTime}}), ` +
  3835. `{documentType: ${this.documentType}}), ` +
  3836. `{documentState: ${this.documentState}})`);
  3837. }
  3838. }
  3839. /**
  3840. * @license
  3841. * Copyright 2019 Google LLC
  3842. *
  3843. * Licensed under the Apache License, Version 2.0 (the "License");
  3844. * you may not use this file except in compliance with the License.
  3845. * You may obtain a copy of the License at
  3846. *
  3847. * http://www.apache.org/licenses/LICENSE-2.0
  3848. *
  3849. * Unless required by applicable law or agreed to in writing, software
  3850. * distributed under the License is distributed on an "AS IS" BASIS,
  3851. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3852. * See the License for the specific language governing permissions and
  3853. * limitations under the License.
  3854. */
  3855. // Visible for testing
  3856. class TargetImpl {
  3857. constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
  3858. this.path = path;
  3859. this.collectionGroup = collectionGroup;
  3860. this.orderBy = orderBy;
  3861. this.filters = filters;
  3862. this.limit = limit;
  3863. this.startAt = startAt;
  3864. this.endAt = endAt;
  3865. this.memoizedCanonicalId = null;
  3866. }
  3867. }
  3868. /**
  3869. * Initializes a Target with a path and optional additional query constraints.
  3870. * Path must currently be empty if this is a collection group query.
  3871. *
  3872. * NOTE: you should always construct `Target` from `Query.toTarget` instead of
  3873. * using this factory method, because `Query` provides an implicit `orderBy`
  3874. * property.
  3875. */
  3876. function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
  3877. return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
  3878. }
  3879. function targetEquals(left, right) {
  3880. if (left.limit !== right.limit) {
  3881. return false;
  3882. }
  3883. if (left.orderBy.length !== right.orderBy.length) {
  3884. return false;
  3885. }
  3886. for (let i = 0; i < left.orderBy.length; i++) {
  3887. if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
  3888. return false;
  3889. }
  3890. }
  3891. if (left.filters.length !== right.filters.length) {
  3892. return false;
  3893. }
  3894. for (let i = 0; i < left.filters.length; i++) {
  3895. if (!filterEquals(left.filters[i], right.filters[i])) {
  3896. return false;
  3897. }
  3898. }
  3899. if (left.collectionGroup !== right.collectionGroup) {
  3900. return false;
  3901. }
  3902. if (!left.path.isEqual(right.path)) {
  3903. return false;
  3904. }
  3905. if (!boundEquals(left.startAt, right.startAt)) {
  3906. return false;
  3907. }
  3908. return boundEquals(left.endAt, right.endAt);
  3909. }
  3910. /**
  3911. * @license
  3912. * Copyright 2017 Google LLC
  3913. *
  3914. * Licensed under the Apache License, Version 2.0 (the "License");
  3915. * you may not use this file except in compliance with the License.
  3916. * You may obtain a copy of the License at
  3917. *
  3918. * http://www.apache.org/licenses/LICENSE-2.0
  3919. *
  3920. * Unless required by applicable law or agreed to in writing, software
  3921. * distributed under the License is distributed on an "AS IS" BASIS,
  3922. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3923. * See the License for the specific language governing permissions and
  3924. * limitations under the License.
  3925. */
  3926. /**
  3927. * Query encapsulates all the query attributes we support in the SDK. It can
  3928. * be run against the LocalStore, as well as be converted to a `Target` to
  3929. * query the RemoteStore results.
  3930. *
  3931. * Visible for testing.
  3932. */
  3933. class QueryImpl {
  3934. /**
  3935. * Initializes a Query with a path and optional additional query constraints.
  3936. * Path must currently be empty if this is a collection group query.
  3937. */
  3938. constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* LimitType.First */, startAt = null, endAt = null) {
  3939. this.path = path;
  3940. this.collectionGroup = collectionGroup;
  3941. this.explicitOrderBy = explicitOrderBy;
  3942. this.filters = filters;
  3943. this.limit = limit;
  3944. this.limitType = limitType;
  3945. this.startAt = startAt;
  3946. this.endAt = endAt;
  3947. this.memoizedOrderBy = null;
  3948. // The corresponding `Target` of this `Query` instance.
  3949. this.memoizedTarget = null;
  3950. if (this.startAt) ;
  3951. if (this.endAt) ;
  3952. }
  3953. }
  3954. /** Creates a new Query for a query that matches all documents at `path` */
  3955. function newQueryForPath(path) {
  3956. return new QueryImpl(path);
  3957. }
  3958. function getFirstOrderByField(query) {
  3959. return query.explicitOrderBy.length > 0
  3960. ? query.explicitOrderBy[0].field
  3961. : null;
  3962. }
  3963. function getInequalityFilterField(query) {
  3964. for (const filter of query.filters) {
  3965. const result = filter.getFirstInequalityField();
  3966. if (result !== null) {
  3967. return result;
  3968. }
  3969. }
  3970. return null;
  3971. }
  3972. /**
  3973. * Creates a new Query for a collection group query that matches all documents
  3974. * within the provided collection group.
  3975. */
  3976. function newQueryForCollectionGroup(collectionId) {
  3977. return new QueryImpl(ResourcePath.emptyPath(), collectionId);
  3978. }
  3979. /**
  3980. * Returns whether the query matches a collection group rather than a specific
  3981. * collection.
  3982. */
  3983. function isCollectionGroupQuery(query) {
  3984. return query.collectionGroup !== null;
  3985. }
  3986. /**
  3987. * Returns the implicit order by constraint that is used to execute the Query,
  3988. * which can be different from the order by constraints the user provided (e.g.
  3989. * the SDK and backend always orders by `__name__`).
  3990. */
  3991. function queryOrderBy(query) {
  3992. const queryImpl = debugCast(query);
  3993. if (queryImpl.memoizedOrderBy === null) {
  3994. queryImpl.memoizedOrderBy = [];
  3995. const inequalityField = getInequalityFilterField(queryImpl);
  3996. const firstOrderByField = getFirstOrderByField(queryImpl);
  3997. if (inequalityField !== null && firstOrderByField === null) {
  3998. // In order to implicitly add key ordering, we must also add the
  3999. // inequality filter field for it to be a valid query.
  4000. // Note that the default inequality field and key ordering is ascending.
  4001. if (!inequalityField.isKeyField()) {
  4002. queryImpl.memoizedOrderBy.push(new OrderBy(inequalityField));
  4003. }
  4004. queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), "asc" /* Direction.ASCENDING */));
  4005. }
  4006. else {
  4007. let foundKeyOrdering = false;
  4008. for (const orderBy of queryImpl.explicitOrderBy) {
  4009. queryImpl.memoizedOrderBy.push(orderBy);
  4010. if (orderBy.field.isKeyField()) {
  4011. foundKeyOrdering = true;
  4012. }
  4013. }
  4014. if (!foundKeyOrdering) {
  4015. // The order of the implicit key ordering always matches the last
  4016. // explicit order by
  4017. const lastDirection = queryImpl.explicitOrderBy.length > 0
  4018. ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1]
  4019. .dir
  4020. : "asc" /* Direction.ASCENDING */;
  4021. queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection));
  4022. }
  4023. }
  4024. }
  4025. return queryImpl.memoizedOrderBy;
  4026. }
  4027. /**
  4028. * Converts this `Query` instance to it's corresponding `Target` representation.
  4029. */
  4030. function queryToTarget(query) {
  4031. const queryImpl = debugCast(query);
  4032. if (!queryImpl.memoizedTarget) {
  4033. if (queryImpl.limitType === "F" /* LimitType.First */) {
  4034. queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, queryOrderBy(queryImpl), queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt);
  4035. }
  4036. else {
  4037. // Flip the orderBy directions since we want the last results
  4038. const orderBys = [];
  4039. for (const orderBy of queryOrderBy(queryImpl)) {
  4040. const dir = orderBy.dir === "desc" /* Direction.DESCENDING */
  4041. ? "asc" /* Direction.ASCENDING */
  4042. : "desc" /* Direction.DESCENDING */;
  4043. orderBys.push(new OrderBy(orderBy.field, dir));
  4044. }
  4045. // We need to swap the cursors to match the now-flipped query ordering.
  4046. const startAt = queryImpl.endAt
  4047. ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive)
  4048. : null;
  4049. const endAt = queryImpl.startAt
  4050. ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive)
  4051. : null;
  4052. // Now return as a LimitType.First query.
  4053. queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt);
  4054. }
  4055. }
  4056. return queryImpl.memoizedTarget;
  4057. }
  4058. function queryWithAddedFilter(query, filter) {
  4059. filter.getFirstInequalityField();
  4060. getInequalityFilterField(query);
  4061. const newFilters = query.filters.concat([filter]);
  4062. return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
  4063. }
  4064. function queryWithAddedOrderBy(query, orderBy) {
  4065. // TODO(dimond): validate that orderBy does not list the same key twice.
  4066. const newOrderBy = query.explicitOrderBy.concat([orderBy]);
  4067. return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
  4068. }
  4069. function queryWithLimit(query, limit, limitType) {
  4070. return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt);
  4071. }
  4072. function queryWithStartAt(query, bound) {
  4073. return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt);
  4074. }
  4075. function queryWithEndAt(query, bound) {
  4076. return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound);
  4077. }
  4078. function queryEquals(left, right) {
  4079. return (targetEquals(queryToTarget(left), queryToTarget(right)) &&
  4080. left.limitType === right.limitType);
  4081. }
  4082. /**
  4083. * @license
  4084. * Copyright 2020 Google LLC
  4085. *
  4086. * Licensed under the Apache License, Version 2.0 (the "License");
  4087. * you may not use this file except in compliance with the License.
  4088. * You may obtain a copy of the License at
  4089. *
  4090. * http://www.apache.org/licenses/LICENSE-2.0
  4091. *
  4092. * Unless required by applicable law or agreed to in writing, software
  4093. * distributed under the License is distributed on an "AS IS" BASIS,
  4094. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4095. * See the License for the specific language governing permissions and
  4096. * limitations under the License.
  4097. */
  4098. /**
  4099. * Returns an DoubleValue for `value` that is encoded based the serializer's
  4100. * `useProto3Json` setting.
  4101. */
  4102. function toDouble(serializer, value) {
  4103. if (serializer.useProto3Json) {
  4104. if (isNaN(value)) {
  4105. return { doubleValue: 'NaN' };
  4106. }
  4107. else if (value === Infinity) {
  4108. return { doubleValue: 'Infinity' };
  4109. }
  4110. else if (value === -Infinity) {
  4111. return { doubleValue: '-Infinity' };
  4112. }
  4113. }
  4114. return { doubleValue: isNegativeZero(value) ? '-0' : value };
  4115. }
  4116. /**
  4117. * Returns an IntegerValue for `value`.
  4118. */
  4119. function toInteger(value) {
  4120. return { integerValue: '' + value };
  4121. }
  4122. /**
  4123. * Returns a value for a number that's appropriate to put into a proto.
  4124. * The return value is an IntegerValue if it can safely represent the value,
  4125. * otherwise a DoubleValue is returned.
  4126. */
  4127. function toNumber(serializer, value) {
  4128. return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value);
  4129. }
  4130. /**
  4131. * @license
  4132. * Copyright 2018 Google LLC
  4133. *
  4134. * Licensed under the Apache License, Version 2.0 (the "License");
  4135. * you may not use this file except in compliance with the License.
  4136. * You may obtain a copy of the License at
  4137. *
  4138. * http://www.apache.org/licenses/LICENSE-2.0
  4139. *
  4140. * Unless required by applicable law or agreed to in writing, software
  4141. * distributed under the License is distributed on an "AS IS" BASIS,
  4142. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4143. * See the License for the specific language governing permissions and
  4144. * limitations under the License.
  4145. */
  4146. /** Used to represent a field transform on a mutation. */
  4147. class TransformOperation {
  4148. constructor() {
  4149. // Make sure that the structural type of `TransformOperation` is unique.
  4150. // See https://github.com/microsoft/TypeScript/issues/5451
  4151. this._ = undefined;
  4152. }
  4153. }
  4154. /** Transforms a value into a server-generated timestamp. */
  4155. class ServerTimestampTransform extends TransformOperation {
  4156. }
  4157. /** Transforms an array value via a union operation. */
  4158. class ArrayUnionTransformOperation extends TransformOperation {
  4159. constructor(elements) {
  4160. super();
  4161. this.elements = elements;
  4162. }
  4163. }
  4164. /** Transforms an array value via a remove operation. */
  4165. class ArrayRemoveTransformOperation extends TransformOperation {
  4166. constructor(elements) {
  4167. super();
  4168. this.elements = elements;
  4169. }
  4170. }
  4171. /**
  4172. * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
  4173. * transforms. Converts all field values to integers or doubles, but unlike the
  4174. * backend does not cap integer values at 2^63. Instead, JavaScript number
  4175. * arithmetic is used and precision loss can occur for values greater than 2^53.
  4176. */
  4177. class NumericIncrementTransformOperation extends TransformOperation {
  4178. constructor(serializer, operand) {
  4179. super();
  4180. this.serializer = serializer;
  4181. this.operand = operand;
  4182. }
  4183. }
  4184. /**
  4185. * @license
  4186. * Copyright 2017 Google LLC
  4187. *
  4188. * Licensed under the Apache License, Version 2.0 (the "License");
  4189. * you may not use this file except in compliance with the License.
  4190. * You may obtain a copy of the License at
  4191. *
  4192. * http://www.apache.org/licenses/LICENSE-2.0
  4193. *
  4194. * Unless required by applicable law or agreed to in writing, software
  4195. * distributed under the License is distributed on an "AS IS" BASIS,
  4196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4197. * See the License for the specific language governing permissions and
  4198. * limitations under the License.
  4199. */
  4200. /** A field path and the TransformOperation to perform upon it. */
  4201. class FieldTransform {
  4202. constructor(field, transform) {
  4203. this.field = field;
  4204. this.transform = transform;
  4205. }
  4206. }
  4207. /**
  4208. * Encodes a precondition for a mutation. This follows the model that the
  4209. * backend accepts with the special case of an explicit "empty" precondition
  4210. * (meaning no precondition).
  4211. */
  4212. class Precondition {
  4213. constructor(updateTime, exists) {
  4214. this.updateTime = updateTime;
  4215. this.exists = exists;
  4216. }
  4217. /** Creates a new empty Precondition. */
  4218. static none() {
  4219. return new Precondition();
  4220. }
  4221. /** Creates a new Precondition with an exists flag. */
  4222. static exists(exists) {
  4223. return new Precondition(undefined, exists);
  4224. }
  4225. /** Creates a new Precondition based on a version a document exists at. */
  4226. static updateTime(version) {
  4227. return new Precondition(version);
  4228. }
  4229. /** Returns whether this Precondition is empty. */
  4230. get isNone() {
  4231. return this.updateTime === undefined && this.exists === undefined;
  4232. }
  4233. isEqual(other) {
  4234. return (this.exists === other.exists &&
  4235. (this.updateTime
  4236. ? !!other.updateTime && this.updateTime.isEqual(other.updateTime)
  4237. : !other.updateTime));
  4238. }
  4239. }
  4240. /**
  4241. * A mutation describes a self-contained change to a document. Mutations can
  4242. * create, replace, delete, and update subsets of documents.
  4243. *
  4244. * Mutations not only act on the value of the document but also its version.
  4245. *
  4246. * For local mutations (mutations that haven't been committed yet), we preserve
  4247. * the existing version for Set and Patch mutations. For Delete mutations, we
  4248. * reset the version to 0.
  4249. *
  4250. * Here's the expected transition table.
  4251. *
  4252. * MUTATION APPLIED TO RESULTS IN
  4253. *
  4254. * SetMutation Document(v3) Document(v3)
  4255. * SetMutation NoDocument(v3) Document(v0)
  4256. * SetMutation InvalidDocument(v0) Document(v0)
  4257. * PatchMutation Document(v3) Document(v3)
  4258. * PatchMutation NoDocument(v3) NoDocument(v3)
  4259. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  4260. * DeleteMutation Document(v3) NoDocument(v0)
  4261. * DeleteMutation NoDocument(v3) NoDocument(v0)
  4262. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  4263. *
  4264. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  4265. * the resulting version for Set and Patch mutations. As deletes have no
  4266. * explicit update time, we use the commitTime of the WriteResponse for
  4267. * Delete mutations.
  4268. *
  4269. * If a mutation is acknowledged by the backend but fails the precondition check
  4270. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  4271. * the updated version.
  4272. *
  4273. * Field transforms are used only with Patch and Set Mutations. We use the
  4274. * `updateTransforms` message to store transforms, rather than the `transforms`s
  4275. * messages.
  4276. *
  4277. * ## Subclassing Notes
  4278. *
  4279. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  4280. * applyToLocalView() to implement the actual behavior of applying the mutation
  4281. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  4282. * example).
  4283. */
  4284. class Mutation {
  4285. }
  4286. /**
  4287. * A mutation that creates or replaces the document at the given key with the
  4288. * object value contents.
  4289. */
  4290. class SetMutation extends Mutation {
  4291. constructor(key, value, precondition, fieldTransforms = []) {
  4292. super();
  4293. this.key = key;
  4294. this.value = value;
  4295. this.precondition = precondition;
  4296. this.fieldTransforms = fieldTransforms;
  4297. this.type = 0 /* MutationType.Set */;
  4298. }
  4299. getFieldMask() {
  4300. return null;
  4301. }
  4302. }
  4303. /**
  4304. * A mutation that modifies fields of the document at the given key with the
  4305. * given values. The values are applied through a field mask:
  4306. *
  4307. * * When a field is in both the mask and the values, the corresponding field
  4308. * is updated.
  4309. * * When a field is in neither the mask nor the values, the corresponding
  4310. * field is unmodified.
  4311. * * When a field is in the mask but not in the values, the corresponding field
  4312. * is deleted.
  4313. * * When a field is not in the mask but is in the values, the values map is
  4314. * ignored.
  4315. */
  4316. class PatchMutation extends Mutation {
  4317. constructor(key, data, fieldMask, precondition, fieldTransforms = []) {
  4318. super();
  4319. this.key = key;
  4320. this.data = data;
  4321. this.fieldMask = fieldMask;
  4322. this.precondition = precondition;
  4323. this.fieldTransforms = fieldTransforms;
  4324. this.type = 1 /* MutationType.Patch */;
  4325. }
  4326. getFieldMask() {
  4327. return this.fieldMask;
  4328. }
  4329. }
  4330. /** A mutation that deletes the document at the given key. */
  4331. class DeleteMutation extends Mutation {
  4332. constructor(key, precondition) {
  4333. super();
  4334. this.key = key;
  4335. this.precondition = precondition;
  4336. this.type = 2 /* MutationType.Delete */;
  4337. this.fieldTransforms = [];
  4338. }
  4339. getFieldMask() {
  4340. return null;
  4341. }
  4342. }
  4343. /**
  4344. * A mutation that verifies the existence of the document at the given key with
  4345. * the provided precondition.
  4346. *
  4347. * The `verify` operation is only used in Transactions, and this class serves
  4348. * primarily to facilitate serialization into protos.
  4349. */
  4350. class VerifyMutation extends Mutation {
  4351. constructor(key, precondition) {
  4352. super();
  4353. this.key = key;
  4354. this.precondition = precondition;
  4355. this.type = 3 /* MutationType.Verify */;
  4356. this.fieldTransforms = [];
  4357. }
  4358. getFieldMask() {
  4359. return null;
  4360. }
  4361. }
  4362. /**
  4363. * @license
  4364. * Copyright 2017 Google LLC
  4365. *
  4366. * Licensed under the Apache License, Version 2.0 (the "License");
  4367. * you may not use this file except in compliance with the License.
  4368. * You may obtain a copy of the License at
  4369. *
  4370. * http://www.apache.org/licenses/LICENSE-2.0
  4371. *
  4372. * Unless required by applicable law or agreed to in writing, software
  4373. * distributed under the License is distributed on an "AS IS" BASIS,
  4374. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4375. * See the License for the specific language governing permissions and
  4376. * limitations under the License.
  4377. */
  4378. const DIRECTIONS = (() => {
  4379. const dirs = {};
  4380. dirs["asc" /* Direction.ASCENDING */] = 'ASCENDING';
  4381. dirs["desc" /* Direction.DESCENDING */] = 'DESCENDING';
  4382. return dirs;
  4383. })();
  4384. const OPERATORS = (() => {
  4385. const ops = {};
  4386. ops["<" /* Operator.LESS_THAN */] = 'LESS_THAN';
  4387. ops["<=" /* Operator.LESS_THAN_OR_EQUAL */] = 'LESS_THAN_OR_EQUAL';
  4388. ops[">" /* Operator.GREATER_THAN */] = 'GREATER_THAN';
  4389. ops[">=" /* Operator.GREATER_THAN_OR_EQUAL */] = 'GREATER_THAN_OR_EQUAL';
  4390. ops["==" /* Operator.EQUAL */] = 'EQUAL';
  4391. ops["!=" /* Operator.NOT_EQUAL */] = 'NOT_EQUAL';
  4392. ops["array-contains" /* Operator.ARRAY_CONTAINS */] = 'ARRAY_CONTAINS';
  4393. ops["in" /* Operator.IN */] = 'IN';
  4394. ops["not-in" /* Operator.NOT_IN */] = 'NOT_IN';
  4395. ops["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */] = 'ARRAY_CONTAINS_ANY';
  4396. return ops;
  4397. })();
  4398. const COMPOSITE_OPERATORS = (() => {
  4399. const ops = {};
  4400. ops["and" /* CompositeOperator.AND */] = 'AND';
  4401. ops["or" /* CompositeOperator.OR */] = 'OR';
  4402. return ops;
  4403. })();
  4404. function assertPresent(value, description) {
  4405. }
  4406. /**
  4407. * This class generates JsonObject values for the Datastore API suitable for
  4408. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  4409. *
  4410. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  4411. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  4412. * format.
  4413. *
  4414. * For a description of the Proto3 JSON format check
  4415. * https://developers.google.com/protocol-buffers/docs/proto3#json
  4416. *
  4417. * TODO(klimt): We can remove the databaseId argument if we keep the full
  4418. * resource name in documents.
  4419. */
  4420. class JsonProtoSerializer {
  4421. constructor(databaseId, useProto3Json) {
  4422. this.databaseId = databaseId;
  4423. this.useProto3Json = useProto3Json;
  4424. }
  4425. }
  4426. /**
  4427. * Returns a value for a number (or null) that's appropriate to put into
  4428. * a google.protobuf.Int32Value proto.
  4429. * DO NOT USE THIS FOR ANYTHING ELSE.
  4430. * This method cheats. It's typed as returning "number" because that's what
  4431. * our generated proto interfaces say Int32Value must be. But GRPC actually
  4432. * expects a { value: <number> } struct.
  4433. */
  4434. function toInt32Proto(serializer, val) {
  4435. if (serializer.useProto3Json || isNullOrUndefined(val)) {
  4436. return val;
  4437. }
  4438. else {
  4439. return { value: val };
  4440. }
  4441. }
  4442. /**
  4443. * Returns a value for a Date that's appropriate to put into a proto.
  4444. */
  4445. function toTimestamp(serializer, timestamp) {
  4446. if (serializer.useProto3Json) {
  4447. // Serialize to ISO-8601 date format, but with full nano resolution.
  4448. // Since JS Date has only millis, let's only use it for the seconds and
  4449. // then manually add the fractions to the end.
  4450. const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();
  4451. // Remove .xxx frac part and Z in the end.
  4452. const strUntilSeconds = jsDateStr.replace(/\.\d*/, '').replace('Z', '');
  4453. // Pad the fraction out to 9 digits (nanos).
  4454. const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);
  4455. return `${strUntilSeconds}.${nanoStr}Z`;
  4456. }
  4457. else {
  4458. return {
  4459. seconds: '' + timestamp.seconds,
  4460. nanos: timestamp.nanoseconds
  4461. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4462. };
  4463. }
  4464. }
  4465. function fromTimestamp(date) {
  4466. const timestamp = normalizeTimestamp(date);
  4467. return new Timestamp(timestamp.seconds, timestamp.nanos);
  4468. }
  4469. /**
  4470. * Returns a value for bytes that's appropriate to put in a proto.
  4471. *
  4472. * Visible for testing.
  4473. */
  4474. function toBytes(serializer, bytes) {
  4475. if (serializer.useProto3Json) {
  4476. return bytes.toBase64();
  4477. }
  4478. else {
  4479. return bytes.toUint8Array();
  4480. }
  4481. }
  4482. function toVersion(serializer, version) {
  4483. return toTimestamp(serializer, version.toTimestamp());
  4484. }
  4485. function fromVersion(version) {
  4486. hardAssert(!!version);
  4487. return SnapshotVersion.fromTimestamp(fromTimestamp(version));
  4488. }
  4489. function toResourceName(databaseId, path) {
  4490. return fullyQualifiedPrefixPath(databaseId)
  4491. .child('documents')
  4492. .child(path)
  4493. .canonicalString();
  4494. }
  4495. function fromResourceName(name) {
  4496. const resource = ResourcePath.fromString(name);
  4497. hardAssert(isValidResourceName(resource));
  4498. return resource;
  4499. }
  4500. function toName(serializer, key) {
  4501. return toResourceName(serializer.databaseId, key.path);
  4502. }
  4503. function fromName(serializer, name) {
  4504. const resource = fromResourceName(name);
  4505. if (resource.get(1) !== serializer.databaseId.projectId) {
  4506. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different project: ' +
  4507. resource.get(1) +
  4508. ' vs ' +
  4509. serializer.databaseId.projectId);
  4510. }
  4511. if (resource.get(3) !== serializer.databaseId.database) {
  4512. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different database: ' +
  4513. resource.get(3) +
  4514. ' vs ' +
  4515. serializer.databaseId.database);
  4516. }
  4517. return new DocumentKey(extractLocalPathFromResourceName(resource));
  4518. }
  4519. function toQueryPath(serializer, path) {
  4520. return toResourceName(serializer.databaseId, path);
  4521. }
  4522. function getEncodedDatabaseId(serializer) {
  4523. const path = new ResourcePath([
  4524. 'projects',
  4525. serializer.databaseId.projectId,
  4526. 'databases',
  4527. serializer.databaseId.database
  4528. ]);
  4529. return path.canonicalString();
  4530. }
  4531. function fullyQualifiedPrefixPath(databaseId) {
  4532. return new ResourcePath([
  4533. 'projects',
  4534. databaseId.projectId,
  4535. 'databases',
  4536. databaseId.database
  4537. ]);
  4538. }
  4539. function extractLocalPathFromResourceName(resourceName) {
  4540. hardAssert(resourceName.length > 4 && resourceName.get(4) === 'documents');
  4541. return resourceName.popFirst(5);
  4542. }
  4543. /** Creates a Document proto from key and fields (but no create/update time) */
  4544. function toMutationDocument(serializer, key, fields) {
  4545. return {
  4546. name: toName(serializer, key),
  4547. fields: fields.value.mapValue.fields
  4548. };
  4549. }
  4550. function fromDocument(serializer, document, hasCommittedMutations) {
  4551. const key = fromName(serializer, document.name);
  4552. const version = fromVersion(document.updateTime);
  4553. // If we read a document from persistence that is missing createTime, it's due
  4554. // to older SDK versions not storing this information. In such cases, we'll
  4555. // set the createTime to zero. This can be removed in the long term.
  4556. const createTime = document.createTime
  4557. ? fromVersion(document.createTime)
  4558. : SnapshotVersion.min();
  4559. const data = new ObjectValue({ mapValue: { fields: document.fields } });
  4560. const result = MutableDocument.newFoundDocument(key, version, createTime, data);
  4561. if (hasCommittedMutations) {
  4562. result.setHasCommittedMutations();
  4563. }
  4564. return hasCommittedMutations ? result.setHasCommittedMutations() : result;
  4565. }
  4566. function fromFound(serializer, doc) {
  4567. hardAssert(!!doc.found);
  4568. assertPresent(doc.found.name);
  4569. assertPresent(doc.found.updateTime);
  4570. const key = fromName(serializer, doc.found.name);
  4571. const version = fromVersion(doc.found.updateTime);
  4572. const createTime = doc.found.createTime
  4573. ? fromVersion(doc.found.createTime)
  4574. : SnapshotVersion.min();
  4575. const data = new ObjectValue({ mapValue: { fields: doc.found.fields } });
  4576. return MutableDocument.newFoundDocument(key, version, createTime, data);
  4577. }
  4578. function fromMissing(serializer, result) {
  4579. hardAssert(!!result.missing);
  4580. hardAssert(!!result.readTime);
  4581. const key = fromName(serializer, result.missing);
  4582. const version = fromVersion(result.readTime);
  4583. return MutableDocument.newNoDocument(key, version);
  4584. }
  4585. function fromBatchGetDocumentsResponse(serializer, result) {
  4586. if ('found' in result) {
  4587. return fromFound(serializer, result);
  4588. }
  4589. else if ('missing' in result) {
  4590. return fromMissing(serializer, result);
  4591. }
  4592. return fail();
  4593. }
  4594. function toMutation(serializer, mutation) {
  4595. let result;
  4596. if (mutation instanceof SetMutation) {
  4597. result = {
  4598. update: toMutationDocument(serializer, mutation.key, mutation.value)
  4599. };
  4600. }
  4601. else if (mutation instanceof DeleteMutation) {
  4602. result = { delete: toName(serializer, mutation.key) };
  4603. }
  4604. else if (mutation instanceof PatchMutation) {
  4605. result = {
  4606. update: toMutationDocument(serializer, mutation.key, mutation.data),
  4607. updateMask: toDocumentMask(mutation.fieldMask)
  4608. };
  4609. }
  4610. else if (mutation instanceof VerifyMutation) {
  4611. result = {
  4612. verify: toName(serializer, mutation.key)
  4613. };
  4614. }
  4615. else {
  4616. return fail();
  4617. }
  4618. if (mutation.fieldTransforms.length > 0) {
  4619. result.updateTransforms = mutation.fieldTransforms.map(transform => toFieldTransform(serializer, transform));
  4620. }
  4621. if (!mutation.precondition.isNone) {
  4622. result.currentDocument = toPrecondition(serializer, mutation.precondition);
  4623. }
  4624. return result;
  4625. }
  4626. function toPrecondition(serializer, precondition) {
  4627. if (precondition.updateTime !== undefined) {
  4628. return {
  4629. updateTime: toVersion(serializer, precondition.updateTime)
  4630. };
  4631. }
  4632. else if (precondition.exists !== undefined) {
  4633. return { exists: precondition.exists };
  4634. }
  4635. else {
  4636. return fail();
  4637. }
  4638. }
  4639. function toFieldTransform(serializer, fieldTransform) {
  4640. const transform = fieldTransform.transform;
  4641. if (transform instanceof ServerTimestampTransform) {
  4642. return {
  4643. fieldPath: fieldTransform.field.canonicalString(),
  4644. setToServerValue: 'REQUEST_TIME'
  4645. };
  4646. }
  4647. else if (transform instanceof ArrayUnionTransformOperation) {
  4648. return {
  4649. fieldPath: fieldTransform.field.canonicalString(),
  4650. appendMissingElements: {
  4651. values: transform.elements
  4652. }
  4653. };
  4654. }
  4655. else if (transform instanceof ArrayRemoveTransformOperation) {
  4656. return {
  4657. fieldPath: fieldTransform.field.canonicalString(),
  4658. removeAllFromArray: {
  4659. values: transform.elements
  4660. }
  4661. };
  4662. }
  4663. else if (transform instanceof NumericIncrementTransformOperation) {
  4664. return {
  4665. fieldPath: fieldTransform.field.canonicalString(),
  4666. increment: transform.operand
  4667. };
  4668. }
  4669. else {
  4670. throw fail();
  4671. }
  4672. }
  4673. function toQueryTarget(serializer, target) {
  4674. // Dissect the path into parent, collectionId, and optional key filter.
  4675. const result = { structuredQuery: {} };
  4676. const path = target.path;
  4677. if (target.collectionGroup !== null) {
  4678. result.parent = toQueryPath(serializer, path);
  4679. result.structuredQuery.from = [
  4680. {
  4681. collectionId: target.collectionGroup,
  4682. allDescendants: true
  4683. }
  4684. ];
  4685. }
  4686. else {
  4687. result.parent = toQueryPath(serializer, path.popLast());
  4688. result.structuredQuery.from = [{ collectionId: path.lastSegment() }];
  4689. }
  4690. const where = toFilters(target.filters);
  4691. if (where) {
  4692. result.structuredQuery.where = where;
  4693. }
  4694. const orderBy = toOrder(target.orderBy);
  4695. if (orderBy) {
  4696. result.structuredQuery.orderBy = orderBy;
  4697. }
  4698. const limit = toInt32Proto(serializer, target.limit);
  4699. if (limit !== null) {
  4700. result.structuredQuery.limit = limit;
  4701. }
  4702. if (target.startAt) {
  4703. result.structuredQuery.startAt = toStartAtCursor(target.startAt);
  4704. }
  4705. if (target.endAt) {
  4706. result.structuredQuery.endAt = toEndAtCursor(target.endAt);
  4707. }
  4708. return result;
  4709. }
  4710. function toRunAggregationQueryRequest(serializer, target) {
  4711. const queryTarget = toQueryTarget(serializer, target);
  4712. return {
  4713. structuredAggregationQuery: {
  4714. aggregations: [
  4715. {
  4716. count: {},
  4717. alias: 'count_alias'
  4718. }
  4719. ],
  4720. structuredQuery: queryTarget.structuredQuery
  4721. },
  4722. parent: queryTarget.parent
  4723. };
  4724. }
  4725. function toFilters(filters) {
  4726. if (filters.length === 0) {
  4727. return;
  4728. }
  4729. return toFilter(CompositeFilter.create(filters, "and" /* CompositeOperator.AND */));
  4730. }
  4731. function toOrder(orderBys) {
  4732. if (orderBys.length === 0) {
  4733. return;
  4734. }
  4735. return orderBys.map(order => toPropertyOrder(order));
  4736. }
  4737. function toStartAtCursor(cursor) {
  4738. return {
  4739. before: cursor.inclusive,
  4740. values: cursor.position
  4741. };
  4742. }
  4743. function toEndAtCursor(cursor) {
  4744. return {
  4745. before: !cursor.inclusive,
  4746. values: cursor.position
  4747. };
  4748. }
  4749. // visible for testing
  4750. function toDirection(dir) {
  4751. return DIRECTIONS[dir];
  4752. }
  4753. // visible for testing
  4754. function toOperatorName(op) {
  4755. return OPERATORS[op];
  4756. }
  4757. function toCompositeOperatorName(op) {
  4758. return COMPOSITE_OPERATORS[op];
  4759. }
  4760. function toFieldPathReference(path) {
  4761. return { fieldPath: path.canonicalString() };
  4762. }
  4763. // visible for testing
  4764. function toPropertyOrder(orderBy) {
  4765. return {
  4766. field: toFieldPathReference(orderBy.field),
  4767. direction: toDirection(orderBy.dir)
  4768. };
  4769. }
  4770. // visible for testing
  4771. function toFilter(filter) {
  4772. if (filter instanceof FieldFilter) {
  4773. return toUnaryOrFieldFilter(filter);
  4774. }
  4775. else if (filter instanceof CompositeFilter) {
  4776. return toCompositeFilter(filter);
  4777. }
  4778. else {
  4779. return fail();
  4780. }
  4781. }
  4782. function toCompositeFilter(filter) {
  4783. const protos = filter.getFilters().map(filter => toFilter(filter));
  4784. if (protos.length === 1) {
  4785. return protos[0];
  4786. }
  4787. return {
  4788. compositeFilter: {
  4789. op: toCompositeOperatorName(filter.op),
  4790. filters: protos
  4791. }
  4792. };
  4793. }
  4794. function toUnaryOrFieldFilter(filter) {
  4795. if (filter.op === "==" /* Operator.EQUAL */) {
  4796. if (isNanValue(filter.value)) {
  4797. return {
  4798. unaryFilter: {
  4799. field: toFieldPathReference(filter.field),
  4800. op: 'IS_NAN'
  4801. }
  4802. };
  4803. }
  4804. else if (isNullValue(filter.value)) {
  4805. return {
  4806. unaryFilter: {
  4807. field: toFieldPathReference(filter.field),
  4808. op: 'IS_NULL'
  4809. }
  4810. };
  4811. }
  4812. }
  4813. else if (filter.op === "!=" /* Operator.NOT_EQUAL */) {
  4814. if (isNanValue(filter.value)) {
  4815. return {
  4816. unaryFilter: {
  4817. field: toFieldPathReference(filter.field),
  4818. op: 'IS_NOT_NAN'
  4819. }
  4820. };
  4821. }
  4822. else if (isNullValue(filter.value)) {
  4823. return {
  4824. unaryFilter: {
  4825. field: toFieldPathReference(filter.field),
  4826. op: 'IS_NOT_NULL'
  4827. }
  4828. };
  4829. }
  4830. }
  4831. return {
  4832. fieldFilter: {
  4833. field: toFieldPathReference(filter.field),
  4834. op: toOperatorName(filter.op),
  4835. value: filter.value
  4836. }
  4837. };
  4838. }
  4839. function toDocumentMask(fieldMask) {
  4840. const canonicalFields = [];
  4841. fieldMask.fields.forEach(field => canonicalFields.push(field.canonicalString()));
  4842. return {
  4843. fieldPaths: canonicalFields
  4844. };
  4845. }
  4846. function isValidResourceName(path) {
  4847. // Resource names have at least 4 components (project ID, database ID)
  4848. return (path.length >= 4 &&
  4849. path.get(0) === 'projects' &&
  4850. path.get(2) === 'databases');
  4851. }
  4852. /**
  4853. * @license
  4854. * Copyright 2020 Google LLC
  4855. *
  4856. * Licensed under the Apache License, Version 2.0 (the "License");
  4857. * you may not use this file except in compliance with the License.
  4858. * You may obtain a copy of the License at
  4859. *
  4860. * http://www.apache.org/licenses/LICENSE-2.0
  4861. *
  4862. * Unless required by applicable law or agreed to in writing, software
  4863. * distributed under the License is distributed on an "AS IS" BASIS,
  4864. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4865. * See the License for the specific language governing permissions and
  4866. * limitations under the License.
  4867. */
  4868. function newSerializer(databaseId) {
  4869. return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true);
  4870. }
  4871. /**
  4872. * @license
  4873. * Copyright 2017 Google LLC
  4874. *
  4875. * Licensed under the Apache License, Version 2.0 (the "License");
  4876. * you may not use this file except in compliance with the License.
  4877. * You may obtain a copy of the License at
  4878. *
  4879. * http://www.apache.org/licenses/LICENSE-2.0
  4880. *
  4881. * Unless required by applicable law or agreed to in writing, software
  4882. * distributed under the License is distributed on an "AS IS" BASIS,
  4883. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4884. * See the License for the specific language governing permissions and
  4885. * limitations under the License.
  4886. */
  4887. const LOG_TAG$2 = 'ExponentialBackoff';
  4888. /**
  4889. * Initial backoff time in milliseconds after an error.
  4890. * Set to 1s according to https://cloud.google.com/apis/design/errors.
  4891. */
  4892. const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;
  4893. const DEFAULT_BACKOFF_FACTOR = 1.5;
  4894. /** Maximum backoff time in milliseconds */
  4895. const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;
  4896. /**
  4897. * A helper for running delayed tasks following an exponential backoff curve
  4898. * between attempts.
  4899. *
  4900. * Each delay is made up of a "base" delay which follows the exponential
  4901. * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
  4902. * base delay. This prevents clients from accidentally synchronizing their
  4903. * delays causing spikes of load to the backend.
  4904. */
  4905. class ExponentialBackoff {
  4906. constructor(
  4907. /**
  4908. * The AsyncQueue to run backoff operations on.
  4909. */
  4910. queue,
  4911. /**
  4912. * The ID to use when scheduling backoff operations on the AsyncQueue.
  4913. */
  4914. timerId,
  4915. /**
  4916. * The initial delay (used as the base delay on the first retry attempt).
  4917. * Note that jitter will still be applied, so the actual delay could be as
  4918. * little as 0.5*initialDelayMs.
  4919. */
  4920. initialDelayMs = DEFAULT_BACKOFF_INITIAL_DELAY_MS,
  4921. /**
  4922. * The multiplier to use to determine the extended base delay after each
  4923. * attempt.
  4924. */
  4925. backoffFactor = DEFAULT_BACKOFF_FACTOR,
  4926. /**
  4927. * The maximum base delay after which no further backoff is performed.
  4928. * Note that jitter will still be applied, so the actual delay could be as
  4929. * much as 1.5*maxDelayMs.
  4930. */
  4931. maxDelayMs = DEFAULT_BACKOFF_MAX_DELAY_MS) {
  4932. this.queue = queue;
  4933. this.timerId = timerId;
  4934. this.initialDelayMs = initialDelayMs;
  4935. this.backoffFactor = backoffFactor;
  4936. this.maxDelayMs = maxDelayMs;
  4937. this.currentBaseMs = 0;
  4938. this.timerPromise = null;
  4939. /** The last backoff attempt, as epoch milliseconds. */
  4940. this.lastAttemptTime = Date.now();
  4941. this.reset();
  4942. }
  4943. /**
  4944. * Resets the backoff delay.
  4945. *
  4946. * The very next backoffAndWait() will have no delay. If it is called again
  4947. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  4948. * subsequent ones will increase according to the backoffFactor.
  4949. */
  4950. reset() {
  4951. this.currentBaseMs = 0;
  4952. }
  4953. /**
  4954. * Resets the backoff delay to the maximum delay (e.g. for use after a
  4955. * RESOURCE_EXHAUSTED error).
  4956. */
  4957. resetToMax() {
  4958. this.currentBaseMs = this.maxDelayMs;
  4959. }
  4960. /**
  4961. * Returns a promise that resolves after currentDelayMs, and increases the
  4962. * delay for any subsequent attempts. If there was a pending backoff operation
  4963. * already, it will be canceled.
  4964. */
  4965. backoffAndRun(op) {
  4966. // Cancel any pending backoff operation.
  4967. this.cancel();
  4968. // First schedule using the current base (which may be 0 and should be
  4969. // honored as such).
  4970. const desiredDelayWithJitterMs = Math.floor(this.currentBaseMs + this.jitterDelayMs());
  4971. // Guard against lastAttemptTime being in the future due to a clock change.
  4972. const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);
  4973. // Guard against the backoff delay already being past.
  4974. const remainingDelayMs = Math.max(0, desiredDelayWithJitterMs - delaySoFarMs);
  4975. if (remainingDelayMs > 0) {
  4976. logDebug(LOG_TAG$2, `Backing off for ${remainingDelayMs} ms ` +
  4977. `(base delay: ${this.currentBaseMs} ms, ` +
  4978. `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +
  4979. `last attempt: ${delaySoFarMs} ms ago)`);
  4980. }
  4981. this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, remainingDelayMs, () => {
  4982. this.lastAttemptTime = Date.now();
  4983. return op();
  4984. });
  4985. // Apply backoff factor to determine next delay and ensure it is within
  4986. // bounds.
  4987. this.currentBaseMs *= this.backoffFactor;
  4988. if (this.currentBaseMs < this.initialDelayMs) {
  4989. this.currentBaseMs = this.initialDelayMs;
  4990. }
  4991. if (this.currentBaseMs > this.maxDelayMs) {
  4992. this.currentBaseMs = this.maxDelayMs;
  4993. }
  4994. }
  4995. skipBackoff() {
  4996. if (this.timerPromise !== null) {
  4997. this.timerPromise.skipDelay();
  4998. this.timerPromise = null;
  4999. }
  5000. }
  5001. cancel() {
  5002. if (this.timerPromise !== null) {
  5003. this.timerPromise.cancel();
  5004. this.timerPromise = null;
  5005. }
  5006. }
  5007. /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */
  5008. jitterDelayMs() {
  5009. return (Math.random() - 0.5) * this.currentBaseMs;
  5010. }
  5011. }
  5012. /**
  5013. * @license
  5014. * Copyright 2017 Google LLC
  5015. *
  5016. * Licensed under the Apache License, Version 2.0 (the "License");
  5017. * you may not use this file except in compliance with the License.
  5018. * You may obtain a copy of the License at
  5019. *
  5020. * http://www.apache.org/licenses/LICENSE-2.0
  5021. *
  5022. * Unless required by applicable law or agreed to in writing, software
  5023. * distributed under the License is distributed on an "AS IS" BASIS,
  5024. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5025. * See the License for the specific language governing permissions and
  5026. * limitations under the License.
  5027. */
  5028. /**
  5029. * Datastore and its related methods are a wrapper around the external Google
  5030. * Cloud Datastore grpc API, which provides an interface that is more convenient
  5031. * for the rest of the client SDK architecture to consume.
  5032. */
  5033. class Datastore {
  5034. }
  5035. /**
  5036. * An implementation of Datastore that exposes additional state for internal
  5037. * consumption.
  5038. */
  5039. class DatastoreImpl extends Datastore {
  5040. constructor(authCredentials, appCheckCredentials, connection, serializer) {
  5041. super();
  5042. this.authCredentials = authCredentials;
  5043. this.appCheckCredentials = appCheckCredentials;
  5044. this.connection = connection;
  5045. this.serializer = serializer;
  5046. this.terminated = false;
  5047. }
  5048. verifyInitialized() {
  5049. if (this.terminated) {
  5050. throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.');
  5051. }
  5052. }
  5053. /** Invokes the provided RPC with auth and AppCheck tokens. */
  5054. invokeRPC(rpcName, path, request) {
  5055. this.verifyInitialized();
  5056. return Promise.all([
  5057. this.authCredentials.getToken(),
  5058. this.appCheckCredentials.getToken()
  5059. ])
  5060. .then(([authToken, appCheckToken]) => {
  5061. return this.connection.invokeRPC(rpcName, path, request, authToken, appCheckToken);
  5062. })
  5063. .catch((error) => {
  5064. if (error.name === 'FirebaseError') {
  5065. if (error.code === Code.UNAUTHENTICATED) {
  5066. this.authCredentials.invalidateToken();
  5067. this.appCheckCredentials.invalidateToken();
  5068. }
  5069. throw error;
  5070. }
  5071. else {
  5072. throw new FirestoreError(Code.UNKNOWN, error.toString());
  5073. }
  5074. });
  5075. }
  5076. /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */
  5077. invokeStreamingRPC(rpcName, path, request, expectedResponseCount) {
  5078. this.verifyInitialized();
  5079. return Promise.all([
  5080. this.authCredentials.getToken(),
  5081. this.appCheckCredentials.getToken()
  5082. ])
  5083. .then(([authToken, appCheckToken]) => {
  5084. return this.connection.invokeStreamingRPC(rpcName, path, request, authToken, appCheckToken, expectedResponseCount);
  5085. })
  5086. .catch((error) => {
  5087. if (error.name === 'FirebaseError') {
  5088. if (error.code === Code.UNAUTHENTICATED) {
  5089. this.authCredentials.invalidateToken();
  5090. this.appCheckCredentials.invalidateToken();
  5091. }
  5092. throw error;
  5093. }
  5094. else {
  5095. throw new FirestoreError(Code.UNKNOWN, error.toString());
  5096. }
  5097. });
  5098. }
  5099. terminate() {
  5100. this.terminated = true;
  5101. }
  5102. }
  5103. // TODO(firestorexp): Make sure there is only one Datastore instance per
  5104. // firestore-exp client.
  5105. function newDatastore(authCredentials, appCheckCredentials, connection, serializer) {
  5106. return new DatastoreImpl(authCredentials, appCheckCredentials, connection, serializer);
  5107. }
  5108. async function invokeCommitRpc(datastore, mutations) {
  5109. const datastoreImpl = debugCast(datastore);
  5110. const path = getEncodedDatabaseId(datastoreImpl.serializer) + '/documents';
  5111. const request = {
  5112. writes: mutations.map(m => toMutation(datastoreImpl.serializer, m))
  5113. };
  5114. await datastoreImpl.invokeRPC('Commit', path, request);
  5115. }
  5116. async function invokeBatchGetDocumentsRpc(datastore, keys) {
  5117. const datastoreImpl = debugCast(datastore);
  5118. const path = getEncodedDatabaseId(datastoreImpl.serializer) + '/documents';
  5119. const request = {
  5120. documents: keys.map(k => toName(datastoreImpl.serializer, k))
  5121. };
  5122. const response = await datastoreImpl.invokeStreamingRPC('BatchGetDocuments', path, request, keys.length);
  5123. const docs = new Map();
  5124. response.forEach(proto => {
  5125. const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto);
  5126. docs.set(doc.key.toString(), doc);
  5127. });
  5128. const result = [];
  5129. keys.forEach(key => {
  5130. const doc = docs.get(key.toString());
  5131. hardAssert(!!doc);
  5132. result.push(doc);
  5133. });
  5134. return result;
  5135. }
  5136. async function invokeRunQueryRpc(datastore, query) {
  5137. const datastoreImpl = debugCast(datastore);
  5138. const request = toQueryTarget(datastoreImpl.serializer, queryToTarget(query));
  5139. const response = await datastoreImpl.invokeStreamingRPC('RunQuery', request.parent, { structuredQuery: request.structuredQuery });
  5140. return (response
  5141. // Omit RunQueryResponses that only contain readTimes.
  5142. .filter(proto => !!proto.document)
  5143. .map(proto => fromDocument(datastoreImpl.serializer, proto.document, undefined)));
  5144. }
  5145. async function invokeRunAggregationQueryRpc(datastore, query) {
  5146. const datastoreImpl = debugCast(datastore);
  5147. const request = toRunAggregationQueryRequest(datastoreImpl.serializer, queryToTarget(query));
  5148. const parent = request.parent;
  5149. if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) {
  5150. delete request.parent;
  5151. }
  5152. const response = await datastoreImpl.invokeStreamingRPC('RunAggregationQuery', parent, request, /*expectedResponseCount=*/ 1);
  5153. return (response
  5154. // Omit RunAggregationQueryResponse that only contain readTimes.
  5155. .filter(proto => !!proto.result)
  5156. .map(proto => proto.result.aggregateFields));
  5157. }
  5158. /**
  5159. * @license
  5160. * Copyright 2020 Google LLC
  5161. *
  5162. * Licensed under the Apache License, Version 2.0 (the "License");
  5163. * you may not use this file except in compliance with the License.
  5164. * You may obtain a copy of the License at
  5165. *
  5166. * http://www.apache.org/licenses/LICENSE-2.0
  5167. *
  5168. * Unless required by applicable law or agreed to in writing, software
  5169. * distributed under the License is distributed on an "AS IS" BASIS,
  5170. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5171. * See the License for the specific language governing permissions and
  5172. * limitations under the License.
  5173. */
  5174. const LOG_TAG$1 = 'ComponentProvider';
  5175. /**
  5176. * An instance map that ensures only one Datastore exists per Firestore
  5177. * instance.
  5178. */
  5179. const datastoreInstances = new Map();
  5180. /**
  5181. * Returns an initialized and started Datastore for the given Firestore
  5182. * instance. Callers must invoke removeComponents() when the Firestore
  5183. * instance is terminated.
  5184. */
  5185. function getDatastore(firestore) {
  5186. if (firestore._terminated) {
  5187. throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.');
  5188. }
  5189. if (!datastoreInstances.has(firestore)) {
  5190. logDebug(LOG_TAG$1, 'Initializing Datastore');
  5191. const databaseInfo = makeDatabaseInfo(firestore._databaseId, firestore.app.options.appId || '', firestore._persistenceKey, firestore._freezeSettings());
  5192. const connection = newConnection(databaseInfo);
  5193. const serializer = newSerializer(firestore._databaseId);
  5194. const datastore = newDatastore(firestore._authCredentials, firestore._appCheckCredentials, connection, serializer);
  5195. datastoreInstances.set(firestore, datastore);
  5196. }
  5197. return datastoreInstances.get(firestore);
  5198. }
  5199. /**
  5200. * Removes all components associated with the provided instance. Must be called
  5201. * when the `Firestore` instance is terminated.
  5202. */
  5203. function removeComponents(firestore) {
  5204. const datastore = datastoreInstances.get(firestore);
  5205. if (datastore) {
  5206. logDebug(LOG_TAG$1, 'Removing Datastore');
  5207. datastoreInstances.delete(firestore);
  5208. datastore.terminate();
  5209. }
  5210. }
  5211. function makeDatabaseInfo(databaseId, appId, persistenceKey, settings) {
  5212. return new DatabaseInfo(databaseId, appId, persistenceKey, settings.host, settings.ssl, settings.experimentalForceLongPolling, settings.experimentalAutoDetectLongPolling, settings.useFetchStreams);
  5213. }
  5214. /**
  5215. * @license
  5216. * Copyright 2018 Google LLC
  5217. *
  5218. * Licensed under the Apache License, Version 2.0 (the "License");
  5219. * you may not use this file except in compliance with the License.
  5220. * You may obtain a copy of the License at
  5221. *
  5222. * http://www.apache.org/licenses/LICENSE-2.0
  5223. *
  5224. * Unless required by applicable law or agreed to in writing, software
  5225. * distributed under the License is distributed on an "AS IS" BASIS,
  5226. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5227. * See the License for the specific language governing permissions and
  5228. * limitations under the License.
  5229. */
  5230. const LRU_COLLECTION_DISABLED = -1;
  5231. const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;
  5232. /**
  5233. * @license
  5234. * Copyright 2017 Google LLC
  5235. *
  5236. * Licensed under the Apache License, Version 2.0 (the "License");
  5237. * you may not use this file except in compliance with the License.
  5238. * You may obtain a copy of the License at
  5239. *
  5240. * http://www.apache.org/licenses/LICENSE-2.0
  5241. *
  5242. * Unless required by applicable law or agreed to in writing, software
  5243. * distributed under the License is distributed on an "AS IS" BASIS,
  5244. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5245. * See the License for the specific language governing permissions and
  5246. * limitations under the License.
  5247. */
  5248. /** Verifies whether `e` is an IndexedDbTransactionError. */
  5249. function isIndexedDbTransactionError(e) {
  5250. // Use name equality, as instanceof checks on errors don't work with errors
  5251. // that wrap other errors.
  5252. return e.name === 'IndexedDbTransactionError';
  5253. }
  5254. /**
  5255. * @license
  5256. * Copyright 2020 Google LLC
  5257. *
  5258. * Licensed under the Apache License, Version 2.0 (the "License");
  5259. * you may not use this file except in compliance with the License.
  5260. * You may obtain a copy of the License at
  5261. *
  5262. * http://www.apache.org/licenses/LICENSE-2.0
  5263. *
  5264. * Unless required by applicable law or agreed to in writing, software
  5265. * distributed under the License is distributed on an "AS IS" BASIS,
  5266. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5267. * See the License for the specific language governing permissions and
  5268. * limitations under the License.
  5269. */
  5270. const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;
  5271. /**
  5272. * @license
  5273. * Copyright 2020 Google LLC
  5274. *
  5275. * Licensed under the Apache License, Version 2.0 (the "License");
  5276. * you may not use this file except in compliance with the License.
  5277. * You may obtain a copy of the License at
  5278. *
  5279. * http://www.apache.org/licenses/LICENSE-2.0
  5280. *
  5281. * Unless required by applicable law or agreed to in writing, software
  5282. * distributed under the License is distributed on an "AS IS" BASIS,
  5283. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5284. * See the License for the specific language governing permissions and
  5285. * limitations under the License.
  5286. */
  5287. // settings() defaults:
  5288. const DEFAULT_HOST = 'firestore.googleapis.com';
  5289. const DEFAULT_SSL = true;
  5290. /**
  5291. * A concrete type describing all the values that can be applied via a
  5292. * user-supplied `FirestoreSettings` object. This is a separate type so that
  5293. * defaults can be supplied and the value can be checked for equality.
  5294. */
  5295. class FirestoreSettingsImpl {
  5296. constructor(settings) {
  5297. var _a;
  5298. if (settings.host === undefined) {
  5299. if (settings.ssl !== undefined) {
  5300. throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
  5301. }
  5302. this.host = DEFAULT_HOST;
  5303. this.ssl = DEFAULT_SSL;
  5304. }
  5305. else {
  5306. this.host = settings.host;
  5307. this.ssl = (_a = settings.ssl) !== null && _a !== void 0 ? _a : DEFAULT_SSL;
  5308. }
  5309. this.credentials = settings.credentials;
  5310. this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;
  5311. if (settings.cacheSizeBytes === undefined) {
  5312. this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;
  5313. }
  5314. else {
  5315. if (settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&
  5316. settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) {
  5317. throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`);
  5318. }
  5319. else {
  5320. this.cacheSizeBytes = settings.cacheSizeBytes;
  5321. }
  5322. }
  5323. this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;
  5324. this.experimentalAutoDetectLongPolling =
  5325. !!settings.experimentalAutoDetectLongPolling;
  5326. this.useFetchStreams = !!settings.useFetchStreams;
  5327. validateIsNotUsedTogether('experimentalForceLongPolling', settings.experimentalForceLongPolling, 'experimentalAutoDetectLongPolling', settings.experimentalAutoDetectLongPolling);
  5328. }
  5329. isEqual(other) {
  5330. return (this.host === other.host &&
  5331. this.ssl === other.ssl &&
  5332. this.credentials === other.credentials &&
  5333. this.cacheSizeBytes === other.cacheSizeBytes &&
  5334. this.experimentalForceLongPolling ===
  5335. other.experimentalForceLongPolling &&
  5336. this.experimentalAutoDetectLongPolling ===
  5337. other.experimentalAutoDetectLongPolling &&
  5338. this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&
  5339. this.useFetchStreams === other.useFetchStreams);
  5340. }
  5341. }
  5342. /**
  5343. * @license
  5344. * Copyright 2020 Google LLC
  5345. *
  5346. * Licensed under the Apache License, Version 2.0 (the "License");
  5347. * you may not use this file except in compliance with the License.
  5348. * You may obtain a copy of the License at
  5349. *
  5350. * http://www.apache.org/licenses/LICENSE-2.0
  5351. *
  5352. * Unless required by applicable law or agreed to in writing, software
  5353. * distributed under the License is distributed on an "AS IS" BASIS,
  5354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5355. * See the License for the specific language governing permissions and
  5356. * limitations under the License.
  5357. */
  5358. /**
  5359. * The Cloud Firestore service interface.
  5360. *
  5361. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  5362. */
  5363. class Firestore {
  5364. /** @hideconstructor */
  5365. constructor(_authCredentials, _appCheckCredentials, _databaseId, _app) {
  5366. this._authCredentials = _authCredentials;
  5367. this._appCheckCredentials = _appCheckCredentials;
  5368. this._databaseId = _databaseId;
  5369. this._app = _app;
  5370. /**
  5371. * Whether it's a Firestore or Firestore Lite instance.
  5372. */
  5373. this.type = 'firestore-lite';
  5374. this._persistenceKey = '(lite)';
  5375. this._settings = new FirestoreSettingsImpl({});
  5376. this._settingsFrozen = false;
  5377. }
  5378. /**
  5379. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  5380. * instance.
  5381. */
  5382. get app() {
  5383. if (!this._app) {
  5384. throw new FirestoreError(Code.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is " +
  5385. 'not available');
  5386. }
  5387. return this._app;
  5388. }
  5389. get _initialized() {
  5390. return this._settingsFrozen;
  5391. }
  5392. get _terminated() {
  5393. return this._terminateTask !== undefined;
  5394. }
  5395. _setSettings(settings) {
  5396. if (this._settingsFrozen) {
  5397. throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' +
  5398. 'be changed. You can only modify settings before calling any other ' +
  5399. 'methods on a Firestore object.');
  5400. }
  5401. this._settings = new FirestoreSettingsImpl(settings);
  5402. if (settings.credentials !== undefined) {
  5403. this._authCredentials = makeAuthCredentialsProvider(settings.credentials);
  5404. }
  5405. }
  5406. _getSettings() {
  5407. return this._settings;
  5408. }
  5409. _freezeSettings() {
  5410. this._settingsFrozen = true;
  5411. return this._settings;
  5412. }
  5413. _delete() {
  5414. if (!this._terminateTask) {
  5415. this._terminateTask = this._terminate();
  5416. }
  5417. return this._terminateTask;
  5418. }
  5419. /** Returns a JSON-serializable representation of this `Firestore` instance. */
  5420. toJSON() {
  5421. return {
  5422. app: this._app,
  5423. databaseId: this._databaseId,
  5424. settings: this._settings
  5425. };
  5426. }
  5427. /**
  5428. * Terminates all components used by this client. Subclasses can override
  5429. * this method to clean up their own dependencies, but must also call this
  5430. * method.
  5431. *
  5432. * Only ever called once.
  5433. */
  5434. _terminate() {
  5435. removeComponents(this);
  5436. return Promise.resolve();
  5437. }
  5438. }
  5439. function initializeFirestore(app$1, settings, databaseId) {
  5440. if (!databaseId) {
  5441. databaseId = DEFAULT_DATABASE_NAME;
  5442. }
  5443. const provider = app._getProvider(app$1, 'firestore/lite');
  5444. if (provider.isInitialized(databaseId)) {
  5445. throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore can only be initialized once per app.');
  5446. }
  5447. return provider.initialize({
  5448. options: settings,
  5449. instanceIdentifier: databaseId
  5450. });
  5451. }
  5452. function getFirestore(appOrDatabaseId, optionalDatabaseId) {
  5453. const app$1 = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : app.getApp();
  5454. const databaseId = typeof appOrDatabaseId === 'string'
  5455. ? appOrDatabaseId
  5456. : optionalDatabaseId || '(default)';
  5457. const db = app._getProvider(app$1, 'firestore/lite').getImmediate({
  5458. identifier: databaseId
  5459. });
  5460. if (!db._initialized) {
  5461. const emulator = util.getDefaultEmulatorHostnameAndPort('firestore');
  5462. if (emulator) {
  5463. connectFirestoreEmulator(db, ...emulator);
  5464. }
  5465. }
  5466. return db;
  5467. }
  5468. /**
  5469. * Modify this instance to communicate with the Cloud Firestore emulator.
  5470. *
  5471. * Note: This must be called before this instance has been used to do any
  5472. * operations.
  5473. *
  5474. * @param firestore - The `Firestore` instance to configure to connect to the
  5475. * emulator.
  5476. * @param host - the emulator host (ex: localhost).
  5477. * @param port - the emulator port (ex: 9000).
  5478. * @param options.mockUserToken - the mock auth token to use for unit testing
  5479. * Security Rules.
  5480. */
  5481. function connectFirestoreEmulator(firestore, host, port, options = {}) {
  5482. var _a;
  5483. firestore = cast(firestore, Firestore);
  5484. const settings = firestore._getSettings();
  5485. if (settings.host !== DEFAULT_HOST && settings.host !== host) {
  5486. logWarn('Host has been set in both settings() and useEmulator(), emulator host ' +
  5487. 'will be used');
  5488. }
  5489. firestore._setSettings(Object.assign(Object.assign({}, settings), { host: `${host}:${port}`, ssl: false }));
  5490. if (options.mockUserToken) {
  5491. let token;
  5492. let user;
  5493. if (typeof options.mockUserToken === 'string') {
  5494. token = options.mockUserToken;
  5495. user = User.MOCK_USER;
  5496. }
  5497. else {
  5498. // Let createMockUserToken validate first (catches common mistakes like
  5499. // invalid field "uid" and missing field "sub" / "user_id".)
  5500. token = util.createMockUserToken(options.mockUserToken, (_a = firestore._app) === null || _a === void 0 ? void 0 : _a.options.projectId);
  5501. const uid = options.mockUserToken.sub || options.mockUserToken.user_id;
  5502. if (!uid) {
  5503. throw new FirestoreError(Code.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
  5504. }
  5505. user = new User(uid);
  5506. }
  5507. firestore._authCredentials = new EmulatorAuthCredentialsProvider(new OAuthToken(token, user));
  5508. }
  5509. }
  5510. /**
  5511. * Terminates the provided `Firestore` instance.
  5512. *
  5513. * After calling `terminate()` only the `clearIndexedDbPersistence()` functions
  5514. * may be used. Any other function will throw a `FirestoreError`. Termination
  5515. * does not cancel any pending writes, and any promises that are awaiting a
  5516. * response from the server will not be resolved.
  5517. *
  5518. * To restart after termination, create a new instance of `Firestore` with
  5519. * {@link (getFirestore:1)}.
  5520. *
  5521. * Note: Under normal circumstances, calling `terminate()` is not required. This
  5522. * function is useful only when you want to force this instance to release all of
  5523. * its resources or in combination with {@link clearIndexedDbPersistence} to
  5524. * ensure that all local state is destroyed between test runs.
  5525. *
  5526. * @param firestore - The `Firestore` instance to terminate.
  5527. * @returns A `Promise` that is resolved when the instance has been successfully
  5528. * terminated.
  5529. */
  5530. function terminate(firestore) {
  5531. firestore = cast(firestore, Firestore);
  5532. app._removeServiceInstance(firestore.app, 'firestore/lite');
  5533. return firestore._delete();
  5534. }
  5535. /**
  5536. * @license
  5537. * Copyright 2020 Google LLC
  5538. *
  5539. * Licensed under the Apache License, Version 2.0 (the "License");
  5540. * you may not use this file except in compliance with the License.
  5541. * You may obtain a copy of the License at
  5542. *
  5543. * http://www.apache.org/licenses/LICENSE-2.0
  5544. *
  5545. * Unless required by applicable law or agreed to in writing, software
  5546. * distributed under the License is distributed on an "AS IS" BASIS,
  5547. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5548. * See the License for the specific language governing permissions and
  5549. * limitations under the License.
  5550. */
  5551. function registerFirestore() {
  5552. setSDKVersion(`${app.SDK_VERSION}_lite`);
  5553. app._registerComponent(new component.Component('firestore/lite', (container, { instanceIdentifier: databaseId, options: settings }) => {
  5554. const app = container.getProvider('app').getImmediate();
  5555. const firestoreInstance = new Firestore(new LiteAuthCredentialsProvider(container.getProvider('auth-internal')), new LiteAppCheckTokenProvider(container.getProvider('app-check-internal')), databaseIdFromApp(app, databaseId), app);
  5556. if (settings) {
  5557. firestoreInstance._setSettings(settings);
  5558. }
  5559. return firestoreInstance;
  5560. }, 'PUBLIC').setMultipleInstances(true));
  5561. // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation
  5562. app.registerVersion('firestore-lite', version$1, 'node');
  5563. app.registerVersion('firestore-lite', version$1, 'cjs5');
  5564. }
  5565. /**
  5566. * @license
  5567. * Copyright 2022 Google LLC
  5568. *
  5569. * Licensed under the Apache License, Version 2.0 (the "License");
  5570. * you may not use this file except in compliance with the License.
  5571. * You may obtain a copy of the License at
  5572. *
  5573. * http://www.apache.org/licenses/LICENSE-2.0
  5574. *
  5575. * Unless required by applicable law or agreed to in writing, software
  5576. * distributed under the License is distributed on an "AS IS" BASIS,
  5577. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5578. * See the License for the specific language governing permissions and
  5579. * limitations under the License.
  5580. */
  5581. /**
  5582. * Represents an aggregation that can be performed by Firestore.
  5583. */
  5584. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  5585. class AggregateField {
  5586. constructor() {
  5587. /** A type string to uniquely identify instances of this class. */
  5588. this.type = 'AggregateField';
  5589. }
  5590. }
  5591. /**
  5592. * The results of executing an aggregation query.
  5593. */
  5594. class AggregateQuerySnapshot {
  5595. /** @hideconstructor */
  5596. constructor(query, _data) {
  5597. this._data = _data;
  5598. /** A type string to uniquely identify instances of this class. */
  5599. this.type = 'AggregateQuerySnapshot';
  5600. this.query = query;
  5601. }
  5602. /**
  5603. * Returns the results of the aggregations performed over the underlying
  5604. * query.
  5605. *
  5606. * The keys of the returned object will be the same as those of the
  5607. * `AggregateSpec` object specified to the aggregation method, and the values
  5608. * will be the corresponding aggregation result.
  5609. *
  5610. * @returns The results of the aggregations performed over the underlying
  5611. * query.
  5612. */
  5613. data() {
  5614. return this._data;
  5615. }
  5616. }
  5617. /**
  5618. * @license
  5619. * Copyright 2022 Google LLC
  5620. *
  5621. * Licensed under the Apache License, Version 2.0 (the "License");
  5622. * you may not use this file except in compliance with the License.
  5623. * You may obtain a copy of the License at
  5624. *
  5625. * http://www.apache.org/licenses/LICENSE-2.0
  5626. *
  5627. * Unless required by applicable law or agreed to in writing, software
  5628. * distributed under the License is distributed on an "AS IS" BASIS,
  5629. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5630. * See the License for the specific language governing permissions and
  5631. * limitations under the License.
  5632. */
  5633. /**
  5634. * CountQueryRunner encapsulates the logic needed to run the count aggregation
  5635. * queries.
  5636. */
  5637. class CountQueryRunner {
  5638. constructor(query, datastore, userDataWriter) {
  5639. this.query = query;
  5640. this.datastore = datastore;
  5641. this.userDataWriter = userDataWriter;
  5642. }
  5643. run() {
  5644. return invokeRunAggregationQueryRpc(this.datastore, this.query._query).then(result => {
  5645. hardAssert(result[0] !== undefined);
  5646. const counts = Object.entries(result[0])
  5647. .filter(([key, value]) => key === 'count_alias')
  5648. .map(([key, value]) => this.userDataWriter.convertValue(value));
  5649. const countValue = counts[0];
  5650. hardAssert(typeof countValue === 'number');
  5651. return Promise.resolve(new AggregateQuerySnapshot(this.query, {
  5652. count: countValue
  5653. }));
  5654. });
  5655. }
  5656. }
  5657. /**
  5658. * @license
  5659. * Copyright 2020 Google LLC
  5660. *
  5661. * Licensed under the Apache License, Version 2.0 (the "License");
  5662. * you may not use this file except in compliance with the License.
  5663. * You may obtain a copy of the License at
  5664. *
  5665. * http://www.apache.org/licenses/LICENSE-2.0
  5666. *
  5667. * Unless required by applicable law or agreed to in writing, software
  5668. * distributed under the License is distributed on an "AS IS" BASIS,
  5669. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5670. * See the License for the specific language governing permissions and
  5671. * limitations under the License.
  5672. */
  5673. /**
  5674. * A `DocumentReference` refers to a document location in a Firestore database
  5675. * and can be used to write, read, or listen to the location. The document at
  5676. * the referenced location may or may not exist.
  5677. */
  5678. class DocumentReference {
  5679. /** @hideconstructor */
  5680. constructor(firestore,
  5681. /**
  5682. * If provided, the `FirestoreDataConverter` associated with this instance.
  5683. */
  5684. converter, _key) {
  5685. this.converter = converter;
  5686. this._key = _key;
  5687. /** The type of this Firestore reference. */
  5688. this.type = 'document';
  5689. this.firestore = firestore;
  5690. }
  5691. get _path() {
  5692. return this._key.path;
  5693. }
  5694. /**
  5695. * The document's identifier within its collection.
  5696. */
  5697. get id() {
  5698. return this._key.path.lastSegment();
  5699. }
  5700. /**
  5701. * A string representing the path of the referenced document (relative
  5702. * to the root of the database).
  5703. */
  5704. get path() {
  5705. return this._key.path.canonicalString();
  5706. }
  5707. /**
  5708. * The collection this `DocumentReference` belongs to.
  5709. */
  5710. get parent() {
  5711. return new CollectionReference(this.firestore, this.converter, this._key.path.popLast());
  5712. }
  5713. withConverter(converter) {
  5714. return new DocumentReference(this.firestore, converter, this._key);
  5715. }
  5716. }
  5717. /**
  5718. * A `Query` refers to a query which you can read or listen to. You can also
  5719. * construct refined `Query` objects by adding filters and ordering.
  5720. */
  5721. class Query {
  5722. // This is the lite version of the Query class in the main SDK.
  5723. /** @hideconstructor protected */
  5724. constructor(firestore,
  5725. /**
  5726. * If provided, the `FirestoreDataConverter` associated with this instance.
  5727. */
  5728. converter, _query) {
  5729. this.converter = converter;
  5730. this._query = _query;
  5731. /** The type of this Firestore reference. */
  5732. this.type = 'query';
  5733. this.firestore = firestore;
  5734. }
  5735. withConverter(converter) {
  5736. return new Query(this.firestore, converter, this._query);
  5737. }
  5738. }
  5739. /**
  5740. * A `CollectionReference` object can be used for adding documents, getting
  5741. * document references, and querying for documents (using {@link query}).
  5742. */
  5743. class CollectionReference extends Query {
  5744. /** @hideconstructor */
  5745. constructor(firestore, converter, _path) {
  5746. super(firestore, converter, newQueryForPath(_path));
  5747. this._path = _path;
  5748. /** The type of this Firestore reference. */
  5749. this.type = 'collection';
  5750. }
  5751. /** The collection's identifier. */
  5752. get id() {
  5753. return this._query.path.lastSegment();
  5754. }
  5755. /**
  5756. * A string representing the path of the referenced collection (relative
  5757. * to the root of the database).
  5758. */
  5759. get path() {
  5760. return this._query.path.canonicalString();
  5761. }
  5762. /**
  5763. * A reference to the containing `DocumentReference` if this is a
  5764. * subcollection. If this isn't a subcollection, the reference is null.
  5765. */
  5766. get parent() {
  5767. const parentPath = this._path.popLast();
  5768. if (parentPath.isEmpty()) {
  5769. return null;
  5770. }
  5771. else {
  5772. return new DocumentReference(this.firestore,
  5773. /* converter= */ null, new DocumentKey(parentPath));
  5774. }
  5775. }
  5776. withConverter(converter) {
  5777. return new CollectionReference(this.firestore, converter, this._path);
  5778. }
  5779. }
  5780. function collection(parent, path, ...pathSegments) {
  5781. parent = util.getModularInstance(parent);
  5782. validateNonEmptyArgument('collection', 'path', path);
  5783. if (parent instanceof Firestore) {
  5784. const absolutePath = ResourcePath.fromString(path, ...pathSegments);
  5785. validateCollectionPath(absolutePath);
  5786. return new CollectionReference(parent, /* converter= */ null, absolutePath);
  5787. }
  5788. else {
  5789. if (!(parent instanceof DocumentReference) &&
  5790. !(parent instanceof CollectionReference)) {
  5791. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' +
  5792. 'a DocumentReference or FirebaseFirestore');
  5793. }
  5794. const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments));
  5795. validateCollectionPath(absolutePath);
  5796. return new CollectionReference(parent.firestore,
  5797. /* converter= */ null, absolutePath);
  5798. }
  5799. }
  5800. // TODO(firestorelite): Consider using ErrorFactory -
  5801. // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
  5802. /**
  5803. * Creates and returns a new `Query` instance that includes all documents in the
  5804. * database that are contained in a collection or subcollection with the
  5805. * given `collectionId`.
  5806. *
  5807. * @param firestore - A reference to the root `Firestore` instance.
  5808. * @param collectionId - Identifies the collections to query over. Every
  5809. * collection or subcollection with this ID as the last segment of its path
  5810. * will be included. Cannot contain a slash.
  5811. * @returns The created `Query`.
  5812. */
  5813. function collectionGroup(firestore, collectionId) {
  5814. firestore = cast(firestore, Firestore);
  5815. validateNonEmptyArgument('collectionGroup', 'collection id', collectionId);
  5816. if (collectionId.indexOf('/') >= 0) {
  5817. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection ID '${collectionId}' passed to function ` +
  5818. `collectionGroup(). Collection IDs must not contain '/'.`);
  5819. }
  5820. return new Query(firestore,
  5821. /* converter= */ null, newQueryForCollectionGroup(collectionId));
  5822. }
  5823. function doc(parent, path, ...pathSegments) {
  5824. parent = util.getModularInstance(parent);
  5825. // We allow omission of 'pathString' but explicitly prohibit passing in both
  5826. // 'undefined' and 'null'.
  5827. if (arguments.length === 1) {
  5828. path = AutoId.newId();
  5829. }
  5830. validateNonEmptyArgument('doc', 'path', path);
  5831. if (parent instanceof Firestore) {
  5832. const absolutePath = ResourcePath.fromString(path, ...pathSegments);
  5833. validateDocumentPath(absolutePath);
  5834. return new DocumentReference(parent,
  5835. /* converter= */ null, new DocumentKey(absolutePath));
  5836. }
  5837. else {
  5838. if (!(parent instanceof DocumentReference) &&
  5839. !(parent instanceof CollectionReference)) {
  5840. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' +
  5841. 'a DocumentReference or FirebaseFirestore');
  5842. }
  5843. const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments));
  5844. validateDocumentPath(absolutePath);
  5845. return new DocumentReference(parent.firestore, parent instanceof CollectionReference ? parent.converter : null, new DocumentKey(absolutePath));
  5846. }
  5847. }
  5848. /**
  5849. * Returns true if the provided references are equal.
  5850. *
  5851. * @param left - A reference to compare.
  5852. * @param right - A reference to compare.
  5853. * @returns true if the references point to the same location in the same
  5854. * Firestore database.
  5855. */
  5856. function refEqual(left, right) {
  5857. left = util.getModularInstance(left);
  5858. right = util.getModularInstance(right);
  5859. if ((left instanceof DocumentReference ||
  5860. left instanceof CollectionReference) &&
  5861. (right instanceof DocumentReference || right instanceof CollectionReference)) {
  5862. return (left.firestore === right.firestore &&
  5863. left.path === right.path &&
  5864. left.converter === right.converter);
  5865. }
  5866. return false;
  5867. }
  5868. /**
  5869. * Returns true if the provided queries point to the same collection and apply
  5870. * the same constraints.
  5871. *
  5872. * @param left - A `Query` to compare.
  5873. * @param right - A `Query` to compare.
  5874. * @returns true if the references point to the same location in the same
  5875. * Firestore database.
  5876. */
  5877. function queryEqual(left, right) {
  5878. left = util.getModularInstance(left);
  5879. right = util.getModularInstance(right);
  5880. if (left instanceof Query && right instanceof Query) {
  5881. return (left.firestore === right.firestore &&
  5882. queryEquals(left._query, right._query) &&
  5883. left.converter === right.converter);
  5884. }
  5885. return false;
  5886. }
  5887. /**
  5888. * @license
  5889. * Copyright 2020 Google LLC
  5890. *
  5891. * Licensed under the Apache License, Version 2.0 (the "License");
  5892. * you may not use this file except in compliance with the License.
  5893. * You may obtain a copy of the License at
  5894. *
  5895. * http://www.apache.org/licenses/LICENSE-2.0
  5896. *
  5897. * Unless required by applicable law or agreed to in writing, software
  5898. * distributed under the License is distributed on an "AS IS" BASIS,
  5899. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5900. * See the License for the specific language governing permissions and
  5901. * limitations under the License.
  5902. */
  5903. /**
  5904. * An immutable object representing an array of bytes.
  5905. */
  5906. class Bytes {
  5907. /** @hideconstructor */
  5908. constructor(byteString) {
  5909. this._byteString = byteString;
  5910. }
  5911. /**
  5912. * Creates a new `Bytes` object from the given Base64 string, converting it to
  5913. * bytes.
  5914. *
  5915. * @param base64 - The Base64 string used to create the `Bytes` object.
  5916. */
  5917. static fromBase64String(base64) {
  5918. try {
  5919. return new Bytes(ByteString.fromBase64String(base64));
  5920. }
  5921. catch (e) {
  5922. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct data from Base64 string: ' + e);
  5923. }
  5924. }
  5925. /**
  5926. * Creates a new `Bytes` object from the given Uint8Array.
  5927. *
  5928. * @param array - The Uint8Array used to create the `Bytes` object.
  5929. */
  5930. static fromUint8Array(array) {
  5931. return new Bytes(ByteString.fromUint8Array(array));
  5932. }
  5933. /**
  5934. * Returns the underlying bytes as a Base64-encoded string.
  5935. *
  5936. * @returns The Base64-encoded string created from the `Bytes` object.
  5937. */
  5938. toBase64() {
  5939. return this._byteString.toBase64();
  5940. }
  5941. /**
  5942. * Returns the underlying bytes in a new `Uint8Array`.
  5943. *
  5944. * @returns The Uint8Array created from the `Bytes` object.
  5945. */
  5946. toUint8Array() {
  5947. return this._byteString.toUint8Array();
  5948. }
  5949. /**
  5950. * Returns a string representation of the `Bytes` object.
  5951. *
  5952. * @returns A string representation of the `Bytes` object.
  5953. */
  5954. toString() {
  5955. return 'Bytes(base64: ' + this.toBase64() + ')';
  5956. }
  5957. /**
  5958. * Returns true if this `Bytes` object is equal to the provided one.
  5959. *
  5960. * @param other - The `Bytes` object to compare against.
  5961. * @returns true if this `Bytes` object is equal to the provided one.
  5962. */
  5963. isEqual(other) {
  5964. return this._byteString.isEqual(other._byteString);
  5965. }
  5966. }
  5967. /**
  5968. * @license
  5969. * Copyright 2020 Google LLC
  5970. *
  5971. * Licensed under the Apache License, Version 2.0 (the "License");
  5972. * you may not use this file except in compliance with the License.
  5973. * You may obtain a copy of the License at
  5974. *
  5975. * http://www.apache.org/licenses/LICENSE-2.0
  5976. *
  5977. * Unless required by applicable law or agreed to in writing, software
  5978. * distributed under the License is distributed on an "AS IS" BASIS,
  5979. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5980. * See the License for the specific language governing permissions and
  5981. * limitations under the License.
  5982. */
  5983. /**
  5984. * A `FieldPath` refers to a field in a document. The path may consist of a
  5985. * single field name (referring to a top-level field in the document), or a
  5986. * list of field names (referring to a nested field in the document).
  5987. *
  5988. * Create a `FieldPath` by providing field names. If more than one field
  5989. * name is provided, the path will point to a nested field in a document.
  5990. */
  5991. class FieldPath {
  5992. /**
  5993. * Creates a `FieldPath` from the provided field names. If more than one field
  5994. * name is provided, the path will point to a nested field in a document.
  5995. *
  5996. * @param fieldNames - A list of field names.
  5997. */
  5998. constructor(...fieldNames) {
  5999. for (let i = 0; i < fieldNames.length; ++i) {
  6000. if (fieldNames[i].length === 0) {
  6001. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field name at argument $(i + 1). ` +
  6002. 'Field names must not be empty.');
  6003. }
  6004. }
  6005. this._internalPath = new FieldPath$1(fieldNames);
  6006. }
  6007. /**
  6008. * Returns true if this `FieldPath` is equal to the provided one.
  6009. *
  6010. * @param other - The `FieldPath` to compare against.
  6011. * @returns true if this `FieldPath` is equal to the provided one.
  6012. */
  6013. isEqual(other) {
  6014. return this._internalPath.isEqual(other._internalPath);
  6015. }
  6016. }
  6017. /**
  6018. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  6019. * It can be used in queries to sort or filter by the document ID.
  6020. */
  6021. function documentId() {
  6022. return new FieldPath(DOCUMENT_KEY_NAME);
  6023. }
  6024. /**
  6025. * @license
  6026. * Copyright 2020 Google LLC
  6027. *
  6028. * Licensed under the Apache License, Version 2.0 (the "License");
  6029. * you may not use this file except in compliance with the License.
  6030. * You may obtain a copy of the License at
  6031. *
  6032. * http://www.apache.org/licenses/LICENSE-2.0
  6033. *
  6034. * Unless required by applicable law or agreed to in writing, software
  6035. * distributed under the License is distributed on an "AS IS" BASIS,
  6036. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6037. * See the License for the specific language governing permissions and
  6038. * limitations under the License.
  6039. */
  6040. /**
  6041. * Sentinel values that can be used when writing document fields with `set()`
  6042. * or `update()`.
  6043. */
  6044. class FieldValue {
  6045. /**
  6046. * @param _methodName - The public API endpoint that returns this class.
  6047. * @hideconstructor
  6048. */
  6049. constructor(_methodName) {
  6050. this._methodName = _methodName;
  6051. }
  6052. }
  6053. /**
  6054. * @license
  6055. * Copyright 2017 Google LLC
  6056. *
  6057. * Licensed under the Apache License, Version 2.0 (the "License");
  6058. * you may not use this file except in compliance with the License.
  6059. * You may obtain a copy of the License at
  6060. *
  6061. * http://www.apache.org/licenses/LICENSE-2.0
  6062. *
  6063. * Unless required by applicable law or agreed to in writing, software
  6064. * distributed under the License is distributed on an "AS IS" BASIS,
  6065. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6066. * See the License for the specific language governing permissions and
  6067. * limitations under the License.
  6068. */
  6069. /**
  6070. * An immutable object representing a geographic location in Firestore. The
  6071. * location is represented as latitude/longitude pair.
  6072. *
  6073. * Latitude values are in the range of [-90, 90].
  6074. * Longitude values are in the range of [-180, 180].
  6075. */
  6076. class GeoPoint {
  6077. /**
  6078. * Creates a new immutable `GeoPoint` object with the provided latitude and
  6079. * longitude values.
  6080. * @param latitude - The latitude as number between -90 and 90.
  6081. * @param longitude - The longitude as number between -180 and 180.
  6082. */
  6083. constructor(latitude, longitude) {
  6084. if (!isFinite(latitude) || latitude < -90 || latitude > 90) {
  6085. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude);
  6086. }
  6087. if (!isFinite(longitude) || longitude < -180 || longitude > 180) {
  6088. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude);
  6089. }
  6090. this._lat = latitude;
  6091. this._long = longitude;
  6092. }
  6093. /**
  6094. * The latitude of this `GeoPoint` instance.
  6095. */
  6096. get latitude() {
  6097. return this._lat;
  6098. }
  6099. /**
  6100. * The longitude of this `GeoPoint` instance.
  6101. */
  6102. get longitude() {
  6103. return this._long;
  6104. }
  6105. /**
  6106. * Returns true if this `GeoPoint` is equal to the provided one.
  6107. *
  6108. * @param other - The `GeoPoint` to compare against.
  6109. * @returns true if this `GeoPoint` is equal to the provided one.
  6110. */
  6111. isEqual(other) {
  6112. return this._lat === other._lat && this._long === other._long;
  6113. }
  6114. /** Returns a JSON-serializable representation of this GeoPoint. */
  6115. toJSON() {
  6116. return { latitude: this._lat, longitude: this._long };
  6117. }
  6118. /**
  6119. * Actually private to JS consumers of our API, so this function is prefixed
  6120. * with an underscore.
  6121. */
  6122. _compareTo(other) {
  6123. return (primitiveComparator(this._lat, other._lat) ||
  6124. primitiveComparator(this._long, other._long));
  6125. }
  6126. }
  6127. /**
  6128. * @license
  6129. * Copyright 2017 Google LLC
  6130. *
  6131. * Licensed under the Apache License, Version 2.0 (the "License");
  6132. * you may not use this file except in compliance with the License.
  6133. * You may obtain a copy of the License at
  6134. *
  6135. * http://www.apache.org/licenses/LICENSE-2.0
  6136. *
  6137. * Unless required by applicable law or agreed to in writing, software
  6138. * distributed under the License is distributed on an "AS IS" BASIS,
  6139. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6140. * See the License for the specific language governing permissions and
  6141. * limitations under the License.
  6142. */
  6143. const RESERVED_FIELD_REGEX = /^__.*__$/;
  6144. /** The result of parsing document data (e.g. for a setData call). */
  6145. class ParsedSetData {
  6146. constructor(data, fieldMask, fieldTransforms) {
  6147. this.data = data;
  6148. this.fieldMask = fieldMask;
  6149. this.fieldTransforms = fieldTransforms;
  6150. }
  6151. toMutation(key, precondition) {
  6152. if (this.fieldMask !== null) {
  6153. return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms);
  6154. }
  6155. else {
  6156. return new SetMutation(key, this.data, precondition, this.fieldTransforms);
  6157. }
  6158. }
  6159. }
  6160. /** The result of parsing "update" data (i.e. for an updateData call). */
  6161. class ParsedUpdateData {
  6162. constructor(data,
  6163. // The fieldMask does not include document transforms.
  6164. fieldMask, fieldTransforms) {
  6165. this.data = data;
  6166. this.fieldMask = fieldMask;
  6167. this.fieldTransforms = fieldTransforms;
  6168. }
  6169. toMutation(key, precondition) {
  6170. return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms);
  6171. }
  6172. }
  6173. function isWrite(dataSource) {
  6174. switch (dataSource) {
  6175. case 0 /* UserDataSource.Set */: // fall through
  6176. case 2 /* UserDataSource.MergeSet */: // fall through
  6177. case 1 /* UserDataSource.Update */:
  6178. return true;
  6179. case 3 /* UserDataSource.Argument */:
  6180. case 4 /* UserDataSource.ArrayArgument */:
  6181. return false;
  6182. default:
  6183. throw fail();
  6184. }
  6185. }
  6186. /** A "context" object passed around while parsing user data. */
  6187. class ParseContextImpl {
  6188. /**
  6189. * Initializes a ParseContext with the given source and path.
  6190. *
  6191. * @param settings - The settings for the parser.
  6192. * @param databaseId - The database ID of the Firestore instance.
  6193. * @param serializer - The serializer to use to generate the Value proto.
  6194. * @param ignoreUndefinedProperties - Whether to ignore undefined properties
  6195. * rather than throw.
  6196. * @param fieldTransforms - A mutable list of field transforms encountered
  6197. * while parsing the data.
  6198. * @param fieldMask - A mutable list of field paths encountered while parsing
  6199. * the data.
  6200. *
  6201. * TODO(b/34871131): We don't support array paths right now, so path can be
  6202. * null to indicate the context represents any location within an array (in
  6203. * which case certain features will not work and errors will be somewhat
  6204. * compromised).
  6205. */
  6206. constructor(settings, databaseId, serializer, ignoreUndefinedProperties, fieldTransforms, fieldMask) {
  6207. this.settings = settings;
  6208. this.databaseId = databaseId;
  6209. this.serializer = serializer;
  6210. this.ignoreUndefinedProperties = ignoreUndefinedProperties;
  6211. // Minor hack: If fieldTransforms is undefined, we assume this is an
  6212. // external call and we need to validate the entire path.
  6213. if (fieldTransforms === undefined) {
  6214. this.validatePath();
  6215. }
  6216. this.fieldTransforms = fieldTransforms || [];
  6217. this.fieldMask = fieldMask || [];
  6218. }
  6219. get path() {
  6220. return this.settings.path;
  6221. }
  6222. get dataSource() {
  6223. return this.settings.dataSource;
  6224. }
  6225. /** Returns a new context with the specified settings overwritten. */
  6226. contextWith(configuration) {
  6227. return new ParseContextImpl(Object.assign(Object.assign({}, this.settings), configuration), this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  6228. }
  6229. childContextForField(field) {
  6230. var _a;
  6231. const childPath = (_a = this.path) === null || _a === void 0 ? void 0 : _a.child(field);
  6232. const context = this.contextWith({ path: childPath, arrayElement: false });
  6233. context.validatePathSegment(field);
  6234. return context;
  6235. }
  6236. childContextForFieldPath(field) {
  6237. var _a;
  6238. const childPath = (_a = this.path) === null || _a === void 0 ? void 0 : _a.child(field);
  6239. const context = this.contextWith({ path: childPath, arrayElement: false });
  6240. context.validatePath();
  6241. return context;
  6242. }
  6243. childContextForArray(index) {
  6244. // TODO(b/34871131): We don't support array paths right now; so make path
  6245. // undefined.
  6246. return this.contextWith({ path: undefined, arrayElement: true });
  6247. }
  6248. createError(reason) {
  6249. return createError(reason, this.settings.methodName, this.settings.hasConverter || false, this.path, this.settings.targetDoc);
  6250. }
  6251. /** Returns 'true' if 'fieldPath' was traversed when creating this context. */
  6252. contains(fieldPath) {
  6253. return (this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||
  6254. this.fieldTransforms.find(transform => fieldPath.isPrefixOf(transform.field)) !== undefined);
  6255. }
  6256. validatePath() {
  6257. // TODO(b/34871131): Remove null check once we have proper paths for fields
  6258. // within arrays.
  6259. if (!this.path) {
  6260. return;
  6261. }
  6262. for (let i = 0; i < this.path.length; i++) {
  6263. this.validatePathSegment(this.path.get(i));
  6264. }
  6265. }
  6266. validatePathSegment(segment) {
  6267. if (segment.length === 0) {
  6268. throw this.createError('Document fields must not be empty');
  6269. }
  6270. if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {
  6271. throw this.createError('Document fields cannot begin and end with "__"');
  6272. }
  6273. }
  6274. }
  6275. /**
  6276. * Helper for parsing raw user input (provided via the API) into internal model
  6277. * classes.
  6278. */
  6279. class UserDataReader {
  6280. constructor(databaseId, ignoreUndefinedProperties, serializer) {
  6281. this.databaseId = databaseId;
  6282. this.ignoreUndefinedProperties = ignoreUndefinedProperties;
  6283. this.serializer = serializer || newSerializer(databaseId);
  6284. }
  6285. /** Creates a new top-level parse context. */
  6286. createContext(dataSource, methodName, targetDoc, hasConverter = false) {
  6287. return new ParseContextImpl({
  6288. dataSource,
  6289. methodName,
  6290. targetDoc,
  6291. path: FieldPath$1.emptyPath(),
  6292. arrayElement: false,
  6293. hasConverter
  6294. }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);
  6295. }
  6296. }
  6297. function newUserDataReader(firestore) {
  6298. const settings = firestore._freezeSettings();
  6299. const serializer = newSerializer(firestore._databaseId);
  6300. return new UserDataReader(firestore._databaseId, !!settings.ignoreUndefinedProperties, serializer);
  6301. }
  6302. /** Parse document data from a set() call. */
  6303. function parseSetData(userDataReader, methodName, targetDoc, input, hasConverter, options = {}) {
  6304. const context = userDataReader.createContext(options.merge || options.mergeFields
  6305. ? 2 /* UserDataSource.MergeSet */
  6306. : 0 /* UserDataSource.Set */, methodName, targetDoc, hasConverter);
  6307. validatePlainObject('Data must be an object, but it was:', context, input);
  6308. const updateData = parseObject(input, context);
  6309. let fieldMask;
  6310. let fieldTransforms;
  6311. if (options.merge) {
  6312. fieldMask = new FieldMask(context.fieldMask);
  6313. fieldTransforms = context.fieldTransforms;
  6314. }
  6315. else if (options.mergeFields) {
  6316. const validatedFieldPaths = [];
  6317. for (const stringOrFieldPath of options.mergeFields) {
  6318. const fieldPath = fieldPathFromArgument$1(methodName, stringOrFieldPath, targetDoc);
  6319. if (!context.contains(fieldPath)) {
  6320. throw new FirestoreError(Code.INVALID_ARGUMENT, `Field '${fieldPath}' is specified in your field mask but missing from your input data.`);
  6321. }
  6322. if (!fieldMaskContains(validatedFieldPaths, fieldPath)) {
  6323. validatedFieldPaths.push(fieldPath);
  6324. }
  6325. }
  6326. fieldMask = new FieldMask(validatedFieldPaths);
  6327. fieldTransforms = context.fieldTransforms.filter(transform => fieldMask.covers(transform.field));
  6328. }
  6329. else {
  6330. fieldMask = null;
  6331. fieldTransforms = context.fieldTransforms;
  6332. }
  6333. return new ParsedSetData(new ObjectValue(updateData), fieldMask, fieldTransforms);
  6334. }
  6335. class DeleteFieldValueImpl extends FieldValue {
  6336. _toFieldTransform(context) {
  6337. if (context.dataSource === 2 /* UserDataSource.MergeSet */) {
  6338. // No transform to add for a delete, but we need to add it to our
  6339. // fieldMask so it gets deleted.
  6340. context.fieldMask.push(context.path);
  6341. }
  6342. else if (context.dataSource === 1 /* UserDataSource.Update */) {
  6343. throw context.createError(`${this._methodName}() can only appear at the top level ` +
  6344. 'of your update data');
  6345. }
  6346. else {
  6347. // We shouldn't encounter delete sentinels for queries or non-merge set() calls.
  6348. throw context.createError(`${this._methodName}() cannot be used with set() unless you pass ` +
  6349. '{merge:true}');
  6350. }
  6351. return null;
  6352. }
  6353. isEqual(other) {
  6354. return other instanceof DeleteFieldValueImpl;
  6355. }
  6356. }
  6357. /**
  6358. * Creates a child context for parsing SerializableFieldValues.
  6359. *
  6360. * This is different than calling `ParseContext.contextWith` because it keeps
  6361. * the fieldTransforms and fieldMask separate.
  6362. *
  6363. * The created context has its `dataSource` set to `UserDataSource.Argument`.
  6364. * Although these values are used with writes, any elements in these FieldValues
  6365. * are not considered writes since they cannot contain any FieldValue sentinels,
  6366. * etc.
  6367. *
  6368. * @param fieldValue - The sentinel FieldValue for which to create a child
  6369. * context.
  6370. * @param context - The parent context.
  6371. * @param arrayElement - Whether or not the FieldValue has an array.
  6372. */
  6373. function createSentinelChildContext(fieldValue, context, arrayElement) {
  6374. return new ParseContextImpl({
  6375. dataSource: 3 /* UserDataSource.Argument */,
  6376. targetDoc: context.settings.targetDoc,
  6377. methodName: fieldValue._methodName,
  6378. arrayElement
  6379. }, context.databaseId, context.serializer, context.ignoreUndefinedProperties);
  6380. }
  6381. class ServerTimestampFieldValueImpl extends FieldValue {
  6382. _toFieldTransform(context) {
  6383. return new FieldTransform(context.path, new ServerTimestampTransform());
  6384. }
  6385. isEqual(other) {
  6386. return other instanceof ServerTimestampFieldValueImpl;
  6387. }
  6388. }
  6389. class ArrayUnionFieldValueImpl extends FieldValue {
  6390. constructor(methodName, _elements) {
  6391. super(methodName);
  6392. this._elements = _elements;
  6393. }
  6394. _toFieldTransform(context) {
  6395. const parseContext = createSentinelChildContext(this, context,
  6396. /*array=*/ true);
  6397. const parsedElements = this._elements.map(element => parseData(element, parseContext));
  6398. const arrayUnion = new ArrayUnionTransformOperation(parsedElements);
  6399. return new FieldTransform(context.path, arrayUnion);
  6400. }
  6401. isEqual(other) {
  6402. // TODO(mrschmidt): Implement isEquals
  6403. return this === other;
  6404. }
  6405. }
  6406. class ArrayRemoveFieldValueImpl extends FieldValue {
  6407. constructor(methodName, _elements) {
  6408. super(methodName);
  6409. this._elements = _elements;
  6410. }
  6411. _toFieldTransform(context) {
  6412. const parseContext = createSentinelChildContext(this, context,
  6413. /*array=*/ true);
  6414. const parsedElements = this._elements.map(element => parseData(element, parseContext));
  6415. const arrayUnion = new ArrayRemoveTransformOperation(parsedElements);
  6416. return new FieldTransform(context.path, arrayUnion);
  6417. }
  6418. isEqual(other) {
  6419. // TODO(mrschmidt): Implement isEquals
  6420. return this === other;
  6421. }
  6422. }
  6423. class NumericIncrementFieldValueImpl extends FieldValue {
  6424. constructor(methodName, _operand) {
  6425. super(methodName);
  6426. this._operand = _operand;
  6427. }
  6428. _toFieldTransform(context) {
  6429. const numericIncrement = new NumericIncrementTransformOperation(context.serializer, toNumber(context.serializer, this._operand));
  6430. return new FieldTransform(context.path, numericIncrement);
  6431. }
  6432. isEqual(other) {
  6433. // TODO(mrschmidt): Implement isEquals
  6434. return this === other;
  6435. }
  6436. }
  6437. /** Parse update data from an update() call. */
  6438. function parseUpdateData(userDataReader, methodName, targetDoc, input) {
  6439. const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc);
  6440. validatePlainObject('Data must be an object, but it was:', context, input);
  6441. const fieldMaskPaths = [];
  6442. const updateData = ObjectValue.empty();
  6443. forEach(input, (key, value) => {
  6444. const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc);
  6445. // For Compat types, we have to "extract" the underlying types before
  6446. // performing validation.
  6447. value = util.getModularInstance(value);
  6448. const childContext = context.childContextForFieldPath(path);
  6449. if (value instanceof DeleteFieldValueImpl) {
  6450. // Add it to the field mask, but don't add anything to updateData.
  6451. fieldMaskPaths.push(path);
  6452. }
  6453. else {
  6454. const parsedValue = parseData(value, childContext);
  6455. if (parsedValue != null) {
  6456. fieldMaskPaths.push(path);
  6457. updateData.set(path, parsedValue);
  6458. }
  6459. }
  6460. });
  6461. const mask = new FieldMask(fieldMaskPaths);
  6462. return new ParsedUpdateData(updateData, mask, context.fieldTransforms);
  6463. }
  6464. /** Parse update data from a list of field/value arguments. */
  6465. function parseUpdateVarargs(userDataReader, methodName, targetDoc, field, value, moreFieldsAndValues) {
  6466. const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc);
  6467. const keys = [fieldPathFromArgument$1(methodName, field, targetDoc)];
  6468. const values = [value];
  6469. if (moreFieldsAndValues.length % 2 !== 0) {
  6470. throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${methodName}() needs to be called with an even number ` +
  6471. 'of arguments that alternate between field names and values.');
  6472. }
  6473. for (let i = 0; i < moreFieldsAndValues.length; i += 2) {
  6474. keys.push(fieldPathFromArgument$1(methodName, moreFieldsAndValues[i]));
  6475. values.push(moreFieldsAndValues[i + 1]);
  6476. }
  6477. const fieldMaskPaths = [];
  6478. const updateData = ObjectValue.empty();
  6479. // We iterate in reverse order to pick the last value for a field if the
  6480. // user specified the field multiple times.
  6481. for (let i = keys.length - 1; i >= 0; --i) {
  6482. if (!fieldMaskContains(fieldMaskPaths, keys[i])) {
  6483. const path = keys[i];
  6484. let value = values[i];
  6485. // For Compat types, we have to "extract" the underlying types before
  6486. // performing validation.
  6487. value = util.getModularInstance(value);
  6488. const childContext = context.childContextForFieldPath(path);
  6489. if (value instanceof DeleteFieldValueImpl) {
  6490. // Add it to the field mask, but don't add anything to updateData.
  6491. fieldMaskPaths.push(path);
  6492. }
  6493. else {
  6494. const parsedValue = parseData(value, childContext);
  6495. if (parsedValue != null) {
  6496. fieldMaskPaths.push(path);
  6497. updateData.set(path, parsedValue);
  6498. }
  6499. }
  6500. }
  6501. }
  6502. const mask = new FieldMask(fieldMaskPaths);
  6503. return new ParsedUpdateData(updateData, mask, context.fieldTransforms);
  6504. }
  6505. /**
  6506. * Parse a "query value" (e.g. value in a where filter or a value in a cursor
  6507. * bound).
  6508. *
  6509. * @param allowArrays - Whether the query value is an array that may directly
  6510. * contain additional arrays (e.g. the operand of an `in` query).
  6511. */
  6512. function parseQueryValue(userDataReader, methodName, input, allowArrays = false) {
  6513. const context = userDataReader.createContext(allowArrays ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */, methodName);
  6514. const parsed = parseData(input, context);
  6515. return parsed;
  6516. }
  6517. /**
  6518. * Parses user data to Protobuf Values.
  6519. *
  6520. * @param input - Data to be parsed.
  6521. * @param context - A context object representing the current path being parsed,
  6522. * the source of the data being parsed, etc.
  6523. * @returns The parsed value, or null if the value was a FieldValue sentinel
  6524. * that should not be included in the resulting parsed data.
  6525. */
  6526. function parseData(input, context) {
  6527. // Unwrap the API type from the Compat SDK. This will return the API type
  6528. // from firestore-exp.
  6529. input = util.getModularInstance(input);
  6530. if (looksLikeJsonObject(input)) {
  6531. validatePlainObject('Unsupported field value:', context, input);
  6532. return parseObject(input, context);
  6533. }
  6534. else if (input instanceof FieldValue) {
  6535. // FieldValues usually parse into transforms (except deleteField())
  6536. // in which case we do not want to include this field in our parsed data
  6537. // (as doing so will overwrite the field directly prior to the transform
  6538. // trying to transform it). So we don't add this location to
  6539. // context.fieldMask and we return null as our parsing result.
  6540. parseSentinelFieldValue(input, context);
  6541. return null;
  6542. }
  6543. else if (input === undefined && context.ignoreUndefinedProperties) {
  6544. // If the input is undefined it can never participate in the fieldMask, so
  6545. // don't handle this below. If `ignoreUndefinedProperties` is false,
  6546. // `parseScalarValue` will reject an undefined value.
  6547. return null;
  6548. }
  6549. else {
  6550. // If context.path is null we are inside an array and we don't support
  6551. // field mask paths more granular than the top-level array.
  6552. if (context.path) {
  6553. context.fieldMask.push(context.path);
  6554. }
  6555. if (input instanceof Array) {
  6556. // TODO(b/34871131): Include the path containing the array in the error
  6557. // message.
  6558. // In the case of IN queries, the parsed data is an array (representing
  6559. // the set of values to be included for the IN query) that may directly
  6560. // contain additional arrays (each representing an individual field
  6561. // value), so we disable this validation.
  6562. if (context.settings.arrayElement &&
  6563. context.dataSource !== 4 /* UserDataSource.ArrayArgument */) {
  6564. throw context.createError('Nested arrays are not supported');
  6565. }
  6566. return parseArray(input, context);
  6567. }
  6568. else {
  6569. return parseScalarValue(input, context);
  6570. }
  6571. }
  6572. }
  6573. function parseObject(obj, context) {
  6574. const fields = {};
  6575. if (isEmpty(obj)) {
  6576. // If we encounter an empty object, we explicitly add it to the update
  6577. // mask to ensure that the server creates a map entry.
  6578. if (context.path && context.path.length > 0) {
  6579. context.fieldMask.push(context.path);
  6580. }
  6581. }
  6582. else {
  6583. forEach(obj, (key, val) => {
  6584. const parsedValue = parseData(val, context.childContextForField(key));
  6585. if (parsedValue != null) {
  6586. fields[key] = parsedValue;
  6587. }
  6588. });
  6589. }
  6590. return { mapValue: { fields } };
  6591. }
  6592. function parseArray(array, context) {
  6593. const values = [];
  6594. let entryIndex = 0;
  6595. for (const entry of array) {
  6596. let parsedEntry = parseData(entry, context.childContextForArray(entryIndex));
  6597. if (parsedEntry == null) {
  6598. // Just include nulls in the array for fields being replaced with a
  6599. // sentinel.
  6600. parsedEntry = { nullValue: 'NULL_VALUE' };
  6601. }
  6602. values.push(parsedEntry);
  6603. entryIndex++;
  6604. }
  6605. return { arrayValue: { values } };
  6606. }
  6607. /**
  6608. * "Parses" the provided FieldValueImpl, adding any necessary transforms to
  6609. * context.fieldTransforms.
  6610. */
  6611. function parseSentinelFieldValue(value, context) {
  6612. // Sentinels are only supported with writes, and not within arrays.
  6613. if (!isWrite(context.dataSource)) {
  6614. throw context.createError(`${value._methodName}() can only be used with update() and set()`);
  6615. }
  6616. if (!context.path) {
  6617. throw context.createError(`${value._methodName}() is not currently supported inside arrays`);
  6618. }
  6619. const fieldTransform = value._toFieldTransform(context);
  6620. if (fieldTransform) {
  6621. context.fieldTransforms.push(fieldTransform);
  6622. }
  6623. }
  6624. /**
  6625. * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
  6626. *
  6627. * @returns The parsed value
  6628. */
  6629. function parseScalarValue(value, context) {
  6630. value = util.getModularInstance(value);
  6631. if (value === null) {
  6632. return { nullValue: 'NULL_VALUE' };
  6633. }
  6634. else if (typeof value === 'number') {
  6635. return toNumber(context.serializer, value);
  6636. }
  6637. else if (typeof value === 'boolean') {
  6638. return { booleanValue: value };
  6639. }
  6640. else if (typeof value === 'string') {
  6641. return { stringValue: value };
  6642. }
  6643. else if (value instanceof Date) {
  6644. const timestamp = Timestamp.fromDate(value);
  6645. return {
  6646. timestampValue: toTimestamp(context.serializer, timestamp)
  6647. };
  6648. }
  6649. else if (value instanceof Timestamp) {
  6650. // Firestore backend truncates precision down to microseconds. To ensure
  6651. // offline mode works the same with regards to truncation, perform the
  6652. // truncation immediately without waiting for the backend to do that.
  6653. const timestamp = new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000);
  6654. return {
  6655. timestampValue: toTimestamp(context.serializer, timestamp)
  6656. };
  6657. }
  6658. else if (value instanceof GeoPoint) {
  6659. return {
  6660. geoPointValue: {
  6661. latitude: value.latitude,
  6662. longitude: value.longitude
  6663. }
  6664. };
  6665. }
  6666. else if (value instanceof Bytes) {
  6667. return { bytesValue: toBytes(context.serializer, value._byteString) };
  6668. }
  6669. else if (value instanceof DocumentReference) {
  6670. const thisDb = context.databaseId;
  6671. const otherDb = value.firestore._databaseId;
  6672. if (!otherDb.isEqual(thisDb)) {
  6673. throw context.createError('Document reference is for database ' +
  6674. `${otherDb.projectId}/${otherDb.database} but should be ` +
  6675. `for database ${thisDb.projectId}/${thisDb.database}`);
  6676. }
  6677. return {
  6678. referenceValue: toResourceName(value.firestore._databaseId || context.databaseId, value._key.path)
  6679. };
  6680. }
  6681. else {
  6682. throw context.createError(`Unsupported field value: ${valueDescription(value)}`);
  6683. }
  6684. }
  6685. /**
  6686. * Checks whether an object looks like a JSON object that should be converted
  6687. * into a struct. Normal class/prototype instances are considered to look like
  6688. * JSON objects since they should be converted to a struct value. Arrays, Dates,
  6689. * GeoPoints, etc. are not considered to look like JSON objects since they map
  6690. * to specific FieldValue types other than ObjectValue.
  6691. */
  6692. function looksLikeJsonObject(input) {
  6693. return (typeof input === 'object' &&
  6694. input !== null &&
  6695. !(input instanceof Array) &&
  6696. !(input instanceof Date) &&
  6697. !(input instanceof Timestamp) &&
  6698. !(input instanceof GeoPoint) &&
  6699. !(input instanceof Bytes) &&
  6700. !(input instanceof DocumentReference) &&
  6701. !(input instanceof FieldValue));
  6702. }
  6703. function validatePlainObject(message, context, input) {
  6704. if (!looksLikeJsonObject(input) || !isPlainObject(input)) {
  6705. const description = valueDescription(input);
  6706. if (description === 'an object') {
  6707. // Massage the error if it was an object.
  6708. throw context.createError(message + ' a custom object');
  6709. }
  6710. else {
  6711. throw context.createError(message + ' ' + description);
  6712. }
  6713. }
  6714. }
  6715. /**
  6716. * Helper that calls fromDotSeparatedString() but wraps any error thrown.
  6717. */
  6718. function fieldPathFromArgument$1(methodName, path, targetDoc) {
  6719. // If required, replace the FieldPath Compat class with with the firestore-exp
  6720. // FieldPath.
  6721. path = util.getModularInstance(path);
  6722. if (path instanceof FieldPath) {
  6723. return path._internalPath;
  6724. }
  6725. else if (typeof path === 'string') {
  6726. return fieldPathFromDotSeparatedString(methodName, path);
  6727. }
  6728. else {
  6729. const message = 'Field path arguments must be of type string or ';
  6730. throw createError(message, methodName,
  6731. /* hasConverter= */ false,
  6732. /* path= */ undefined, targetDoc);
  6733. }
  6734. }
  6735. /**
  6736. * Matches any characters in a field path string that are reserved.
  6737. */
  6738. const FIELD_PATH_RESERVED = new RegExp('[~\\*/\\[\\]]');
  6739. /**
  6740. * Wraps fromDotSeparatedString with an error message about the method that
  6741. * was thrown.
  6742. * @param methodName - The publicly visible method name
  6743. * @param path - The dot-separated string form of a field path which will be
  6744. * split on dots.
  6745. * @param targetDoc - The document against which the field path will be
  6746. * evaluated.
  6747. */
  6748. function fieldPathFromDotSeparatedString(methodName, path, targetDoc) {
  6749. const found = path.search(FIELD_PATH_RESERVED);
  6750. if (found >= 0) {
  6751. throw createError(`Invalid field path (${path}). Paths must not contain ` +
  6752. `'~', '*', '/', '[', or ']'`, methodName,
  6753. /* hasConverter= */ false,
  6754. /* path= */ undefined, targetDoc);
  6755. }
  6756. try {
  6757. return new FieldPath(...path.split('.'))._internalPath;
  6758. }
  6759. catch (e) {
  6760. throw createError(`Invalid field path (${path}). Paths must not be empty, ` +
  6761. `begin with '.', end with '.', or contain '..'`, methodName,
  6762. /* hasConverter= */ false,
  6763. /* path= */ undefined, targetDoc);
  6764. }
  6765. }
  6766. function createError(reason, methodName, hasConverter, path, targetDoc) {
  6767. const hasPath = path && !path.isEmpty();
  6768. const hasDocument = targetDoc !== undefined;
  6769. let message = `Function ${methodName}() called with invalid data`;
  6770. if (hasConverter) {
  6771. message += ' (via `toFirestore()`)';
  6772. }
  6773. message += '. ';
  6774. let description = '';
  6775. if (hasPath || hasDocument) {
  6776. description += ' (found';
  6777. if (hasPath) {
  6778. description += ` in field ${path}`;
  6779. }
  6780. if (hasDocument) {
  6781. description += ` in document ${targetDoc}`;
  6782. }
  6783. description += ')';
  6784. }
  6785. return new FirestoreError(Code.INVALID_ARGUMENT, message + reason + description);
  6786. }
  6787. /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */
  6788. function fieldMaskContains(haystack, needle) {
  6789. return haystack.some(v => v.isEqual(needle));
  6790. }
  6791. /**
  6792. * @license
  6793. * Copyright 2020 Google LLC
  6794. *
  6795. * Licensed under the Apache License, Version 2.0 (the "License");
  6796. * you may not use this file except in compliance with the License.
  6797. * You may obtain a copy of the License at
  6798. *
  6799. * http://www.apache.org/licenses/LICENSE-2.0
  6800. *
  6801. * Unless required by applicable law or agreed to in writing, software
  6802. * distributed under the License is distributed on an "AS IS" BASIS,
  6803. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6804. * See the License for the specific language governing permissions and
  6805. * limitations under the License.
  6806. */
  6807. /**
  6808. * A `DocumentSnapshot` contains data read from a document in your Firestore
  6809. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  6810. * get a specific field.
  6811. *
  6812. * For a `DocumentSnapshot` that points to a non-existing document, any data
  6813. * access will return 'undefined'. You can use the `exists()` method to
  6814. * explicitly verify a document's existence.
  6815. */
  6816. class DocumentSnapshot {
  6817. // Note: This class is stripped down version of the DocumentSnapshot in
  6818. // the legacy SDK. The changes are:
  6819. // - No support for SnapshotMetadata.
  6820. // - No support for SnapshotOptions.
  6821. /** @hideconstructor protected */
  6822. constructor(_firestore, _userDataWriter, _key, _document, _converter) {
  6823. this._firestore = _firestore;
  6824. this._userDataWriter = _userDataWriter;
  6825. this._key = _key;
  6826. this._document = _document;
  6827. this._converter = _converter;
  6828. }
  6829. /** Property of the `DocumentSnapshot` that provides the document's ID. */
  6830. get id() {
  6831. return this._key.path.lastSegment();
  6832. }
  6833. /**
  6834. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  6835. */
  6836. get ref() {
  6837. return new DocumentReference(this._firestore, this._converter, this._key);
  6838. }
  6839. /**
  6840. * Signals whether or not the document at the snapshot's location exists.
  6841. *
  6842. * @returns true if the document exists.
  6843. */
  6844. exists() {
  6845. return this._document !== null;
  6846. }
  6847. /**
  6848. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  6849. * the document doesn't exist.
  6850. *
  6851. * @returns An `Object` containing all fields in the document or `undefined`
  6852. * if the document doesn't exist.
  6853. */
  6854. data() {
  6855. if (!this._document) {
  6856. return undefined;
  6857. }
  6858. else if (this._converter) {
  6859. // We only want to use the converter and create a new DocumentSnapshot
  6860. // if a converter has been provided.
  6861. const snapshot = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document,
  6862. /* converter= */ null);
  6863. return this._converter.fromFirestore(snapshot);
  6864. }
  6865. else {
  6866. return this._userDataWriter.convertValue(this._document.data.value);
  6867. }
  6868. }
  6869. /**
  6870. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  6871. * document or field doesn't exist.
  6872. *
  6873. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  6874. * field.
  6875. * @returns The data at the specified field location or undefined if no such
  6876. * field exists in the document.
  6877. */
  6878. // We are using `any` here to avoid an explicit cast by our users.
  6879. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6880. get(fieldPath) {
  6881. if (this._document) {
  6882. const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));
  6883. if (value !== null) {
  6884. return this._userDataWriter.convertValue(value);
  6885. }
  6886. }
  6887. return undefined;
  6888. }
  6889. }
  6890. /**
  6891. * A `QueryDocumentSnapshot` contains data read from a document in your
  6892. * Firestore database as part of a query. The document is guaranteed to exist
  6893. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  6894. * specific field.
  6895. *
  6896. * A `QueryDocumentSnapshot` offers the same API surface as a
  6897. * `DocumentSnapshot`. Since query results contain only existing documents, the
  6898. * `exists` property will always be true and `data()` will never return
  6899. * 'undefined'.
  6900. */
  6901. class QueryDocumentSnapshot extends DocumentSnapshot {
  6902. /**
  6903. * Retrieves all fields in the document as an `Object`.
  6904. *
  6905. * @override
  6906. * @returns An `Object` containing all fields in the document.
  6907. */
  6908. data() {
  6909. return super.data();
  6910. }
  6911. }
  6912. /**
  6913. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  6914. * representing the results of a query. The documents can be accessed as an
  6915. * array via the `docs` property or enumerated using the `forEach` method. The
  6916. * number of documents can be determined via the `empty` and `size`
  6917. * properties.
  6918. */
  6919. class QuerySnapshot {
  6920. /** @hideconstructor */
  6921. constructor(_query, _docs) {
  6922. this._docs = _docs;
  6923. this.query = _query;
  6924. }
  6925. /** An array of all the documents in the `QuerySnapshot`. */
  6926. get docs() {
  6927. return [...this._docs];
  6928. }
  6929. /** The number of documents in the `QuerySnapshot`. */
  6930. get size() {
  6931. return this.docs.length;
  6932. }
  6933. /** True if there are no documents in the `QuerySnapshot`. */
  6934. get empty() {
  6935. return this.docs.length === 0;
  6936. }
  6937. /**
  6938. * Enumerates all of the documents in the `QuerySnapshot`.
  6939. *
  6940. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  6941. * each document in the snapshot.
  6942. * @param thisArg - The `this` binding for the callback.
  6943. */
  6944. forEach(callback, thisArg) {
  6945. this._docs.forEach(callback, thisArg);
  6946. }
  6947. }
  6948. /**
  6949. * Returns true if the provided snapshots are equal.
  6950. *
  6951. * @param left - A snapshot to compare.
  6952. * @param right - A snapshot to compare.
  6953. * @returns true if the snapshots are equal.
  6954. */
  6955. function snapshotEqual(left, right) {
  6956. left = util.getModularInstance(left);
  6957. right = util.getModularInstance(right);
  6958. if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) {
  6959. return (left._firestore === right._firestore &&
  6960. left._key.isEqual(right._key) &&
  6961. (left._document === null
  6962. ? right._document === null
  6963. : left._document.isEqual(right._document)) &&
  6964. left._converter === right._converter);
  6965. }
  6966. else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) {
  6967. return (queryEqual(left.query, right.query) &&
  6968. arrayEquals(left.docs, right.docs, snapshotEqual));
  6969. }
  6970. return false;
  6971. }
  6972. /**
  6973. * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
  6974. */
  6975. function fieldPathFromArgument(methodName, arg) {
  6976. if (typeof arg === 'string') {
  6977. return fieldPathFromDotSeparatedString(methodName, arg);
  6978. }
  6979. else if (arg instanceof FieldPath) {
  6980. return arg._internalPath;
  6981. }
  6982. else {
  6983. return arg._delegate._internalPath;
  6984. }
  6985. }
  6986. /**
  6987. * @license
  6988. * Copyright 2020 Google LLC
  6989. *
  6990. * Licensed under the Apache License, Version 2.0 (the "License");
  6991. * you may not use this file except in compliance with the License.
  6992. * You may obtain a copy of the License at
  6993. *
  6994. * http://www.apache.org/licenses/LICENSE-2.0
  6995. *
  6996. * Unless required by applicable law or agreed to in writing, software
  6997. * distributed under the License is distributed on an "AS IS" BASIS,
  6998. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6999. * See the License for the specific language governing permissions and
  7000. * limitations under the License.
  7001. */
  7002. function validateHasExplicitOrderByForLimitToLast(query) {
  7003. if (query.limitType === "L" /* LimitType.Last */ &&
  7004. query.explicitOrderBy.length === 0) {
  7005. throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause');
  7006. }
  7007. }
  7008. /**
  7009. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  7010. * to a Firestore query.
  7011. */
  7012. class AppliableConstraint {
  7013. }
  7014. /**
  7015. * A `QueryConstraint` is used to narrow the set of documents returned by a
  7016. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  7017. * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link
  7018. * endBefore}, {@link endAt}, {@link limit}, {@link limitToLast} and
  7019. * can then be passed to {@link query} to create a new query instance that
  7020. * also contains this `QueryConstraint`.
  7021. */
  7022. class QueryConstraint extends AppliableConstraint {
  7023. }
  7024. function query(query, queryConstraint, ...additionalQueryConstraints) {
  7025. let queryConstraints = [];
  7026. if (queryConstraint instanceof AppliableConstraint) {
  7027. queryConstraints.push(queryConstraint);
  7028. }
  7029. queryConstraints = queryConstraints.concat(additionalQueryConstraints);
  7030. validateQueryConstraintArray(queryConstraints);
  7031. for (const constraint of queryConstraints) {
  7032. query = constraint._apply(query);
  7033. }
  7034. return query;
  7035. }
  7036. /**
  7037. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  7038. * a Firestore query by filtering on one or more document fields.
  7039. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  7040. * be passed to {@link query} to create a new query instance that also contains
  7041. * this `QueryFieldFilterConstraint`.
  7042. */
  7043. class QueryFieldFilterConstraint extends QueryConstraint {
  7044. /**
  7045. * @internal
  7046. */
  7047. constructor(_field, _op, _value) {
  7048. super();
  7049. this._field = _field;
  7050. this._op = _op;
  7051. this._value = _value;
  7052. /** The type of this query constraint */
  7053. this.type = 'where';
  7054. }
  7055. static _create(_field, _op, _value) {
  7056. return new QueryFieldFilterConstraint(_field, _op, _value);
  7057. }
  7058. _apply(query) {
  7059. const filter = this._parse(query);
  7060. validateNewFieldFilter(query._query, filter);
  7061. return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter));
  7062. }
  7063. _parse(query) {
  7064. const reader = newUserDataReader(query.firestore);
  7065. const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value);
  7066. return filter;
  7067. }
  7068. }
  7069. /**
  7070. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  7071. * must contain the specified field and that the value should satisfy the
  7072. * relation constraint provided.
  7073. *
  7074. * @param fieldPath - The path to compare
  7075. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  7076. * "&lt;=", "!=").
  7077. * @param value - The value for comparison
  7078. * @returns The created {@link QueryFieldFilterConstraint}.
  7079. */
  7080. function where(fieldPath, opStr, value) {
  7081. const op = opStr;
  7082. const field = fieldPathFromArgument('where', fieldPath);
  7083. return QueryFieldFilterConstraint._create(field, op, value);
  7084. }
  7085. /**
  7086. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  7087. * returned by a Firestore query by performing the logical OR or AND of multiple
  7088. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  7089. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  7090. * {@link and} and can then be passed to {@link query} to create a new query
  7091. * instance that also contains the `QueryCompositeFilterConstraint`.
  7092. * @internal TODO remove this internal tag with OR Query support in the server
  7093. */
  7094. class QueryCompositeFilterConstraint extends AppliableConstraint {
  7095. /**
  7096. * @internal
  7097. */
  7098. constructor(
  7099. /** The type of this query constraint */
  7100. type, _queryConstraints) {
  7101. super();
  7102. this.type = type;
  7103. this._queryConstraints = _queryConstraints;
  7104. }
  7105. static _create(type, _queryConstraints) {
  7106. return new QueryCompositeFilterConstraint(type, _queryConstraints);
  7107. }
  7108. _parse(query) {
  7109. const parsedFilters = this._queryConstraints
  7110. .map(queryConstraint => {
  7111. return queryConstraint._parse(query);
  7112. })
  7113. .filter(parsedFilter => parsedFilter.getFilters().length > 0);
  7114. if (parsedFilters.length === 1) {
  7115. return parsedFilters[0];
  7116. }
  7117. return CompositeFilter.create(parsedFilters, this._getOperator());
  7118. }
  7119. _apply(query) {
  7120. const parsedFilter = this._parse(query);
  7121. if (parsedFilter.getFilters().length === 0) {
  7122. // Return the existing query if not adding any more filters (e.g. an empty
  7123. // composite filter).
  7124. return query;
  7125. }
  7126. validateNewFilter(query._query, parsedFilter);
  7127. return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, parsedFilter));
  7128. }
  7129. _getQueryConstraints() {
  7130. return this._queryConstraints;
  7131. }
  7132. _getOperator() {
  7133. return this.type === 'and' ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
  7134. }
  7135. }
  7136. /**
  7137. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  7138. * the given filter constraints. A disjunction filter includes a document if it
  7139. * satisfies any of the given filters.
  7140. *
  7141. * @param queryConstraints - Optional. The list of
  7142. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  7143. * created with calls to {@link where}, {@link or}, or {@link and}.
  7144. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  7145. * @internal TODO remove this internal tag with OR Query support in the server
  7146. */
  7147. function or(...queryConstraints) {
  7148. // Only support QueryFilterConstraints
  7149. queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('or', queryConstraint));
  7150. return QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */, queryConstraints);
  7151. }
  7152. /**
  7153. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  7154. * the given filter constraints. A conjunction filter includes a document if it
  7155. * satisfies all of the given filters.
  7156. *
  7157. * @param queryConstraints - Optional. The list of
  7158. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  7159. * created with calls to {@link where}, {@link or}, or {@link and}.
  7160. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  7161. * @internal TODO remove this internal tag with OR Query support in the server
  7162. */
  7163. function and(...queryConstraints) {
  7164. // Only support QueryFilterConstraints
  7165. queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('and', queryConstraint));
  7166. return QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */, queryConstraints);
  7167. }
  7168. /**
  7169. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  7170. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  7171. * {@link orderBy} and can then be passed to {@link query} to create a new query
  7172. * instance that also contains this `QueryOrderByConstraint`.
  7173. *
  7174. * Note: Documents that do not contain the orderBy field will not be present in
  7175. * the query result.
  7176. */
  7177. class QueryOrderByConstraint extends QueryConstraint {
  7178. /**
  7179. * @internal
  7180. */
  7181. constructor(_field, _direction) {
  7182. super();
  7183. this._field = _field;
  7184. this._direction = _direction;
  7185. /** The type of this query constraint */
  7186. this.type = 'orderBy';
  7187. }
  7188. static _create(_field, _direction) {
  7189. return new QueryOrderByConstraint(_field, _direction);
  7190. }
  7191. _apply(query) {
  7192. const orderBy = newQueryOrderBy(query._query, this._field, this._direction);
  7193. return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy));
  7194. }
  7195. }
  7196. /**
  7197. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  7198. * specified field, optionally in descending order instead of ascending.
  7199. *
  7200. * Note: Documents that do not contain the specified field will not be present
  7201. * in the query result.
  7202. *
  7203. * @param fieldPath - The field to sort by.
  7204. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  7205. * not specified, order will be ascending.
  7206. * @returns The created {@link QueryOrderByConstraint}.
  7207. */
  7208. function orderBy(fieldPath, directionStr = 'asc') {
  7209. const direction = directionStr;
  7210. const path = fieldPathFromArgument('orderBy', fieldPath);
  7211. return QueryOrderByConstraint._create(path, direction);
  7212. }
  7213. /**
  7214. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  7215. * a Firestore query.
  7216. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  7217. * {@link limitToLast} and can then be passed to {@link query} to create a new
  7218. * query instance that also contains this `QueryLimitConstraint`.
  7219. */
  7220. class QueryLimitConstraint extends QueryConstraint {
  7221. /**
  7222. * @internal
  7223. */
  7224. constructor(
  7225. /** The type of this query constraint */
  7226. type, _limit, _limitType) {
  7227. super();
  7228. this.type = type;
  7229. this._limit = _limit;
  7230. this._limitType = _limitType;
  7231. }
  7232. static _create(type, _limit, _limitType) {
  7233. return new QueryLimitConstraint(type, _limit, _limitType);
  7234. }
  7235. _apply(query) {
  7236. return new Query(query.firestore, query.converter, queryWithLimit(query._query, this._limit, this._limitType));
  7237. }
  7238. }
  7239. /**
  7240. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  7241. * documents.
  7242. *
  7243. * @param limit - The maximum number of items to return.
  7244. * @returns The created {@link QueryLimitConstraint}.
  7245. */
  7246. function limit(limit) {
  7247. validatePositiveNumber('limit', limit);
  7248. return QueryLimitConstraint._create('limit', limit, "F" /* LimitType.First */);
  7249. }
  7250. /**
  7251. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  7252. * documents.
  7253. *
  7254. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  7255. * otherwise an exception will be thrown during execution.
  7256. *
  7257. * @param limit - The maximum number of items to return.
  7258. * @returns The created {@link QueryLimitConstraint}.
  7259. */
  7260. function limitToLast(limit) {
  7261. validatePositiveNumber('limitToLast', limit);
  7262. return QueryLimitConstraint._create('limitToLast', limit, "L" /* LimitType.Last */);
  7263. }
  7264. /**
  7265. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  7266. * result set returned by a Firestore query.
  7267. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  7268. * {@link (startAfter:1)} and can then be passed to {@link query} to create a
  7269. * new query instance that also contains this `QueryStartAtConstraint`.
  7270. */
  7271. class QueryStartAtConstraint extends QueryConstraint {
  7272. /**
  7273. * @internal
  7274. */
  7275. constructor(
  7276. /** The type of this query constraint */
  7277. type, _docOrFields, _inclusive) {
  7278. super();
  7279. this.type = type;
  7280. this._docOrFields = _docOrFields;
  7281. this._inclusive = _inclusive;
  7282. }
  7283. static _create(type, _docOrFields, _inclusive) {
  7284. return new QueryStartAtConstraint(type, _docOrFields, _inclusive);
  7285. }
  7286. _apply(query) {
  7287. const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive);
  7288. return new Query(query.firestore, query.converter, queryWithStartAt(query._query, bound));
  7289. }
  7290. }
  7291. function startAt(...docOrFields) {
  7292. return QueryStartAtConstraint._create('startAt', docOrFields,
  7293. /*inclusive=*/ true);
  7294. }
  7295. function startAfter(...docOrFields) {
  7296. return QueryStartAtConstraint._create('startAfter', docOrFields,
  7297. /*inclusive=*/ false);
  7298. }
  7299. /**
  7300. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  7301. * result set returned by a Firestore query.
  7302. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  7303. * {@link (endBefore:1)} and can then be passed to {@link query} to create a new
  7304. * query instance that also contains this `QueryEndAtConstraint`.
  7305. */
  7306. class QueryEndAtConstraint extends QueryConstraint {
  7307. /**
  7308. * @internal
  7309. */
  7310. constructor(
  7311. /** The type of this query constraint */
  7312. type, _docOrFields, _inclusive) {
  7313. super();
  7314. this.type = type;
  7315. this._docOrFields = _docOrFields;
  7316. this._inclusive = _inclusive;
  7317. }
  7318. static _create(type, _docOrFields, _inclusive) {
  7319. return new QueryEndAtConstraint(type, _docOrFields, _inclusive);
  7320. }
  7321. _apply(query) {
  7322. const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive);
  7323. return new Query(query.firestore, query.converter, queryWithEndAt(query._query, bound));
  7324. }
  7325. }
  7326. function endBefore(...docOrFields) {
  7327. return QueryEndAtConstraint._create('endBefore', docOrFields,
  7328. /*inclusive=*/ false);
  7329. }
  7330. function endAt(...docOrFields) {
  7331. return QueryEndAtConstraint._create('endAt', docOrFields,
  7332. /*inclusive=*/ true);
  7333. }
  7334. /** Helper function to create a bound from a document or fields */
  7335. function newQueryBoundFromDocOrFields(query, methodName, docOrFields, inclusive) {
  7336. docOrFields[0] = util.getModularInstance(docOrFields[0]);
  7337. if (docOrFields[0] instanceof DocumentSnapshot) {
  7338. return newQueryBoundFromDocument(query._query, query.firestore._databaseId, methodName, docOrFields[0]._document, inclusive);
  7339. }
  7340. else {
  7341. const reader = newUserDataReader(query.firestore);
  7342. return newQueryBoundFromFields(query._query, query.firestore._databaseId, reader, methodName, docOrFields, inclusive);
  7343. }
  7344. }
  7345. function newQueryFilter(query, methodName, dataReader, databaseId, fieldPath, op, value) {
  7346. let fieldValue;
  7347. if (fieldPath.isKeyField()) {
  7348. if (op === "array-contains" /* Operator.ARRAY_CONTAINS */ || op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
  7349. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid Query. You can't perform '${op}' queries on documentId().`);
  7350. }
  7351. else if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) {
  7352. validateDisjunctiveFilterElements(value, op);
  7353. const referenceList = [];
  7354. for (const arrayValue of value) {
  7355. referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue));
  7356. }
  7357. fieldValue = { arrayValue: { values: referenceList } };
  7358. }
  7359. else {
  7360. fieldValue = parseDocumentIdValue(databaseId, query, value);
  7361. }
  7362. }
  7363. else {
  7364. if (op === "in" /* Operator.IN */ ||
  7365. op === "not-in" /* Operator.NOT_IN */ ||
  7366. op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
  7367. validateDisjunctiveFilterElements(value, op);
  7368. }
  7369. fieldValue = parseQueryValue(dataReader, methodName, value,
  7370. /* allowArrays= */ op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */);
  7371. }
  7372. const filter = FieldFilter.create(fieldPath, op, fieldValue);
  7373. return filter;
  7374. }
  7375. function newQueryOrderBy(query, fieldPath, direction) {
  7376. if (query.startAt !== null) {
  7377. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call startAt() or startAfter() before ' +
  7378. 'calling orderBy().');
  7379. }
  7380. if (query.endAt !== null) {
  7381. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call endAt() or endBefore() before ' +
  7382. 'calling orderBy().');
  7383. }
  7384. const orderBy = new OrderBy(fieldPath, direction);
  7385. validateNewOrderBy(query, orderBy);
  7386. return orderBy;
  7387. }
  7388. /**
  7389. * Create a `Bound` from a query and a document.
  7390. *
  7391. * Note that the `Bound` will always include the key of the document
  7392. * and so only the provided document will compare equal to the returned
  7393. * position.
  7394. *
  7395. * Will throw if the document does not contain all fields of the order by
  7396. * of the query or if any of the fields in the order by are an uncommitted
  7397. * server timestamp.
  7398. */
  7399. function newQueryBoundFromDocument(query, databaseId, methodName, doc, inclusive) {
  7400. if (!doc) {
  7401. throw new FirestoreError(Code.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ` +
  7402. `${methodName}().`);
  7403. }
  7404. const components = [];
  7405. // Because people expect to continue/end a query at the exact document
  7406. // provided, we need to use the implicit sort order rather than the explicit
  7407. // sort order, because it's guaranteed to contain the document key. That way
  7408. // the position becomes unambiguous and the query continues/ends exactly at
  7409. // the provided document. Without the key (by using the explicit sort
  7410. // orders), multiple documents could match the position, yielding duplicate
  7411. // results.
  7412. for (const orderBy of queryOrderBy(query)) {
  7413. if (orderBy.field.isKeyField()) {
  7414. components.push(refValue(databaseId, doc.key));
  7415. }
  7416. else {
  7417. const value = doc.data.field(orderBy.field);
  7418. if (isServerTimestamp(value)) {
  7419. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a ' +
  7420. 'document for which the field "' +
  7421. orderBy.field +
  7422. '" is an uncommitted server timestamp. (Since the value of ' +
  7423. 'this field is unknown, you cannot start/end a query with it.)');
  7424. }
  7425. else if (value !== null) {
  7426. components.push(value);
  7427. }
  7428. else {
  7429. const field = orderBy.field.canonicalString();
  7430. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a ` +
  7431. `document for which the field '${field}' (used as the ` +
  7432. `orderBy) does not exist.`);
  7433. }
  7434. }
  7435. }
  7436. return new Bound(components, inclusive);
  7437. }
  7438. /**
  7439. * Converts a list of field values to a `Bound` for the given query.
  7440. */
  7441. function newQueryBoundFromFields(query, databaseId, dataReader, methodName, values, inclusive) {
  7442. // Use explicit order by's because it has to match the query the user made
  7443. const orderBy = query.explicitOrderBy;
  7444. if (values.length > orderBy.length) {
  7445. throw new FirestoreError(Code.INVALID_ARGUMENT, `Too many arguments provided to ${methodName}(). ` +
  7446. `The number of arguments must be less than or equal to the ` +
  7447. `number of orderBy() clauses`);
  7448. }
  7449. const components = [];
  7450. for (let i = 0; i < values.length; i++) {
  7451. const rawValue = values[i];
  7452. const orderByComponent = orderBy[i];
  7453. if (orderByComponent.field.isKeyField()) {
  7454. if (typeof rawValue !== 'string') {
  7455. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ` +
  7456. `${methodName}(), but got a ${typeof rawValue}`);
  7457. }
  7458. if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) {
  7459. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), ` +
  7460. `the value passed to ${methodName}() must be a plain document ID, but ` +
  7461. `'${rawValue}' contains a slash.`);
  7462. }
  7463. const path = query.path.child(ResourcePath.fromString(rawValue));
  7464. if (!DocumentKey.isDocumentKey(path)) {
  7465. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by ` +
  7466. `documentId(), the value passed to ${methodName}() must result in a ` +
  7467. `valid document path, but '${path}' is not because it contains an odd number ` +
  7468. `of segments.`);
  7469. }
  7470. const key = new DocumentKey(path);
  7471. components.push(refValue(databaseId, key));
  7472. }
  7473. else {
  7474. const wrapped = parseQueryValue(dataReader, methodName, rawValue);
  7475. components.push(wrapped);
  7476. }
  7477. }
  7478. return new Bound(components, inclusive);
  7479. }
  7480. /**
  7481. * Parses the given `documentIdValue` into a `ReferenceValue`, throwing
  7482. * appropriate errors if the value is anything other than a `DocumentReference`
  7483. * or `string`, or if the string is malformed.
  7484. */
  7485. function parseDocumentIdValue(databaseId, query, documentIdValue) {
  7486. documentIdValue = util.getModularInstance(documentIdValue);
  7487. if (typeof documentIdValue === 'string') {
  7488. if (documentIdValue === '') {
  7489. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. When querying with documentId(), you ' +
  7490. 'must provide a valid document ID, but it was an empty string.');
  7491. }
  7492. if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) {
  7493. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection by ` +
  7494. `documentId(), you must provide a plain document ID, but ` +
  7495. `'${documentIdValue}' contains a '/' character.`);
  7496. }
  7497. const path = query.path.child(ResourcePath.fromString(documentIdValue));
  7498. if (!DocumentKey.isDocumentKey(path)) {
  7499. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group by ` +
  7500. `documentId(), the value provided must result in a valid document path, ` +
  7501. `but '${path}' is not because it has an odd number of segments (${path.length}).`);
  7502. }
  7503. return refValue(databaseId, new DocumentKey(path));
  7504. }
  7505. else if (documentIdValue instanceof DocumentReference) {
  7506. return refValue(databaseId, documentIdValue._key);
  7507. }
  7508. else {
  7509. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid ` +
  7510. `string or a DocumentReference, but it was: ` +
  7511. `${valueDescription(documentIdValue)}.`);
  7512. }
  7513. }
  7514. /**
  7515. * Validates that the value passed into a disjunctive filter satisfies all
  7516. * array requirements.
  7517. */
  7518. function validateDisjunctiveFilterElements(value, operator) {
  7519. if (!Array.isArray(value) || value.length === 0) {
  7520. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid Query. A non-empty array is required for ' +
  7521. `'${operator.toString()}' filters.`);
  7522. }
  7523. if (value.length > 10) {
  7524. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid Query. '${operator.toString()}' filters support a ` +
  7525. 'maximum of 10 elements in the value array.');
  7526. }
  7527. }
  7528. /**
  7529. * Given an operator, returns the set of operators that cannot be used with it.
  7530. *
  7531. * Operators in a query must adhere to the following set of rules:
  7532. * 1. Only one array operator is allowed.
  7533. * 2. Only one disjunctive operator is allowed.
  7534. * 3. `NOT_EQUAL` cannot be used with another `NOT_EQUAL` operator.
  7535. * 4. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.
  7536. *
  7537. * Array operators: `ARRAY_CONTAINS`, `ARRAY_CONTAINS_ANY`
  7538. * Disjunctive operators: `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`
  7539. */
  7540. function conflictingOps(op) {
  7541. switch (op) {
  7542. case "!=" /* Operator.NOT_EQUAL */:
  7543. return ["!=" /* Operator.NOT_EQUAL */, "not-in" /* Operator.NOT_IN */];
  7544. case "array-contains" /* Operator.ARRAY_CONTAINS */:
  7545. return [
  7546. "array-contains" /* Operator.ARRAY_CONTAINS */,
  7547. "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */,
  7548. "not-in" /* Operator.NOT_IN */
  7549. ];
  7550. case "in" /* Operator.IN */:
  7551. return ["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, "in" /* Operator.IN */, "not-in" /* Operator.NOT_IN */];
  7552. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */:
  7553. return [
  7554. "array-contains" /* Operator.ARRAY_CONTAINS */,
  7555. "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */,
  7556. "in" /* Operator.IN */,
  7557. "not-in" /* Operator.NOT_IN */
  7558. ];
  7559. case "not-in" /* Operator.NOT_IN */:
  7560. return [
  7561. "array-contains" /* Operator.ARRAY_CONTAINS */,
  7562. "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */,
  7563. "in" /* Operator.IN */,
  7564. "not-in" /* Operator.NOT_IN */,
  7565. "!=" /* Operator.NOT_EQUAL */
  7566. ];
  7567. default:
  7568. return [];
  7569. }
  7570. }
  7571. function validateNewFieldFilter(query, fieldFilter) {
  7572. if (fieldFilter.isInequality()) {
  7573. const existingInequality = getInequalityFilterField(query);
  7574. const newInequality = fieldFilter.field;
  7575. if (existingInequality !== null &&
  7576. !existingInequality.isEqual(newInequality)) {
  7577. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +
  7578. ' (<, <=, !=, not-in, >, or >=) must be on the same field. But you have' +
  7579. ` inequality filters on '${existingInequality.toString()}'` +
  7580. ` and '${newInequality.toString()}'`);
  7581. }
  7582. const firstOrderByField = getFirstOrderByField(query);
  7583. if (firstOrderByField !== null) {
  7584. validateOrderByAndInequalityMatch(query, newInequality, firstOrderByField);
  7585. }
  7586. }
  7587. const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op));
  7588. if (conflictingOp !== null) {
  7589. // Special case when it's a duplicate op to give a slightly clearer error message.
  7590. if (conflictingOp === fieldFilter.op) {
  7591. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You cannot use more than one ' +
  7592. `'${fieldFilter.op.toString()}' filter.`);
  7593. }
  7594. else {
  7595. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +
  7596. `with '${conflictingOp.toString()}' filters.`);
  7597. }
  7598. }
  7599. }
  7600. function validateNewFilter(query, filter) {
  7601. let testQuery = query;
  7602. const subFilters = filter.getFlattenedFilters();
  7603. for (const subFilter of subFilters) {
  7604. validateNewFieldFilter(testQuery, subFilter);
  7605. testQuery = queryWithAddedFilter(testQuery, subFilter);
  7606. }
  7607. }
  7608. // Checks if any of the provided filter operators are included in the given list of filters and
  7609. // returns the first one that is, or null if none are.
  7610. function findOpInsideFilters(filters, operators) {
  7611. for (const filter of filters) {
  7612. for (const fieldFilter of filter.getFlattenedFilters()) {
  7613. if (operators.indexOf(fieldFilter.op) >= 0) {
  7614. return fieldFilter.op;
  7615. }
  7616. }
  7617. }
  7618. return null;
  7619. }
  7620. function validateNewOrderBy(query, orderBy) {
  7621. if (getFirstOrderByField(query) === null) {
  7622. // This is the first order by. It must match any inequality.
  7623. const inequalityField = getInequalityFilterField(query);
  7624. if (inequalityField !== null) {
  7625. validateOrderByAndInequalityMatch(query, inequalityField, orderBy.field);
  7626. }
  7627. }
  7628. }
  7629. function validateOrderByAndInequalityMatch(baseQuery, inequality, orderBy) {
  7630. if (!orderBy.isEqual(inequality)) {
  7631. throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality ` +
  7632. `(<, <=, !=, not-in, >, or >=) on field '${inequality.toString()}' ` +
  7633. `and so you must also use '${inequality.toString()}' ` +
  7634. `as your first argument to orderBy(), but your first orderBy() ` +
  7635. `is on field '${orderBy.toString()}' instead.`);
  7636. }
  7637. }
  7638. function validateQueryFilterConstraint(functionName, queryConstraint) {
  7639. if (!(queryConstraint instanceof QueryFieldFilterConstraint) &&
  7640. !(queryConstraint instanceof QueryCompositeFilterConstraint)) {
  7641. throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
  7642. }
  7643. }
  7644. function validateQueryConstraintArray(queryConstraint) {
  7645. const compositeFilterCount = queryConstraint.filter(filter => filter instanceof QueryCompositeFilterConstraint).length;
  7646. const fieldFilterCount = queryConstraint.filter(filter => filter instanceof QueryFieldFilterConstraint).length;
  7647. if (compositeFilterCount > 1 ||
  7648. (compositeFilterCount > 0 && fieldFilterCount > 0)) {
  7649. throw new FirestoreError(Code.INVALID_ARGUMENT, 'InvalidQuery. When using composite filters, you cannot use ' +
  7650. 'more than one filter at the top level. Consider nesting the multiple ' +
  7651. 'filters within an `and(...)` statement. For example: ' +
  7652. 'change `query(query, where(...), or(...))` to ' +
  7653. '`query(query, and(where(...), or(...)))`.');
  7654. }
  7655. }
  7656. /**
  7657. * @license
  7658. * Copyright 2020 Google LLC
  7659. *
  7660. * Licensed under the Apache License, Version 2.0 (the "License");
  7661. * you may not use this file except in compliance with the License.
  7662. * You may obtain a copy of the License at
  7663. *
  7664. * http://www.apache.org/licenses/LICENSE-2.0
  7665. *
  7666. * Unless required by applicable law or agreed to in writing, software
  7667. * distributed under the License is distributed on an "AS IS" BASIS,
  7668. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7669. * See the License for the specific language governing permissions and
  7670. * limitations under the License.
  7671. */
  7672. /**
  7673. * Converts Firestore's internal types to the JavaScript types that we expose
  7674. * to the user.
  7675. *
  7676. * @internal
  7677. */
  7678. class AbstractUserDataWriter {
  7679. convertValue(value, serverTimestampBehavior = 'none') {
  7680. switch (typeOrder(value)) {
  7681. case 0 /* TypeOrder.NullValue */:
  7682. return null;
  7683. case 1 /* TypeOrder.BooleanValue */:
  7684. return value.booleanValue;
  7685. case 2 /* TypeOrder.NumberValue */:
  7686. return normalizeNumber(value.integerValue || value.doubleValue);
  7687. case 3 /* TypeOrder.TimestampValue */:
  7688. return this.convertTimestamp(value.timestampValue);
  7689. case 4 /* TypeOrder.ServerTimestampValue */:
  7690. return this.convertServerTimestamp(value, serverTimestampBehavior);
  7691. case 5 /* TypeOrder.StringValue */:
  7692. return value.stringValue;
  7693. case 6 /* TypeOrder.BlobValue */:
  7694. return this.convertBytes(normalizeByteString(value.bytesValue));
  7695. case 7 /* TypeOrder.RefValue */:
  7696. return this.convertReference(value.referenceValue);
  7697. case 8 /* TypeOrder.GeoPointValue */:
  7698. return this.convertGeoPoint(value.geoPointValue);
  7699. case 9 /* TypeOrder.ArrayValue */:
  7700. return this.convertArray(value.arrayValue, serverTimestampBehavior);
  7701. case 10 /* TypeOrder.ObjectValue */:
  7702. return this.convertObject(value.mapValue, serverTimestampBehavior);
  7703. default:
  7704. throw fail();
  7705. }
  7706. }
  7707. convertObject(mapValue, serverTimestampBehavior) {
  7708. const result = {};
  7709. forEach(mapValue.fields, (key, value) => {
  7710. result[key] = this.convertValue(value, serverTimestampBehavior);
  7711. });
  7712. return result;
  7713. }
  7714. convertGeoPoint(value) {
  7715. return new GeoPoint(normalizeNumber(value.latitude), normalizeNumber(value.longitude));
  7716. }
  7717. convertArray(arrayValue, serverTimestampBehavior) {
  7718. return (arrayValue.values || []).map(value => this.convertValue(value, serverTimestampBehavior));
  7719. }
  7720. convertServerTimestamp(value, serverTimestampBehavior) {
  7721. switch (serverTimestampBehavior) {
  7722. case 'previous':
  7723. const previousValue = getPreviousValue(value);
  7724. if (previousValue == null) {
  7725. return null;
  7726. }
  7727. return this.convertValue(previousValue, serverTimestampBehavior);
  7728. case 'estimate':
  7729. return this.convertTimestamp(getLocalWriteTime(value));
  7730. default:
  7731. return null;
  7732. }
  7733. }
  7734. convertTimestamp(value) {
  7735. const normalizedValue = normalizeTimestamp(value);
  7736. return new Timestamp(normalizedValue.seconds, normalizedValue.nanos);
  7737. }
  7738. convertDocumentKey(name, expectedDatabaseId) {
  7739. const resourcePath = ResourcePath.fromString(name);
  7740. hardAssert(isValidResourceName(resourcePath));
  7741. const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));
  7742. const key = new DocumentKey(resourcePath.popFirst(5));
  7743. if (!databaseId.isEqual(expectedDatabaseId)) {
  7744. // TODO(b/64130202): Somehow support foreign references.
  7745. logError(`Document ${key} contains a document ` +
  7746. `reference within a different database (` +
  7747. `${databaseId.projectId}/${databaseId.database}) which is not ` +
  7748. `supported. It will be treated as a reference in the current ` +
  7749. `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +
  7750. `instead.`);
  7751. }
  7752. return key;
  7753. }
  7754. }
  7755. /**
  7756. * @license
  7757. * Copyright 2020 Google LLC
  7758. *
  7759. * Licensed under the Apache License, Version 2.0 (the "License");
  7760. * you may not use this file except in compliance with the License.
  7761. * You may obtain a copy of the License at
  7762. *
  7763. * http://www.apache.org/licenses/LICENSE-2.0
  7764. *
  7765. * Unless required by applicable law or agreed to in writing, software
  7766. * distributed under the License is distributed on an "AS IS" BASIS,
  7767. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7768. * See the License for the specific language governing permissions and
  7769. * limitations under the License.
  7770. */
  7771. /**
  7772. * Converts custom model object of type T into `DocumentData` by applying the
  7773. * converter if it exists.
  7774. *
  7775. * This function is used when converting user objects to `DocumentData`
  7776. * because we want to provide the user with a more specific error message if
  7777. * their `set()` or fails due to invalid data originating from a `toFirestore()`
  7778. * call.
  7779. */
  7780. function applyFirestoreDataConverter(converter, value, options) {
  7781. let convertedValue;
  7782. if (converter) {
  7783. if (options && (options.merge || options.mergeFields)) {
  7784. // Cast to `any` in order to satisfy the union type constraint on
  7785. // toFirestore().
  7786. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  7787. convertedValue = converter.toFirestore(value, options);
  7788. }
  7789. else {
  7790. convertedValue = converter.toFirestore(value);
  7791. }
  7792. }
  7793. else {
  7794. convertedValue = value;
  7795. }
  7796. return convertedValue;
  7797. }
  7798. class LiteUserDataWriter extends AbstractUserDataWriter {
  7799. constructor(firestore) {
  7800. super();
  7801. this.firestore = firestore;
  7802. }
  7803. convertBytes(bytes) {
  7804. return new Bytes(bytes);
  7805. }
  7806. convertReference(name) {
  7807. const key = this.convertDocumentKey(name, this.firestore._databaseId);
  7808. return new DocumentReference(this.firestore, /* converter= */ null, key);
  7809. }
  7810. }
  7811. /**
  7812. * Reads the document referred to by the specified document reference.
  7813. *
  7814. * All documents are directly fetched from the server, even if the document was
  7815. * previously read or modified. Recent modifications are only reflected in the
  7816. * retrieved `DocumentSnapshot` if they have already been applied by the
  7817. * backend. If the client is offline, the read fails. If you like to use
  7818. * caching or see local modifications, please use the full Firestore SDK.
  7819. *
  7820. * @param reference - The reference of the document to fetch.
  7821. * @returns A Promise resolved with a `DocumentSnapshot` containing the current
  7822. * document contents.
  7823. */
  7824. function getDoc(reference) {
  7825. reference = cast(reference, DocumentReference);
  7826. const datastore = getDatastore(reference.firestore);
  7827. const userDataWriter = new LiteUserDataWriter(reference.firestore);
  7828. return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(result => {
  7829. hardAssert(result.length === 1);
  7830. const document = result[0];
  7831. return new DocumentSnapshot(reference.firestore, userDataWriter, reference._key, document.isFoundDocument() ? document : null, reference.converter);
  7832. });
  7833. }
  7834. /**
  7835. * Executes the query and returns the results as a {@link QuerySnapshot}.
  7836. *
  7837. * All queries are executed directly by the server, even if the the query was
  7838. * previously executed. Recent modifications are only reflected in the retrieved
  7839. * results if they have already been applied by the backend. If the client is
  7840. * offline, the operation fails. To see previously cached result and local
  7841. * modifications, use the full Firestore SDK.
  7842. *
  7843. * @param query - The `Query` to execute.
  7844. * @returns A Promise that will be resolved with the results of the query.
  7845. */
  7846. function getDocs(query) {
  7847. query = cast(query, Query);
  7848. validateHasExplicitOrderByForLimitToLast(query._query);
  7849. const datastore = getDatastore(query.firestore);
  7850. const userDataWriter = new LiteUserDataWriter(query.firestore);
  7851. return invokeRunQueryRpc(datastore, query._query).then(result => {
  7852. const docs = result.map(doc => new QueryDocumentSnapshot(query.firestore, userDataWriter, doc.key, doc, query.converter));
  7853. if (query._query.limitType === "L" /* LimitType.Last */) {
  7854. // Limit to last queries reverse the orderBy constraint that was
  7855. // specified by the user. As such, we need to reverse the order of the
  7856. // results to return the documents in the expected order.
  7857. docs.reverse();
  7858. }
  7859. return new QuerySnapshot(query, docs);
  7860. });
  7861. }
  7862. function setDoc(reference, data, options) {
  7863. reference = cast(reference, DocumentReference);
  7864. const convertedValue = applyFirestoreDataConverter(reference.converter, data, options);
  7865. const dataReader = newUserDataReader(reference.firestore);
  7866. const parsed = parseSetData(dataReader, 'setDoc', reference._key, convertedValue, reference.converter !== null, options);
  7867. const datastore = getDatastore(reference.firestore);
  7868. return invokeCommitRpc(datastore, [
  7869. parsed.toMutation(reference._key, Precondition.none())
  7870. ]);
  7871. }
  7872. function updateDoc(reference, fieldOrUpdateData, value, ...moreFieldsAndValues) {
  7873. reference = cast(reference, DocumentReference);
  7874. const dataReader = newUserDataReader(reference.firestore);
  7875. // For Compat types, we have to "extract" the underlying types before
  7876. // performing validation.
  7877. fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData);
  7878. let parsed;
  7879. if (typeof fieldOrUpdateData === 'string' ||
  7880. fieldOrUpdateData instanceof FieldPath) {
  7881. parsed = parseUpdateVarargs(dataReader, 'updateDoc', reference._key, fieldOrUpdateData, value, moreFieldsAndValues);
  7882. }
  7883. else {
  7884. parsed = parseUpdateData(dataReader, 'updateDoc', reference._key, fieldOrUpdateData);
  7885. }
  7886. const datastore = getDatastore(reference.firestore);
  7887. return invokeCommitRpc(datastore, [
  7888. parsed.toMutation(reference._key, Precondition.exists(true))
  7889. ]);
  7890. }
  7891. /**
  7892. * Deletes the document referred to by the specified `DocumentReference`.
  7893. *
  7894. * The deletion will only be reflected in document reads that occur after the
  7895. * returned promise resolves. If the client is offline, the
  7896. * delete fails. If you would like to see local modifications or buffer writes
  7897. * until the client is online, use the full Firestore SDK.
  7898. *
  7899. * @param reference - A reference to the document to delete.
  7900. * @returns A `Promise` resolved once the document has been successfully
  7901. * deleted from the backend.
  7902. */
  7903. function deleteDoc(reference) {
  7904. reference = cast(reference, DocumentReference);
  7905. const datastore = getDatastore(reference.firestore);
  7906. return invokeCommitRpc(datastore, [
  7907. new DeleteMutation(reference._key, Precondition.none())
  7908. ]);
  7909. }
  7910. /**
  7911. * Add a new document to specified `CollectionReference` with the given data,
  7912. * assigning it a document ID automatically.
  7913. *
  7914. * The result of this write will only be reflected in document reads that occur
  7915. * after the returned promise resolves. If the client is offline, the
  7916. * write fails. If you would like to see local modifications or buffer writes
  7917. * until the client is online, use the full Firestore SDK.
  7918. *
  7919. * @param reference - A reference to the collection to add this document to.
  7920. * @param data - An Object containing the data for the new document.
  7921. * @throws Error - If the provided input is not a valid Firestore document.
  7922. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  7923. * newly created document after it has been written to the backend.
  7924. */
  7925. function addDoc(reference, data) {
  7926. reference = cast(reference, CollectionReference);
  7927. const docRef = doc(reference);
  7928. const convertedValue = applyFirestoreDataConverter(reference.converter, data);
  7929. const dataReader = newUserDataReader(reference.firestore);
  7930. const parsed = parseSetData(dataReader, 'addDoc', docRef._key, convertedValue, docRef.converter !== null, {});
  7931. const datastore = getDatastore(reference.firestore);
  7932. return invokeCommitRpc(datastore, [
  7933. parsed.toMutation(docRef._key, Precondition.exists(false))
  7934. ]).then(() => docRef);
  7935. }
  7936. /**
  7937. * @license
  7938. * Copyright 2022 Google LLC
  7939. *
  7940. * Licensed under the Apache License, Version 2.0 (the "License");
  7941. * you may not use this file except in compliance with the License.
  7942. * You may obtain a copy of the License at
  7943. *
  7944. * http://www.apache.org/licenses/LICENSE-2.0
  7945. *
  7946. * Unless required by applicable law or agreed to in writing, software
  7947. * distributed under the License is distributed on an "AS IS" BASIS,
  7948. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7949. * See the License for the specific language governing permissions and
  7950. * limitations under the License.
  7951. */
  7952. /**
  7953. * Calculates the number of documents in the result set of the given query,
  7954. * without actually downloading the documents.
  7955. *
  7956. * Using this function to count the documents is efficient because only the
  7957. * final count, not the documents' data, is downloaded. This function can even
  7958. * count the documents if the result set would be prohibitively large to
  7959. * download entirely (e.g. thousands of documents).
  7960. *
  7961. * @param query - The query whose result set size to calculate.
  7962. * @returns A Promise that will be resolved with the count; the count can be
  7963. * retrieved from `snapshot.data().count`, where `snapshot` is the
  7964. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  7965. */
  7966. function getCount(query) {
  7967. const firestore = cast(query.firestore, Firestore);
  7968. const datastore = getDatastore(firestore);
  7969. const userDataWriter = new LiteUserDataWriter(firestore);
  7970. return new CountQueryRunner(query, datastore, userDataWriter).run();
  7971. }
  7972. /**
  7973. * Compares two `AggregateQuerySnapshot` instances for equality.
  7974. *
  7975. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  7976. * underlying queries that compare equal, and the same data.
  7977. *
  7978. * @param left - The first `AggregateQuerySnapshot` to compare.
  7979. * @param right - The second `AggregateQuerySnapshot` to compare.
  7980. *
  7981. * @returns `true` if the objects are "equal", as defined above, or `false`
  7982. * otherwise.
  7983. */
  7984. function aggregateQuerySnapshotEqual(left, right) {
  7985. return (queryEqual(left.query, right.query) && util.deepEqual(left.data(), right.data()));
  7986. }
  7987. /**
  7988. * @license
  7989. * Copyright 2020 Google LLC
  7990. *
  7991. * Licensed under the Apache License, Version 2.0 (the "License");
  7992. * you may not use this file except in compliance with the License.
  7993. * You may obtain a copy of the License at
  7994. *
  7995. * http://www.apache.org/licenses/LICENSE-2.0
  7996. *
  7997. * Unless required by applicable law or agreed to in writing, software
  7998. * distributed under the License is distributed on an "AS IS" BASIS,
  7999. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8000. * See the License for the specific language governing permissions and
  8001. * limitations under the License.
  8002. */
  8003. /**
  8004. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  8005. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  8006. */
  8007. function deleteField() {
  8008. return new DeleteFieldValueImpl('deleteField');
  8009. }
  8010. /**
  8011. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  8012. * include a server-generated timestamp in the written data.
  8013. */
  8014. function serverTimestamp() {
  8015. return new ServerTimestampFieldValueImpl('serverTimestamp');
  8016. }
  8017. /**
  8018. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  8019. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  8020. * value that already exists on the server. Each specified element that doesn't
  8021. * already exist in the array will be added to the end. If the field being
  8022. * modified is not already an array it will be overwritten with an array
  8023. * containing exactly the specified elements.
  8024. *
  8025. * @param elements - The elements to union into the array.
  8026. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  8027. * `updateDoc()`.
  8028. */
  8029. function arrayUnion(...elements) {
  8030. // NOTE: We don't actually parse the data until it's used in set() or
  8031. // update() since we'd need the Firestore instance to do this.
  8032. return new ArrayUnionFieldValueImpl('arrayUnion', elements);
  8033. }
  8034. /**
  8035. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  8036. * updateDoc:1} that tells the server to remove the given elements from any
  8037. * array value that already exists on the server. All instances of each element
  8038. * specified will be removed from the array. If the field being modified is not
  8039. * already an array it will be overwritten with an empty array.
  8040. *
  8041. * @param elements - The elements to remove from the array.
  8042. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  8043. * `updateDoc()`
  8044. */
  8045. function arrayRemove(...elements) {
  8046. // NOTE: We don't actually parse the data until it's used in set() or
  8047. // update() since we'd need the Firestore instance to do this.
  8048. return new ArrayRemoveFieldValueImpl('arrayRemove', elements);
  8049. }
  8050. /**
  8051. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  8052. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  8053. * the given value.
  8054. *
  8055. * If either the operand or the current field value uses floating point
  8056. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  8057. * integers, values outside of JavaScript's safe number range
  8058. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  8059. * precision loss. Furthermore, once processed by the Firestore backend, all
  8060. * integer operations are capped between -2^63 and 2^63-1.
  8061. *
  8062. * If the current field value is not of type `number`, or if the field does not
  8063. * yet exist, the transformation sets the field to the given value.
  8064. *
  8065. * @param n - The value to increment by.
  8066. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  8067. * `updateDoc()`
  8068. */
  8069. function increment(n) {
  8070. return new NumericIncrementFieldValueImpl('increment', n);
  8071. }
  8072. /**
  8073. * @license
  8074. * Copyright 2020 Google LLC
  8075. *
  8076. * Licensed under the Apache License, Version 2.0 (the "License");
  8077. * you may not use this file except in compliance with the License.
  8078. * You may obtain a copy of the License at
  8079. *
  8080. * http://www.apache.org/licenses/LICENSE-2.0
  8081. *
  8082. * Unless required by applicable law or agreed to in writing, software
  8083. * distributed under the License is distributed on an "AS IS" BASIS,
  8084. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8085. * See the License for the specific language governing permissions and
  8086. * limitations under the License.
  8087. */
  8088. /**
  8089. * A write batch, used to perform multiple writes as a single atomic unit.
  8090. *
  8091. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  8092. * provides methods for adding writes to the write batch. None of the writes
  8093. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  8094. * called.
  8095. */
  8096. class WriteBatch {
  8097. /** @hideconstructor */
  8098. constructor(_firestore, _commitHandler) {
  8099. this._firestore = _firestore;
  8100. this._commitHandler = _commitHandler;
  8101. this._mutations = [];
  8102. this._committed = false;
  8103. this._dataReader = newUserDataReader(_firestore);
  8104. }
  8105. set(documentRef, data, options) {
  8106. this._verifyNotCommitted();
  8107. const ref = validateReference(documentRef, this._firestore);
  8108. const convertedValue = applyFirestoreDataConverter(ref.converter, data, options);
  8109. const parsed = parseSetData(this._dataReader, 'WriteBatch.set', ref._key, convertedValue, ref.converter !== null, options);
  8110. this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));
  8111. return this;
  8112. }
  8113. update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) {
  8114. this._verifyNotCommitted();
  8115. const ref = validateReference(documentRef, this._firestore);
  8116. // For Compat types, we have to "extract" the underlying types before
  8117. // performing validation.
  8118. fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData);
  8119. let parsed;
  8120. if (typeof fieldOrUpdateData === 'string' ||
  8121. fieldOrUpdateData instanceof FieldPath) {
  8122. parsed = parseUpdateVarargs(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues);
  8123. }
  8124. else {
  8125. parsed = parseUpdateData(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData);
  8126. }
  8127. this._mutations.push(parsed.toMutation(ref._key, Precondition.exists(true)));
  8128. return this;
  8129. }
  8130. /**
  8131. * Deletes the document referred to by the provided {@link DocumentReference}.
  8132. *
  8133. * @param documentRef - A reference to the document to be deleted.
  8134. * @returns This `WriteBatch` instance. Used for chaining method calls.
  8135. */
  8136. delete(documentRef) {
  8137. this._verifyNotCommitted();
  8138. const ref = validateReference(documentRef, this._firestore);
  8139. this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.none()));
  8140. return this;
  8141. }
  8142. /**
  8143. * Commits all of the writes in this write batch as a single atomic unit.
  8144. *
  8145. * The result of these writes will only be reflected in document reads that
  8146. * occur after the returned promise resolves. If the client is offline, the
  8147. * write fails. If you would like to see local modifications or buffer writes
  8148. * until the client is online, use the full Firestore SDK.
  8149. *
  8150. * @returns A `Promise` resolved once all of the writes in the batch have been
  8151. * successfully written to the backend as an atomic unit (note that it won't
  8152. * resolve while you're offline).
  8153. */
  8154. commit() {
  8155. this._verifyNotCommitted();
  8156. this._committed = true;
  8157. if (this._mutations.length > 0) {
  8158. return this._commitHandler(this._mutations);
  8159. }
  8160. return Promise.resolve();
  8161. }
  8162. _verifyNotCommitted() {
  8163. if (this._committed) {
  8164. throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' +
  8165. 'has been called.');
  8166. }
  8167. }
  8168. }
  8169. function validateReference(documentRef, firestore) {
  8170. documentRef = util.getModularInstance(documentRef);
  8171. if (documentRef.firestore !== firestore) {
  8172. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');
  8173. }
  8174. else {
  8175. return documentRef;
  8176. }
  8177. }
  8178. /**
  8179. * Creates a write batch, used for performing multiple writes as a single
  8180. * atomic operation. The maximum number of writes allowed in a single WriteBatch
  8181. * is 500.
  8182. *
  8183. * The result of these writes will only be reflected in document reads that
  8184. * occur after the returned promise resolves. If the client is offline, the
  8185. * write fails. If you would like to see local modifications or buffer writes
  8186. * until the client is online, use the full Firestore SDK.
  8187. *
  8188. * @returns A `WriteBatch` that can be used to atomically execute multiple
  8189. * writes.
  8190. */
  8191. function writeBatch(firestore) {
  8192. firestore = cast(firestore, Firestore);
  8193. const datastore = getDatastore(firestore);
  8194. return new WriteBatch(firestore, writes => invokeCommitRpc(datastore, writes));
  8195. }
  8196. /**
  8197. * @license
  8198. * Copyright 2022 Google LLC
  8199. *
  8200. * Licensed under the Apache License, Version 2.0 (the "License");
  8201. * you may not use this file except in compliance with the License.
  8202. * You may obtain a copy of the License at
  8203. *
  8204. * http://www.apache.org/licenses/LICENSE-2.0
  8205. *
  8206. * Unless required by applicable law or agreed to in writing, software
  8207. * distributed under the License is distributed on an "AS IS" BASIS,
  8208. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8209. * See the License for the specific language governing permissions and
  8210. * limitations under the License.
  8211. */
  8212. const DEFAULT_TRANSACTION_OPTIONS = {
  8213. maxAttempts: 5
  8214. };
  8215. function validateTransactionOptions(options) {
  8216. if (options.maxAttempts < 1) {
  8217. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Max attempts must be at least 1');
  8218. }
  8219. }
  8220. /**
  8221. * @license
  8222. * Copyright 2017 Google LLC
  8223. *
  8224. * Licensed under the Apache License, Version 2.0 (the "License");
  8225. * you may not use this file except in compliance with the License.
  8226. * You may obtain a copy of the License at
  8227. *
  8228. * http://www.apache.org/licenses/LICENSE-2.0
  8229. *
  8230. * Unless required by applicable law or agreed to in writing, software
  8231. * distributed under the License is distributed on an "AS IS" BASIS,
  8232. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8233. * See the License for the specific language governing permissions and
  8234. * limitations under the License.
  8235. */
  8236. /**
  8237. * Internal transaction object responsible for accumulating the mutations to
  8238. * perform and the base versions for any documents read.
  8239. */
  8240. class Transaction$1 {
  8241. constructor(datastore) {
  8242. this.datastore = datastore;
  8243. // The version of each document that was read during this transaction.
  8244. this.readVersions = new Map();
  8245. this.mutations = [];
  8246. this.committed = false;
  8247. /**
  8248. * A deferred usage error that occurred previously in this transaction that
  8249. * will cause the transaction to fail once it actually commits.
  8250. */
  8251. this.lastWriteError = null;
  8252. /**
  8253. * Set of documents that have been written in the transaction.
  8254. *
  8255. * When there's more than one write to the same key in a transaction, any
  8256. * writes after the first are handled differently.
  8257. */
  8258. this.writtenDocs = new Set();
  8259. }
  8260. async lookup(keys) {
  8261. this.ensureCommitNotCalled();
  8262. if (this.mutations.length > 0) {
  8263. throw new FirestoreError(Code.INVALID_ARGUMENT, 'Firestore transactions require all reads to be executed before all writes.');
  8264. }
  8265. const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);
  8266. docs.forEach(doc => this.recordVersion(doc));
  8267. return docs;
  8268. }
  8269. set(key, data) {
  8270. this.write(data.toMutation(key, this.precondition(key)));
  8271. this.writtenDocs.add(key.toString());
  8272. }
  8273. update(key, data) {
  8274. try {
  8275. this.write(data.toMutation(key, this.preconditionForUpdate(key)));
  8276. }
  8277. catch (e) {
  8278. this.lastWriteError = e;
  8279. }
  8280. this.writtenDocs.add(key.toString());
  8281. }
  8282. delete(key) {
  8283. this.write(new DeleteMutation(key, this.precondition(key)));
  8284. this.writtenDocs.add(key.toString());
  8285. }
  8286. async commit() {
  8287. this.ensureCommitNotCalled();
  8288. if (this.lastWriteError) {
  8289. throw this.lastWriteError;
  8290. }
  8291. const unwritten = this.readVersions;
  8292. // For each mutation, note that the doc was written.
  8293. this.mutations.forEach(mutation => {
  8294. unwritten.delete(mutation.key.toString());
  8295. });
  8296. // For each document that was read but not written to, we want to perform
  8297. // a `verify` operation.
  8298. unwritten.forEach((_, path) => {
  8299. const key = DocumentKey.fromPath(path);
  8300. this.mutations.push(new VerifyMutation(key, this.precondition(key)));
  8301. });
  8302. await invokeCommitRpc(this.datastore, this.mutations);
  8303. this.committed = true;
  8304. }
  8305. recordVersion(doc) {
  8306. let docVersion;
  8307. if (doc.isFoundDocument()) {
  8308. docVersion = doc.version;
  8309. }
  8310. else if (doc.isNoDocument()) {
  8311. // Represent a deleted doc using SnapshotVersion.min().
  8312. docVersion = SnapshotVersion.min();
  8313. }
  8314. else {
  8315. throw fail();
  8316. }
  8317. const existingVersion = this.readVersions.get(doc.key.toString());
  8318. if (existingVersion) {
  8319. if (!docVersion.isEqual(existingVersion)) {
  8320. // This transaction will fail no matter what.
  8321. throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.');
  8322. }
  8323. }
  8324. else {
  8325. this.readVersions.set(doc.key.toString(), docVersion);
  8326. }
  8327. }
  8328. /**
  8329. * Returns the version of this document when it was read in this transaction,
  8330. * as a precondition, or no precondition if it was not read.
  8331. */
  8332. precondition(key) {
  8333. const version = this.readVersions.get(key.toString());
  8334. if (!this.writtenDocs.has(key.toString()) && version) {
  8335. if (version.isEqual(SnapshotVersion.min())) {
  8336. return Precondition.exists(false);
  8337. }
  8338. else {
  8339. return Precondition.updateTime(version);
  8340. }
  8341. }
  8342. else {
  8343. return Precondition.none();
  8344. }
  8345. }
  8346. /**
  8347. * Returns the precondition for a document if the operation is an update.
  8348. */
  8349. preconditionForUpdate(key) {
  8350. const version = this.readVersions.get(key.toString());
  8351. // The first time a document is written, we want to take into account the
  8352. // read time and existence
  8353. if (!this.writtenDocs.has(key.toString()) && version) {
  8354. if (version.isEqual(SnapshotVersion.min())) {
  8355. // The document doesn't exist, so fail the transaction.
  8356. // This has to be validated locally because you can't send a
  8357. // precondition that a document does not exist without changing the
  8358. // semantics of the backend write to be an insert. This is the reverse
  8359. // of what we want, since we want to assert that the document doesn't
  8360. // exist but then send the update and have it fail. Since we can't
  8361. // express that to the backend, we have to validate locally.
  8362. // Note: this can change once we can send separate verify writes in the
  8363. // transaction.
  8364. throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
  8365. }
  8366. // Document exists, base precondition on document update time.
  8367. return Precondition.updateTime(version);
  8368. }
  8369. else {
  8370. // Document was not read, so we just use the preconditions for a blind
  8371. // update.
  8372. return Precondition.exists(true);
  8373. }
  8374. }
  8375. write(mutation) {
  8376. this.ensureCommitNotCalled();
  8377. this.mutations.push(mutation);
  8378. }
  8379. ensureCommitNotCalled() {
  8380. }
  8381. }
  8382. /**
  8383. * @license
  8384. * Copyright 2019 Google LLC
  8385. *
  8386. * Licensed under the Apache License, Version 2.0 (the "License");
  8387. * you may not use this file except in compliance with the License.
  8388. * You may obtain a copy of the License at
  8389. *
  8390. * http://www.apache.org/licenses/LICENSE-2.0
  8391. *
  8392. * Unless required by applicable law or agreed to in writing, software
  8393. * distributed under the License is distributed on an "AS IS" BASIS,
  8394. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8395. * See the License for the specific language governing permissions and
  8396. * limitations under the License.
  8397. */
  8398. /**
  8399. * TransactionRunner encapsulates the logic needed to run and retry transactions
  8400. * with backoff.
  8401. */
  8402. class TransactionRunner {
  8403. constructor(asyncQueue, datastore, options, updateFunction, deferred) {
  8404. this.asyncQueue = asyncQueue;
  8405. this.datastore = datastore;
  8406. this.options = options;
  8407. this.updateFunction = updateFunction;
  8408. this.deferred = deferred;
  8409. this.attemptsRemaining = options.maxAttempts;
  8410. this.backoff = new ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */);
  8411. }
  8412. /** Runs the transaction and sets the result on deferred. */
  8413. run() {
  8414. this.attemptsRemaining -= 1;
  8415. this.runWithBackOff();
  8416. }
  8417. runWithBackOff() {
  8418. this.backoff.backoffAndRun(async () => {
  8419. const transaction = new Transaction$1(this.datastore);
  8420. const userPromise = this.tryRunUpdateFunction(transaction);
  8421. if (userPromise) {
  8422. userPromise
  8423. .then(result => {
  8424. this.asyncQueue.enqueueAndForget(() => {
  8425. return transaction
  8426. .commit()
  8427. .then(() => {
  8428. this.deferred.resolve(result);
  8429. })
  8430. .catch(commitError => {
  8431. this.handleTransactionError(commitError);
  8432. });
  8433. });
  8434. })
  8435. .catch(userPromiseError => {
  8436. this.handleTransactionError(userPromiseError);
  8437. });
  8438. }
  8439. });
  8440. }
  8441. tryRunUpdateFunction(transaction) {
  8442. try {
  8443. const userPromise = this.updateFunction(transaction);
  8444. if (isNullOrUndefined(userPromise) ||
  8445. !userPromise.catch ||
  8446. !userPromise.then) {
  8447. this.deferred.reject(Error('Transaction callback must return a Promise'));
  8448. return null;
  8449. }
  8450. return userPromise;
  8451. }
  8452. catch (error) {
  8453. // Do not retry errors thrown by user provided updateFunction.
  8454. this.deferred.reject(error);
  8455. return null;
  8456. }
  8457. }
  8458. handleTransactionError(error) {
  8459. if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {
  8460. this.attemptsRemaining -= 1;
  8461. this.asyncQueue.enqueueAndForget(() => {
  8462. this.runWithBackOff();
  8463. return Promise.resolve();
  8464. });
  8465. }
  8466. else {
  8467. this.deferred.reject(error);
  8468. }
  8469. }
  8470. isRetryableTransactionError(error) {
  8471. if (error.name === 'FirebaseError') {
  8472. // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
  8473. // non-matching document versions with ABORTED. These errors should be retried.
  8474. const code = error.code;
  8475. return (code === 'aborted' ||
  8476. code === 'failed-precondition' ||
  8477. code === 'already-exists' ||
  8478. !isPermanentError(code));
  8479. }
  8480. return false;
  8481. }
  8482. }
  8483. /**
  8484. * @license
  8485. * Copyright 2017 Google LLC
  8486. *
  8487. * Licensed under the Apache License, Version 2.0 (the "License");
  8488. * you may not use this file except in compliance with the License.
  8489. * You may obtain a copy of the License at
  8490. *
  8491. * http://www.apache.org/licenses/LICENSE-2.0
  8492. *
  8493. * Unless required by applicable law or agreed to in writing, software
  8494. * distributed under the License is distributed on an "AS IS" BASIS,
  8495. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8496. * See the License for the specific language governing permissions and
  8497. * limitations under the License.
  8498. */
  8499. /**
  8500. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  8501. *
  8502. * It is created via DelayedOperation.createAndSchedule().
  8503. *
  8504. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  8505. *
  8506. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  8507. * in newer versions of TypeScript defines `finally`, which is not available in
  8508. * IE.
  8509. */
  8510. class DelayedOperation {
  8511. constructor(asyncQueue, timerId, targetTimeMs, op, removalCallback) {
  8512. this.asyncQueue = asyncQueue;
  8513. this.timerId = timerId;
  8514. this.targetTimeMs = targetTimeMs;
  8515. this.op = op;
  8516. this.removalCallback = removalCallback;
  8517. this.deferred = new Deferred();
  8518. this.then = this.deferred.promise.then.bind(this.deferred.promise);
  8519. // It's normal for the deferred promise to be canceled (due to cancellation)
  8520. // and so we attach a dummy catch callback to avoid
  8521. // 'UnhandledPromiseRejectionWarning' log spam.
  8522. this.deferred.promise.catch(err => { });
  8523. }
  8524. /**
  8525. * Creates and returns a DelayedOperation that has been scheduled to be
  8526. * executed on the provided asyncQueue after the provided delayMs.
  8527. *
  8528. * @param asyncQueue - The queue to schedule the operation on.
  8529. * @param id - A Timer ID identifying the type of operation this is.
  8530. * @param delayMs - The delay (ms) before the operation should be scheduled.
  8531. * @param op - The operation to run.
  8532. * @param removalCallback - A callback to be called synchronously once the
  8533. * operation is executed or canceled, notifying the AsyncQueue to remove it
  8534. * from its delayedOperations list.
  8535. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  8536. * the DelayedOperation class public.
  8537. */
  8538. static createAndSchedule(asyncQueue, timerId, delayMs, op, removalCallback) {
  8539. const targetTime = Date.now() + delayMs;
  8540. const delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback);
  8541. delayedOp.start(delayMs);
  8542. return delayedOp;
  8543. }
  8544. /**
  8545. * Starts the timer. This is called immediately after construction by
  8546. * createAndSchedule().
  8547. */
  8548. start(delayMs) {
  8549. this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);
  8550. }
  8551. /**
  8552. * Queues the operation to run immediately (if it hasn't already been run or
  8553. * canceled).
  8554. */
  8555. skipDelay() {
  8556. return this.handleDelayElapsed();
  8557. }
  8558. /**
  8559. * Cancels the operation if it hasn't already been executed or canceled. The
  8560. * promise will be rejected.
  8561. *
  8562. * As long as the operation has not yet been run, calling cancel() provides a
  8563. * guarantee that the operation will not be run.
  8564. */
  8565. cancel(reason) {
  8566. if (this.timerHandle !== null) {
  8567. this.clearTimeout();
  8568. this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : '')));
  8569. }
  8570. }
  8571. handleDelayElapsed() {
  8572. this.asyncQueue.enqueueAndForget(() => {
  8573. if (this.timerHandle !== null) {
  8574. this.clearTimeout();
  8575. return this.op().then(result => {
  8576. return this.deferred.resolve(result);
  8577. });
  8578. }
  8579. else {
  8580. return Promise.resolve();
  8581. }
  8582. });
  8583. }
  8584. clearTimeout() {
  8585. if (this.timerHandle !== null) {
  8586. this.removalCallback(this);
  8587. clearTimeout(this.timerHandle);
  8588. this.timerHandle = null;
  8589. }
  8590. }
  8591. }
  8592. /**
  8593. * @license
  8594. * Copyright 2020 Google LLC
  8595. *
  8596. * Licensed under the Apache License, Version 2.0 (the "License");
  8597. * you may not use this file except in compliance with the License.
  8598. * You may obtain a copy of the License at
  8599. *
  8600. * http://www.apache.org/licenses/LICENSE-2.0
  8601. *
  8602. * Unless required by applicable law or agreed to in writing, software
  8603. * distributed under the License is distributed on an "AS IS" BASIS,
  8604. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8605. * See the License for the specific language governing permissions and
  8606. * limitations under the License.
  8607. */
  8608. const LOG_TAG = 'AsyncQueue';
  8609. class AsyncQueueImpl {
  8610. constructor() {
  8611. // The last promise in the queue.
  8612. this.tail = Promise.resolve();
  8613. // A list of retryable operations. Retryable operations are run in order and
  8614. // retried with backoff.
  8615. this.retryableOps = [];
  8616. // Is this AsyncQueue being shut down? Once it is set to true, it will not
  8617. // be changed again.
  8618. this._isShuttingDown = false;
  8619. // Operations scheduled to be queued in the future. Operations are
  8620. // automatically removed after they are run or canceled.
  8621. this.delayedOperations = [];
  8622. // visible for testing
  8623. this.failure = null;
  8624. // Flag set while there's an outstanding AsyncQueue operation, used for
  8625. // assertion sanity-checks.
  8626. this.operationInProgress = false;
  8627. // Enabled during shutdown on Safari to prevent future access to IndexedDB.
  8628. this.skipNonRestrictedTasks = false;
  8629. // List of TimerIds to fast-forward delays for.
  8630. this.timerIdsToSkip = [];
  8631. // Backoff timer used to schedule retries for retryable operations
  8632. this.backoff = new ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */);
  8633. // Visibility handler that triggers an immediate retry of all retryable
  8634. // operations. Meant to speed up recovery when we regain file system access
  8635. // after page comes into foreground.
  8636. this.visibilityHandler = () => {
  8637. this.backoff.skipBackoff();
  8638. };
  8639. }
  8640. get isShuttingDown() {
  8641. return this._isShuttingDown;
  8642. }
  8643. /**
  8644. * Adds a new operation to the queue without waiting for it to complete (i.e.
  8645. * we ignore the Promise result).
  8646. */
  8647. enqueueAndForget(op) {
  8648. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  8649. this.enqueue(op);
  8650. }
  8651. enqueueAndForgetEvenWhileRestricted(op) {
  8652. this.verifyNotFailed();
  8653. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  8654. this.enqueueInternal(op);
  8655. }
  8656. enterRestrictedMode(purgeExistingTasks) {
  8657. if (!this._isShuttingDown) {
  8658. this._isShuttingDown = true;
  8659. this.skipNonRestrictedTasks = purgeExistingTasks || false;
  8660. }
  8661. }
  8662. enqueue(op) {
  8663. this.verifyNotFailed();
  8664. if (this._isShuttingDown) {
  8665. // Return a Promise which never resolves.
  8666. return new Promise(() => { });
  8667. }
  8668. // Create a deferred Promise that we can return to the callee. This
  8669. // allows us to return a "hanging Promise" only to the callee and still
  8670. // advance the queue even when the operation is not run.
  8671. const task = new Deferred();
  8672. return this.enqueueInternal(() => {
  8673. if (this._isShuttingDown && this.skipNonRestrictedTasks) {
  8674. // We do not resolve 'task'
  8675. return Promise.resolve();
  8676. }
  8677. op().then(task.resolve, task.reject);
  8678. return task.promise;
  8679. }).then(() => task.promise);
  8680. }
  8681. enqueueRetryable(op) {
  8682. this.enqueueAndForget(() => {
  8683. this.retryableOps.push(op);
  8684. return this.retryNextOp();
  8685. });
  8686. }
  8687. /**
  8688. * Runs the next operation from the retryable queue. If the operation fails,
  8689. * reschedules with backoff.
  8690. */
  8691. async retryNextOp() {
  8692. if (this.retryableOps.length === 0) {
  8693. return;
  8694. }
  8695. try {
  8696. await this.retryableOps[0]();
  8697. this.retryableOps.shift();
  8698. this.backoff.reset();
  8699. }
  8700. catch (e) {
  8701. if (isIndexedDbTransactionError(e)) {
  8702. logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);
  8703. }
  8704. else {
  8705. throw e; // Failure will be handled by AsyncQueue
  8706. }
  8707. }
  8708. if (this.retryableOps.length > 0) {
  8709. // If there are additional operations, we re-schedule `retryNextOp()`.
  8710. // This is necessary to run retryable operations that failed during
  8711. // their initial attempt since we don't know whether they are already
  8712. // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
  8713. // needs to be re-run, we will run `op1`, `op1`, `op2` using the
  8714. // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
  8715. // call scheduled here.
  8716. // Since `backoffAndRun()` cancels an existing backoff and schedules a
  8717. // new backoff on every call, there is only ever a single additional
  8718. // operation in the queue.
  8719. this.backoff.backoffAndRun(() => this.retryNextOp());
  8720. }
  8721. }
  8722. enqueueInternal(op) {
  8723. const newTail = this.tail.then(() => {
  8724. this.operationInProgress = true;
  8725. return op()
  8726. .catch((error) => {
  8727. this.failure = error;
  8728. this.operationInProgress = false;
  8729. const message = getMessageOrStack(error);
  8730. logError('INTERNAL UNHANDLED ERROR: ', message);
  8731. // Re-throw the error so that this.tail becomes a rejected Promise and
  8732. // all further attempts to chain (via .then) will just short-circuit
  8733. // and return the rejected Promise.
  8734. throw error;
  8735. })
  8736. .then(result => {
  8737. this.operationInProgress = false;
  8738. return result;
  8739. });
  8740. });
  8741. this.tail = newTail;
  8742. return newTail;
  8743. }
  8744. enqueueAfterDelay(timerId, delayMs, op) {
  8745. this.verifyNotFailed();
  8746. // Fast-forward delays for timerIds that have been overriden.
  8747. if (this.timerIdsToSkip.indexOf(timerId) > -1) {
  8748. delayMs = 0;
  8749. }
  8750. const delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, removedOp => this.removeDelayedOperation(removedOp));
  8751. this.delayedOperations.push(delayedOp);
  8752. return delayedOp;
  8753. }
  8754. verifyNotFailed() {
  8755. if (this.failure) {
  8756. fail();
  8757. }
  8758. }
  8759. verifyOperationInProgress() {
  8760. }
  8761. /**
  8762. * Waits until all currently queued tasks are finished executing. Delayed
  8763. * operations are not run.
  8764. */
  8765. async drain() {
  8766. // Operations in the queue prior to draining may have enqueued additional
  8767. // operations. Keep draining the queue until the tail is no longer advanced,
  8768. // which indicates that no more new operations were enqueued and that all
  8769. // operations were executed.
  8770. let currentTail;
  8771. do {
  8772. currentTail = this.tail;
  8773. await currentTail;
  8774. } while (currentTail !== this.tail);
  8775. }
  8776. /**
  8777. * For Tests: Determine if a delayed operation with a particular TimerId
  8778. * exists.
  8779. */
  8780. containsDelayedOperation(timerId) {
  8781. for (const op of this.delayedOperations) {
  8782. if (op.timerId === timerId) {
  8783. return true;
  8784. }
  8785. }
  8786. return false;
  8787. }
  8788. /**
  8789. * For Tests: Runs some or all delayed operations early.
  8790. *
  8791. * @param lastTimerId - Delayed operations up to and including this TimerId
  8792. * will be drained. Pass TimerId.All to run all delayed operations.
  8793. * @returns a Promise that resolves once all operations have been run.
  8794. */
  8795. runAllDelayedOperationsUntil(lastTimerId) {
  8796. // Note that draining may generate more delayed ops, so we do that first.
  8797. return this.drain().then(() => {
  8798. // Run ops in the same order they'd run if they ran naturally.
  8799. this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);
  8800. for (const op of this.delayedOperations) {
  8801. op.skipDelay();
  8802. if (lastTimerId !== "all" /* TimerId.All */ && op.timerId === lastTimerId) {
  8803. break;
  8804. }
  8805. }
  8806. return this.drain();
  8807. });
  8808. }
  8809. /**
  8810. * For Tests: Skip all subsequent delays for a timer id.
  8811. */
  8812. skipDelaysForTimerId(timerId) {
  8813. this.timerIdsToSkip.push(timerId);
  8814. }
  8815. /** Called once a DelayedOperation is run or canceled. */
  8816. removeDelayedOperation(op) {
  8817. // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
  8818. const index = this.delayedOperations.indexOf(op);
  8819. this.delayedOperations.splice(index, 1);
  8820. }
  8821. }
  8822. function newAsyncQueue() {
  8823. return new AsyncQueueImpl();
  8824. }
  8825. /**
  8826. * Chrome includes Error.message in Error.stack. Other browsers do not.
  8827. * This returns expected output of message + stack when available.
  8828. * @param error - Error or FirestoreError
  8829. */
  8830. function getMessageOrStack(error) {
  8831. let message = error.message || '';
  8832. if (error.stack) {
  8833. if (error.stack.includes(error.message)) {
  8834. message = error.stack;
  8835. }
  8836. else {
  8837. message = error.message + '\n' + error.stack;
  8838. }
  8839. }
  8840. return message;
  8841. }
  8842. /**
  8843. * @license
  8844. * Copyright 2020 Google LLC
  8845. *
  8846. * Licensed under the Apache License, Version 2.0 (the "License");
  8847. * you may not use this file except in compliance with the License.
  8848. * You may obtain a copy of the License at
  8849. *
  8850. * http://www.apache.org/licenses/LICENSE-2.0
  8851. *
  8852. * Unless required by applicable law or agreed to in writing, software
  8853. * distributed under the License is distributed on an "AS IS" BASIS,
  8854. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8855. * See the License for the specific language governing permissions and
  8856. * limitations under the License.
  8857. */
  8858. // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
  8859. // legacy SDK.
  8860. /**
  8861. * A reference to a transaction.
  8862. *
  8863. * The `Transaction` object passed to a transaction's `updateFunction` provides
  8864. * the methods to read and write data within the transaction context. See
  8865. * {@link runTransaction}.
  8866. */
  8867. class Transaction {
  8868. /** @hideconstructor */
  8869. constructor(_firestore, _transaction) {
  8870. this._firestore = _firestore;
  8871. this._transaction = _transaction;
  8872. this._dataReader = newUserDataReader(_firestore);
  8873. }
  8874. /**
  8875. * Reads the document referenced by the provided {@link DocumentReference}.
  8876. *
  8877. * @param documentRef - A reference to the document to be read.
  8878. * @returns A `DocumentSnapshot` with the read data.
  8879. */
  8880. get(documentRef) {
  8881. const ref = validateReference(documentRef, this._firestore);
  8882. const userDataWriter = new LiteUserDataWriter(this._firestore);
  8883. return this._transaction.lookup([ref._key]).then(docs => {
  8884. if (!docs || docs.length !== 1) {
  8885. return fail();
  8886. }
  8887. const doc = docs[0];
  8888. if (doc.isFoundDocument()) {
  8889. return new DocumentSnapshot(this._firestore, userDataWriter, doc.key, doc, ref.converter);
  8890. }
  8891. else if (doc.isNoDocument()) {
  8892. return new DocumentSnapshot(this._firestore, userDataWriter, ref._key, null, ref.converter);
  8893. }
  8894. else {
  8895. throw fail();
  8896. }
  8897. });
  8898. }
  8899. set(documentRef, value, options) {
  8900. const ref = validateReference(documentRef, this._firestore);
  8901. const convertedValue = applyFirestoreDataConverter(ref.converter, value, options);
  8902. const parsed = parseSetData(this._dataReader, 'Transaction.set', ref._key, convertedValue, ref.converter !== null, options);
  8903. this._transaction.set(ref._key, parsed);
  8904. return this;
  8905. }
  8906. update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) {
  8907. const ref = validateReference(documentRef, this._firestore);
  8908. // For Compat types, we have to "extract" the underlying types before
  8909. // performing validation.
  8910. fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData);
  8911. let parsed;
  8912. if (typeof fieldOrUpdateData === 'string' ||
  8913. fieldOrUpdateData instanceof FieldPath) {
  8914. parsed = parseUpdateVarargs(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues);
  8915. }
  8916. else {
  8917. parsed = parseUpdateData(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData);
  8918. }
  8919. this._transaction.update(ref._key, parsed);
  8920. return this;
  8921. }
  8922. /**
  8923. * Deletes the document referred to by the provided {@link DocumentReference}.
  8924. *
  8925. * @param documentRef - A reference to the document to be deleted.
  8926. * @returns This `Transaction` instance. Used for chaining method calls.
  8927. */
  8928. delete(documentRef) {
  8929. const ref = validateReference(documentRef, this._firestore);
  8930. this._transaction.delete(ref._key);
  8931. return this;
  8932. }
  8933. }
  8934. /**
  8935. * Executes the given `updateFunction` and then attempts to commit the changes
  8936. * applied within the transaction. If any document read within the transaction
  8937. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  8938. * commit after 5 attempts, the transaction fails.
  8939. *
  8940. * The maximum number of writes allowed in a single transaction is 500.
  8941. *
  8942. * @param firestore - A reference to the Firestore database to run this
  8943. * transaction against.
  8944. * @param updateFunction - The function to execute within the transaction
  8945. * context.
  8946. * @param options - An options object to configure maximum number of attempts to
  8947. * commit.
  8948. * @returns If the transaction completed successfully or was explicitly aborted
  8949. * (the `updateFunction` returned a failed promise), the promise returned by the
  8950. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  8951. * rejected promise with the corresponding failure error is returned.
  8952. */
  8953. function runTransaction(firestore, updateFunction, options) {
  8954. firestore = cast(firestore, Firestore);
  8955. const datastore = getDatastore(firestore);
  8956. const optionsWithDefaults = Object.assign(Object.assign({}, DEFAULT_TRANSACTION_OPTIONS), options);
  8957. validateTransactionOptions(optionsWithDefaults);
  8958. const deferred = new Deferred();
  8959. new TransactionRunner(newAsyncQueue(), datastore, optionsWithDefaults, internalTransaction => updateFunction(new Transaction(firestore, internalTransaction)), deferred).run();
  8960. return deferred.promise;
  8961. }
  8962. /**
  8963. * Firestore Lite
  8964. *
  8965. * @remarks Firestore Lite is a small online-only SDK that allows read
  8966. * and write access to your Firestore database. All operations connect
  8967. * directly to the backend, and `onSnapshot()` APIs are not supported.
  8968. * @packageDocumentation
  8969. */
  8970. registerFirestore();
  8971. exports.AggregateField = AggregateField;
  8972. exports.AggregateQuerySnapshot = AggregateQuerySnapshot;
  8973. exports.Bytes = Bytes;
  8974. exports.CollectionReference = CollectionReference;
  8975. exports.DocumentReference = DocumentReference;
  8976. exports.DocumentSnapshot = DocumentSnapshot;
  8977. exports.FieldPath = FieldPath;
  8978. exports.FieldValue = FieldValue;
  8979. exports.Firestore = Firestore;
  8980. exports.FirestoreError = FirestoreError;
  8981. exports.GeoPoint = GeoPoint;
  8982. exports.Query = Query;
  8983. exports.QueryCompositeFilterConstraint = QueryCompositeFilterConstraint;
  8984. exports.QueryConstraint = QueryConstraint;
  8985. exports.QueryDocumentSnapshot = QueryDocumentSnapshot;
  8986. exports.QueryEndAtConstraint = QueryEndAtConstraint;
  8987. exports.QueryFieldFilterConstraint = QueryFieldFilterConstraint;
  8988. exports.QueryLimitConstraint = QueryLimitConstraint;
  8989. exports.QueryOrderByConstraint = QueryOrderByConstraint;
  8990. exports.QuerySnapshot = QuerySnapshot;
  8991. exports.QueryStartAtConstraint = QueryStartAtConstraint;
  8992. exports.Timestamp = Timestamp;
  8993. exports.Transaction = Transaction;
  8994. exports.WriteBatch = WriteBatch;
  8995. exports.addDoc = addDoc;
  8996. exports.aggregateQuerySnapshotEqual = aggregateQuerySnapshotEqual;
  8997. exports.and = and;
  8998. exports.arrayRemove = arrayRemove;
  8999. exports.arrayUnion = arrayUnion;
  9000. exports.collection = collection;
  9001. exports.collectionGroup = collectionGroup;
  9002. exports.connectFirestoreEmulator = connectFirestoreEmulator;
  9003. exports.deleteDoc = deleteDoc;
  9004. exports.deleteField = deleteField;
  9005. exports.doc = doc;
  9006. exports.documentId = documentId;
  9007. exports.endAt = endAt;
  9008. exports.endBefore = endBefore;
  9009. exports.getCount = getCount;
  9010. exports.getDoc = getDoc;
  9011. exports.getDocs = getDocs;
  9012. exports.getFirestore = getFirestore;
  9013. exports.increment = increment;
  9014. exports.initializeFirestore = initializeFirestore;
  9015. exports.limit = limit;
  9016. exports.limitToLast = limitToLast;
  9017. exports.or = or;
  9018. exports.orderBy = orderBy;
  9019. exports.query = query;
  9020. exports.queryEqual = queryEqual;
  9021. exports.refEqual = refEqual;
  9022. exports.runTransaction = runTransaction;
  9023. exports.serverTimestamp = serverTimestamp;
  9024. exports.setDoc = setDoc;
  9025. exports.setLogLevel = setLogLevel;
  9026. exports.snapshotEqual = snapshotEqual;
  9027. exports.startAfter = startAfter;
  9028. exports.startAt = startAt;
  9029. exports.terminate = terminate;
  9030. exports.updateDoc = updateDoc;
  9031. exports.where = where;
  9032. exports.writeBatch = writeBatch;
  9033. //# sourceMappingURL=index.node.cjs.js.map