index.node.cjs.js 353 KB

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