private.d.ts 270 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765
  1. /**
  2. * Cloud Firestore
  3. *
  4. * @packageDocumentation
  5. */
  6. import { DocumentData as DocumentData_2 } from '@firebase/firestore-types';
  7. import { EmulatorMockTokenOptions } from '@firebase/util';
  8. import { FirebaseApp } from '@firebase/app';
  9. import { FirebaseError } from '@firebase/util';
  10. import { LogLevelString as LogLevel } from '@firebase/logger';
  11. import { SetOptions as SetOptions_2 } from '@firebase/firestore-types';
  12. /* Excluded from this release type: AbstractUserDataWriter */
  13. /**
  14. * Describes a map whose keys are active target ids. We do not care about the type of the
  15. * values.
  16. */
  17. declare type ActiveTargets = SortedMap<TargetId, unknown>;
  18. /**
  19. * Add a new document to specified `CollectionReference` with the given data,
  20. * assigning it a document ID automatically.
  21. *
  22. * @param reference - A reference to the collection to add this document to.
  23. * @param data - An Object containing the data for the new document.
  24. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  25. * newly created document after it has been written to the backend (Note that it
  26. * won't resolve while you're offline).
  27. */
  28. export declare function addDoc<T>(reference: CollectionReference<T>, data: WithFieldValue<T>): Promise<DocumentReference<T>>;
  29. /**
  30. * Returns a new map where every key is prefixed with the outer key appended
  31. * to a dot.
  32. */
  33. export declare type AddPrefixToKeys<Prefix extends string, T extends Record<string, unknown>> = {
  34. [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
  35. };
  36. /**
  37. * Represents an aggregation that can be performed by Firestore.
  38. */
  39. export declare class AggregateField<T> {
  40. readonly _aggregateType: AggregateType;
  41. readonly _internalFieldPath?: _FieldPath | undefined;
  42. /** A type string to uniquely identify instances of this class. */
  43. readonly type = "AggregateField";
  44. /* Excluded from this release type: __constructor */
  45. }
  46. /* Excluded from this release type: aggregateFieldEqual */
  47. /**
  48. * The union of all `AggregateField` types that are supported by Firestore.
  49. */
  50. export declare type AggregateFieldType = AggregateField<number | null>;
  51. /**
  52. * The results of executing an aggregation query.
  53. */
  54. export declare class AggregateQuerySnapshot<T extends AggregateSpec> {
  55. private readonly _userDataWriter;
  56. private readonly _data;
  57. /** A type string to uniquely identify instances of this class. */
  58. readonly type = "AggregateQuerySnapshot";
  59. /**
  60. * The underlying query over which the aggregations recorded in this
  61. * `AggregateQuerySnapshot` were performed.
  62. */
  63. readonly query: Query<unknown>;
  64. /** @hideconstructor */
  65. constructor(query: Query<unknown>, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap<Value>);
  66. /**
  67. * Returns the results of the aggregations performed over the underlying
  68. * query.
  69. *
  70. * The keys of the returned object will be the same as those of the
  71. * `AggregateSpec` object specified to the aggregation method, and the values
  72. * will be the corresponding aggregation result.
  73. *
  74. * @returns The results of the aggregations performed over the underlying
  75. * query.
  76. */
  77. data(): AggregateSpecData<T>;
  78. }
  79. /**
  80. * Compares two `AggregateQuerySnapshot` instances for equality.
  81. *
  82. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  83. * underlying queries that compare equal, and the same data.
  84. *
  85. * @param left - The first `AggregateQuerySnapshot` to compare.
  86. * @param right - The second `AggregateQuerySnapshot` to compare.
  87. *
  88. * @returns `true` if the objects are "equal", as defined above, or `false`
  89. * otherwise.
  90. */
  91. export declare function aggregateQuerySnapshotEqual<T extends AggregateSpec>(left: AggregateQuerySnapshot<T>, right: AggregateQuerySnapshot<T>): boolean;
  92. /**
  93. * Specifies a set of aggregations and their aliases.
  94. */
  95. export declare interface AggregateSpec {
  96. [field: string]: AggregateFieldType;
  97. }
  98. /**
  99. * A type whose keys are taken from an `AggregateSpec`, and whose values are the
  100. * result of the aggregation performed by the corresponding `AggregateField`
  101. * from the input `AggregateSpec`.
  102. */
  103. export declare type AggregateSpecData<T extends AggregateSpec> = {
  104. [P in keyof T]: T[P] extends AggregateField<infer U> ? U : never;
  105. };
  106. /* Excluded from this release type: AggregateType */
  107. /**
  108. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  109. * the given filter constraints. A conjunction filter includes a document if it
  110. * satisfies all of the given filters.
  111. *
  112. * @param queryConstraints - Optional. The list of
  113. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  114. * created with calls to {@link where}, {@link or}, or {@link and}.
  115. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  116. */
  117. export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint;
  118. declare interface ApiClientObjectMap<T> {
  119. [k: string]: T;
  120. }
  121. /**
  122. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  123. * to a Firestore query.
  124. */
  125. declare abstract class AppliableConstraint {
  126. /**
  127. * Takes the provided {@link Query} and returns a copy of the {@link Query} with this
  128. * {@link AppliableConstraint} applied.
  129. */
  130. abstract _apply<T>(query: Query<T>): Query<T>;
  131. }
  132. /**
  133. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  134. * updateDoc:1} that tells the server to remove the given elements from any
  135. * array value that already exists on the server. All instances of each element
  136. * specified will be removed from the array. If the field being modified is not
  137. * already an array it will be overwritten with an empty array.
  138. *
  139. * @param elements - The elements to remove from the array.
  140. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  141. * `updateDoc()`
  142. */
  143. export declare function arrayRemove(...elements: unknown[]): FieldValue;
  144. /**
  145. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  146. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  147. * value that already exists on the server. Each specified element that doesn't
  148. * already exist in the array will be added to the end. If the field being
  149. * modified is not already an array it will be overwritten with an array
  150. * containing exactly the specified elements.
  151. *
  152. * @param elements - The elements to union into the array.
  153. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  154. * `updateDoc()`.
  155. */
  156. export declare function arrayUnion(...elements: unknown[]): FieldValue;
  157. declare interface AsyncQueue {
  158. readonly isShuttingDown: boolean;
  159. /**
  160. * Adds a new operation to the queue without waiting for it to complete (i.e.
  161. * we ignore the Promise result).
  162. */
  163. enqueueAndForget<T extends unknown>(op: () => Promise<T>): void;
  164. /**
  165. * Regardless if the queue has initialized shutdown, adds a new operation to the
  166. * queue without waiting for it to complete (i.e. we ignore the Promise result).
  167. */
  168. enqueueAndForgetEvenWhileRestricted<T extends unknown>(op: () => Promise<T>): void;
  169. /**
  170. * Initialize the shutdown of this queue. Once this method is called, the
  171. * only possible way to request running an operation is through
  172. * `enqueueEvenWhileRestricted()`.
  173. *
  174. * @param purgeExistingTasks Whether already enqueued tasked should be
  175. * rejected (unless enqueued wih `enqueueEvenWhileRestricted()`). Defaults
  176. * to false.
  177. */
  178. enterRestrictedMode(purgeExistingTasks?: boolean): void;
  179. /**
  180. * Adds a new operation to the queue. Returns a promise that will be resolved
  181. * when the promise returned by the new operation is (with its value).
  182. */
  183. enqueue<T extends unknown>(op: () => Promise<T>): Promise<T>;
  184. /**
  185. * Enqueue a retryable operation.
  186. *
  187. * A retryable operation is rescheduled with backoff if it fails with a
  188. * IndexedDbTransactionError (the error type used by SimpleDb). All
  189. * retryable operations are executed in order and only run if all prior
  190. * operations were retried successfully.
  191. */
  192. enqueueRetryable(op: () => Promise<void>): void;
  193. /**
  194. * Schedules an operation to be queued on the AsyncQueue once the specified
  195. * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel
  196. * or fast-forward the operation prior to its running.
  197. */
  198. enqueueAfterDelay<T extends unknown>(timerId: TimerId, delayMs: number, op: () => Promise<T>): DelayedOperation<T>;
  199. /**
  200. * Verifies there's an operation currently in-progress on the AsyncQueue.
  201. * Unfortunately we can't verify that the running code is in the promise chain
  202. * of that operation, so this isn't a foolproof check, but it should be enough
  203. * to catch some bugs.
  204. */
  205. verifyOperationInProgress(): void;
  206. }
  207. declare type AuthTokenFactory = () => string;
  208. /* Excluded from this release type: average */
  209. /**
  210. * Path represents an ordered sequence of string segments.
  211. */
  212. declare abstract class BasePath<B extends BasePath<B>> {
  213. private segments;
  214. private offset;
  215. private len;
  216. constructor(segments: string[], offset?: number, length?: number);
  217. /**
  218. * Abstract constructor method to construct an instance of B with the given
  219. * parameters.
  220. */
  221. protected abstract construct(segments: string[], offset?: number, length?: number): B;
  222. /**
  223. * Returns a String representation.
  224. *
  225. * Implementing classes are required to provide deterministic implementations as
  226. * the String representation is used to obtain canonical Query IDs.
  227. */
  228. abstract toString(): string;
  229. get length(): number;
  230. isEqual(other: B): boolean;
  231. child(nameOrPath: string | B): B;
  232. /** The index of one past the last segment of the path. */
  233. private limit;
  234. popFirst(size?: number): B;
  235. popLast(): B;
  236. firstSegment(): string;
  237. lastSegment(): string;
  238. get(index: number): string;
  239. isEmpty(): boolean;
  240. isPrefixOf(other: this): boolean;
  241. isImmediateParentOf(potentialChild: this): boolean;
  242. forEach(fn: (segment: string) => void): void;
  243. toArray(): string[];
  244. static comparator<T extends BasePath<T>>(p1: BasePath<T>, p2: BasePath<T>): number;
  245. }
  246. /**
  247. * @license
  248. * Copyright 2017 Google LLC
  249. *
  250. * Licensed under the Apache License, Version 2.0 (the "License");
  251. * you may not use this file except in compliance with the License.
  252. * You may obtain a copy of the License at
  253. *
  254. * http://www.apache.org/licenses/LICENSE-2.0
  255. *
  256. * Unless required by applicable law or agreed to in writing, software
  257. * distributed under the License is distributed on an "AS IS" BASIS,
  258. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  259. * See the License for the specific language governing permissions and
  260. * limitations under the License.
  261. */
  262. /**
  263. * BatchID is a locally assigned ID for a batch of mutations that have been
  264. * applied.
  265. */
  266. declare type BatchId = number;
  267. /**
  268. * Represents a bound of a query.
  269. *
  270. * The bound is specified with the given components representing a position and
  271. * whether it's just before or just after the position (relative to whatever the
  272. * query order is).
  273. *
  274. * The position represents a logical index position for a query. It's a prefix
  275. * of values for the (potentially implicit) order by clauses of a query.
  276. *
  277. * Bound provides a function to determine whether a document comes before or
  278. * after a bound. This is influenced by whether the position is just before or
  279. * just after the provided values.
  280. */
  281. declare class Bound {
  282. readonly position: Value[];
  283. readonly inclusive: boolean;
  284. constructor(position: Value[], inclusive: boolean);
  285. }
  286. /**
  287. * Provides interfaces to save and read Firestore bundles.
  288. */
  289. declare interface BundleCache {
  290. /**
  291. * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined
  292. * if no bundle metadata is found under the given id.
  293. */
  294. getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise<BundleMetadata | undefined>;
  295. /**
  296. * Saves a `BundleMetadata` from a bundle into local storage, using its id as
  297. * the persistent key.
  298. */
  299. saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata_2): PersistencePromise<void>;
  300. /**
  301. * Gets a saved `NamedQuery` for the given query name. Returns undefined if
  302. * no queries are found under the given name.
  303. */
  304. getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise<NamedQuery | undefined>;
  305. /**
  306. * Saves a `NamedQuery` from a bundle, using its name as the persistent key.
  307. */
  308. saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery_2): PersistencePromise<void>;
  309. }
  310. /** Properties of a BundledQuery. */
  311. declare interface BundledQuery {
  312. /** BundledQuery parent */
  313. parent?: string | null;
  314. /** BundledQuery structuredQuery */
  315. structuredQuery?: StructuredQuery | null;
  316. /** BundledQuery limitType */
  317. limitType?: LimitType_2 | null;
  318. }
  319. /**
  320. * Represents a Firestore bundle saved by the SDK in its local storage.
  321. */
  322. declare interface BundleMetadata {
  323. /**
  324. * Id of the bundle. It is used together with `createTime` to determine if a
  325. * bundle has been loaded by the SDK.
  326. */
  327. readonly id: string;
  328. /** Schema version of the bundle. */
  329. readonly version: number;
  330. /**
  331. * Set to the snapshot version of the bundle if created by the Server SDKs.
  332. * Otherwise set to SnapshotVersion.MIN.
  333. */
  334. readonly createTime: SnapshotVersion;
  335. }
  336. /** Properties of a BundleMetadata. */
  337. declare interface BundleMetadata_2 {
  338. /** BundleMetadata id */
  339. id?: string | null;
  340. /** BundleMetadata createTime */
  341. createTime?: Timestamp_2 | null;
  342. /** BundleMetadata version */
  343. version?: number | null;
  344. /** BundleMetadata totalDocuments */
  345. totalDocuments?: number | null;
  346. /** BundleMetadata totalBytes */
  347. totalBytes?: number | null;
  348. }
  349. /**
  350. * An immutable object representing an array of bytes.
  351. */
  352. export declare class Bytes {
  353. _byteString: _ByteString;
  354. /** @hideconstructor */
  355. constructor(byteString: _ByteString);
  356. /**
  357. * Creates a new `Bytes` object from the given Base64 string, converting it to
  358. * bytes.
  359. *
  360. * @param base64 - The Base64 string used to create the `Bytes` object.
  361. */
  362. static fromBase64String(base64: string): Bytes;
  363. /**
  364. * Creates a new `Bytes` object from the given Uint8Array.
  365. *
  366. * @param array - The Uint8Array used to create the `Bytes` object.
  367. */
  368. static fromUint8Array(array: Uint8Array): Bytes;
  369. /**
  370. * Returns the underlying bytes as a Base64-encoded string.
  371. *
  372. * @returns The Base64-encoded string created from the `Bytes` object.
  373. */
  374. toBase64(): string;
  375. /**
  376. * Returns the underlying bytes in a new `Uint8Array`.
  377. *
  378. * @returns The Uint8Array created from the `Bytes` object.
  379. */
  380. toUint8Array(): Uint8Array;
  381. /**
  382. * Returns a string representation of the `Bytes` object.
  383. *
  384. * @returns A string representation of the `Bytes` object.
  385. */
  386. toString(): string;
  387. /**
  388. * Returns true if this `Bytes` object is equal to the provided one.
  389. *
  390. * @param other - The `Bytes` object to compare against.
  391. * @returns true if this `Bytes` object is equal to the provided one.
  392. */
  393. isEqual(other: Bytes): boolean;
  394. }
  395. /* Excluded from this release type: _ByteString */
  396. /**
  397. * Constant used to indicate the LRU garbage collection should be disabled.
  398. * Set this value as the `cacheSizeBytes` on the settings passed to the
  399. * {@link Firestore} instance.
  400. */
  401. export declare const CACHE_SIZE_UNLIMITED = -1;
  402. /* Excluded from this release type: _cast */
  403. declare const enum ChangeType {
  404. Added = 0,
  405. Removed = 1,
  406. Modified = 2,
  407. Metadata = 3
  408. }
  409. /**
  410. * Helper for calculating the nested fields for a given type T1. This is needed
  411. * to distribute union types such as `undefined | {...}` (happens for optional
  412. * props) or `{a: A} | {b: B}`.
  413. *
  414. * In this use case, `V` is used to distribute the union types of `T[K]` on
  415. * `Record`, since `T[K]` is evaluated as an expression and not distributed.
  416. *
  417. * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
  418. */
  419. export declare type ChildUpdateFields<K extends string, V> = V extends Record<string, unknown> ? AddPrefixToKeys<K, UpdateData<V>> : never;
  420. /**
  421. * Clears the persistent storage. This includes pending writes and cached
  422. * documents.
  423. *
  424. * Must be called while the {@link Firestore} instance is not started (after the app is
  425. * terminated or when the app is first initialized). On startup, this function
  426. * must be called before other functions (other than {@link
  427. * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}
  428. * instance is still running, the promise will be rejected with the error code
  429. * of `failed-precondition`.
  430. *
  431. * Note: `clearIndexedDbPersistence()` is primarily intended to help write
  432. * reliable tests that use Cloud Firestore. It uses an efficient mechanism for
  433. * dropping existing data but does not attempt to securely overwrite or
  434. * otherwise make cached data unrecoverable. For applications that are sensitive
  435. * to the disclosure of cached data in between user sessions, we strongly
  436. * recommend not enabling persistence at all.
  437. *
  438. * @param firestore - The {@link Firestore} instance to clear persistence for.
  439. * @returns A `Promise` that is resolved when the persistent storage is
  440. * cleared. Otherwise, the promise is rejected with an error.
  441. */
  442. export declare function clearIndexedDbPersistence(firestore: Firestore): Promise<void>;
  443. /**
  444. * A randomly-generated key assigned to each Firestore instance at startup.
  445. */
  446. declare type ClientId = string;
  447. /**
  448. * Gets a `CollectionReference` instance that refers to the collection at
  449. * the specified absolute path.
  450. *
  451. * @param firestore - A reference to the root `Firestore` instance.
  452. * @param path - A slash-separated path to a collection.
  453. * @param pathSegments - Additional path segments to apply relative to the first
  454. * argument.
  455. * @throws If the final path has an even number of segments and does not point
  456. * to a collection.
  457. * @returns The `CollectionReference` instance.
  458. */
  459. export declare function collection(firestore: Firestore_2, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
  460. /**
  461. * Gets a `CollectionReference` instance that refers to a subcollection of
  462. * `reference` at the the specified relative path.
  463. *
  464. * @param reference - A reference to a collection.
  465. * @param path - A slash-separated path to a collection.
  466. * @param pathSegments - Additional path segments to apply relative to the first
  467. * argument.
  468. * @throws If the final path has an even number of segments and does not point
  469. * to a collection.
  470. * @returns The `CollectionReference` instance.
  471. */
  472. export declare function collection(reference: CollectionReference<unknown>, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
  473. /**
  474. * Gets a `CollectionReference` instance that refers to a subcollection of
  475. * `reference` at the the specified relative path.
  476. *
  477. * @param reference - A reference to a Firestore document.
  478. * @param path - A slash-separated path to a collection.
  479. * @param pathSegments - Additional path segments that will be applied relative
  480. * to the first argument.
  481. * @throws If the final path has an even number of segments and does not point
  482. * to a collection.
  483. * @returns The `CollectionReference` instance.
  484. */
  485. export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
  486. /**
  487. * Creates and returns a new `Query` instance that includes all documents in the
  488. * database that are contained in a collection or subcollection with the
  489. * given `collectionId`.
  490. *
  491. * @param firestore - A reference to the root `Firestore` instance.
  492. * @param collectionId - Identifies the collections to query over. Every
  493. * collection or subcollection with this ID as the last segment of its path
  494. * will be included. Cannot contain a slash.
  495. * @returns The created `Query`.
  496. */
  497. export declare function collectionGroup(firestore: Firestore_2, collectionId: string): Query<DocumentData>;
  498. /**
  499. * A `CollectionReference` object can be used for adding documents, getting
  500. * document references, and querying for documents (using {@link (query:1)}).
  501. */
  502. export declare class CollectionReference<T = DocumentData> extends Query<T> {
  503. readonly _path: _ResourcePath;
  504. /** The type of this Firestore reference. */
  505. readonly type = "collection";
  506. /** @hideconstructor */
  507. constructor(firestore: Firestore_2, converter: FirestoreDataConverter_2<T> | null, _path: _ResourcePath);
  508. /** The collection's identifier. */
  509. get id(): string;
  510. /**
  511. * A string representing the path of the referenced collection (relative
  512. * to the root of the database).
  513. */
  514. get path(): string;
  515. /**
  516. * A reference to the containing `DocumentReference` if this is a
  517. * subcollection. If this isn't a subcollection, the reference is null.
  518. */
  519. get parent(): DocumentReference<DocumentData> | null;
  520. /**
  521. * Applies a custom data converter to this `CollectionReference`, allowing you
  522. * to use your own custom model objects with Firestore. When you call {@link
  523. * addDoc} with the returned `CollectionReference` instance, the provided
  524. * converter will convert between Firestore data and your custom type `U`.
  525. *
  526. * @param converter - Converts objects to and from Firestore.
  527. * @returns A `CollectionReference<U>` that uses the provided converter.
  528. */
  529. withConverter<U>(converter: FirestoreDataConverter_2<U>): CollectionReference<U>;
  530. /**
  531. * Removes the current converter.
  532. *
  533. * @param converter - `null` removes the current converter.
  534. * @returns A `CollectionReference<DocumentData>` that does not use a
  535. * converter.
  536. */
  537. withConverter(converter: null): CollectionReference<DocumentData>;
  538. }
  539. /**
  540. * @license
  541. * Copyright 2017 Google LLC
  542. *
  543. * Licensed under the Apache License, Version 2.0 (the "License");
  544. * you may not use this file except in compliance with the License.
  545. * You may obtain a copy of the License at
  546. *
  547. * http://www.apache.org/licenses/LICENSE-2.0
  548. *
  549. * Unless required by applicable law or agreed to in writing, software
  550. * distributed under the License is distributed on an "AS IS" BASIS,
  551. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  552. * See the License for the specific language governing permissions and
  553. * limitations under the License.
  554. */
  555. declare type Comparator<K> = (key1: K, key2: K) => number;
  556. declare interface ComponentConfiguration {
  557. asyncQueue: AsyncQueue;
  558. databaseInfo: DatabaseInfo;
  559. authCredentials: CredentialsProvider<User>;
  560. appCheckCredentials: CredentialsProvider<string>;
  561. clientId: ClientId;
  562. initialUser: User;
  563. maxConcurrentLimboResolutions: number;
  564. }
  565. declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR';
  566. declare const enum CompositeOperator {
  567. OR = "or",
  568. AND = "and"
  569. }
  570. /**
  571. * Modify this instance to communicate with the Cloud Firestore emulator.
  572. *
  573. * Note: This must be called before this instance has been used to do any
  574. * operations.
  575. *
  576. * @param firestore - The `Firestore` instance to configure to connect to the
  577. * emulator.
  578. * @param host - the emulator host (ex: localhost).
  579. * @param port - the emulator port (ex: 9000).
  580. * @param options.mockUserToken - the mock auth token to use for unit testing
  581. * Security Rules.
  582. */
  583. export declare function connectFirestoreEmulator(firestore: Firestore_2, host: string, port: number, options?: {
  584. mockUserToken?: EmulatorMockTokenOptions | string;
  585. }): void;
  586. /* Excluded from this release type: count */
  587. /**
  588. * A Listener for credential change events. The listener should fetch a new
  589. * token and may need to invalidate other state if the current user has also
  590. * changed.
  591. */
  592. declare type CredentialChangeListener<T> = (credential: T) => Promise<void>;
  593. /**
  594. * Provides methods for getting the uid and token for the current user and
  595. * listening for changes.
  596. */
  597. declare interface CredentialsProvider<T> {
  598. /**
  599. * Starts the credentials provider and specifies a listener to be notified of
  600. * credential changes (sign-in / sign-out, token changes). It is immediately
  601. * called once with the initial user.
  602. *
  603. * The change listener is invoked on the provided AsyncQueue.
  604. */
  605. start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener<T>): void;
  606. /** Requests a token for the current user. */
  607. getToken(): Promise<Token | null>;
  608. /**
  609. * Marks the last retrieved token as invalid, making the next GetToken request
  610. * force-refresh the token.
  611. */
  612. invalidateToken(): void;
  613. shutdown(): void;
  614. }
  615. /** Settings for private credentials */
  616. declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings;
  617. /* Excluded from this release type: _DatabaseId */
  618. /**
  619. * @license
  620. * Copyright 2017 Google LLC
  621. *
  622. * Licensed under the Apache License, Version 2.0 (the "License");
  623. * you may not use this file except in compliance with the License.
  624. * You may obtain a copy of the License at
  625. *
  626. * http://www.apache.org/licenses/LICENSE-2.0
  627. *
  628. * Unless required by applicable law or agreed to in writing, software
  629. * distributed under the License is distributed on an "AS IS" BASIS,
  630. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  631. * See the License for the specific language governing permissions and
  632. * limitations under the License.
  633. */
  634. declare class DatabaseInfo {
  635. readonly databaseId: _DatabaseId;
  636. readonly appId: string;
  637. readonly persistenceKey: string;
  638. readonly host: string;
  639. readonly ssl: boolean;
  640. readonly forceLongPolling: boolean;
  641. readonly autoDetectLongPolling: boolean;
  642. readonly longPollingOptions: ExperimentalLongPollingOptions;
  643. readonly useFetchStreams: boolean;
  644. /**
  645. * Constructs a DatabaseInfo using the provided host, databaseId and
  646. * persistenceKey.
  647. *
  648. * @param databaseId - The database to use.
  649. * @param appId - The Firebase App Id.
  650. * @param persistenceKey - A unique identifier for this Firestore's local
  651. * storage (used in conjunction with the databaseId).
  652. * @param host - The Firestore backend host to connect to.
  653. * @param ssl - Whether to use SSL when connecting.
  654. * @param forceLongPolling - Whether to use the forceLongPolling option
  655. * when using WebChannel as the network transport.
  656. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  657. * option when using WebChannel as the network transport.
  658. * @param longPollingOptions Options that configure long-polling.
  659. * @param useFetchStreams Whether to use the Fetch API instead of
  660. * XMLHTTPRequest
  661. */
  662. constructor(databaseId: _DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean);
  663. }
  664. /**
  665. * Datastore and its related methods are a wrapper around the external Google
  666. * Cloud Datastore grpc API, which provides an interface that is more convenient
  667. * for the rest of the client SDK architecture to consume.
  668. */
  669. declare abstract class Datastore {
  670. abstract terminate(): void;
  671. abstract serializer: JsonProtoSerializer;
  672. }
  673. /* Excluded from this release type: _debugAssert */
  674. /**
  675. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  676. *
  677. * It is created via DelayedOperation.createAndSchedule().
  678. *
  679. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  680. *
  681. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  682. * in newer versions of TypeScript defines `finally`, which is not available in
  683. * IE.
  684. */
  685. declare class DelayedOperation<T extends unknown> implements PromiseLike<T> {
  686. private readonly asyncQueue;
  687. readonly timerId: TimerId;
  688. readonly targetTimeMs: number;
  689. private readonly op;
  690. private readonly removalCallback;
  691. private timerHandle;
  692. private readonly deferred;
  693. private constructor();
  694. /**
  695. * Creates and returns a DelayedOperation that has been scheduled to be
  696. * executed on the provided asyncQueue after the provided delayMs.
  697. *
  698. * @param asyncQueue - The queue to schedule the operation on.
  699. * @param id - A Timer ID identifying the type of operation this is.
  700. * @param delayMs - The delay (ms) before the operation should be scheduled.
  701. * @param op - The operation to run.
  702. * @param removalCallback - A callback to be called synchronously once the
  703. * operation is executed or canceled, notifying the AsyncQueue to remove it
  704. * from its delayedOperations list.
  705. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  706. * the DelayedOperation class public.
  707. */
  708. static createAndSchedule<R extends unknown>(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise<R>, removalCallback: (op: DelayedOperation<R>) => void): DelayedOperation<R>;
  709. /**
  710. * Starts the timer. This is called immediately after construction by
  711. * createAndSchedule().
  712. */
  713. private start;
  714. /**
  715. * Queues the operation to run immediately (if it hasn't already been run or
  716. * canceled).
  717. */
  718. skipDelay(): void;
  719. /**
  720. * Cancels the operation if it hasn't already been executed or canceled. The
  721. * promise will be rejected.
  722. *
  723. * As long as the operation has not yet been run, calling cancel() provides a
  724. * guarantee that the operation will not be run.
  725. */
  726. cancel(reason?: string): void;
  727. then: <TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined) => Promise<TResult1 | TResult2>;
  728. private handleDelayElapsed;
  729. private clearTimeout;
  730. }
  731. /**
  732. * Deletes the document referred to by the specified `DocumentReference`.
  733. *
  734. * @param reference - A reference to the document to delete.
  735. * @returns A Promise resolved once the document has been successfully
  736. * deleted from the backend (note that it won't resolve while you're offline).
  737. */
  738. export declare function deleteDoc(reference: DocumentReference<unknown>): Promise<void>;
  739. /**
  740. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  741. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  742. */
  743. export declare function deleteField(): FieldValue;
  744. /**
  745. * The direction of sorting in an order by.
  746. */
  747. declare const enum Direction {
  748. ASCENDING = "asc",
  749. DESCENDING = "desc"
  750. }
  751. /**
  752. * Disables network usage for this instance. It can be re-enabled via {@link
  753. * enableNetwork}. While the network is disabled, any snapshot listeners,
  754. * `getDoc()` or `getDocs()` calls will return results from cache, and any write
  755. * operations will be queued until the network is restored.
  756. *
  757. * @returns A `Promise` that is resolved once the network has been disabled.
  758. */
  759. export declare function disableNetwork(firestore: Firestore): Promise<void>;
  760. /**
  761. * Gets a `DocumentReference` instance that refers to the document at the
  762. * specified absolute path.
  763. *
  764. * @param firestore - A reference to the root `Firestore` instance.
  765. * @param path - A slash-separated path to a document.
  766. * @param pathSegments - Additional path segments that will be applied relative
  767. * to the first argument.
  768. * @throws If the final path has an odd number of segments and does not point to
  769. * a document.
  770. * @returns The `DocumentReference` instance.
  771. */
  772. export declare function doc(firestore: Firestore_2, path: string, ...pathSegments: string[]): DocumentReference<DocumentData>;
  773. /**
  774. * Gets a `DocumentReference` instance that refers to a document within
  775. * `reference` at the specified relative path. If no path is specified, an
  776. * automatically-generated unique ID will be used for the returned
  777. * `DocumentReference`.
  778. *
  779. * @param reference - A reference to a collection.
  780. * @param path - A slash-separated path to a document. Has to be omitted to use
  781. * auto-genrated IDs.
  782. * @param pathSegments - Additional path segments that will be applied relative
  783. * to the first argument.
  784. * @throws If the final path has an odd number of segments and does not point to
  785. * a document.
  786. * @returns The `DocumentReference` instance.
  787. */
  788. export declare function doc<T>(reference: CollectionReference<T>, path?: string, ...pathSegments: string[]): DocumentReference<T>;
  789. /**
  790. * Gets a `DocumentReference` instance that refers to a document within
  791. * `reference` at the specified relative path.
  792. *
  793. * @param reference - A reference to a Firestore document.
  794. * @param path - A slash-separated path to a document.
  795. * @param pathSegments - Additional path segments that will be applied relative
  796. * to the first argument.
  797. * @throws If the final path has an odd number of segments and does not point to
  798. * a document.
  799. * @returns The `DocumentReference` instance.
  800. */
  801. export declare function doc(reference: DocumentReference<unknown>, path: string, ...pathSegments: string[]): DocumentReference<DocumentData>;
  802. /**
  803. * Represents a document in Firestore with a key, version, data and whether the
  804. * data has local mutations applied to it.
  805. */
  806. declare interface Document_2 {
  807. /** The key for this document */
  808. readonly key: _DocumentKey;
  809. /**
  810. * The version of this document if it exists or a version at which this
  811. * document was guaranteed to not exist.
  812. */
  813. readonly version: SnapshotVersion;
  814. /**
  815. * The timestamp at which this document was read from the remote server. Uses
  816. * `SnapshotVersion.min()` for documents created by the user.
  817. */
  818. readonly readTime: SnapshotVersion;
  819. /**
  820. * The timestamp at which the document was created. This value increases
  821. * monotonically when a document is deleted then recreated. It can also be
  822. * compared to `createTime` of other documents and the `readTime` of a query.
  823. */
  824. readonly createTime: SnapshotVersion;
  825. /** The underlying data of this document or an empty value if no data exists. */
  826. readonly data: ObjectValue;
  827. /** Returns whether local mutations were applied via the mutation queue. */
  828. readonly hasLocalMutations: boolean;
  829. /** Returns whether mutations were applied based on a write acknowledgment. */
  830. readonly hasCommittedMutations: boolean;
  831. /**
  832. * Whether this document had a local mutation applied that has not yet been
  833. * acknowledged by Watch.
  834. */
  835. readonly hasPendingWrites: boolean;
  836. /**
  837. * Returns whether this document is valid (i.e. it is an entry in the
  838. * RemoteDocumentCache, was created by a mutation or read from the backend).
  839. */
  840. isValidDocument(): boolean;
  841. /**
  842. * Returns whether the document exists and its data is known at the current
  843. * version.
  844. */
  845. isFoundDocument(): boolean;
  846. /**
  847. * Returns whether the document is known to not exist at the current version.
  848. */
  849. isNoDocument(): boolean;
  850. /**
  851. * Returns whether the document exists and its data is unknown at the current
  852. * version.
  853. */
  854. isUnknownDocument(): boolean;
  855. isEqual(other: Document_2 | null | undefined): boolean;
  856. /** Creates a mutable copy of this document. */
  857. mutableCopy(): MutableDocument;
  858. toString(): string;
  859. }
  860. /**
  861. * A `DocumentChange` represents a change to the documents matching a query.
  862. * It contains the document affected and the type of change that occurred.
  863. */
  864. export declare interface DocumentChange<T = DocumentData> {
  865. /** The type of change ('added', 'modified', or 'removed'). */
  866. readonly type: DocumentChangeType;
  867. /** The document affected by this change. */
  868. readonly doc: QueryDocumentSnapshot<T>;
  869. /**
  870. * The index of the changed document in the result set immediately prior to
  871. * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects
  872. * have been applied). Is `-1` for 'added' events.
  873. */
  874. readonly oldIndex: number;
  875. /**
  876. * The index of the changed document in the result set immediately after
  877. * this `DocumentChange` (i.e. supposing that all prior `DocumentChange`
  878. * objects and the current `DocumentChange` object have been applied).
  879. * Is -1 for 'removed' events.
  880. */
  881. readonly newIndex: number;
  882. }
  883. /**
  884. * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'.
  885. */
  886. export declare type DocumentChangeType = 'added' | 'removed' | 'modified';
  887. declare type DocumentComparator = (doc1: Document_2, doc2: Document_2) => number;
  888. /**
  889. * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to
  890. * values.
  891. */
  892. export declare interface DocumentData {
  893. /** A mapping between a field and its value. */
  894. [field: string]: any;
  895. }
  896. /**
  897. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  898. * It can be used in queries to sort or filter by the document ID.
  899. */
  900. export declare function documentId(): FieldPath;
  901. /* Excluded from this release type: _DocumentKey */
  902. declare type DocumentKeyMap<T> = ObjectMap<_DocumentKey, T>;
  903. declare type DocumentKeySet = SortedSet<_DocumentKey>;
  904. declare type DocumentMap = SortedMap<_DocumentKey, Document_2>;
  905. /**
  906. * Provides methods to read and write document overlays.
  907. *
  908. * An overlay is a saved mutation, that gives a local view of a document when
  909. * applied to the remote version of the document.
  910. *
  911. * Each overlay stores the largest batch ID that is included in the overlay,
  912. * which allows us to remove the overlay once all batches leading up to it have
  913. * been acknowledged.
  914. */
  915. declare interface DocumentOverlayCache {
  916. /**
  917. * Gets the saved overlay mutation for the given document key.
  918. * Returns null if there is no overlay for that key.
  919. */
  920. getOverlay(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise<Overlay | null>;
  921. /**
  922. * Gets the saved overlay mutation for the given document keys. Skips keys for
  923. * which there are no overlays.
  924. */
  925. getOverlays(transaction: PersistenceTransaction, keys: _DocumentKey[]): PersistencePromise<OverlayMap>;
  926. /**
  927. * Saves the given document mutation map to persistence as overlays.
  928. * All overlays will have their largest batch id set to `largestBatchId`.
  929. */
  930. saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise<void>;
  931. /** Removes overlays for the given document keys and batch ID. */
  932. removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise<void>;
  933. /**
  934. * Returns all saved overlays for the given collection.
  935. *
  936. * @param transaction - The persistence transaction to use for this operation.
  937. * @param collection - The collection path to get the overlays for.
  938. * @param sinceBatchId - The minimum batch ID to filter by (exclusive).
  939. * Only overlays that contain a change past `sinceBatchId` are returned.
  940. * @returns Mapping of each document key in the collection to its overlay.
  941. */
  942. getOverlaysForCollection(transaction: PersistenceTransaction, collection: _ResourcePath, sinceBatchId: number): PersistencePromise<OverlayMap>;
  943. /**
  944. * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the
  945. * provided collection group, processed by ascending batch ID. The method
  946. * always returns all overlays for a batch even if the last batch contains
  947. * more documents than the remaining limit.
  948. *
  949. * @param transaction - The persistence transaction used for this operation.
  950. * @param collectionGroup - The collection group to get the overlays for.
  951. * @param sinceBatchId - The minimum batch ID to filter by (exclusive).
  952. * Only overlays that contain a change past `sinceBatchId` are returned.
  953. * @param count - The number of overlays to return. Can be exceeded if the last
  954. * batch contains more entries.
  955. * @return Mapping of each document key in the collection group to its overlay.
  956. */
  957. getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise<OverlayMap>;
  958. }
  959. /**
  960. * A `DocumentReference` refers to a document location in a Firestore database
  961. * and can be used to write, read, or listen to the location. The document at
  962. * the referenced location may or may not exist.
  963. */
  964. export declare class DocumentReference<T = DocumentData> {
  965. /**
  966. * If provided, the `FirestoreDataConverter` associated with this instance.
  967. */
  968. readonly converter: FirestoreDataConverter_2<T> | null;
  969. readonly _key: _DocumentKey;
  970. /** The type of this Firestore reference. */
  971. readonly type = "document";
  972. /**
  973. * The {@link Firestore} instance the document is in.
  974. * This is useful for performing transactions, for example.
  975. */
  976. readonly firestore: Firestore_2;
  977. /** @hideconstructor */
  978. constructor(firestore: Firestore_2,
  979. /**
  980. * If provided, the `FirestoreDataConverter` associated with this instance.
  981. */
  982. converter: FirestoreDataConverter_2<T> | null, _key: _DocumentKey);
  983. get _path(): _ResourcePath;
  984. /**
  985. * The document's identifier within its collection.
  986. */
  987. get id(): string;
  988. /**
  989. * A string representing the path of the referenced document (relative
  990. * to the root of the database).
  991. */
  992. get path(): string;
  993. /**
  994. * The collection this `DocumentReference` belongs to.
  995. */
  996. get parent(): CollectionReference<T>;
  997. /**
  998. * Applies a custom data converter to this `DocumentReference`, allowing you
  999. * to use your own custom model objects with Firestore. When you call {@link
  1000. * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference`
  1001. * instance, the provided converter will convert between Firestore data and
  1002. * your custom type `U`.
  1003. *
  1004. * @param converter - Converts objects to and from Firestore.
  1005. * @returns A `DocumentReference<U>` that uses the provided converter.
  1006. */
  1007. withConverter<U>(converter: FirestoreDataConverter_2<U>): DocumentReference<U>;
  1008. /**
  1009. * Removes the current converter.
  1010. *
  1011. * @param converter - `null` removes the current converter.
  1012. * @returns A `DocumentReference<DocumentData>` that does not use a converter.
  1013. */
  1014. withConverter(converter: null): DocumentReference<DocumentData>;
  1015. }
  1016. /**
  1017. * DocumentSet is an immutable (copy-on-write) collection that holds documents
  1018. * in order specified by the provided comparator. We always add a document key
  1019. * comparator on top of what is provided to guarantee document equality based on
  1020. * the key.
  1021. */
  1022. declare class DocumentSet {
  1023. /**
  1024. * Returns an empty copy of the existing DocumentSet, using the same
  1025. * comparator.
  1026. */
  1027. static emptySet(oldSet: DocumentSet): DocumentSet;
  1028. private comparator;
  1029. private keyedMap;
  1030. private sortedSet;
  1031. /** The default ordering is by key if the comparator is omitted */
  1032. constructor(comp?: DocumentComparator);
  1033. has(key: _DocumentKey): boolean;
  1034. get(key: _DocumentKey): Document_2 | null;
  1035. first(): Document_2 | null;
  1036. last(): Document_2 | null;
  1037. isEmpty(): boolean;
  1038. /**
  1039. * Returns the index of the provided key in the document set, or -1 if the
  1040. * document key is not present in the set;
  1041. */
  1042. indexOf(key: _DocumentKey): number;
  1043. get size(): number;
  1044. /** Iterates documents in order defined by "comparator" */
  1045. forEach(cb: (doc: Document_2) => void): void;
  1046. /** Inserts or updates a document with the same key */
  1047. add(doc: Document_2): DocumentSet;
  1048. /** Deletes a document with a given key */
  1049. delete(key: _DocumentKey): DocumentSet;
  1050. isEqual(other: DocumentSet | null | undefined): boolean;
  1051. toString(): string;
  1052. private copy;
  1053. }
  1054. /**
  1055. * A `DocumentSnapshot` contains data read from a document in your Firestore
  1056. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  1057. * get a specific field.
  1058. *
  1059. * For a `DocumentSnapshot` that points to a non-existing document, any data
  1060. * access will return 'undefined'. You can use the `exists()` method to
  1061. * explicitly verify a document's existence.
  1062. */
  1063. export declare class DocumentSnapshot<T = DocumentData> extends DocumentSnapshot_2<T> {
  1064. readonly _firestore: Firestore;
  1065. private readonly _firestoreImpl;
  1066. /**
  1067. * Metadata about the `DocumentSnapshot`, including information about its
  1068. * source and local modifications.
  1069. */
  1070. readonly metadata: SnapshotMetadata;
  1071. /** @hideconstructor protected */
  1072. constructor(_firestore: Firestore, userDataWriter: AbstractUserDataWriter, key: _DocumentKey, document: Document_2 | null, metadata: SnapshotMetadata, converter: UntypedFirestoreDataConverter<T> | null);
  1073. /**
  1074. * Returns whether or not the data exists. True if the document exists.
  1075. */
  1076. exists(): this is QueryDocumentSnapshot<T>;
  1077. /**
  1078. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  1079. * the document doesn't exist.
  1080. *
  1081. * By default, `serverTimestamp()` values that have not yet been
  1082. * set to their final value will be returned as `null`. You can override
  1083. * this by passing an options object.
  1084. *
  1085. * @param options - An options object to configure how data is retrieved from
  1086. * the snapshot (for example the desired behavior for server timestamps that
  1087. * have not yet been set to their final value).
  1088. * @returns An `Object` containing all fields in the document or `undefined` if
  1089. * the document doesn't exist.
  1090. */
  1091. data(options?: SnapshotOptions): T | undefined;
  1092. /**
  1093. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  1094. * document or field doesn't exist.
  1095. *
  1096. * By default, a `serverTimestamp()` that has not yet been set to
  1097. * its final value will be returned as `null`. You can override this by
  1098. * passing an options object.
  1099. *
  1100. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  1101. * field.
  1102. * @param options - An options object to configure how the field is retrieved
  1103. * from the snapshot (for example the desired behavior for server timestamps
  1104. * that have not yet been set to their final value).
  1105. * @returns The data at the specified field location or undefined if no such
  1106. * field exists in the document.
  1107. */
  1108. get(fieldPath: string | FieldPath, options?: SnapshotOptions): any;
  1109. }
  1110. /**
  1111. * A `DocumentSnapshot` contains data read from a document in your Firestore
  1112. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  1113. * get a specific field.
  1114. *
  1115. * For a `DocumentSnapshot` that points to a non-existing document, any data
  1116. * access will return 'undefined'. You can use the `exists()` method to
  1117. * explicitly verify a document's existence.
  1118. */
  1119. declare class DocumentSnapshot_2<T = DocumentData> {
  1120. _firestore: Firestore_2;
  1121. _userDataWriter: AbstractUserDataWriter;
  1122. _key: _DocumentKey;
  1123. _document: Document_2 | null;
  1124. _converter: UntypedFirestoreDataConverter<T> | null;
  1125. /** @hideconstructor protected */
  1126. constructor(_firestore: Firestore_2, _userDataWriter: AbstractUserDataWriter, _key: _DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter<T> | null);
  1127. /** Property of the `DocumentSnapshot` that provides the document's ID. */
  1128. get id(): string;
  1129. /**
  1130. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  1131. */
  1132. get ref(): DocumentReference<T>;
  1133. /**
  1134. * Signals whether or not the document at the snapshot's location exists.
  1135. *
  1136. * @returns true if the document exists.
  1137. */
  1138. exists(): this is QueryDocumentSnapshot_2<T>;
  1139. /**
  1140. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  1141. * the document doesn't exist.
  1142. *
  1143. * @returns An `Object` containing all fields in the document or `undefined`
  1144. * if the document doesn't exist.
  1145. */
  1146. data(): T | undefined;
  1147. /**
  1148. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  1149. * document or field doesn't exist.
  1150. *
  1151. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  1152. * field.
  1153. * @returns The data at the specified field location or undefined if no such
  1154. * field exists in the document.
  1155. */
  1156. get(fieldPath: string | FieldPath): any;
  1157. }
  1158. declare type DocumentVersionMap = SortedMap<_DocumentKey, SnapshotVersion>;
  1159. declare interface DocumentViewChange {
  1160. type: ChangeType;
  1161. doc: Document_2;
  1162. }
  1163. /* Excluded from this release type: _EmptyAppCheckTokenProvider */
  1164. /* Excluded from this release type: _EmptyAuthCredentialsProvider */
  1165. export { EmulatorMockTokenOptions }
  1166. /**
  1167. * Attempts to enable persistent storage, if possible.
  1168. *
  1169. * Must be called before any other functions (other than
  1170. * {@link initializeFirestore}, {@link (getFirestore:1)} or
  1171. * {@link clearIndexedDbPersistence}.
  1172. *
  1173. * If this fails, `enableIndexedDbPersistence()` will reject the promise it
  1174. * returns. Note that even after this failure, the {@link Firestore} instance will
  1175. * remain usable, however offline persistence will be disabled.
  1176. *
  1177. * There are several reasons why this can fail, which can be identified by
  1178. * the `code` on the error.
  1179. *
  1180. * * failed-precondition: The app is already open in another browser tab.
  1181. * * unimplemented: The browser is incompatible with the offline
  1182. * persistence implementation.
  1183. *
  1184. * Persistence cannot be used in a Node.js environment.
  1185. *
  1186. * @param firestore - The {@link Firestore} instance to enable persistence for.
  1187. * @param persistenceSettings - Optional settings object to configure
  1188. * persistence.
  1189. * @returns A `Promise` that represents successfully enabling persistent storage.
  1190. * @deprecated This function will be removed in a future major release. Instead, set
  1191. * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to
  1192. * turn on IndexedDb cache. Calling this function when `FirestoreSettings.cache`
  1193. * is already specified will throw an exception.
  1194. */
  1195. export declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise<void>;
  1196. /**
  1197. * Attempts to enable multi-tab persistent storage, if possible. If enabled
  1198. * across all tabs, all operations share access to local persistence, including
  1199. * shared execution of queries and latency-compensated local document updates
  1200. * across all connected instances.
  1201. *
  1202. * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
  1203. * it returns. Note that even after this failure, the {@link Firestore} instance will
  1204. * remain usable, however offline persistence will be disabled.
  1205. *
  1206. * There are several reasons why this can fail, which can be identified by
  1207. * the `code` on the error.
  1208. *
  1209. * * failed-precondition: The app is already open in another browser tab and
  1210. * multi-tab is not enabled.
  1211. * * unimplemented: The browser is incompatible with the offline
  1212. * persistence implementation.
  1213. *
  1214. * @param firestore - The {@link Firestore} instance to enable persistence for.
  1215. * @returns A `Promise` that represents successfully enabling persistent
  1216. * storage.
  1217. * @deprecated This function will be removed in a future major release. Instead, set
  1218. * `FirestoreSettings.cache` to an instance of `IndexedDbLocalCache` to
  1219. * turn on indexeddb cache. Calling this function when `FirestoreSettings.cache`
  1220. * is already specified will throw an exception.
  1221. */
  1222. export declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void>;
  1223. /**
  1224. * Re-enables use of the network for this {@link Firestore} instance after a prior
  1225. * call to {@link disableNetwork}.
  1226. *
  1227. * @returns A `Promise` that is resolved once the network has been enabled.
  1228. */
  1229. export declare function enableNetwork(firestore: Firestore): Promise<void>;
  1230. /**
  1231. * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at
  1232. * the provided document (inclusive). The end position is relative to the order
  1233. * of the query. The document must contain all of the fields provided in the
  1234. * orderBy of the query.
  1235. *
  1236. * @param snapshot - The snapshot of the document to end at.
  1237. * @returns A {@link QueryEndAtConstraint} to pass to `query()`
  1238. */
  1239. export declare function endAt(snapshot: DocumentSnapshot_2<unknown>): QueryEndAtConstraint;
  1240. /**
  1241. * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at
  1242. * the provided fields relative to the order of the query. The order of the field
  1243. * values must match the order of the order by clauses of the query.
  1244. *
  1245. * @param fieldValues - The field values to end this query at, in order
  1246. * of the query's order by.
  1247. * @returns A {@link QueryEndAtConstraint} to pass to `query()`
  1248. */
  1249. export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;
  1250. /**
  1251. * Creates a {@link QueryEndAtConstraint} that modifies the result set to end
  1252. * before the provided document (exclusive). The end position is relative to the
  1253. * order of the query. The document must contain all of the fields provided in
  1254. * the orderBy of the query.
  1255. *
  1256. * @param snapshot - The snapshot of the document to end before.
  1257. * @returns A {@link QueryEndAtConstraint} to pass to `query()`
  1258. */
  1259. export declare function endBefore(snapshot: DocumentSnapshot_2<unknown>): QueryEndAtConstraint;
  1260. /**
  1261. * Creates a {@link QueryEndAtConstraint} that modifies the result set to end
  1262. * before the provided fields relative to the order of the query. The order of
  1263. * the field values must match the order of the order by clauses of the query.
  1264. *
  1265. * @param fieldValues - The field values to end this query before, in order
  1266. * of the query's order by.
  1267. * @returns A {@link QueryEndAtConstraint} to pass to `query()`
  1268. */
  1269. export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;
  1270. /* Excluded from this release type: ensureFirestoreConfigured */
  1271. declare interface Entry<K, V> {
  1272. key: K;
  1273. value: V;
  1274. }
  1275. /**
  1276. * EventManager is responsible for mapping queries to query event emitters.
  1277. * It handles "fan-out". -- Identical queries will re-use the same watch on the
  1278. * backend.
  1279. *
  1280. * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be
  1281. * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This
  1282. * allows users to tree-shake the Watch logic.
  1283. */
  1284. declare interface EventManager {
  1285. onListen?: (query: Query_2) => Promise<ViewSnapshot>;
  1286. onUnlisten?: (query: Query_2) => Promise<void>;
  1287. }
  1288. /* Excluded from this release type: executeWrite */
  1289. /**
  1290. * The signature of callbacks registered with
  1291. * `TestingUtils.onExistenceFilterMismatch()`.
  1292. */
  1293. declare type ExistenceFilterMismatchCallback = (info: ExistenceFilterMismatchInfo) => void;
  1294. /**
  1295. * Information about an existence filter mismatch, as specified to callbacks
  1296. * registered with `TestingUtils.onExistenceFilterMismatch()`.
  1297. */
  1298. declare interface ExistenceFilterMismatchInfo {
  1299. /** The number of documents that matched the query in the local cache. */
  1300. localCacheCount: number;
  1301. /**
  1302. * The number of documents that matched the query on the server, as specified
  1303. * in the ExistenceFilter message's `count` field.
  1304. */
  1305. existenceFilterCount: number;
  1306. /**
  1307. * Information about the bloom filter provided by Watch in the ExistenceFilter
  1308. * message's `unchangedNames` field. If this property is omitted or undefined
  1309. * then that means that Watch did _not_ provide a bloom filter.
  1310. */
  1311. bloomFilter?: {
  1312. /**
  1313. * Whether a full requery was averted by using the bloom filter. If false,
  1314. * then something happened, such as a false positive, to prevent using the
  1315. * bloom filter to avoid a full requery.
  1316. */
  1317. applied: boolean;
  1318. /** The number of hash functions used in the bloom filter. */
  1319. hashCount: number;
  1320. /** The number of bytes in the bloom filter's bitmask. */
  1321. bitmapLength: number;
  1322. /** The number of bits of padding in the last byte of the bloom filter. */
  1323. padding: number;
  1324. };
  1325. }
  1326. /**
  1327. * @license
  1328. * Copyright 2023 Google LLC
  1329. *
  1330. * Licensed under the Apache License, Version 2.0 (the "License");
  1331. * you may not use this file except in compliance with the License.
  1332. * You may obtain a copy of the License at
  1333. *
  1334. * http://www.apache.org/licenses/LICENSE-2.0
  1335. *
  1336. * Unless required by applicable law or agreed to in writing, software
  1337. * distributed under the License is distributed on an "AS IS" BASIS,
  1338. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1339. * See the License for the specific language governing permissions and
  1340. * limitations under the License.
  1341. */
  1342. /**
  1343. * Options that configure the SDK’s underlying network transport (WebChannel)
  1344. * when long-polling is used.
  1345. *
  1346. * Note: This interface is "experimental" and is subject to change.
  1347. *
  1348. * See `FirestoreSettings.experimentalAutoDetectLongPolling`,
  1349. * `FirestoreSettings.experimentalForceLongPolling`, and
  1350. * `FirestoreSettings.experimentalLongPollingOptions`.
  1351. */
  1352. export declare interface ExperimentalLongPollingOptions {
  1353. /**
  1354. * The desired maximum timeout interval, in seconds, to complete a
  1355. * long-polling GET response. Valid values are between 5 and 30, inclusive.
  1356. * Floating point values are allowed and will be rounded to the nearest
  1357. * millisecond.
  1358. *
  1359. * By default, when long-polling is used the "hanging GET" request sent by
  1360. * the client times out after 30 seconds. To request a different timeout
  1361. * from the server, set this setting with the desired timeout.
  1362. *
  1363. * Changing the default timeout may be useful, for example, if the buffering
  1364. * proxy that necessitated enabling long-polling in the first place has a
  1365. * shorter timeout for hanging GET requests, in which case setting the
  1366. * long-polling timeout to a shorter value, such as 25 seconds, may fix
  1367. * prematurely-closed hanging GET requests.
  1368. * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.
  1369. */
  1370. timeoutSeconds?: number;
  1371. }
  1372. declare class FieldFilter extends Filter {
  1373. readonly field: _FieldPath;
  1374. readonly op: Operator;
  1375. readonly value: Value;
  1376. protected constructor(field: _FieldPath, op: Operator, value: Value);
  1377. /**
  1378. * Creates a filter based on the provided arguments.
  1379. */
  1380. static create(field: _FieldPath, op: Operator, value: Value): FieldFilter;
  1381. private static createKeyFieldInFilter;
  1382. matches(doc: Document_2): boolean;
  1383. protected matchesComparison(comparison: number): boolean;
  1384. isInequality(): boolean;
  1385. getFlattenedFilters(): readonly FieldFilter[];
  1386. getFilters(): Filter[];
  1387. getFirstInequalityField(): _FieldPath | null;
  1388. }
  1389. declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN';
  1390. /**
  1391. * An index definition for field indexes in Firestore.
  1392. *
  1393. * Every index is associated with a collection. The definition contains a list
  1394. * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or
  1395. * `CONTAINS` for ArrayContains/ArrayContainsAny queries).
  1396. *
  1397. * Unlike the backend, the SDK does not differentiate between collection or
  1398. * collection group-scoped indices. Every index can be used for both single
  1399. * collection and collection group queries.
  1400. */
  1401. declare class FieldIndex {
  1402. /**
  1403. * The index ID. Returns -1 if the index ID is not available (e.g. the index
  1404. * has not yet been persisted).
  1405. */
  1406. readonly indexId: number;
  1407. /** The collection ID this index applies to. */
  1408. readonly collectionGroup: string;
  1409. /** The field segments for this index. */
  1410. readonly fields: IndexSegment[];
  1411. /** Shows how up-to-date the index is for the current user. */
  1412. readonly indexState: IndexState;
  1413. /** An ID for an index that has not yet been added to persistence. */
  1414. static UNKNOWN_ID: number;
  1415. constructor(
  1416. /**
  1417. * The index ID. Returns -1 if the index ID is not available (e.g. the index
  1418. * has not yet been persisted).
  1419. */
  1420. indexId: number,
  1421. /** The collection ID this index applies to. */
  1422. collectionGroup: string,
  1423. /** The field segments for this index. */
  1424. fields: IndexSegment[],
  1425. /** Shows how up-to-date the index is for the current user. */
  1426. indexState: IndexState);
  1427. }
  1428. /**
  1429. * Provides a set of fields that can be used to partially patch a document.
  1430. * FieldMask is used in conjunction with ObjectValue.
  1431. * Examples:
  1432. * foo - Overwrites foo entirely with the provided value. If foo is not
  1433. * present in the companion ObjectValue, the field is deleted.
  1434. * foo.bar - Overwrites only the field bar of the object foo.
  1435. * If foo is not an object, foo is replaced with an object
  1436. * containing foo
  1437. */
  1438. declare class FieldMask {
  1439. readonly fields: _FieldPath[];
  1440. constructor(fields: _FieldPath[]);
  1441. static empty(): FieldMask;
  1442. /**
  1443. * Returns a new FieldMask object that is the result of adding all the given
  1444. * fields paths to this field mask.
  1445. */
  1446. unionWith(extraFields: _FieldPath[]): FieldMask;
  1447. /**
  1448. * Verifies that `fieldPath` is included by at least one field in this field
  1449. * mask.
  1450. *
  1451. * This is an O(n) operation, where `n` is the size of the field mask.
  1452. */
  1453. covers(fieldPath: _FieldPath): boolean;
  1454. isEqual(other: FieldMask): boolean;
  1455. }
  1456. /**
  1457. * A `FieldPath` refers to a field in a document. The path may consist of a
  1458. * single field name (referring to a top-level field in the document), or a
  1459. * list of field names (referring to a nested field in the document).
  1460. *
  1461. * Create a `FieldPath` by providing field names. If more than one field
  1462. * name is provided, the path will point to a nested field in a document.
  1463. */
  1464. export declare class FieldPath {
  1465. /** Internal representation of a Firestore field path. */
  1466. readonly _internalPath: _FieldPath;
  1467. /**
  1468. * Creates a `FieldPath` from the provided field names. If more than one field
  1469. * name is provided, the path will point to a nested field in a document.
  1470. *
  1471. * @param fieldNames - A list of field names.
  1472. */
  1473. constructor(...fieldNames: string[]);
  1474. /**
  1475. * Returns true if this `FieldPath` is equal to the provided one.
  1476. *
  1477. * @param other - The `FieldPath` to compare against.
  1478. * @returns true if this `FieldPath` is equal to the provided one.
  1479. */
  1480. isEqual(other: FieldPath): boolean;
  1481. }
  1482. /* Excluded from this release type: _FieldPath */
  1483. /** A field path and the TransformOperation to perform upon it. */
  1484. declare class FieldTransform {
  1485. readonly field: _FieldPath;
  1486. readonly transform: TransformOperation;
  1487. constructor(field: _FieldPath, transform: TransformOperation);
  1488. }
  1489. declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME';
  1490. /**
  1491. * Sentinel values that can be used when writing document fields with `set()`
  1492. * or `update()`.
  1493. */
  1494. export declare abstract class FieldValue {
  1495. _methodName: string;
  1496. /**
  1497. * @param _methodName - The public API endpoint that returns this class.
  1498. * @hideconstructor
  1499. */
  1500. constructor(_methodName: string);
  1501. /** Compares `FieldValue`s for equality. */
  1502. abstract isEqual(other: FieldValue): boolean;
  1503. abstract _toFieldTransform(context: ParseContext): FieldTransform | null;
  1504. }
  1505. declare abstract class Filter {
  1506. abstract matches(doc: Document_2): boolean;
  1507. abstract getFlattenedFilters(): readonly FieldFilter[];
  1508. abstract getFilters(): Filter[];
  1509. abstract getFirstInequalityField(): _FieldPath | null;
  1510. }
  1511. /* Excluded from this release type: _FirebaseService */
  1512. /**
  1513. * The Cloud Firestore service interface.
  1514. *
  1515. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  1516. */
  1517. export declare class Firestore extends Firestore_2 {
  1518. /**
  1519. * Whether it's a {@link Firestore} or Firestore Lite instance.
  1520. */
  1521. type: 'firestore-lite' | 'firestore';
  1522. readonly _queue: AsyncQueue;
  1523. readonly _persistenceKey: string;
  1524. _firestoreClient: FirestoreClient | undefined;
  1525. /** @hideconstructor */
  1526. constructor(authCredentialsProvider: CredentialsProvider<User>, appCheckCredentialsProvider: CredentialsProvider<string>, databaseId: _DatabaseId, app?: FirebaseApp);
  1527. _terminate(): Promise<void>;
  1528. }
  1529. /**
  1530. * The Cloud Firestore service interface.
  1531. *
  1532. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  1533. */
  1534. declare class Firestore_2 implements FirestoreService {
  1535. _authCredentials: CredentialsProvider<User>;
  1536. _appCheckCredentials: CredentialsProvider<string>;
  1537. readonly _databaseId: _DatabaseId;
  1538. readonly _app?: FirebaseApp | undefined;
  1539. /**
  1540. * Whether it's a Firestore or Firestore Lite instance.
  1541. */
  1542. type: 'firestore-lite' | 'firestore';
  1543. readonly _persistenceKey: string;
  1544. private _settings;
  1545. private _settingsFrozen;
  1546. private _terminateTask?;
  1547. /** @hideconstructor */
  1548. constructor(_authCredentials: CredentialsProvider<User>, _appCheckCredentials: CredentialsProvider<string>, _databaseId: _DatabaseId, _app?: FirebaseApp | undefined);
  1549. /**
  1550. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  1551. * instance.
  1552. */
  1553. get app(): FirebaseApp;
  1554. get _initialized(): boolean;
  1555. get _terminated(): boolean;
  1556. _setSettings(settings: PrivateSettings): void;
  1557. _getSettings(): FirestoreSettingsImpl;
  1558. _freezeSettings(): FirestoreSettingsImpl;
  1559. _delete(): Promise<void>;
  1560. /** Returns a JSON-serializable representation of this `Firestore` instance. */
  1561. toJSON(): object;
  1562. /**
  1563. * Terminates all components used by this client. Subclasses can override
  1564. * this method to clean up their own dependencies, but must also call this
  1565. * method.
  1566. *
  1567. * Only ever called once.
  1568. */
  1569. protected _terminate(): Promise<void>;
  1570. }
  1571. /**
  1572. * FirestoreClient is a top-level class that constructs and owns all of the //
  1573. * pieces of the client SDK architecture. It is responsible for creating the //
  1574. * async queue that is shared by all of the other components in the system. //
  1575. */
  1576. declare class FirestoreClient {
  1577. private authCredentials;
  1578. private appCheckCredentials;
  1579. /**
  1580. * Asynchronous queue responsible for all of our internal processing. When
  1581. * we get incoming work from the user (via public API) or the network
  1582. * (incoming GRPC messages), we should always schedule onto this queue.
  1583. * This ensures all of our work is properly serialized (e.g. we don't
  1584. * start processing a new operation while the previous one is waiting for
  1585. * an async I/O to complete).
  1586. */
  1587. asyncQueue: AsyncQueue;
  1588. private databaseInfo;
  1589. private user;
  1590. private readonly clientId;
  1591. private authCredentialListener;
  1592. private appCheckCredentialListener;
  1593. _uninitializedComponentsProvider?: {
  1594. _offline: OfflineComponentProvider;
  1595. _offlineKind: 'memory' | 'persistent';
  1596. _online: OnlineComponentProvider;
  1597. };
  1598. _offlineComponents?: OfflineComponentProvider;
  1599. _onlineComponents?: OnlineComponentProvider;
  1600. constructor(authCredentials: CredentialsProvider<User>, appCheckCredentials: CredentialsProvider<string>,
  1601. /**
  1602. * Asynchronous queue responsible for all of our internal processing. When
  1603. * we get incoming work from the user (via public API) or the network
  1604. * (incoming GRPC messages), we should always schedule onto this queue.
  1605. * This ensures all of our work is properly serialized (e.g. we don't
  1606. * start processing a new operation while the previous one is waiting for
  1607. * an async I/O to complete).
  1608. */
  1609. asyncQueue: AsyncQueue, databaseInfo: DatabaseInfo);
  1610. getConfiguration(): Promise<ComponentConfiguration>;
  1611. setCredentialChangeListener(listener: (user: User) => Promise<void>): void;
  1612. setAppCheckTokenChangeListener(listener: (appCheckToken: string, user: User) => Promise<void>): void;
  1613. /**
  1614. * Checks that the client has not been terminated. Ensures that other methods on //
  1615. * this class cannot be called after the client is terminated. //
  1616. */
  1617. verifyNotTerminated(): void;
  1618. terminate(): Promise<void>;
  1619. }
  1620. /**
  1621. * Converter used by `withConverter()` to transform user objects of type `T`
  1622. * into Firestore data.
  1623. *
  1624. * Using the converter allows you to specify generic type arguments when
  1625. * storing and retrieving objects from Firestore.
  1626. *
  1627. * @example
  1628. * ```typescript
  1629. * class Post {
  1630. * constructor(readonly title: string, readonly author: string) {}
  1631. *
  1632. * toString(): string {
  1633. * return this.title + ', by ' + this.author;
  1634. * }
  1635. * }
  1636. *
  1637. * const postConverter = {
  1638. * toFirestore(post: WithFieldValue<Post>): DocumentData {
  1639. * return {title: post.title, author: post.author};
  1640. * },
  1641. * fromFirestore(
  1642. * snapshot: QueryDocumentSnapshot,
  1643. * options: SnapshotOptions
  1644. * ): Post {
  1645. * const data = snapshot.data(options)!;
  1646. * return new Post(data.title, data.author);
  1647. * }
  1648. * };
  1649. *
  1650. * const postSnap = await firebase.firestore()
  1651. * .collection('posts')
  1652. * .withConverter(postConverter)
  1653. * .doc().get();
  1654. * const post = postSnap.data();
  1655. * if (post !== undefined) {
  1656. * post.title; // string
  1657. * post.toString(); // Should be defined
  1658. * post.someNonExistentProperty; // TS error
  1659. * }
  1660. * ```
  1661. */
  1662. export declare interface FirestoreDataConverter<T> extends FirestoreDataConverter_2<T> {
  1663. /**
  1664. * Called by the Firestore SDK to convert a custom model object of type `T`
  1665. * into a plain JavaScript object (suitable for writing directly to the
  1666. * Firestore database). To use `set()` with `merge` and `mergeFields`,
  1667. * `toFirestore()` must be defined with `PartialWithFieldValue<T>`.
  1668. *
  1669. * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as
  1670. * {@link (deleteField:1)} to be used as property values.
  1671. */
  1672. toFirestore(modelObject: WithFieldValue<T>): DocumentData;
  1673. /**
  1674. * Called by the Firestore SDK to convert a custom model object of type `T`
  1675. * into a plain JavaScript object (suitable for writing directly to the
  1676. * Firestore database). Used with {@link (setDoc:1)}, {@link (WriteBatch.set:1)}
  1677. * and {@link (Transaction.set:1)} with `merge:true` or `mergeFields`.
  1678. *
  1679. * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow
  1680. * FieldValues such as {@link (arrayUnion:1)} to be used as property values.
  1681. * It also supports nested `Partial` by allowing nested fields to be
  1682. * omitted.
  1683. */
  1684. toFirestore(modelObject: PartialWithFieldValue<T>, options: SetOptions): DocumentData;
  1685. /**
  1686. * Called by the Firestore SDK to convert Firestore data into an object of
  1687. * type T. You can access your data by calling: `snapshot.data(options)`.
  1688. *
  1689. * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata.
  1690. * @param options - The `SnapshotOptions` from the initial call to `data()`.
  1691. */
  1692. fromFirestore(snapshot: QueryDocumentSnapshot<DocumentData>, options?: SnapshotOptions): T;
  1693. }
  1694. /**
  1695. * Converter used by `withConverter()` to transform user objects of type `T`
  1696. * into Firestore data.
  1697. *
  1698. * Using the converter allows you to specify generic type arguments when
  1699. * storing and retrieving objects from Firestore.
  1700. *
  1701. * @example
  1702. * ```typescript
  1703. * class Post {
  1704. * constructor(readonly title: string, readonly author: string) {}
  1705. *
  1706. * toString(): string {
  1707. * return this.title + ', by ' + this.author;
  1708. * }
  1709. * }
  1710. *
  1711. * const postConverter = {
  1712. * toFirestore(post: WithFieldValue<Post>): DocumentData {
  1713. * return {title: post.title, author: post.author};
  1714. * },
  1715. * fromFirestore(snapshot: QueryDocumentSnapshot): Post {
  1716. * const data = snapshot.data(options)!;
  1717. * return new Post(data.title, data.author);
  1718. * }
  1719. * };
  1720. *
  1721. * const postSnap = await firebase.firestore()
  1722. * .collection('posts')
  1723. * .withConverter(postConverter)
  1724. * .doc().get();
  1725. * const post = postSnap.data();
  1726. * if (post !== undefined) {
  1727. * post.title; // string
  1728. * post.toString(); // Should be defined
  1729. * post.someNonExistentProperty; // TS error
  1730. * }
  1731. * ```
  1732. */
  1733. declare interface FirestoreDataConverter_2<T> {
  1734. /**
  1735. * Called by the Firestore SDK to convert a custom model object of type `T`
  1736. * into a plain Javascript object (suitable for writing directly to the
  1737. * Firestore database). Used with {@link @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#(WriteBatch.set:1)}
  1738. * and {@link @firebase/firestore/lite#(Transaction.set:1)}.
  1739. *
  1740. * The `WithFieldValue<T>` type extends `T` to also allow FieldValues such as
  1741. * {@link (deleteField:1)} to be used as property values.
  1742. */
  1743. toFirestore(modelObject: WithFieldValue<T>): DocumentData;
  1744. /**
  1745. * Called by the Firestore SDK to convert a custom model object of type `T`
  1746. * into a plain Javascript object (suitable for writing directly to the
  1747. * Firestore database). Used with {@link @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#(WriteBatch.set:1)}
  1748. * and {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` or `mergeFields`.
  1749. *
  1750. * The `PartialWithFieldValue<T>` type extends `Partial<T>` to allow
  1751. * FieldValues such as {@link (arrayUnion:1)} to be used as property values.
  1752. * It also supports nested `Partial` by allowing nested fields to be
  1753. * omitted.
  1754. */
  1755. toFirestore(modelObject: PartialWithFieldValue<T>, options: SetOptions): DocumentData;
  1756. /**
  1757. * Called by the Firestore SDK to convert Firestore data into an object of
  1758. * type T. You can access your data by calling: `snapshot.data()`.
  1759. *
  1760. * @param snapshot - A `QueryDocumentSnapshot` containing your data and
  1761. * metadata.
  1762. */
  1763. fromFirestore(snapshot: QueryDocumentSnapshot_2<DocumentData>): T;
  1764. }
  1765. /** An error returned by a Firestore operation. */
  1766. export declare class FirestoreError extends FirebaseError {
  1767. /**
  1768. * The backend error code associated with this error.
  1769. */
  1770. readonly code: FirestoreErrorCode;
  1771. /**
  1772. * A custom error description.
  1773. */
  1774. readonly message: string;
  1775. /** The stack of the error. */
  1776. readonly stack?: string;
  1777. /** @hideconstructor */
  1778. constructor(
  1779. /**
  1780. * The backend error code associated with this error.
  1781. */
  1782. code: FirestoreErrorCode,
  1783. /**
  1784. * A custom error description.
  1785. */
  1786. message: string);
  1787. }
  1788. /**
  1789. * The set of Firestore status codes. The codes are the same at the ones
  1790. * exposed by gRPC here:
  1791. * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
  1792. *
  1793. * Possible values:
  1794. * - 'cancelled': The operation was cancelled (typically by the caller).
  1795. * - 'unknown': Unknown error or an error from a different error domain.
  1796. * - 'invalid-argument': Client specified an invalid argument. Note that this
  1797. * differs from 'failed-precondition'. 'invalid-argument' indicates
  1798. * arguments that are problematic regardless of the state of the system
  1799. * (e.g. an invalid field name).
  1800. * - 'deadline-exceeded': Deadline expired before operation could complete.
  1801. * For operations that change the state of the system, this error may be
  1802. * returned even if the operation has completed successfully. For example,
  1803. * a successful response from a server could have been delayed long enough
  1804. * for the deadline to expire.
  1805. * - 'not-found': Some requested document was not found.
  1806. * - 'already-exists': Some document that we attempted to create already
  1807. * exists.
  1808. * - 'permission-denied': The caller does not have permission to execute the
  1809. * specified operation.
  1810. * - 'resource-exhausted': Some resource has been exhausted, perhaps a
  1811. * per-user quota, or perhaps the entire file system is out of space.
  1812. * - 'failed-precondition': Operation was rejected because the system is not
  1813. * in a state required for the operation's execution.
  1814. * - 'aborted': The operation was aborted, typically due to a concurrency
  1815. * issue like transaction aborts, etc.
  1816. * - 'out-of-range': Operation was attempted past the valid range.
  1817. * - 'unimplemented': Operation is not implemented or not supported/enabled.
  1818. * - 'internal': Internal errors. Means some invariants expected by
  1819. * underlying system has been broken. If you see one of these errors,
  1820. * something is very broken.
  1821. * - 'unavailable': The service is currently unavailable. This is most likely
  1822. * a transient condition and may be corrected by retrying with a backoff.
  1823. * - 'data-loss': Unrecoverable data loss or corruption.
  1824. * - 'unauthenticated': The request does not have valid authentication
  1825. * credentials for the operation.
  1826. */
  1827. export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated';
  1828. /**
  1829. * Union type from all supported SDK cache layer.
  1830. */
  1831. export declare type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache;
  1832. /**
  1833. * An interface implemented by FirebaseFirestore that provides compatibility
  1834. * with the usage in this file.
  1835. *
  1836. * This interface mainly exists to remove a cyclic dependency.
  1837. */
  1838. declare interface FirestoreService extends _FirebaseService {
  1839. _authCredentials: CredentialsProvider<User>;
  1840. _appCheckCredentials: CredentialsProvider<string>;
  1841. _persistenceKey: string;
  1842. _databaseId: _DatabaseId;
  1843. _terminated: boolean;
  1844. _freezeSettings(): FirestoreSettingsImpl;
  1845. }
  1846. /**
  1847. * Specifies custom configurations for your Cloud Firestore instance.
  1848. * You must set these before invoking any other methods.
  1849. */
  1850. export declare interface FirestoreSettings extends FirestoreSettings_2 {
  1851. /**
  1852. * NOTE: This field will be deprecated in a future major release. Use `cache` field
  1853. * instead to specify cache size, and other cache configurations.
  1854. *
  1855. * An approximate cache size threshold for the on-disk data. If the cache
  1856. * grows beyond this size, Firestore will start removing data that hasn't been
  1857. * recently used. The size is not a guarantee that the cache will stay below
  1858. * that size, only that if the cache exceeds the given size, cleanup will be
  1859. * attempted.
  1860. *
  1861. * The default value is 40 MB. The threshold must be set to at least 1 MB, and
  1862. * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.
  1863. */
  1864. cacheSizeBytes?: number;
  1865. /**
  1866. * Specifies the cache used by the SDK. Available options are `MemoryLocalCache`
  1867. * and `IndexedDbLocalCache`, each with different configuration options.
  1868. *
  1869. * When unspecified, `MemoryLocalCache` will be used by default.
  1870. *
  1871. * NOTE: setting this field and `cacheSizeBytes` at the same time will throw
  1872. * exception during SDK initialization. Instead, using the configuration in
  1873. * the `FirestoreLocalCache` object to specify the cache size.
  1874. */
  1875. localCache?: FirestoreLocalCache;
  1876. /**
  1877. * Forces the SDK’s underlying network transport (WebChannel) to use
  1878. * long-polling. Each response from the backend will be closed immediately
  1879. * after the backend sends data (by default responses are kept open in
  1880. * case the backend has more data to send). This avoids incompatibility
  1881. * issues with certain proxies, antivirus software, etc. that incorrectly
  1882. * buffer traffic indefinitely. Use of this option will cause some
  1883. * performance degradation though.
  1884. *
  1885. * This setting cannot be used with `experimentalAutoDetectLongPolling` and
  1886. * may be removed in a future release. If you find yourself using it to
  1887. * work around a specific network reliability issue, please tell us about
  1888. * it in https://github.com/firebase/firebase-js-sdk/issues/1674.
  1889. *
  1890. * This setting cannot be used in a Node.js environment.
  1891. */
  1892. experimentalForceLongPolling?: boolean;
  1893. /**
  1894. * Configures the SDK's underlying transport (WebChannel) to automatically
  1895. * detect if long-polling should be used. This is very similar to
  1896. * `experimentalForceLongPolling`, but only uses long-polling if required.
  1897. *
  1898. * After having had a default value of `false` since its inception in 2019,
  1899. * the default value of this setting was changed in May 2023 to `true` in
  1900. * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long
  1901. * polling is now enabled by default. To disable it, set this setting to
  1902. * `false`, and please open a GitHub issue to share the problems that
  1903. * motivated you disabling long-polling auto-detection.
  1904. *
  1905. * This setting cannot be used in a Node.js environment.
  1906. */
  1907. experimentalAutoDetectLongPolling?: boolean;
  1908. /**
  1909. * Options that configure the SDK’s underlying network transport (WebChannel)
  1910. * when long-polling is used.
  1911. *
  1912. * These options are only used if `experimentalForceLongPolling` is true or if
  1913. * `experimentalAutoDetectLongPolling` is true and the auto-detection
  1914. * determined that long-polling was needed. Otherwise, these options have no
  1915. * effect.
  1916. */
  1917. experimentalLongPollingOptions?: ExperimentalLongPollingOptions;
  1918. }
  1919. /**
  1920. * Specifies custom configurations for your Cloud Firestore instance.
  1921. * You must set these before invoking any other methods.
  1922. */
  1923. declare interface FirestoreSettings_2 {
  1924. /** The hostname to connect to. */
  1925. host?: string;
  1926. /** Whether to use SSL when connecting. */
  1927. ssl?: boolean;
  1928. /**
  1929. * Whether to skip nested properties that are set to `undefined` during
  1930. * object serialization. If set to `true`, these properties are skipped
  1931. * and not written to Firestore. If set to `false` or omitted, the SDK
  1932. * throws an exception when it encounters properties of type `undefined`.
  1933. */
  1934. ignoreUndefinedProperties?: boolean;
  1935. }
  1936. /**
  1937. * A concrete type describing all the values that can be applied via a
  1938. * user-supplied `FirestoreSettings` object. This is a separate type so that
  1939. * defaults can be supplied and the value can be checked for equality.
  1940. */
  1941. declare class FirestoreSettingsImpl {
  1942. /** The hostname to connect to. */
  1943. readonly host: string;
  1944. /** Whether to use SSL when connecting. */
  1945. readonly ssl: boolean;
  1946. readonly cacheSizeBytes: number;
  1947. readonly experimentalForceLongPolling: boolean;
  1948. readonly experimentalAutoDetectLongPolling: boolean;
  1949. readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions;
  1950. readonly ignoreUndefinedProperties: boolean;
  1951. readonly useFetchStreams: boolean;
  1952. readonly cache?: FirestoreLocalCache;
  1953. credentials?: any;
  1954. constructor(settings: PrivateSettings);
  1955. isEqual(other: FirestoreSettingsImpl): boolean;
  1956. }
  1957. declare namespace firestoreV1ApiClientInterfaces {
  1958. interface ArrayValue {
  1959. values?: Value[];
  1960. }
  1961. interface BatchGetDocumentsRequest {
  1962. database?: string;
  1963. documents?: string[];
  1964. mask?: DocumentMask;
  1965. transaction?: string;
  1966. newTransaction?: TransactionOptions;
  1967. readTime?: string;
  1968. }
  1969. interface BatchGetDocumentsResponse {
  1970. found?: Document;
  1971. missing?: string;
  1972. transaction?: string;
  1973. readTime?: string;
  1974. }
  1975. interface BeginTransactionRequest {
  1976. options?: TransactionOptions;
  1977. }
  1978. interface BeginTransactionResponse {
  1979. transaction?: string;
  1980. }
  1981. interface CollectionSelector {
  1982. collectionId?: string;
  1983. allDescendants?: boolean;
  1984. }
  1985. interface CommitRequest {
  1986. database?: string;
  1987. writes?: Write[];
  1988. transaction?: string;
  1989. }
  1990. interface CommitResponse {
  1991. writeResults?: WriteResult[];
  1992. commitTime?: string;
  1993. }
  1994. interface CompositeFilter {
  1995. op?: CompositeFilterOp;
  1996. filters?: Filter[];
  1997. }
  1998. interface Cursor {
  1999. values?: Value[];
  2000. before?: boolean;
  2001. }
  2002. interface Document {
  2003. name?: string;
  2004. fields?: ApiClientObjectMap<Value>;
  2005. createTime?: Timestamp_2;
  2006. updateTime?: Timestamp_2;
  2007. }
  2008. interface DocumentChange {
  2009. document?: Document;
  2010. targetIds?: number[];
  2011. removedTargetIds?: number[];
  2012. }
  2013. interface DocumentDelete {
  2014. document?: string;
  2015. removedTargetIds?: number[];
  2016. readTime?: Timestamp_2;
  2017. }
  2018. interface DocumentMask {
  2019. fieldPaths?: string[];
  2020. }
  2021. interface DocumentRemove {
  2022. document?: string;
  2023. removedTargetIds?: number[];
  2024. readTime?: string;
  2025. }
  2026. interface DocumentTransform {
  2027. document?: string;
  2028. fieldTransforms?: FieldTransform[];
  2029. }
  2030. interface DocumentsTarget {
  2031. documents?: string[];
  2032. }
  2033. interface Empty {
  2034. }
  2035. interface ExistenceFilter {
  2036. targetId?: number;
  2037. count?: number;
  2038. unchangedNames?: BloomFilter;
  2039. }
  2040. interface BloomFilter {
  2041. bits?: BitSequence;
  2042. hashCount?: number;
  2043. }
  2044. interface BitSequence {
  2045. bitmap?: string | Uint8Array;
  2046. padding?: number;
  2047. }
  2048. interface FieldFilter {
  2049. field?: FieldReference;
  2050. op?: FieldFilterOp;
  2051. value?: Value;
  2052. }
  2053. interface FieldReference {
  2054. fieldPath?: string;
  2055. }
  2056. interface FieldTransform {
  2057. fieldPath?: string;
  2058. setToServerValue?: FieldTransformSetToServerValue;
  2059. appendMissingElements?: ArrayValue;
  2060. removeAllFromArray?: ArrayValue;
  2061. increment?: Value;
  2062. }
  2063. interface Filter {
  2064. compositeFilter?: CompositeFilter;
  2065. fieldFilter?: FieldFilter;
  2066. unaryFilter?: UnaryFilter;
  2067. }
  2068. interface Index {
  2069. name?: string;
  2070. collectionId?: string;
  2071. fields?: IndexField[];
  2072. state?: IndexState_2;
  2073. }
  2074. interface IndexField {
  2075. fieldPath?: string;
  2076. mode?: IndexFieldMode;
  2077. }
  2078. interface LatLng {
  2079. latitude?: number;
  2080. longitude?: number;
  2081. }
  2082. interface ListCollectionIdsRequest {
  2083. pageSize?: number;
  2084. pageToken?: string;
  2085. }
  2086. interface ListCollectionIdsResponse {
  2087. collectionIds?: string[];
  2088. nextPageToken?: string;
  2089. }
  2090. interface ListDocumentsResponse {
  2091. documents?: Document[];
  2092. nextPageToken?: string;
  2093. }
  2094. interface ListIndexesResponse {
  2095. indexes?: Index[];
  2096. nextPageToken?: string;
  2097. }
  2098. interface ListenRequest {
  2099. addTarget?: Target;
  2100. removeTarget?: number;
  2101. labels?: ApiClientObjectMap<string>;
  2102. }
  2103. interface ListenResponse {
  2104. targetChange?: TargetChange;
  2105. documentChange?: DocumentChange;
  2106. documentDelete?: DocumentDelete;
  2107. documentRemove?: DocumentRemove;
  2108. filter?: ExistenceFilter;
  2109. }
  2110. interface MapValue {
  2111. fields?: ApiClientObjectMap<Value>;
  2112. }
  2113. interface Operation {
  2114. name?: string;
  2115. metadata?: ApiClientObjectMap<any>;
  2116. done?: boolean;
  2117. error?: Status;
  2118. response?: ApiClientObjectMap<any>;
  2119. }
  2120. interface Order {
  2121. field?: FieldReference;
  2122. direction?: OrderDirection;
  2123. }
  2124. interface Precondition {
  2125. exists?: boolean;
  2126. updateTime?: Timestamp_2;
  2127. }
  2128. interface Projection {
  2129. fields?: FieldReference[];
  2130. }
  2131. interface QueryTarget {
  2132. parent?: string;
  2133. structuredQuery?: StructuredQuery;
  2134. }
  2135. interface ReadOnly {
  2136. readTime?: string;
  2137. }
  2138. interface ReadWrite {
  2139. retryTransaction?: string;
  2140. }
  2141. interface RollbackRequest {
  2142. transaction?: string;
  2143. }
  2144. interface RunQueryRequest {
  2145. parent?: string;
  2146. structuredQuery?: StructuredQuery;
  2147. transaction?: string;
  2148. newTransaction?: TransactionOptions;
  2149. readTime?: string;
  2150. }
  2151. interface RunQueryResponse {
  2152. transaction?: string;
  2153. document?: Document;
  2154. readTime?: string;
  2155. skippedResults?: number;
  2156. }
  2157. interface RunAggregationQueryRequest {
  2158. parent?: string;
  2159. structuredAggregationQuery?: StructuredAggregationQuery;
  2160. transaction?: string;
  2161. newTransaction?: TransactionOptions;
  2162. readTime?: string;
  2163. }
  2164. interface RunAggregationQueryResponse {
  2165. result?: AggregationResult;
  2166. transaction?: string;
  2167. readTime?: string;
  2168. }
  2169. interface AggregationResult {
  2170. aggregateFields?: ApiClientObjectMap<Value>;
  2171. }
  2172. interface StructuredAggregationQuery {
  2173. structuredQuery?: StructuredQuery;
  2174. aggregations?: Aggregation[];
  2175. }
  2176. interface Aggregation {
  2177. count?: Count;
  2178. sum?: Sum;
  2179. avg?: Avg;
  2180. alias?: string;
  2181. }
  2182. interface Count {
  2183. upTo?: number;
  2184. }
  2185. interface Sum {
  2186. field?: FieldReference;
  2187. }
  2188. interface Avg {
  2189. field?: FieldReference;
  2190. }
  2191. interface Status {
  2192. code?: number;
  2193. message?: string;
  2194. details?: Array<ApiClientObjectMap<any>>;
  2195. }
  2196. interface StructuredQuery {
  2197. select?: Projection;
  2198. from?: CollectionSelector[];
  2199. where?: Filter;
  2200. orderBy?: Order[];
  2201. startAt?: Cursor;
  2202. endAt?: Cursor;
  2203. offset?: number;
  2204. limit?: number | {
  2205. value: number;
  2206. };
  2207. }
  2208. interface Target {
  2209. query?: QueryTarget;
  2210. documents?: DocumentsTarget;
  2211. resumeToken?: string | Uint8Array;
  2212. readTime?: Timestamp_2;
  2213. targetId?: number;
  2214. once?: boolean;
  2215. expectedCount?: number | {
  2216. value: number;
  2217. };
  2218. }
  2219. interface TargetChange {
  2220. targetChangeType?: TargetChangeTargetChangeType;
  2221. targetIds?: number[];
  2222. cause?: Status;
  2223. resumeToken?: string | Uint8Array;
  2224. readTime?: Timestamp_2;
  2225. }
  2226. interface TransactionOptions {
  2227. readOnly?: ReadOnly;
  2228. readWrite?: ReadWrite;
  2229. }
  2230. interface UnaryFilter {
  2231. op?: UnaryFilterOp;
  2232. field?: FieldReference;
  2233. }
  2234. interface Value {
  2235. nullValue?: ValueNullValue;
  2236. booleanValue?: boolean;
  2237. integerValue?: string | number;
  2238. doubleValue?: string | number;
  2239. timestampValue?: Timestamp_2;
  2240. stringValue?: string;
  2241. bytesValue?: string | Uint8Array;
  2242. referenceValue?: string;
  2243. geoPointValue?: LatLng;
  2244. arrayValue?: ArrayValue;
  2245. mapValue?: MapValue;
  2246. }
  2247. interface Write {
  2248. update?: Document;
  2249. delete?: string;
  2250. verify?: string;
  2251. transform?: DocumentTransform;
  2252. updateMask?: DocumentMask;
  2253. updateTransforms?: FieldTransform[];
  2254. currentDocument?: Precondition;
  2255. }
  2256. interface WriteRequest {
  2257. streamId?: string;
  2258. writes?: Write[];
  2259. streamToken?: string | Uint8Array;
  2260. labels?: ApiClientObjectMap<string>;
  2261. }
  2262. interface WriteResponse {
  2263. streamId?: string;
  2264. streamToken?: string | Uint8Array;
  2265. writeResults?: WriteResult[];
  2266. commitTime?: Timestamp_2;
  2267. }
  2268. interface WriteResult {
  2269. updateTime?: Timestamp_2;
  2270. transformResults?: Value[];
  2271. }
  2272. }
  2273. declare interface FirstPartyCredentialsSettings {
  2274. ['type']: 'firstParty';
  2275. ['sessionIndex']: string;
  2276. ['iamToken']: string | null;
  2277. ['authTokenFactory']: AuthTokenFactory | null;
  2278. }
  2279. /**
  2280. * @license
  2281. * Copyright 2017 Google LLC
  2282. *
  2283. * Licensed under the Apache License, Version 2.0 (the "License");
  2284. * you may not use this file except in compliance with the License.
  2285. * You may obtain a copy of the License at
  2286. *
  2287. * http://www.apache.org/licenses/LICENSE-2.0
  2288. *
  2289. * Unless required by applicable law or agreed to in writing, software
  2290. * distributed under the License is distributed on an "AS IS" BASIS,
  2291. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2292. * See the License for the specific language governing permissions and
  2293. * limitations under the License.
  2294. */
  2295. declare type FulfilledHandler<T, R> = ((result: T) => R | PersistencePromise<R>) | null;
  2296. /**
  2297. * @license
  2298. * Copyright 2017 Google LLC
  2299. *
  2300. * Licensed under the Apache License, Version 2.0 (the "License");
  2301. * you may not use this file except in compliance with the License.
  2302. * You may obtain a copy of the License at
  2303. *
  2304. * http://www.apache.org/licenses/LICENSE-2.0
  2305. *
  2306. * Unless required by applicable law or agreed to in writing, software
  2307. * distributed under the License is distributed on an "AS IS" BASIS,
  2308. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2309. * See the License for the specific language governing permissions and
  2310. * limitations under the License.
  2311. */
  2312. /**
  2313. * An immutable object representing a geographic location in Firestore. The
  2314. * location is represented as latitude/longitude pair.
  2315. *
  2316. * Latitude values are in the range of [-90, 90].
  2317. * Longitude values are in the range of [-180, 180].
  2318. */
  2319. export declare class GeoPoint {
  2320. private _lat;
  2321. private _long;
  2322. /**
  2323. * Creates a new immutable `GeoPoint` object with the provided latitude and
  2324. * longitude values.
  2325. * @param latitude - The latitude as number between -90 and 90.
  2326. * @param longitude - The longitude as number between -180 and 180.
  2327. */
  2328. constructor(latitude: number, longitude: number);
  2329. /**
  2330. * The latitude of this `GeoPoint` instance.
  2331. */
  2332. get latitude(): number;
  2333. /**
  2334. * The longitude of this `GeoPoint` instance.
  2335. */
  2336. get longitude(): number;
  2337. /**
  2338. * Returns true if this `GeoPoint` is equal to the provided one.
  2339. *
  2340. * @param other - The `GeoPoint` to compare against.
  2341. * @returns true if this `GeoPoint` is equal to the provided one.
  2342. */
  2343. isEqual(other: GeoPoint): boolean;
  2344. /** Returns a JSON-serializable representation of this GeoPoint. */
  2345. toJSON(): {
  2346. latitude: number;
  2347. longitude: number;
  2348. };
  2349. /**
  2350. * Actually private to JS consumers of our API, so this function is prefixed
  2351. * with an underscore.
  2352. */
  2353. _compareTo(other: GeoPoint): number;
  2354. }
  2355. /* Excluded from this release type: getAggregateFromServer */
  2356. /**
  2357. * Calculates the number of documents in the result set of the given query,
  2358. * without actually downloading the documents.
  2359. *
  2360. * Using this function to count the documents is efficient because only the
  2361. * final count, not the documents' data, is downloaded. This function can even
  2362. * count the documents if the result set would be prohibitively large to
  2363. * download entirely (e.g. thousands of documents).
  2364. *
  2365. * The result received from the server is presented, unaltered, without
  2366. * considering any local state. That is, documents in the local cache are not
  2367. * taken into consideration, neither are local modifications not yet
  2368. * synchronized with the server. Previously-downloaded results, if any, are not
  2369. * used: every request using this source necessarily involves a round trip to
  2370. * the server.
  2371. *
  2372. * @param query - The query whose result set size to calculate.
  2373. * @returns A Promise that will be resolved with the count; the count can be
  2374. * retrieved from `snapshot.data().count`, where `snapshot` is the
  2375. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  2376. */
  2377. export declare function getCountFromServer(query: Query<unknown>): Promise<AggregateQuerySnapshot<{
  2378. count: AggregateField<number>;
  2379. }>>;
  2380. /**
  2381. * Reads the document referred to by this `DocumentReference`.
  2382. *
  2383. * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting
  2384. * for data from the server, but it may return cached data or fail if you are
  2385. * offline and the server cannot be reached. To specify this behavior, invoke
  2386. * {@link getDocFromCache} or {@link getDocFromServer}.
  2387. *
  2388. * @param reference - The reference of the document to fetch.
  2389. * @returns A Promise resolved with a `DocumentSnapshot` containing the
  2390. * current document contents.
  2391. */
  2392. export declare function getDoc<T>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
  2393. /**
  2394. * Reads the document referred to by this `DocumentReference` from cache.
  2395. * Returns an error if the document is not currently cached.
  2396. *
  2397. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  2398. * current document contents.
  2399. */
  2400. export declare function getDocFromCache<T>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
  2401. /**
  2402. * Reads the document referred to by this `DocumentReference` from the server.
  2403. * Returns an error if the network is not available.
  2404. *
  2405. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  2406. * current document contents.
  2407. */
  2408. export declare function getDocFromServer<T>(reference: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
  2409. /**
  2410. * Executes the query and returns the results as a `QuerySnapshot`.
  2411. *
  2412. * Note: `getDocs()` attempts to provide up-to-date data when possible by
  2413. * waiting for data from the server, but it may return cached data or fail if
  2414. * you are offline and the server cannot be reached. To specify this behavior,
  2415. * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
  2416. *
  2417. * @returns A `Promise` that will be resolved with the results of the query.
  2418. */
  2419. export declare function getDocs<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
  2420. /**
  2421. * Executes the query and returns the results as a `QuerySnapshot` from cache.
  2422. * Returns an empty result set if no documents matching the query are currently
  2423. * cached.
  2424. *
  2425. * @returns A `Promise` that will be resolved with the results of the query.
  2426. */
  2427. export declare function getDocsFromCache<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
  2428. /**
  2429. * Executes the query and returns the results as a `QuerySnapshot` from the
  2430. * server. Returns an error if the network is not available.
  2431. *
  2432. * @returns A `Promise` that will be resolved with the results of the query.
  2433. */
  2434. export declare function getDocsFromServer<T>(query: Query<T>): Promise<QuerySnapshot<T>>;
  2435. /**
  2436. * Returns the existing default {@link Firestore} instance that is associated with the
  2437. * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
  2438. * instance with default settings.
  2439. *
  2440. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}
  2441. * instance is associated with.
  2442. * @returns The {@link Firestore} instance of the provided app.
  2443. */
  2444. export declare function getFirestore(app: FirebaseApp): Firestore;
  2445. /**
  2446. * Returns the existing {@link Firestore} instance that is associated with the
  2447. * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
  2448. * instance with default settings.
  2449. *
  2450. * @param databaseId - The name of the database.
  2451. * @returns The {@link Firestore} instance of the provided app.
  2452. * @beta
  2453. */
  2454. export declare function getFirestore(databaseId: string): Firestore;
  2455. /**
  2456. * Returns the existing default {@link Firestore} instance that is associated with the
  2457. * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
  2458. * instance with default settings.
  2459. *
  2460. * @returns The {@link Firestore} instance of the provided app.
  2461. */
  2462. export declare function getFirestore(): Firestore;
  2463. /**
  2464. * Returns the existing default {@link Firestore} instance that is associated with the
  2465. * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new
  2466. * instance with default settings.
  2467. *
  2468. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}
  2469. * instance is associated with.
  2470. * @param databaseId - The name of the database.
  2471. * @returns The {@link Firestore} instance of the provided app.
  2472. * @beta
  2473. */
  2474. export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore;
  2475. /**
  2476. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  2477. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  2478. * the given value.
  2479. *
  2480. * If either the operand or the current field value uses floating point
  2481. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  2482. * integers, values outside of JavaScript's safe number range
  2483. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  2484. * precision loss. Furthermore, once processed by the Firestore backend, all
  2485. * integer operations are capped between -2^63 and 2^63-1.
  2486. *
  2487. * If the current field value is not of type `number`, or if the field does not
  2488. * yet exist, the transformation sets the field to the given value.
  2489. *
  2490. * @param n - The value to increment by.
  2491. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  2492. * `updateDoc()`
  2493. */
  2494. export declare function increment(n: number): FieldValue;
  2495. /**
  2496. * The SDK definition of a Firestore index.
  2497. * @beta
  2498. */
  2499. export declare interface Index {
  2500. /** The ID of the collection to index. */
  2501. readonly collectionGroup: string;
  2502. /** A list of fields to index. */
  2503. readonly fields?: IndexField[];
  2504. [key: string]: unknown;
  2505. }
  2506. /**
  2507. * A list of Firestore indexes to speed up local query execution.
  2508. *
  2509. * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format}
  2510. * for a description of the format of the index definition.
  2511. * @beta
  2512. */
  2513. export declare interface IndexConfiguration {
  2514. /** A list of all Firestore indexes. */
  2515. readonly indexes?: Index[];
  2516. [key: string]: unknown;
  2517. }
  2518. /**
  2519. * A single field element in an index configuration.
  2520. * @beta
  2521. */
  2522. export declare interface IndexField {
  2523. /** The field path to index. */
  2524. readonly fieldPath: string;
  2525. /**
  2526. * What type of array index to create. Set to `CONTAINS` for `array-contains`
  2527. * and `array-contains-any` indexes.
  2528. *
  2529. * Only one of `arrayConfig` or `order` should be set;
  2530. */
  2531. readonly arrayConfig?: 'CONTAINS';
  2532. /**
  2533. * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for
  2534. * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters.
  2535. *
  2536. * Only one of `arrayConfig` or `order` should be set.
  2537. */
  2538. readonly order?: 'ASCENDING' | 'DESCENDING';
  2539. [key: string]: unknown;
  2540. }
  2541. declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING';
  2542. /** The type of the index, e.g. for which type of query it can be used. */
  2543. declare const enum IndexKind {
  2544. /**
  2545. * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.
  2546. */
  2547. ASCENDING = 0,
  2548. /**
  2549. * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries.
  2550. */
  2551. DESCENDING = 1,
  2552. /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */
  2553. CONTAINS = 2
  2554. }
  2555. /**
  2556. * Represents a set of indexes that are used to execute queries efficiently.
  2557. *
  2558. * Currently the only index is a [collection id] =&gt; [parent path] index, used
  2559. * to execute Collection Group queries.
  2560. */
  2561. declare interface IndexManager {
  2562. /**
  2563. * Creates an index entry mapping the collectionId (last segment of the path)
  2564. * to the parent path (either the containing document location or the empty
  2565. * path for root-level collections). Index entries can be retrieved via
  2566. * getCollectionParents().
  2567. *
  2568. * NOTE: Currently we don't remove index entries. If this ends up being an
  2569. * issue we can devise some sort of GC strategy.
  2570. */
  2571. addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: _ResourcePath): PersistencePromise<void>;
  2572. /**
  2573. * Retrieves all parent locations containing the given collectionId, as a
  2574. * list of paths (each path being either a document location or the empty
  2575. * path for a root-level collection).
  2576. */
  2577. getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise<_ResourcePath[]>;
  2578. /**
  2579. * Adds a field path index.
  2580. *
  2581. * Values for this index are persisted via the index backfill, which runs
  2582. * asynchronously in the background. Once the first values are written,
  2583. * an index can be used to serve partial results for any matching queries.
  2584. * Any unindexed portion of the database will continue to be served via
  2585. * collection scons.
  2586. */
  2587. addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise<void>;
  2588. /** Removes the given field index and deletes all index values. */
  2589. deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise<void>;
  2590. /**
  2591. * Returns a list of field indexes that correspond to the specified collection
  2592. * group.
  2593. *
  2594. * @param collectionGroup The collection group to get matching field indexes
  2595. * for.
  2596. * @return A collection of field indexes for the specified collection group.
  2597. */
  2598. getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise<FieldIndex[]>;
  2599. /** Returns all configured field indexes. */
  2600. getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise<FieldIndex[]>;
  2601. /**
  2602. * Returns the type of index (if any) that can be used to serve the given
  2603. * target.
  2604. */
  2605. getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise<IndexType>;
  2606. /**
  2607. * Returns the documents that match the given target based on the provided
  2608. * index or `null` if the target does not have a matching index.
  2609. */
  2610. getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise<_DocumentKey[] | null>;
  2611. /**
  2612. * Returns the next collection group to update. Returns `null` if no group
  2613. * exists.
  2614. */
  2615. getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise<string | null>;
  2616. /**
  2617. * Sets the collection group's latest read time.
  2618. *
  2619. * This method updates the index offset for all field indices for the
  2620. * collection group and increments their sequence number. Subsequent calls to
  2621. * `getNextCollectionGroupToUpdate()` will return a different collection group
  2622. * (unless only one collection group is configured).
  2623. */
  2624. updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise<void>;
  2625. /** Updates the index entries for the provided documents. */
  2626. updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise<void>;
  2627. /**
  2628. * Iterates over all field indexes that are used to serve the given target,
  2629. * and returns the minimum offset of them all.
  2630. */
  2631. getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise<IndexOffset>;
  2632. /** Returns the minimum offset for the given collection group. */
  2633. getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise<IndexOffset>;
  2634. }
  2635. /**
  2636. * Stores the latest read time, document and batch ID that were processed for an
  2637. * index.
  2638. */
  2639. declare class IndexOffset {
  2640. /**
  2641. * The latest read time version that has been indexed by Firestore for this
  2642. * field index.
  2643. */
  2644. readonly readTime: SnapshotVersion;
  2645. /**
  2646. * The key of the last document that was indexed for this query. Use
  2647. * `DocumentKey.empty()` if no document has been indexed.
  2648. */
  2649. readonly documentKey: _DocumentKey;
  2650. readonly largestBatchId: number;
  2651. constructor(
  2652. /**
  2653. * The latest read time version that has been indexed by Firestore for this
  2654. * field index.
  2655. */
  2656. readTime: SnapshotVersion,
  2657. /**
  2658. * The key of the last document that was indexed for this query. Use
  2659. * `DocumentKey.empty()` if no document has been indexed.
  2660. */
  2661. documentKey: _DocumentKey, largestBatchId: number);
  2662. /** Returns an offset that sorts before all regular offsets. */
  2663. static min(): IndexOffset;
  2664. /** Returns an offset that sorts after all regular offsets. */
  2665. static max(): IndexOffset;
  2666. }
  2667. /** An index component consisting of field path and index type. */
  2668. declare class IndexSegment {
  2669. /** The field path of the component. */
  2670. readonly fieldPath: _FieldPath;
  2671. /** The fields sorting order. */
  2672. readonly kind: IndexKind;
  2673. constructor(
  2674. /** The field path of the component. */
  2675. fieldPath: _FieldPath,
  2676. /** The fields sorting order. */
  2677. kind: IndexKind);
  2678. }
  2679. /**
  2680. * Stores the "high water mark" that indicates how updated the Index is for the
  2681. * current user.
  2682. */
  2683. declare class IndexState {
  2684. /**
  2685. * Indicates when the index was last updated (relative to other indexes).
  2686. */
  2687. readonly sequenceNumber: number;
  2688. /** The the latest indexed read time, document and batch id. */
  2689. readonly offset: IndexOffset;
  2690. constructor(
  2691. /**
  2692. * Indicates when the index was last updated (relative to other indexes).
  2693. */
  2694. sequenceNumber: number,
  2695. /** The the latest indexed read time, document and batch id. */
  2696. offset: IndexOffset);
  2697. /** The state of an index that has not yet been backfilled. */
  2698. static empty(): IndexState;
  2699. }
  2700. declare type IndexState_2 = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR';
  2701. /** Represents the index state as it relates to a particular target. */
  2702. declare const enum IndexType {
  2703. /** Indicates that no index could be found for serving the target. */
  2704. NONE = 0,
  2705. /**
  2706. * Indicates that only a "partial index" could be found for serving the
  2707. * target. A partial index is one which does not have a segment for every
  2708. * filter/orderBy in the target.
  2709. */
  2710. PARTIAL = 1,
  2711. /**
  2712. * Indicates that a "full index" could be found for serving the target. A full
  2713. * index is one which has a segment for every filter/orderBy in the target.
  2714. */
  2715. FULL = 2
  2716. }
  2717. /**
  2718. * Initializes a new instance of {@link Firestore} with the provided settings.
  2719. * Can only be called before any other function, including
  2720. * {@link (getFirestore:1)}. If the custom settings are empty, this function is
  2721. * equivalent to calling {@link (getFirestore:1)}.
  2722. *
  2723. * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
  2724. * be associated.
  2725. * @param settings - A settings object to configure the {@link Firestore} instance.
  2726. * @param databaseId - The name of the database.
  2727. * @returns A newly initialized {@link Firestore} instance.
  2728. */
  2729. export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore;
  2730. /* Excluded from this release type: _isBase64Available */
  2731. /**
  2732. * This class generates JsonObject values for the Datastore API suitable for
  2733. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  2734. *
  2735. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  2736. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  2737. * format.
  2738. *
  2739. * For a description of the Proto3 JSON format check
  2740. * https://developers.google.com/protocol-buffers/docs/proto3#json
  2741. *
  2742. * TODO(klimt): We can remove the databaseId argument if we keep the full
  2743. * resource name in documents.
  2744. */
  2745. declare class JsonProtoSerializer implements Serializer {
  2746. readonly databaseId: _DatabaseId;
  2747. readonly useProto3Json: boolean;
  2748. constructor(databaseId: _DatabaseId, useProto3Json: boolean);
  2749. }
  2750. /**
  2751. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  2752. * documents.
  2753. *
  2754. * @param limit - The maximum number of items to return.
  2755. * @returns The created {@link QueryLimitConstraint}.
  2756. */
  2757. export declare function limit(limit: number): QueryLimitConstraint;
  2758. /**
  2759. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  2760. * documents.
  2761. *
  2762. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  2763. * otherwise an exception will be thrown during execution.
  2764. *
  2765. * @param limit - The maximum number of items to return.
  2766. * @returns The created {@link QueryLimitConstraint}.
  2767. */
  2768. export declare function limitToLast(limit: number): QueryLimitConstraint;
  2769. declare const enum LimitType {
  2770. First = "F",
  2771. Last = "L"
  2772. }
  2773. /** LimitType enum. */
  2774. declare type LimitType_2 = 'FIRST' | 'LAST';
  2775. declare type ListenSequenceNumber = number;
  2776. declare class LLRBEmptyNode<K, V> {
  2777. get key(): never;
  2778. get value(): never;
  2779. get color(): never;
  2780. get left(): never;
  2781. get right(): never;
  2782. size: number;
  2783. copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null, right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null): LLRBEmptyNode<K, V>;
  2784. insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V>;
  2785. remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V>;
  2786. isEmpty(): boolean;
  2787. inorderTraversal(action: (k: K, v: V) => boolean): boolean;
  2788. reverseTraversal(action: (k: K, v: V) => boolean): boolean;
  2789. minKey(): K | null;
  2790. maxKey(): K | null;
  2791. isRed(): boolean;
  2792. checkMaxDepth(): boolean;
  2793. protected check(): 0;
  2794. }
  2795. declare class LLRBNode<K, V> {
  2796. key: K;
  2797. value: V;
  2798. readonly color: boolean;
  2799. readonly left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
  2800. readonly right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
  2801. readonly size: number;
  2802. static EMPTY: LLRBEmptyNode<any, any>;
  2803. static RED: boolean;
  2804. static BLACK: boolean;
  2805. constructor(key: K, value: V, color?: boolean, left?: LLRBNode<K, V> | LLRBEmptyNode<K, V>, right?: LLRBNode<K, V> | LLRBEmptyNode<K, V>);
  2806. copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null, right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null): LLRBNode<K, V>;
  2807. isEmpty(): boolean;
  2808. inorderTraversal<T>(action: (k: K, v: V) => T): T;
  2809. reverseTraversal<T>(action: (k: K, v: V) => T): T;
  2810. private min;
  2811. minKey(): K | null;
  2812. maxKey(): K | null;
  2813. insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V>;
  2814. private removeMin;
  2815. remove(key: K, comparator: Comparator<K>): LLRBNode<K, V> | LLRBEmptyNode<K, V>;
  2816. isRed(): boolean;
  2817. private fixUp;
  2818. private moveRedLeft;
  2819. private moveRedRight;
  2820. private rotateLeft;
  2821. private rotateRight;
  2822. private colorFlip;
  2823. checkMaxDepth(): boolean;
  2824. protected check(): number;
  2825. }
  2826. /**
  2827. * Loads a Firestore bundle into the local cache.
  2828. *
  2829. * @param firestore - The {@link Firestore} instance to load bundles for.
  2830. * @param bundleData - An object representing the bundle to be loaded. Valid
  2831. * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.
  2832. *
  2833. * @returns A `LoadBundleTask` object, which notifies callers with progress
  2834. * updates, and completion or error events. It can be used as a
  2835. * `Promise<LoadBundleTaskProgress>`.
  2836. */
  2837. export declare function loadBundle(firestore: Firestore, bundleData: ReadableStream<Uint8Array> | ArrayBuffer | string): LoadBundleTask;
  2838. /**
  2839. * Represents the task of loading a Firestore bundle. It provides progress of bundle
  2840. * loading, as well as task completion and error events.
  2841. *
  2842. * The API is compatible with `Promise<LoadBundleTaskProgress>`.
  2843. */
  2844. export declare class LoadBundleTask implements PromiseLike<LoadBundleTaskProgress> {
  2845. private _progressObserver;
  2846. private _taskCompletionResolver;
  2847. private _lastProgress;
  2848. /**
  2849. * Registers functions to listen to bundle loading progress events.
  2850. * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
  2851. * each time a Firestore document is loaded from the bundle.
  2852. * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
  2853. * error, and there should be no more updates after this.
  2854. * @param complete - Called when the loading task is complete.
  2855. */
  2856. onProgress(next?: (progress: LoadBundleTaskProgress) => unknown, error?: (err: Error) => unknown, complete?: () => void): void;
  2857. /**
  2858. * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
  2859. *
  2860. * @param onRejected - Called when an error occurs during bundle loading.
  2861. */
  2862. catch<R>(onRejected: (a: Error) => R | PromiseLike<R>): Promise<R | LoadBundleTaskProgress>;
  2863. /**
  2864. * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
  2865. *
  2866. * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
  2867. * The update will always have its `taskState` set to `"Success"`.
  2868. * @param onRejected - Called when an error occurs during bundle loading.
  2869. */
  2870. then<T, R>(onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike<T>, onRejected?: (a: Error) => R | PromiseLike<R>): Promise<T | R>;
  2871. /**
  2872. * Notifies all observers that bundle loading has completed, with a provided
  2873. * `LoadBundleTaskProgress` object.
  2874. *
  2875. * @private
  2876. */
  2877. _completeWith(progress: LoadBundleTaskProgress): void;
  2878. /**
  2879. * Notifies all observers that bundle loading has failed, with a provided
  2880. * `Error` as the reason.
  2881. *
  2882. * @private
  2883. */
  2884. _failWith(error: FirestoreError): void;
  2885. /**
  2886. * Notifies a progress update of loading a bundle.
  2887. * @param progress - The new progress.
  2888. *
  2889. * @private
  2890. */
  2891. _updateProgress(progress: LoadBundleTaskProgress): void;
  2892. }
  2893. /**
  2894. * Represents a progress update or a final state from loading bundles.
  2895. */
  2896. export declare interface LoadBundleTaskProgress {
  2897. /** How many documents have been loaded. */
  2898. documentsLoaded: number;
  2899. /** How many documents are in the bundle being loaded. */
  2900. totalDocuments: number;
  2901. /** How many bytes have been loaded. */
  2902. bytesLoaded: number;
  2903. /** How many bytes are in the bundle being loaded. */
  2904. totalBytes: number;
  2905. /** Current task state. */
  2906. taskState: TaskState;
  2907. }
  2908. /**
  2909. * A readonly view of the local state of all documents we're tracking (i.e. we
  2910. * have a cached version in remoteDocumentCache or local mutations for the
  2911. * document). The view is computed by applying the mutations in the
  2912. * MutationQueue to the RemoteDocumentCache.
  2913. */
  2914. declare class LocalDocumentsView {
  2915. readonly remoteDocumentCache: RemoteDocumentCache;
  2916. readonly mutationQueue: MutationQueue;
  2917. readonly documentOverlayCache: DocumentOverlayCache;
  2918. readonly indexManager: IndexManager;
  2919. constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager);
  2920. /**
  2921. * Get the local view of the document identified by `key`.
  2922. *
  2923. * @returns Local view of the document or null if we don't have any cached
  2924. * state for it.
  2925. */
  2926. getDocument(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise<Document_2>;
  2927. /**
  2928. * Gets the local view of the documents identified by `keys`.
  2929. *
  2930. * If we don't have cached state for a document in `keys`, a NoDocument will
  2931. * be stored for that key in the resulting set.
  2932. */
  2933. getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise<DocumentMap>;
  2934. /**
  2935. * Similar to `getDocuments`, but creates the local view from the given
  2936. * `baseDocs` without retrieving documents from the local store.
  2937. *
  2938. * @param transaction - The transaction this operation is scoped to.
  2939. * @param docs - The documents to apply local mutations to get the local views.
  2940. * @param existenceStateChanged - The set of document keys whose existence state
  2941. * is changed. This is useful to determine if some documents overlay needs
  2942. * to be recalculated.
  2943. */
  2944. getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise<DocumentMap>;
  2945. /**
  2946. * Gets the overlayed documents for the given document map, which will include
  2947. * the local view of those documents and a `FieldMask` indicating which fields
  2948. * are mutated locally, `null` if overlay is a Set or Delete mutation.
  2949. */
  2950. getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise<OverlayedDocumentMap>;
  2951. /**
  2952. * Fetches the overlays for {@code docs} and adds them to provided overlay map
  2953. * if the map does not already contain an entry for the given document key.
  2954. */
  2955. private populateOverlays;
  2956. /**
  2957. * Computes the local view for the given documents.
  2958. *
  2959. * @param docs - The documents to compute views for. It also has the base
  2960. * version of the documents.
  2961. * @param overlays - The overlays that need to be applied to the given base
  2962. * version of the documents.
  2963. * @param existenceStateChanged - A set of documents whose existence states
  2964. * might have changed. This is used to determine if we need to re-calculate
  2965. * overlays from mutation queues.
  2966. * @return A map represents the local documents view.
  2967. */
  2968. computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise<OverlayedDocumentMap>;
  2969. private recalculateAndSaveOverlays;
  2970. /**
  2971. * Recalculates overlays by reading the documents from remote document cache
  2972. * first, and saves them after they are calculated.
  2973. */
  2974. recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<DocumentKeyMap<FieldMask | null>>;
  2975. /**
  2976. * Performs a query against the local view of all documents.
  2977. *
  2978. * @param transaction - The persistence transaction.
  2979. * @param query - The query to match documents against.
  2980. * @param offset - Read time and key to start scanning by (exclusive).
  2981. */
  2982. getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset): PersistencePromise<DocumentMap>;
  2983. /**
  2984. * Given a collection group, returns the next documents that follow the provided offset, along
  2985. * with an updated batch ID.
  2986. *
  2987. * <p>The documents returned by this method are ordered by remote version from the provided
  2988. * offset. If there are no more remote documents after the provided offset, documents with
  2989. * mutations in order of batch id from the offset are returned. Since all documents in a batch are
  2990. * returned together, the total number of documents returned can exceed {@code count}.
  2991. *
  2992. * @param transaction
  2993. * @param collectionGroup The collection group for the documents.
  2994. * @param offset The offset to index into.
  2995. * @param count The number of documents to return
  2996. * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
  2997. */
  2998. getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise<LocalWriteResult>;
  2999. private getDocumentsMatchingDocumentQuery;
  3000. private getDocumentsMatchingCollectionGroupQuery;
  3001. private getDocumentsMatchingCollectionQuery;
  3002. }
  3003. declare interface LocalStore {
  3004. collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults>;
  3005. /** Manages the list of active field and collection indices. */
  3006. indexManager: IndexManager;
  3007. /**
  3008. * The "local" view of all documents (layering mutationQueue on top of
  3009. * remoteDocumentCache).
  3010. */
  3011. localDocuments: LocalDocumentsView;
  3012. }
  3013. /** The result of a write to the local store. */
  3014. declare interface LocalWriteResult {
  3015. batchId: BatchId;
  3016. changes: DocumentMap;
  3017. }
  3018. export { LogLevel }
  3019. /* Excluded from this release type: _logWarn */
  3020. declare interface LruGarbageCollector {
  3021. readonly params: LruParams;
  3022. collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise<LruResults>;
  3023. /** Given a percentile of target to collect, returns the number of targets to collect. */
  3024. calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise<number>;
  3025. /** Returns the nth sequence number, counting in order from the smallest. */
  3026. nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise<number>;
  3027. /**
  3028. * Removes documents that have a sequence number equal to or less than the
  3029. * upper bound and are not otherwise pinned.
  3030. */
  3031. removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise<number>;
  3032. getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;
  3033. /**
  3034. * Removes targets with a sequence number equal to or less than the given
  3035. * upper bound, and removes document associations with those targets.
  3036. */
  3037. removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise<number>;
  3038. }
  3039. declare class LruParams {
  3040. readonly cacheSizeCollectionThreshold: number;
  3041. readonly percentileToCollect: number;
  3042. readonly maximumSequenceNumbersToCollect: number;
  3043. private static readonly DEFAULT_COLLECTION_PERCENTILE;
  3044. private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT;
  3045. static withCacheSize(cacheSize: number): LruParams;
  3046. static readonly DEFAULT: LruParams;
  3047. static readonly DISABLED: LruParams;
  3048. constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number);
  3049. }
  3050. /**
  3051. * Describes the results of a garbage collection run. `didRun` will be set to
  3052. * `false` if collection was skipped (either it is disabled or the cache size
  3053. * has not hit the threshold). If collection ran, the other fields will be
  3054. * filled in with the details of the results.
  3055. */
  3056. declare interface LruResults {
  3057. readonly didRun: boolean;
  3058. readonly sequenceNumbersCollected: number;
  3059. readonly targetsRemoved: number;
  3060. readonly documentsRemoved: number;
  3061. }
  3062. declare type MapValue = firestoreV1ApiClientInterfaces.MapValue;
  3063. /**
  3064. * An settings object to configure an `MemoryLocalCache` instance.
  3065. */
  3066. export declare type MemoryCacheSettings = {
  3067. /**
  3068. * The garbage collector to use, for the memory cache layer.
  3069. * A `MemoryEagerGarbageCollector` is used when this is undefined.
  3070. */
  3071. garbageCollector?: MemoryGarbageCollector;
  3072. };
  3073. /**
  3074. * A garbage collector deletes documents whenever they are not part of any
  3075. * active queries, and have no local mutations attached to them.
  3076. *
  3077. * This collector tries to ensure lowest memory footprints from the SDK,
  3078. * at the risk of documents not being cached for offline queries or for
  3079. * direct queries to the cache.
  3080. *
  3081. * Use factory function {@link memoryEagerGarbageCollector()} to create an
  3082. * instance of this collector.
  3083. */
  3084. export declare type MemoryEagerGarbageCollector = {
  3085. kind: 'memoryEager';
  3086. /* Excluded from this release type: _offlineComponentProvider */
  3087. };
  3088. /**
  3089. * Creates an instance of `MemoryEagerGarbageCollector`. This is also the
  3090. * default garbage collector unless it is explicitly specified otherwise.
  3091. */
  3092. export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector;
  3093. /**
  3094. * Union type from all support gabage collectors for memory local cache.
  3095. */
  3096. export declare type MemoryGarbageCollector = MemoryEagerGarbageCollector | MemoryLruGarbageCollector;
  3097. /**
  3098. * Provides an in-memory cache to the SDK. This is the default cache unless explicitly
  3099. * configured otherwise.
  3100. *
  3101. * To use, create an instance using the factory function {@link memoryLocalCache()}, then
  3102. * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using
  3103. * the settings object.
  3104. */
  3105. export declare type MemoryLocalCache = {
  3106. kind: 'memory';
  3107. /* Excluded from this release type: _onlineComponentProvider */
  3108. /* Excluded from this release type: _offlineComponentProvider */
  3109. };
  3110. /**
  3111. * Creates an instance of `MemoryLocalCache`. The instance can be set to
  3112. * `FirestoreSettings.cache` to tell the SDK which cache layer to use.
  3113. */
  3114. export declare function memoryLocalCache(settings?: MemoryCacheSettings): MemoryLocalCache;
  3115. /**
  3116. * A garbage collector deletes Least-Recently-Used documents in multiple
  3117. * batches.
  3118. *
  3119. * This collector is configured with a target size, and will only perform
  3120. * collection when the cached documents exceed the target size. It avoids
  3121. * querying backend repeated for the same query or document, at the risk
  3122. * of having a larger memory footprint.
  3123. *
  3124. * Use factory function {@link memoryLruGarbageCollector()} to create a
  3125. * instance of this collector.
  3126. */
  3127. export declare type MemoryLruGarbageCollector = {
  3128. kind: 'memoryLru';
  3129. /* Excluded from this release type: _offlineComponentProvider */
  3130. };
  3131. /**
  3132. * Creates an instance of `MemoryLruGarbageCollector`.
  3133. *
  3134. * A target size can be specified as part of the setting parameter. The
  3135. * collector will start deleting documents once the cache size exceeds
  3136. * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).
  3137. */
  3138. export declare function memoryLruGarbageCollector(settings?: {
  3139. cacheSizeBytes?: number;
  3140. }): MemoryLruGarbageCollector;
  3141. /**
  3142. * Provides all components needed for Firestore with in-memory persistence.
  3143. * Uses EagerGC garbage collection.
  3144. */
  3145. declare class MemoryOfflineComponentProvider implements OfflineComponentProvider {
  3146. persistence: Persistence;
  3147. sharedClientState: SharedClientState;
  3148. localStore: LocalStore;
  3149. gcScheduler: Scheduler | null;
  3150. indexBackfillerScheduler: Scheduler | null;
  3151. synchronizeTabs: boolean;
  3152. serializer: JsonProtoSerializer;
  3153. initialize(cfg: ComponentConfiguration): Promise<void>;
  3154. createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null;
  3155. createIndexBackfillerScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null;
  3156. createLocalStore(cfg: ComponentConfiguration): LocalStore;
  3157. createPersistence(cfg: ComponentConfiguration): Persistence;
  3158. createSharedClientState(cfg: ComponentConfiguration): SharedClientState;
  3159. terminate(): Promise<void>;
  3160. }
  3161. /**
  3162. * Represents a document in Firestore with a key, version, data and whether it
  3163. * has local mutations applied to it.
  3164. *
  3165. * Documents can transition between states via `convertToFoundDocument()`,
  3166. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  3167. * not transition to one of these states even after all mutations have been
  3168. * applied, `isValidDocument()` returns false and the document should be removed
  3169. * from all views.
  3170. */
  3171. declare class MutableDocument implements Document_2 {
  3172. readonly key: _DocumentKey;
  3173. private documentType;
  3174. version: SnapshotVersion;
  3175. readTime: SnapshotVersion;
  3176. createTime: SnapshotVersion;
  3177. data: ObjectValue;
  3178. private documentState;
  3179. private constructor();
  3180. /**
  3181. * Creates a document with no known version or data, but which can serve as
  3182. * base document for mutations.
  3183. */
  3184. static newInvalidDocument(documentKey: _DocumentKey): MutableDocument;
  3185. /**
  3186. * Creates a new document that is known to exist with the given data at the
  3187. * given version.
  3188. */
  3189. static newFoundDocument(documentKey: _DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument;
  3190. /** Creates a new document that is known to not exist at the given version. */
  3191. static newNoDocument(documentKey: _DocumentKey, version: SnapshotVersion): MutableDocument;
  3192. /**
  3193. * Creates a new document that is known to exist at the given version but
  3194. * whose data is not known (e.g. a document that was updated without a known
  3195. * base document).
  3196. */
  3197. static newUnknownDocument(documentKey: _DocumentKey, version: SnapshotVersion): MutableDocument;
  3198. /**
  3199. * Changes the document type to indicate that it exists and that its version
  3200. * and data are known.
  3201. */
  3202. convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument;
  3203. /**
  3204. * Changes the document type to indicate that it doesn't exist at the given
  3205. * version.
  3206. */
  3207. convertToNoDocument(version: SnapshotVersion): MutableDocument;
  3208. /**
  3209. * Changes the document type to indicate that it exists at a given version but
  3210. * that its data is not known (e.g. a document that was updated without a known
  3211. * base document).
  3212. */
  3213. convertToUnknownDocument(version: SnapshotVersion): MutableDocument;
  3214. setHasCommittedMutations(): MutableDocument;
  3215. setHasLocalMutations(): MutableDocument;
  3216. setReadTime(readTime: SnapshotVersion): MutableDocument;
  3217. get hasLocalMutations(): boolean;
  3218. get hasCommittedMutations(): boolean;
  3219. get hasPendingWrites(): boolean;
  3220. isValidDocument(): boolean;
  3221. isFoundDocument(): boolean;
  3222. isNoDocument(): boolean;
  3223. isUnknownDocument(): boolean;
  3224. isEqual(other: Document_2 | null | undefined): boolean;
  3225. mutableCopy(): MutableDocument;
  3226. toString(): string;
  3227. }
  3228. /** Miscellaneous collection types / constants. */
  3229. declare type MutableDocumentMap = SortedMap<_DocumentKey, MutableDocument>;
  3230. /**
  3231. * A mutation describes a self-contained change to a document. Mutations can
  3232. * create, replace, delete, and update subsets of documents.
  3233. *
  3234. * Mutations not only act on the value of the document but also its version.
  3235. *
  3236. * For local mutations (mutations that haven't been committed yet), we preserve
  3237. * the existing version for Set and Patch mutations. For Delete mutations, we
  3238. * reset the version to 0.
  3239. *
  3240. * Here's the expected transition table.
  3241. *
  3242. * MUTATION APPLIED TO RESULTS IN
  3243. *
  3244. * SetMutation Document(v3) Document(v3)
  3245. * SetMutation NoDocument(v3) Document(v0)
  3246. * SetMutation InvalidDocument(v0) Document(v0)
  3247. * PatchMutation Document(v3) Document(v3)
  3248. * PatchMutation NoDocument(v3) NoDocument(v3)
  3249. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  3250. * DeleteMutation Document(v3) NoDocument(v0)
  3251. * DeleteMutation NoDocument(v3) NoDocument(v0)
  3252. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  3253. *
  3254. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  3255. * the resulting version for Set and Patch mutations. As deletes have no
  3256. * explicit update time, we use the commitTime of the WriteResponse for
  3257. * Delete mutations.
  3258. *
  3259. * If a mutation is acknowledged by the backend but fails the precondition check
  3260. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  3261. * the updated version.
  3262. *
  3263. * Field transforms are used only with Patch and Set Mutations. We use the
  3264. * `updateTransforms` message to store transforms, rather than the `transforms`s
  3265. * messages.
  3266. *
  3267. * ## Subclassing Notes
  3268. *
  3269. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  3270. * applyToLocalView() to implement the actual behavior of applying the mutation
  3271. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  3272. * example).
  3273. */
  3274. declare abstract class Mutation {
  3275. abstract readonly type: MutationType;
  3276. abstract readonly key: _DocumentKey;
  3277. abstract readonly precondition: Precondition;
  3278. abstract readonly fieldTransforms: FieldTransform[];
  3279. /**
  3280. * Returns a `FieldMask` representing the fields that will be changed by
  3281. * applying this mutation. Returns `null` if the mutation will overwrite the
  3282. * entire document.
  3283. */
  3284. abstract getFieldMask(): FieldMask | null;
  3285. }
  3286. /**
  3287. * A batch of mutations that will be sent as one unit to the backend.
  3288. */
  3289. declare class MutationBatch {
  3290. batchId: BatchId;
  3291. localWriteTime: Timestamp;
  3292. baseMutations: Mutation[];
  3293. mutations: Mutation[];
  3294. /**
  3295. * @param batchId - The unique ID of this mutation batch.
  3296. * @param localWriteTime - The original write time of this mutation.
  3297. * @param baseMutations - Mutations that are used to populate the base
  3298. * values when this mutation is applied locally. This can be used to locally
  3299. * overwrite values that are persisted in the remote document cache. Base
  3300. * mutations are never sent to the backend.
  3301. * @param mutations - The user-provided mutations in this mutation batch.
  3302. * User-provided mutations are applied both locally and remotely on the
  3303. * backend.
  3304. */
  3305. constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]);
  3306. /**
  3307. * Applies all the mutations in this MutationBatch to the specified document
  3308. * to compute the state of the remote document
  3309. *
  3310. * @param document - The document to apply mutations to.
  3311. * @param batchResult - The result of applying the MutationBatch to the
  3312. * backend.
  3313. */
  3314. applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void;
  3315. /**
  3316. * Computes the local view of a document given all the mutations in this
  3317. * batch.
  3318. *
  3319. * @param document - The document to apply mutations to.
  3320. * @param mutatedFields - Fields that have been updated before applying this mutation batch.
  3321. * @returns A `FieldMask` representing all the fields that are mutated.
  3322. */
  3323. applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null;
  3324. /**
  3325. * Computes the local view for all provided documents given the mutations in
  3326. * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
  3327. * replace all the mutation applications.
  3328. */
  3329. applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap;
  3330. keys(): DocumentKeySet;
  3331. isEqual(other: MutationBatch): boolean;
  3332. }
  3333. /** The result of applying a mutation batch to the backend. */
  3334. declare class MutationBatchResult {
  3335. readonly batch: MutationBatch;
  3336. readonly commitVersion: SnapshotVersion;
  3337. readonly mutationResults: MutationResult[];
  3338. /**
  3339. * A pre-computed mapping from each mutated document to the resulting
  3340. * version.
  3341. */
  3342. readonly docVersions: DocumentVersionMap;
  3343. private constructor();
  3344. /**
  3345. * Creates a new MutationBatchResult for the given batch and results. There
  3346. * must be one result for each mutation in the batch. This static factory
  3347. * caches a document=&gt;version mapping (docVersions).
  3348. */
  3349. static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult;
  3350. }
  3351. declare type MutationMap = DocumentKeyMap<Mutation>;
  3352. /** A queue of mutations to apply to the remote store. */
  3353. declare interface MutationQueue {
  3354. /** Returns true if this queue contains no mutation batches. */
  3355. checkEmpty(transaction: PersistenceTransaction): PersistencePromise<boolean>;
  3356. /**
  3357. * Creates a new mutation batch and adds it to this mutation queue.
  3358. *
  3359. * @param transaction - The transaction this operation is scoped to.
  3360. * @param localWriteTime - The original write time of this mutation.
  3361. * @param baseMutations - Mutations that are used to populate the base values
  3362. * when this mutation is applied locally. These mutations are used to locally
  3363. * overwrite values that are persisted in the remote document cache.
  3364. * @param mutations - The user-provided mutations in this mutation batch.
  3365. */
  3366. addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise<MutationBatch>;
  3367. /**
  3368. * Loads the mutation batch with the given batchId.
  3369. */
  3370. lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise<MutationBatch | null>;
  3371. /**
  3372. * Gets the first unacknowledged mutation batch after the passed in batchId
  3373. * in the mutation queue or null if empty.
  3374. *
  3375. * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the
  3376. * first mutation in the queue.
  3377. *
  3378. * @returns the next mutation or null if there wasn't one.
  3379. */
  3380. getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise<MutationBatch | null>;
  3381. /**
  3382. * Gets the largest (latest) batch id in mutation queue for the current user
  3383. * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is
  3384. * empty.
  3385. *
  3386. * @returns the largest batch id in the mutation queue that is not
  3387. * acknowledged.
  3388. */
  3389. getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise<BatchId>;
  3390. /** Gets all mutation batches in the mutation queue. */
  3391. getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise<MutationBatch[]>;
  3392. /**
  3393. * Finds all mutation batches that could possibly affect the given
  3394. * document key. Not all mutations in a batch will necessarily affect the
  3395. * document key, so when looping through the batch you'll need to check that
  3396. * the mutation itself matches the key.
  3397. *
  3398. * Batches are guaranteed to be in sorted order.
  3399. *
  3400. * Note that because of this requirement implementations are free to return
  3401. * mutation batches that don't contain the document key at all if it's
  3402. * convenient.
  3403. */
  3404. getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutationBatch[]>;
  3405. /**
  3406. * Finds all mutation batches that could possibly affect the given set of
  3407. * document keys. Not all mutations in a batch will necessarily affect each
  3408. * key, so when looping through the batch you'll need to check that the
  3409. * mutation itself matches the key.
  3410. *
  3411. * Batches are guaranteed to be in sorted order.
  3412. *
  3413. * Note that because of this requirement implementations are free to return
  3414. * mutation batches that don't contain any of the document keys at all if it's
  3415. * convenient.
  3416. */
  3417. getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap<_DocumentKey, unknown>): PersistencePromise<MutationBatch[]>;
  3418. /**
  3419. * Finds all mutation batches that could affect the results for the given
  3420. * query. Not all mutations in a batch will necessarily affect the query, so
  3421. * when looping through the batch you'll need to check that the mutation
  3422. * itself matches the query.
  3423. *
  3424. * Batches are guaranteed to be in sorted order.
  3425. *
  3426. * Note that because of this requirement implementations are free to return
  3427. * mutation batches that don't match the query at all if it's convenient.
  3428. *
  3429. * NOTE: A PatchMutation does not need to include all fields in the query
  3430. * filter criteria in order to be a match (but any fields it does contain do
  3431. * need to match).
  3432. */
  3433. getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query_2): PersistencePromise<MutationBatch[]>;
  3434. /**
  3435. * Removes the given mutation batch from the queue. This is useful in two
  3436. * circumstances:
  3437. *
  3438. * + Removing an applied mutation from the head of the queue
  3439. * + Removing a rejected mutation from anywhere in the queue
  3440. *
  3441. * Multi-Tab Note: This operation should only be called by the primary client.
  3442. */
  3443. removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise<void>;
  3444. /**
  3445. * Performs a consistency check, examining the mutation queue for any
  3446. * leaks, if possible.
  3447. */
  3448. performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise<void>;
  3449. }
  3450. /** The result of successfully applying a mutation to the backend. */
  3451. declare class MutationResult {
  3452. /**
  3453. * The version at which the mutation was committed:
  3454. *
  3455. * - For most operations, this is the updateTime in the WriteResult.
  3456. * - For deletes, the commitTime of the WriteResponse (because deletes are
  3457. * not stored and have no updateTime).
  3458. *
  3459. * Note that these versions can be different: No-op writes will not change
  3460. * the updateTime even though the commitTime advances.
  3461. */
  3462. readonly version: SnapshotVersion;
  3463. /**
  3464. * The resulting fields returned from the backend after a mutation
  3465. * containing field transforms has been committed. Contains one FieldValue
  3466. * for each FieldTransform that was in the mutation.
  3467. *
  3468. * Will be empty if the mutation did not contain any field transforms.
  3469. */
  3470. readonly transformResults: Array<Value | null>;
  3471. constructor(
  3472. /**
  3473. * The version at which the mutation was committed:
  3474. *
  3475. * - For most operations, this is the updateTime in the WriteResult.
  3476. * - For deletes, the commitTime of the WriteResponse (because deletes are
  3477. * not stored and have no updateTime).
  3478. *
  3479. * Note that these versions can be different: No-op writes will not change
  3480. * the updateTime even though the commitTime advances.
  3481. */
  3482. version: SnapshotVersion,
  3483. /**
  3484. * The resulting fields returned from the backend after a mutation
  3485. * containing field transforms has been committed. Contains one FieldValue
  3486. * for each FieldTransform that was in the mutation.
  3487. *
  3488. * Will be empty if the mutation did not contain any field transforms.
  3489. */
  3490. transformResults: Array<Value | null>);
  3491. }
  3492. declare const enum MutationType {
  3493. Set = 0,
  3494. Patch = 1,
  3495. Delete = 2,
  3496. Verify = 3
  3497. }
  3498. /**
  3499. * Represents a Query saved by the SDK in its local storage.
  3500. */
  3501. declare interface NamedQuery {
  3502. /** The name of the query. */
  3503. readonly name: string;
  3504. /** The underlying query associated with `name`. */
  3505. readonly query: Query_2;
  3506. /** The time at which the results for this query were read. */
  3507. readonly readTime: SnapshotVersion;
  3508. }
  3509. /**
  3510. * Reads a Firestore {@link Query} from local cache, identified by the given
  3511. * name.
  3512. *
  3513. * The named queries are packaged into bundles on the server side (along
  3514. * with resulting documents), and loaded to local cache using `loadBundle`. Once
  3515. * in local cache, use this method to extract a {@link Query} by name.
  3516. *
  3517. * @param firestore - The {@link Firestore} instance to read the query from.
  3518. * @param name - The name of the query.
  3519. * @returns A `Promise` that is resolved with the Query or `null`.
  3520. */
  3521. export declare function namedQuery(firestore: Firestore, name: string): Promise<Query | null>;
  3522. /** Properties of a NamedQuery. */
  3523. declare interface NamedQuery_2 {
  3524. /** NamedQuery name */
  3525. name?: string | null;
  3526. /** NamedQuery bundledQuery */
  3527. bundledQuery?: BundledQuery | null;
  3528. /** NamedQuery readTime */
  3529. readTime?: Timestamp_2 | null;
  3530. }
  3531. /**
  3532. * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1,
  3533. * 'bar.qux': T2}). Intersect them together to make a single map containing
  3534. * all possible keys that are all marked as optional
  3535. */
  3536. export declare type NestedUpdateFields<T extends Record<string, unknown>> = UnionToIntersection<{
  3537. [K in keyof T & string]: ChildUpdateFields<K, T[K]>;
  3538. }[keyof T & string]>;
  3539. /**
  3540. * @license
  3541. * Copyright 2017 Google LLC
  3542. *
  3543. * Licensed under the Apache License, Version 2.0 (the "License");
  3544. * you may not use this file except in compliance with the License.
  3545. * You may obtain a copy of the License at
  3546. *
  3547. * http://www.apache.org/licenses/LICENSE-2.0
  3548. *
  3549. * Unless required by applicable law or agreed to in writing, software
  3550. * distributed under the License is distributed on an "AS IS" BASIS,
  3551. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3552. * See the License for the specific language governing permissions and
  3553. * limitations under the License.
  3554. */
  3555. /**
  3556. * A map implementation that uses objects as keys. Objects must have an
  3557. * associated equals function and must be immutable. Entries in the map are
  3558. * stored together with the key being produced from the mapKeyFn. This map
  3559. * automatically handles collisions of keys.
  3560. */
  3561. declare class ObjectMap<KeyType, ValueType> {
  3562. private mapKeyFn;
  3563. private equalsFn;
  3564. /**
  3565. * The inner map for a key/value pair. Due to the possibility of collisions we
  3566. * keep a list of entries that we do a linear search through to find an actual
  3567. * match. Note that collisions should be rare, so we still expect near
  3568. * constant time lookups in practice.
  3569. */
  3570. private inner;
  3571. /** The number of entries stored in the map */
  3572. private innerSize;
  3573. constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean);
  3574. /** Get a value for this key, or undefined if it does not exist. */
  3575. get(key: KeyType): ValueType | undefined;
  3576. has(key: KeyType): boolean;
  3577. /** Put this key and value in the map. */
  3578. set(key: KeyType, value: ValueType): void;
  3579. /**
  3580. * Remove this key from the map. Returns a boolean if anything was deleted.
  3581. */
  3582. delete(key: KeyType): boolean;
  3583. forEach(fn: (key: KeyType, val: ValueType) => void): void;
  3584. isEmpty(): boolean;
  3585. size(): number;
  3586. }
  3587. /**
  3588. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  3589. * ability to add and remove fields (via the ObjectValueBuilder).
  3590. */
  3591. declare class ObjectValue {
  3592. readonly value: {
  3593. mapValue: MapValue;
  3594. };
  3595. constructor(value: {
  3596. mapValue: MapValue;
  3597. });
  3598. static empty(): ObjectValue;
  3599. /**
  3600. * Returns the value at the given path or null.
  3601. *
  3602. * @param path - the path to search
  3603. * @returns The value at the path or null if the path is not set.
  3604. */
  3605. field(path: _FieldPath): Value | null;
  3606. /**
  3607. * Sets the field to the provided value.
  3608. *
  3609. * @param path - The field path to set.
  3610. * @param value - The value to set.
  3611. */
  3612. set(path: _FieldPath, value: Value): void;
  3613. /**
  3614. * Sets the provided fields to the provided values.
  3615. *
  3616. * @param data - A map of fields to values (or null for deletes).
  3617. */
  3618. setAll(data: Map<_FieldPath, Value | null>): void;
  3619. /**
  3620. * Removes the field at the specified path. If there is no field at the
  3621. * specified path, nothing is changed.
  3622. *
  3623. * @param path - The field path to remove.
  3624. */
  3625. delete(path: _FieldPath): void;
  3626. isEqual(other: ObjectValue): boolean;
  3627. /**
  3628. * Returns the map that contains the leaf element of `path`. If the parent
  3629. * entry does not yet exist, or if it is not a map, a new map will be created.
  3630. */
  3631. private getFieldsMap;
  3632. /**
  3633. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  3634. * entries.
  3635. */
  3636. private applyChanges;
  3637. clone(): ObjectValue;
  3638. }
  3639. /**
  3640. * Initializes and wires components that are needed to interface with the local
  3641. * cache. Implementations override `initialize()` to provide all components.
  3642. */
  3643. declare interface OfflineComponentProvider {
  3644. persistence: Persistence;
  3645. sharedClientState: SharedClientState;
  3646. localStore: LocalStore;
  3647. gcScheduler: Scheduler | null;
  3648. indexBackfillerScheduler: Scheduler | null;
  3649. synchronizeTabs: boolean;
  3650. initialize(cfg: ComponentConfiguration): Promise<void>;
  3651. terminate(): Promise<void>;
  3652. }
  3653. /**
  3654. * Initializes and wires the components that are needed to interface with the
  3655. * network.
  3656. */
  3657. declare class OnlineComponentProvider {
  3658. protected localStore: LocalStore;
  3659. protected sharedClientState: SharedClientState;
  3660. datastore: Datastore;
  3661. eventManager: EventManager;
  3662. remoteStore: RemoteStore;
  3663. syncEngine: SyncEngine;
  3664. initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise<void>;
  3665. createEventManager(cfg: ComponentConfiguration): EventManager;
  3666. createDatastore(cfg: ComponentConfiguration): Datastore;
  3667. createRemoteStore(cfg: ComponentConfiguration): RemoteStore;
  3668. createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine;
  3669. terminate(): Promise<void>;
  3670. }
  3671. /**
  3672. * Describes the online state of the Firestore client. Note that this does not
  3673. * indicate whether or not the remote store is trying to connect or not. This is
  3674. * primarily used by the View / EventManager code to change their behavior while
  3675. * offline (e.g. get() calls shouldn't wait for data from the server and
  3676. * snapshot events should set metadata.isFromCache=true).
  3677. *
  3678. * The string values should not be changed since they are persisted in
  3679. * WebStorage.
  3680. */
  3681. declare const enum OnlineState {
  3682. /**
  3683. * The Firestore client is in an unknown online state. This means the client
  3684. * is either not actively trying to establish a connection or it is currently
  3685. * trying to establish a connection, but it has not succeeded or failed yet.
  3686. * Higher-level components should not operate in offline mode.
  3687. */
  3688. Unknown = "Unknown",
  3689. /**
  3690. * The client is connected and the connections are healthy. This state is
  3691. * reached after a successful connection and there has been at least one
  3692. * successful message received from the backends.
  3693. */
  3694. Online = "Online",
  3695. /**
  3696. * The client is either trying to establish a connection but failing, or it
  3697. * has been explicitly marked offline via a call to disableNetwork().
  3698. * Higher-level components should operate in offline mode.
  3699. */
  3700. Offline = "Offline"
  3701. }
  3702. /**
  3703. * Attaches a listener for `DocumentSnapshot` events. You may either pass
  3704. * individual `onNext` and `onError` callbacks or pass a single observer
  3705. * object with `next` and `error` callbacks.
  3706. *
  3707. * NOTE: Although an `onCompletion` callback can be provided, it will
  3708. * never be called because the snapshot stream is never-ending.
  3709. *
  3710. * @param reference - A reference to the document to listen to.
  3711. * @param observer - A single object containing `next` and `error` callbacks.
  3712. * @returns An unsubscribe function that can be called to cancel
  3713. * the snapshot listener.
  3714. */
  3715. export declare function onSnapshot<T>(reference: DocumentReference<T>, observer: {
  3716. next?: (snapshot: DocumentSnapshot<T>) => void;
  3717. error?: (error: FirestoreError) => void;
  3718. complete?: () => void;
  3719. }): Unsubscribe;
  3720. /**
  3721. * Attaches a listener for `DocumentSnapshot` events. You may either pass
  3722. * individual `onNext` and `onError` callbacks or pass a single observer
  3723. * object with `next` and `error` callbacks.
  3724. *
  3725. * NOTE: Although an `onCompletion` callback can be provided, it will
  3726. * never be called because the snapshot stream is never-ending.
  3727. *
  3728. * @param reference - A reference to the document to listen to.
  3729. * @param options - Options controlling the listen behavior.
  3730. * @param observer - A single object containing `next` and `error` callbacks.
  3731. * @returns An unsubscribe function that can be called to cancel
  3732. * the snapshot listener.
  3733. */
  3734. export declare function onSnapshot<T>(reference: DocumentReference<T>, options: SnapshotListenOptions, observer: {
  3735. next?: (snapshot: DocumentSnapshot<T>) => void;
  3736. error?: (error: FirestoreError) => void;
  3737. complete?: () => void;
  3738. }): Unsubscribe;
  3739. /**
  3740. * Attaches a listener for `DocumentSnapshot` events. You may either pass
  3741. * individual `onNext` and `onError` callbacks or pass a single observer
  3742. * object with `next` and `error` callbacks.
  3743. *
  3744. * NOTE: Although an `onCompletion` callback can be provided, it will
  3745. * never be called because the snapshot stream is never-ending.
  3746. *
  3747. * @param reference - A reference to the document to listen to.
  3748. * @param onNext - A callback to be called every time a new `DocumentSnapshot`
  3749. * is available.
  3750. * @param onError - A callback to be called if the listen fails or is
  3751. * cancelled. No further callbacks will occur.
  3752. * @param onCompletion - Can be provided, but will not be called since streams are
  3753. * never ending.
  3754. * @returns An unsubscribe function that can be called to cancel
  3755. * the snapshot listener.
  3756. */
  3757. export declare function onSnapshot<T>(reference: DocumentReference<T>, onNext: (snapshot: DocumentSnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
  3758. /**
  3759. * Attaches a listener for `DocumentSnapshot` events. You may either pass
  3760. * individual `onNext` and `onError` callbacks or pass a single observer
  3761. * object with `next` and `error` callbacks.
  3762. *
  3763. * NOTE: Although an `onCompletion` callback can be provided, it will
  3764. * never be called because the snapshot stream is never-ending.
  3765. *
  3766. * @param reference - A reference to the document to listen to.
  3767. * @param options - Options controlling the listen behavior.
  3768. * @param onNext - A callback to be called every time a new `DocumentSnapshot`
  3769. * is available.
  3770. * @param onError - A callback to be called if the listen fails or is
  3771. * cancelled. No further callbacks will occur.
  3772. * @param onCompletion - Can be provided, but will not be called since streams are
  3773. * never ending.
  3774. * @returns An unsubscribe function that can be called to cancel
  3775. * the snapshot listener.
  3776. */
  3777. export declare function onSnapshot<T>(reference: DocumentReference<T>, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
  3778. /**
  3779. * Attaches a listener for `QuerySnapshot` events. You may either pass
  3780. * individual `onNext` and `onError` callbacks or pass a single observer
  3781. * object with `next` and `error` callbacks. The listener can be cancelled by
  3782. * calling the function that is returned when `onSnapshot` is called.
  3783. *
  3784. * NOTE: Although an `onCompletion` callback can be provided, it will
  3785. * never be called because the snapshot stream is never-ending.
  3786. *
  3787. * @param query - The query to listen to.
  3788. * @param observer - A single object containing `next` and `error` callbacks.
  3789. * @returns An unsubscribe function that can be called to cancel
  3790. * the snapshot listener.
  3791. */
  3792. export declare function onSnapshot<T>(query: Query<T>, observer: {
  3793. next?: (snapshot: QuerySnapshot<T>) => void;
  3794. error?: (error: FirestoreError) => void;
  3795. complete?: () => void;
  3796. }): Unsubscribe;
  3797. /**
  3798. * Attaches a listener for `QuerySnapshot` events. You may either pass
  3799. * individual `onNext` and `onError` callbacks or pass a single observer
  3800. * object with `next` and `error` callbacks. The listener can be cancelled by
  3801. * calling the function that is returned when `onSnapshot` is called.
  3802. *
  3803. * NOTE: Although an `onCompletion` callback can be provided, it will
  3804. * never be called because the snapshot stream is never-ending.
  3805. *
  3806. * @param query - The query to listen to.
  3807. * @param options - Options controlling the listen behavior.
  3808. * @param observer - A single object containing `next` and `error` callbacks.
  3809. * @returns An unsubscribe function that can be called to cancel
  3810. * the snapshot listener.
  3811. */
  3812. export declare function onSnapshot<T>(query: Query<T>, options: SnapshotListenOptions, observer: {
  3813. next?: (snapshot: QuerySnapshot<T>) => void;
  3814. error?: (error: FirestoreError) => void;
  3815. complete?: () => void;
  3816. }): Unsubscribe;
  3817. /**
  3818. * Attaches a listener for `QuerySnapshot` events. You may either pass
  3819. * individual `onNext` and `onError` callbacks or pass a single observer
  3820. * object with `next` and `error` callbacks. The listener can be cancelled by
  3821. * calling the function that is returned when `onSnapshot` is called.
  3822. *
  3823. * NOTE: Although an `onCompletion` callback can be provided, it will
  3824. * never be called because the snapshot stream is never-ending.
  3825. *
  3826. * @param query - The query to listen to.
  3827. * @param onNext - A callback to be called every time a new `QuerySnapshot`
  3828. * is available.
  3829. * @param onCompletion - Can be provided, but will not be called since streams are
  3830. * never ending.
  3831. * @param onError - A callback to be called if the listen fails or is
  3832. * cancelled. No further callbacks will occur.
  3833. * @returns An unsubscribe function that can be called to cancel
  3834. * the snapshot listener.
  3835. */
  3836. export declare function onSnapshot<T>(query: Query<T>, onNext: (snapshot: QuerySnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
  3837. /**
  3838. * Attaches a listener for `QuerySnapshot` events. You may either pass
  3839. * individual `onNext` and `onError` callbacks or pass a single observer
  3840. * object with `next` and `error` callbacks. The listener can be cancelled by
  3841. * calling the function that is returned when `onSnapshot` is called.
  3842. *
  3843. * NOTE: Although an `onCompletion` callback can be provided, it will
  3844. * never be called because the snapshot stream is never-ending.
  3845. *
  3846. * @param query - The query to listen to.
  3847. * @param options - Options controlling the listen behavior.
  3848. * @param onNext - A callback to be called every time a new `QuerySnapshot`
  3849. * is available.
  3850. * @param onCompletion - Can be provided, but will not be called since streams are
  3851. * never ending.
  3852. * @param onError - A callback to be called if the listen fails or is
  3853. * cancelled. No further callbacks will occur.
  3854. * @returns An unsubscribe function that can be called to cancel
  3855. * the snapshot listener.
  3856. */
  3857. export declare function onSnapshot<T>(query: Query<T>, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot<T>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;
  3858. /**
  3859. * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync
  3860. * event indicates that all listeners affected by a given change have fired,
  3861. * even if a single server-generated change affects multiple listeners.
  3862. *
  3863. * NOTE: The snapshots-in-sync event only indicates that listeners are in sync
  3864. * with each other, but does not relate to whether those snapshots are in sync
  3865. * with the server. Use SnapshotMetadata in the individual listeners to
  3866. * determine if a snapshot is from the cache or the server.
  3867. *
  3868. * @param firestore - The instance of Firestore for synchronizing snapshots.
  3869. * @param observer - A single object containing `next` and `error` callbacks.
  3870. * @returns An unsubscribe function that can be called to cancel the snapshot
  3871. * listener.
  3872. */
  3873. export declare function onSnapshotsInSync(firestore: Firestore, observer: {
  3874. next?: (value: void) => void;
  3875. error?: (error: FirestoreError) => void;
  3876. complete?: () => void;
  3877. }): Unsubscribe;
  3878. /**
  3879. * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync
  3880. * event indicates that all listeners affected by a given change have fired,
  3881. * even if a single server-generated change affects multiple listeners.
  3882. *
  3883. * NOTE: The snapshots-in-sync event only indicates that listeners are in sync
  3884. * with each other, but does not relate to whether those snapshots are in sync
  3885. * with the server. Use `SnapshotMetadata` in the individual listeners to
  3886. * determine if a snapshot is from the cache or the server.
  3887. *
  3888. * @param firestore - The `Firestore` instance for synchronizing snapshots.
  3889. * @param onSync - A callback to be called every time all snapshot listeners are
  3890. * in sync with each other.
  3891. * @returns An unsubscribe function that can be called to cancel the snapshot
  3892. * listener.
  3893. */
  3894. export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe;
  3895. declare const enum Operator {
  3896. LESS_THAN = "<",
  3897. LESS_THAN_OR_EQUAL = "<=",
  3898. EQUAL = "==",
  3899. NOT_EQUAL = "!=",
  3900. GREATER_THAN = ">",
  3901. GREATER_THAN_OR_EQUAL = ">=",
  3902. ARRAY_CONTAINS = "array-contains",
  3903. IN = "in",
  3904. NOT_IN = "not-in",
  3905. ARRAY_CONTAINS_ANY = "array-contains-any"
  3906. }
  3907. /**
  3908. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  3909. * the given filter constraints. A disjunction filter includes a document if it
  3910. * satisfies any of the given filters.
  3911. *
  3912. * @param queryConstraints - Optional. The list of
  3913. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  3914. * created with calls to {@link where}, {@link or}, or {@link and}.
  3915. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  3916. */
  3917. export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint;
  3918. /**
  3919. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  3920. */
  3921. declare class OrderBy {
  3922. readonly field: _FieldPath;
  3923. readonly dir: Direction;
  3924. constructor(field: _FieldPath, dir?: Direction);
  3925. }
  3926. /**
  3927. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  3928. * specified field, optionally in descending order instead of ascending.
  3929. *
  3930. * Note: Documents that do not contain the specified field will not be present
  3931. * in the query result.
  3932. *
  3933. * @param fieldPath - The field to sort by.
  3934. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  3935. * not specified, order will be ascending.
  3936. * @returns The created {@link QueryOrderByConstraint}.
  3937. */
  3938. export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint;
  3939. /**
  3940. * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc'
  3941. * (descending or ascending).
  3942. */
  3943. export declare type OrderByDirection = 'desc' | 'asc';
  3944. declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING';
  3945. /**
  3946. * Representation of an overlay computed by Firestore.
  3947. *
  3948. * Holds information about a mutation and the largest batch id in Firestore when
  3949. * the mutation was created.
  3950. */
  3951. declare class Overlay {
  3952. readonly largestBatchId: number;
  3953. readonly mutation: Mutation;
  3954. constructor(largestBatchId: number, mutation: Mutation);
  3955. getKey(): _DocumentKey;
  3956. isEqual(other: Overlay | null): boolean;
  3957. toString(): string;
  3958. }
  3959. /**
  3960. * Represents a local view (overlay) of a document, and the fields that are
  3961. * locally mutated.
  3962. */
  3963. declare class OverlayedDocument {
  3964. readonly overlayedDocument: Document_2;
  3965. /**
  3966. * The fields that are locally mutated by patch mutations.
  3967. *
  3968. * If the overlayed document is from set or delete mutations, this is `null`.
  3969. * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
  3970. */
  3971. readonly mutatedFields: FieldMask | null;
  3972. constructor(overlayedDocument: Document_2,
  3973. /**
  3974. * The fields that are locally mutated by patch mutations.
  3975. *
  3976. * If the overlayed document is from set or delete mutations, this is `null`.
  3977. * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
  3978. */
  3979. mutatedFields: FieldMask | null);
  3980. }
  3981. declare type OverlayedDocumentMap = DocumentKeyMap<OverlayedDocument>;
  3982. declare type OverlayMap = DocumentKeyMap<Overlay>;
  3983. declare interface ParseContext {
  3984. readonly databaseId: _DatabaseId;
  3985. readonly ignoreUndefinedProperties: boolean;
  3986. }
  3987. /** The result of parsing document data (e.g. for a setData call). */
  3988. declare class ParsedSetData {
  3989. readonly data: ObjectValue;
  3990. readonly fieldMask: FieldMask | null;
  3991. readonly fieldTransforms: FieldTransform[];
  3992. constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]);
  3993. toMutation(key: _DocumentKey, precondition: Precondition): Mutation;
  3994. }
  3995. /** The result of parsing "update" data (i.e. for an updateData call). */
  3996. declare class ParsedUpdateData {
  3997. readonly data: ObjectValue;
  3998. readonly fieldMask: FieldMask;
  3999. readonly fieldTransforms: FieldTransform[];
  4000. constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]);
  4001. toMutation(key: _DocumentKey, precondition: Precondition): Mutation;
  4002. }
  4003. /**
  4004. * Similar to Typescript's `Partial<T>`, but allows nested fields to be
  4005. * omitted and FieldValues to be passed in as property values.
  4006. */
  4007. export declare type PartialWithFieldValue<T> = Partial<T> | (T extends Primitive ? T : T extends {} ? {
  4008. [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue;
  4009. } : never);
  4010. /**
  4011. * Persistence is the lowest-level shared interface to persistent storage in
  4012. * Firestore.
  4013. *
  4014. * Persistence is used to create MutationQueue and RemoteDocumentCache
  4015. * instances backed by persistence (which might be in-memory or LevelDB).
  4016. *
  4017. * Persistence also exposes an API to create and run PersistenceTransactions
  4018. * against persistence. All read / write operations must be wrapped in a
  4019. * transaction. Implementations of PersistenceTransaction / Persistence only
  4020. * need to guarantee that writes made against the transaction are not made to
  4021. * durable storage until the transaction resolves its PersistencePromise.
  4022. * Since memory-only storage components do not alter durable storage, they are
  4023. * free to ignore the transaction.
  4024. *
  4025. * This contract is enough to allow the LocalStore be be written
  4026. * independently of whether or not the stored state actually is durably
  4027. * persisted. If persistent storage is enabled, writes are grouped together to
  4028. * avoid inconsistent state that could cause crashes.
  4029. *
  4030. * Concretely, when persistent storage is enabled, the persistent versions of
  4031. * MutationQueue, RemoteDocumentCache, and others (the mutators) will
  4032. * defer their writes into a transaction. Once the local store has completed
  4033. * one logical operation, it commits the transaction.
  4034. *
  4035. * When persistent storage is disabled, the non-persistent versions of the
  4036. * mutators ignore the transaction. This short-cut is allowed because
  4037. * memory-only storage leaves no state so it cannot be inconsistent.
  4038. *
  4039. * This simplifies the implementations of the mutators and allows memory-only
  4040. * implementations to supplement the persistent ones without requiring any
  4041. * special dual-store implementation of Persistence. The cost is that the
  4042. * LocalStore needs to be slightly careful about the order of its reads and
  4043. * writes in order to avoid relying on being able to read back uncommitted
  4044. * writes.
  4045. */
  4046. declare interface Persistence {
  4047. /**
  4048. * Whether or not this persistence instance has been started.
  4049. */
  4050. readonly started: boolean;
  4051. readonly referenceDelegate: ReferenceDelegate;
  4052. /** Starts persistence. */
  4053. start(): Promise<void>;
  4054. /**
  4055. * Releases any resources held during eager shutdown.
  4056. */
  4057. shutdown(): Promise<void>;
  4058. /**
  4059. * Registers a listener that gets called when the database receives a
  4060. * version change event indicating that it has deleted.
  4061. *
  4062. * PORTING NOTE: This is only used for Web multi-tab.
  4063. */
  4064. setDatabaseDeletedListener(databaseDeletedListener: () => Promise<void>): void;
  4065. /**
  4066. * Adjusts the current network state in the client's metadata, potentially
  4067. * affecting the primary lease.
  4068. *
  4069. * PORTING NOTE: This is only used for Web multi-tab.
  4070. */
  4071. setNetworkEnabled(networkEnabled: boolean): void;
  4072. /**
  4073. * Returns a MutationQueue representing the persisted mutations for the
  4074. * given user.
  4075. *
  4076. * Note: The implementation is free to return the same instance every time
  4077. * this is called for a given user. In particular, the memory-backed
  4078. * implementation does this to emulate the persisted implementation to the
  4079. * extent possible (e.g. in the case of uid switching from
  4080. * sally=&gt;jack=&gt;sally, sally's mutation queue will be preserved).
  4081. */
  4082. getMutationQueue(user: User, indexManager: IndexManager): MutationQueue;
  4083. /**
  4084. * Returns a TargetCache representing the persisted cache of targets.
  4085. *
  4086. * Note: The implementation is free to return the same instance every time
  4087. * this is called. In particular, the memory-backed implementation does this
  4088. * to emulate the persisted implementation to the extent possible.
  4089. */
  4090. getTargetCache(): TargetCache;
  4091. /**
  4092. * Returns a RemoteDocumentCache representing the persisted cache of remote
  4093. * documents.
  4094. *
  4095. * Note: The implementation is free to return the same instance every time
  4096. * this is called. In particular, the memory-backed implementation does this
  4097. * to emulate the persisted implementation to the extent possible.
  4098. */
  4099. getRemoteDocumentCache(): RemoteDocumentCache;
  4100. /**
  4101. * Returns a BundleCache representing the persisted cache of loaded bundles.
  4102. *
  4103. * Note: The implementation is free to return the same instance every time
  4104. * this is called. In particular, the memory-backed implementation does this
  4105. * to emulate the persisted implementation to the extent possible.
  4106. */
  4107. getBundleCache(): BundleCache;
  4108. /**
  4109. * Returns an IndexManager instance that manages our persisted query indexes.
  4110. *
  4111. * Note: The implementation is free to return the same instance every time
  4112. * this is called. In particular, the memory-backed implementation does this
  4113. * to emulate the persisted implementation to the extent possible.
  4114. */
  4115. getIndexManager(user: User): IndexManager;
  4116. /**
  4117. * Returns a DocumentOverlayCache representing the documents that are mutated
  4118. * locally.
  4119. */
  4120. getDocumentOverlayCache(user: User): DocumentOverlayCache;
  4121. /**
  4122. * Performs an operation inside a persistence transaction. Any reads or writes
  4123. * against persistence must be performed within a transaction. Writes will be
  4124. * committed atomically once the transaction completes.
  4125. *
  4126. * Persistence operations are asynchronous and therefore the provided
  4127. * transactionOperation must return a PersistencePromise. When it is resolved,
  4128. * the transaction will be committed and the Promise returned by this method
  4129. * will resolve.
  4130. *
  4131. * @param action - A description of the action performed by this transaction,
  4132. * used for logging.
  4133. * @param mode - The underlying mode of the IndexedDb transaction. Can be
  4134. * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked
  4135. * 'readwrite-primary' can only be executed by the primary client. In this
  4136. * mode, the transactionOperation will not be run if the primary lease cannot
  4137. * be acquired and the returned promise will be rejected with a
  4138. * FAILED_PRECONDITION error.
  4139. * @param transactionOperation - The operation to run inside a transaction.
  4140. * @returns A `Promise` that is resolved once the transaction completes.
  4141. */
  4142. runTransaction<T>(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise<T>): Promise<T>;
  4143. }
  4144. /**
  4145. * PersistencePromise is essentially a re-implementation of Promise except
  4146. * it has a .next() method instead of .then() and .next() and .catch() callbacks
  4147. * are executed synchronously when a PersistencePromise resolves rather than
  4148. * asynchronously (Promise implementations use setImmediate() or similar).
  4149. *
  4150. * This is necessary to interoperate with IndexedDB which will automatically
  4151. * commit transactions if control is returned to the event loop without
  4152. * synchronously initiating another operation on the transaction.
  4153. *
  4154. * NOTE: .then() and .catch() only allow a single consumer, unlike normal
  4155. * Promises.
  4156. */
  4157. declare class PersistencePromise<T> {
  4158. private nextCallback;
  4159. private catchCallback;
  4160. private result;
  4161. private error;
  4162. private isDone;
  4163. private callbackAttached;
  4164. constructor(callback: (resolve: Resolver<T>, reject: Rejector) => void);
  4165. catch<R>(fn: (error: Error) => R | PersistencePromise<R>): PersistencePromise<R>;
  4166. next<R>(nextFn?: FulfilledHandler<T, R>, catchFn?: RejectedHandler<R>): PersistencePromise<R>;
  4167. toPromise(): Promise<T>;
  4168. private wrapUserFunction;
  4169. private wrapSuccess;
  4170. private wrapFailure;
  4171. static resolve(): PersistencePromise<void>;
  4172. static resolve<R>(result: R): PersistencePromise<R>;
  4173. static reject<R>(error: Error): PersistencePromise<R>;
  4174. static waitFor(all: {
  4175. forEach: (cb: (el: PersistencePromise<any>) => void) => void;
  4176. }): PersistencePromise<void>;
  4177. /**
  4178. * Given an array of predicate functions that asynchronously evaluate to a
  4179. * boolean, implements a short-circuiting `or` between the results. Predicates
  4180. * will be evaluated until one of them returns `true`, then stop. The final
  4181. * result will be whether any of them returned `true`.
  4182. */
  4183. static or(predicates: Array<() => PersistencePromise<boolean>>): PersistencePromise<boolean>;
  4184. /**
  4185. * Given an iterable, call the given function on each element in the
  4186. * collection and wait for all of the resulting concurrent PersistencePromises
  4187. * to resolve.
  4188. */
  4189. static forEach<R, S>(collection: {
  4190. forEach: (cb: (r: R, s: S) => void) => void;
  4191. }, f: ((r: R, s: S) => PersistencePromise<void>) | ((r: R) => PersistencePromise<void>)): PersistencePromise<void>;
  4192. static forEach<R>(collection: {
  4193. forEach: (cb: (r: R) => void) => void;
  4194. }, f: (r: R) => PersistencePromise<void>): PersistencePromise<void>;
  4195. /**
  4196. * Concurrently map all array elements through asynchronous function.
  4197. */
  4198. static mapArray<T, U>(array: T[], f: (t: T) => PersistencePromise<U>): PersistencePromise<U[]>;
  4199. /**
  4200. * An alternative to recursive PersistencePromise calls, that avoids
  4201. * potential memory problems from unbounded chains of promises.
  4202. *
  4203. * The `action` will be called repeatedly while `condition` is true.
  4204. */
  4205. static doWhile(condition: () => boolean, action: () => PersistencePromise<void>): PersistencePromise<void>;
  4206. }
  4207. /**
  4208. * Settings that can be passed to `enableIndexedDbPersistence()` to configure
  4209. * Firestore persistence.
  4210. *
  4211. * Persistence cannot be used in a Node.js environment.
  4212. */
  4213. export declare interface PersistenceSettings {
  4214. /**
  4215. * Whether to force enable persistence for the client. This cannot be used
  4216. * with multi-tab synchronization and is primarily intended for use with Web
  4217. * Workers. Setting this to `true` will enable persistence, but cause other
  4218. * tabs using persistence to fail.
  4219. */
  4220. forceOwnership?: boolean;
  4221. }
  4222. /**
  4223. * A base class representing a persistence transaction, encapsulating both the
  4224. * transaction's sequence numbers as well as a list of onCommitted listeners.
  4225. *
  4226. * When you call Persistence.runTransaction(), it will create a transaction and
  4227. * pass it to your callback. You then pass it to any method that operates
  4228. * on persistence.
  4229. */
  4230. declare abstract class PersistenceTransaction {
  4231. private readonly onCommittedListeners;
  4232. abstract readonly currentSequenceNumber: ListenSequenceNumber;
  4233. addOnCommittedListener(listener: () => void): void;
  4234. raiseOnCommittedEvent(): void;
  4235. }
  4236. /** The different modes supported by `Persistence.runTransaction()`. */
  4237. declare type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary';
  4238. /**
  4239. * An settings object to configure an `PersistentLocalCache` instance.
  4240. *
  4241. * Persistent cache cannot be used in a Node.js environment.
  4242. */
  4243. export declare type PersistentCacheSettings = {
  4244. /**
  4245. * An approximate cache size threshold for the on-disk data. If the cache
  4246. * grows beyond this size, Firestore will start removing data that hasn't been
  4247. * recently used. The SDK does not guarantee that the cache will stay below
  4248. * that size, only that if the cache exceeds the given size, cleanup will be
  4249. * attempted.
  4250. *
  4251. * The default value is 40 MB. The threshold must be set to at least 1 MB, and
  4252. * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.
  4253. */
  4254. cacheSizeBytes?: number;
  4255. /**
  4256. * Specifies how multiple tabs/windows will be managed by the SDK.
  4257. */
  4258. tabManager?: PersistentTabManager;
  4259. };
  4260. /**
  4261. * Provides a persistent cache backed by IndexedDb to the SDK.
  4262. *
  4263. * To use, create an instance using the factory function {@link persistentLocalCache()}, then
  4264. * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using
  4265. * the settings object.
  4266. */
  4267. export declare type PersistentLocalCache = {
  4268. kind: 'persistent';
  4269. /* Excluded from this release type: _onlineComponentProvider */
  4270. /* Excluded from this release type: _offlineComponentProvider */
  4271. };
  4272. /**
  4273. * Creates an instance of `PersistentLocalCache`. The instance can be set to
  4274. * `FirestoreSettings.cache` to tell the SDK which cache layer to use.
  4275. *
  4276. * Persistent cache cannot be used in a Node.js environment.
  4277. */
  4278. export declare function persistentLocalCache(settings?: PersistentCacheSettings): PersistentLocalCache;
  4279. /**
  4280. * A tab manager supporting multiple tabs. SDK will synchronize queries and
  4281. * mutations done across all tabs using the SDK.
  4282. */
  4283. export declare type PersistentMultipleTabManager = {
  4284. kind: 'PersistentMultipleTab';
  4285. /* Excluded from this release type: _initialize */
  4286. /* Excluded from this release type: _onlineComponentProvider */
  4287. /* Excluded from this release type: _offlineComponentProvider */
  4288. };
  4289. /**
  4290. * Creates an instance of `PersistentMultipleTabManager`.
  4291. */
  4292. export declare function persistentMultipleTabManager(): PersistentMultipleTabManager;
  4293. /**
  4294. * A tab manager supportting only one tab, no synchronization will be
  4295. * performed across tabs.
  4296. */
  4297. export declare type PersistentSingleTabManager = {
  4298. kind: 'persistentSingleTab';
  4299. /* Excluded from this release type: _initialize */
  4300. /* Excluded from this release type: _onlineComponentProvider */
  4301. /* Excluded from this release type: _offlineComponentProvider */
  4302. };
  4303. /**
  4304. * Creates an instance of `PersistentSingleTabManager`.
  4305. *
  4306. * @param settings Configures the created tab manager.
  4307. */
  4308. export declare function persistentSingleTabManager(settings: PersistentSingleTabManagerSettings | undefined): PersistentSingleTabManager;
  4309. /**
  4310. * Type to configure an `PersistentSingleTabManager` instance.
  4311. */
  4312. export declare type PersistentSingleTabManagerSettings = {
  4313. /**
  4314. * Whether to force-enable persistent (IndexedDB) cache for the client. This
  4315. * cannot be used with multi-tab synchronization and is primarily intended for
  4316. * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause
  4317. * other tabs using IndexedDB cache to fail.
  4318. */
  4319. forceOwnership?: boolean;
  4320. };
  4321. /**
  4322. * A union of all available tab managers.
  4323. */
  4324. export declare type PersistentTabManager = PersistentSingleTabManager | PersistentMultipleTabManager;
  4325. /**
  4326. * Encodes a precondition for a mutation. This follows the model that the
  4327. * backend accepts with the special case of an explicit "empty" precondition
  4328. * (meaning no precondition).
  4329. */
  4330. declare class Precondition {
  4331. readonly updateTime?: SnapshotVersion | undefined;
  4332. readonly exists?: boolean | undefined;
  4333. private constructor();
  4334. /** Creates a new empty Precondition. */
  4335. static none(): Precondition;
  4336. /** Creates a new Precondition with an exists flag. */
  4337. static exists(exists: boolean): Precondition;
  4338. /** Creates a new Precondition based on a version a document exists at. */
  4339. static updateTime(version: SnapshotVersion): Precondition;
  4340. /** Returns whether this Precondition is empty. */
  4341. get isNone(): boolean;
  4342. isEqual(other: Precondition): boolean;
  4343. }
  4344. /**
  4345. * These types primarily exist to support the `UpdateData`,
  4346. * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed
  4347. * directly by the end developer.
  4348. */
  4349. /** Primitive types. */
  4350. export declare type Primitive = string | number | boolean | undefined | null;
  4351. /** Undocumented, private additional settings not exposed in our public API. */
  4352. declare interface PrivateSettings extends FirestoreSettings_2 {
  4353. credentials?: CredentialsSettings;
  4354. cacheSizeBytes?: number;
  4355. experimentalForceLongPolling?: boolean;
  4356. experimentalAutoDetectLongPolling?: boolean;
  4357. experimentalLongPollingOptions?: ExperimentalLongPollingOptions;
  4358. useFetchStreams?: boolean;
  4359. localCache?: FirestoreLocalCache;
  4360. }
  4361. declare interface ProviderCredentialsSettings {
  4362. ['type']: 'provider';
  4363. ['client']: CredentialsProvider<User>;
  4364. }
  4365. /**
  4366. * A `Query` refers to a query which you can read or listen to. You can also
  4367. * construct refined `Query` objects by adding filters and ordering.
  4368. */
  4369. export declare class Query<T = DocumentData> {
  4370. /**
  4371. * If provided, the `FirestoreDataConverter` associated with this instance.
  4372. */
  4373. readonly converter: FirestoreDataConverter_2<T> | null;
  4374. readonly _query: Query_2;
  4375. /** The type of this Firestore reference. */
  4376. readonly type: 'query' | 'collection';
  4377. /**
  4378. * The `Firestore` instance for the Firestore database (useful for performing
  4379. * transactions, etc.).
  4380. */
  4381. readonly firestore: Firestore_2;
  4382. /** @hideconstructor protected */
  4383. constructor(firestore: Firestore_2,
  4384. /**
  4385. * If provided, the `FirestoreDataConverter` associated with this instance.
  4386. */
  4387. converter: FirestoreDataConverter_2<T> | null, _query: Query_2);
  4388. /**
  4389. * Removes the current converter.
  4390. *
  4391. * @param converter - `null` removes the current converter.
  4392. * @returns A `Query<DocumentData>` that does not use a converter.
  4393. */
  4394. withConverter(converter: null): Query<DocumentData>;
  4395. /**
  4396. * Applies a custom data converter to this query, allowing you to use your own
  4397. * custom model objects with Firestore. When you call {@link getDocs} with
  4398. * the returned query, the provided converter will convert between Firestore
  4399. * data and your custom type `U`.
  4400. *
  4401. * @param converter - Converts objects to and from Firestore.
  4402. * @returns A `Query<U>` that uses the provided converter.
  4403. */
  4404. withConverter<U>(converter: FirestoreDataConverter_2<U>): Query<U>;
  4405. }
  4406. /**
  4407. * Creates a new immutable instance of {@link Query} that is extended to also
  4408. * include additional query constraints.
  4409. *
  4410. * @param query - The {@link Query} instance to use as a base for the new
  4411. * constraints.
  4412. * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to
  4413. * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or
  4414. * {@link or}.
  4415. * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to
  4416. * apply (e.g. {@link orderBy}, {@link limit}).
  4417. * @throws if any of the provided query constraints cannot be combined with the
  4418. * existing or new constraints.
  4419. */
  4420. export declare function query<T>(query: Query<T>, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query<T>;
  4421. /**
  4422. * Creates a new immutable instance of {@link Query} that is extended to also
  4423. * include additional query constraints.
  4424. *
  4425. * @param query - The {@link Query} instance to use as a base for the new
  4426. * constraints.
  4427. * @param queryConstraints - The list of {@link QueryConstraint}s to apply.
  4428. * @throws if any of the provided query constraints cannot be combined with the
  4429. * existing or new constraints.
  4430. */
  4431. export declare function query<T>(query: Query<T>, ...queryConstraints: QueryConstraint[]): Query<T>;
  4432. /**
  4433. * The Query interface defines all external properties of a query.
  4434. *
  4435. * QueryImpl implements this interface to provide memoization for `queryOrderBy`
  4436. * and `queryToTarget`.
  4437. */
  4438. declare interface Query_2 {
  4439. readonly path: _ResourcePath;
  4440. readonly collectionGroup: string | null;
  4441. readonly explicitOrderBy: OrderBy[];
  4442. readonly filters: Filter[];
  4443. readonly limit: number | null;
  4444. readonly limitType: LimitType;
  4445. readonly startAt: Bound | null;
  4446. readonly endAt: Bound | null;
  4447. }
  4448. /**
  4449. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  4450. * returned by a Firestore query by performing the logical OR or AND of multiple
  4451. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  4452. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  4453. * {@link and} and can then be passed to {@link (query:1)} to create a new query
  4454. * instance that also contains the `QueryCompositeFilterConstraint`.
  4455. */
  4456. export declare class QueryCompositeFilterConstraint extends AppliableConstraint {
  4457. /** The type of this query constraint */
  4458. readonly type: 'or' | 'and';
  4459. private readonly _queryConstraints;
  4460. /* Excluded from this release type: __constructor */
  4461. static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint;
  4462. _parse<T>(query: Query<T>): Filter;
  4463. _apply<T>(query: Query<T>): Query<T>;
  4464. _getQueryConstraints(): readonly AppliableConstraint[];
  4465. _getOperator(): CompositeOperator;
  4466. }
  4467. /**
  4468. * A `QueryConstraint` is used to narrow the set of documents returned by a
  4469. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  4470. * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
  4471. * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and
  4472. * can then be passed to {@link (query:1)} to create a new query instance that
  4473. * also contains this `QueryConstraint`.
  4474. */
  4475. export declare abstract class QueryConstraint extends AppliableConstraint {
  4476. /** The type of this query constraint */
  4477. abstract readonly type: QueryConstraintType;
  4478. /**
  4479. * Takes the provided {@link Query} and returns a copy of the {@link Query} with this
  4480. * {@link AppliableConstraint} applied.
  4481. */
  4482. abstract _apply<T>(query: Query<T>): Query<T>;
  4483. }
  4484. /** Describes the different query constraints available in this SDK. */
  4485. export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore';
  4486. /**
  4487. * A `QueryDocumentSnapshot` contains data read from a document in your
  4488. * Firestore database as part of a query. The document is guaranteed to exist
  4489. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  4490. * specific field.
  4491. *
  4492. * A `QueryDocumentSnapshot` offers the same API surface as a
  4493. * `DocumentSnapshot`. Since query results contain only existing documents, the
  4494. * `exists` property will always be true and `data()` will never return
  4495. * 'undefined'.
  4496. */
  4497. export declare class QueryDocumentSnapshot<T = DocumentData> extends DocumentSnapshot<T> {
  4498. /**
  4499. * Retrieves all fields in the document as an `Object`.
  4500. *
  4501. * By default, `serverTimestamp()` values that have not yet been
  4502. * set to their final value will be returned as `null`. You can override
  4503. * this by passing an options object.
  4504. *
  4505. * @override
  4506. * @param options - An options object to configure how data is retrieved from
  4507. * the snapshot (for example the desired behavior for server timestamps that
  4508. * have not yet been set to their final value).
  4509. * @returns An `Object` containing all fields in the document.
  4510. */
  4511. data(options?: SnapshotOptions): T;
  4512. }
  4513. /**
  4514. * A `QueryDocumentSnapshot` contains data read from a document in your
  4515. * Firestore database as part of a query. The document is guaranteed to exist
  4516. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  4517. * specific field.
  4518. *
  4519. * A `QueryDocumentSnapshot` offers the same API surface as a
  4520. * `DocumentSnapshot`. Since query results contain only existing documents, the
  4521. * `exists` property will always be true and `data()` will never return
  4522. * 'undefined'.
  4523. */
  4524. declare class QueryDocumentSnapshot_2<T = DocumentData> extends DocumentSnapshot_2<T> {
  4525. /**
  4526. * Retrieves all fields in the document as an `Object`.
  4527. *
  4528. * @override
  4529. * @returns An `Object` containing all fields in the document.
  4530. */
  4531. data(): T;
  4532. }
  4533. /**
  4534. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  4535. * result set returned by a Firestore query.
  4536. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  4537. * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new
  4538. * query instance that also contains this `QueryEndAtConstraint`.
  4539. */
  4540. export declare class QueryEndAtConstraint extends QueryConstraint {
  4541. /** The type of this query constraint */
  4542. readonly type: 'endBefore' | 'endAt';
  4543. private readonly _docOrFields;
  4544. private readonly _inclusive;
  4545. /* Excluded from this release type: __constructor */
  4546. static _create(type: 'endBefore' | 'endAt', _docOrFields: Array<unknown | DocumentSnapshot_2<unknown>>, _inclusive: boolean): QueryEndAtConstraint;
  4547. _apply<T>(query: Query<T>): Query<T>;
  4548. }
  4549. /**
  4550. * Returns true if the provided queries point to the same collection and apply
  4551. * the same constraints.
  4552. *
  4553. * @param left - A `Query` to compare.
  4554. * @param right - A `Query` to compare.
  4555. * @returns true if the references point to the same location in the same
  4556. * Firestore database.
  4557. */
  4558. export declare function queryEqual<T>(left: Query<T>, right: Query<T>): boolean;
  4559. /**
  4560. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  4561. * a Firestore query by filtering on one or more document fields.
  4562. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  4563. * be passed to {@link (query:1)} to create a new query instance that also contains
  4564. * this `QueryFieldFilterConstraint`.
  4565. */
  4566. export declare class QueryFieldFilterConstraint extends QueryConstraint {
  4567. private readonly _field;
  4568. private _op;
  4569. private _value;
  4570. /** The type of this query constraint */
  4571. readonly type = "where";
  4572. /* Excluded from this release type: __constructor */
  4573. static _create(_field: _FieldPath, _op: Operator, _value: unknown): QueryFieldFilterConstraint;
  4574. _apply<T>(query: Query<T>): Query<T>;
  4575. _parse<T>(query: Query<T>): FieldFilter;
  4576. }
  4577. /**
  4578. * `QueryFilterConstraint` is a helper union type that represents
  4579. * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}.
  4580. */
  4581. export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint;
  4582. /**
  4583. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  4584. * a Firestore query.
  4585. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  4586. * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new
  4587. * query instance that also contains this `QueryLimitConstraint`.
  4588. */
  4589. export declare class QueryLimitConstraint extends QueryConstraint {
  4590. /** The type of this query constraint */
  4591. readonly type: 'limit' | 'limitToLast';
  4592. private readonly _limit;
  4593. private readonly _limitType;
  4594. /* Excluded from this release type: __constructor */
  4595. static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType): QueryLimitConstraint;
  4596. _apply<T>(query: Query<T>): Query<T>;
  4597. }
  4598. /**
  4599. * `QueryNonFilterConstraint` is a helper union type that represents
  4600. * QueryConstraints which are used to narrow or order the set of documents,
  4601. * but that do not explicitly filter on a document field.
  4602. * `QueryNonFilterConstraint`s are created by invoking {@link orderBy},
  4603. * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)},
  4604. * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)}
  4605. * to create a new query instance that also contains the `QueryConstraint`.
  4606. */
  4607. export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint;
  4608. /**
  4609. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  4610. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  4611. * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query
  4612. * instance that also contains this `QueryOrderByConstraint`.
  4613. *
  4614. * Note: Documents that do not contain the orderBy field will not be present in
  4615. * the query result.
  4616. */
  4617. export declare class QueryOrderByConstraint extends QueryConstraint {
  4618. private readonly _field;
  4619. private _direction;
  4620. /** The type of this query constraint */
  4621. readonly type = "orderBy";
  4622. /* Excluded from this release type: __constructor */
  4623. static _create(_field: _FieldPath, _direction: Direction): QueryOrderByConstraint;
  4624. _apply<T>(query: Query<T>): Query<T>;
  4625. }
  4626. /**
  4627. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  4628. * representing the results of a query. The documents can be accessed as an
  4629. * array via the `docs` property or enumerated using the `forEach` method. The
  4630. * number of documents can be determined via the `empty` and `size`
  4631. * properties.
  4632. */
  4633. export declare class QuerySnapshot<T = DocumentData> {
  4634. readonly _firestore: Firestore;
  4635. readonly _userDataWriter: AbstractUserDataWriter;
  4636. readonly _snapshot: ViewSnapshot;
  4637. /**
  4638. * Metadata about this snapshot, concerning its source and if it has local
  4639. * modifications.
  4640. */
  4641. readonly metadata: SnapshotMetadata;
  4642. /**
  4643. * The query on which you called `get` or `onSnapshot` in order to get this
  4644. * `QuerySnapshot`.
  4645. */
  4646. readonly query: Query<T>;
  4647. private _cachedChanges?;
  4648. private _cachedChangesIncludeMetadataChanges?;
  4649. /** @hideconstructor */
  4650. constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, query: Query<T>, _snapshot: ViewSnapshot);
  4651. /** An array of all the documents in the `QuerySnapshot`. */
  4652. get docs(): Array<QueryDocumentSnapshot<T>>;
  4653. /** The number of documents in the `QuerySnapshot`. */
  4654. get size(): number;
  4655. /** True if there are no documents in the `QuerySnapshot`. */
  4656. get empty(): boolean;
  4657. /**
  4658. * Enumerates all of the documents in the `QuerySnapshot`.
  4659. *
  4660. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  4661. * each document in the snapshot.
  4662. * @param thisArg - The `this` binding for the callback.
  4663. */
  4664. forEach(callback: (result: QueryDocumentSnapshot<T>) => void, thisArg?: unknown): void;
  4665. /**
  4666. * Returns an array of the documents changes since the last snapshot. If this
  4667. * is the first snapshot, all documents will be in the list as 'added'
  4668. * changes.
  4669. *
  4670. * @param options - `SnapshotListenOptions` that control whether metadata-only
  4671. * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
  4672. * snapshot events.
  4673. */
  4674. docChanges(options?: SnapshotListenOptions): Array<DocumentChange<T>>;
  4675. }
  4676. /**
  4677. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  4678. * result set returned by a Firestore query.
  4679. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  4680. * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a
  4681. * new query instance that also contains this `QueryStartAtConstraint`.
  4682. */
  4683. export declare class QueryStartAtConstraint extends QueryConstraint {
  4684. /** The type of this query constraint */
  4685. readonly type: 'startAt' | 'startAfter';
  4686. private readonly _docOrFields;
  4687. private readonly _inclusive;
  4688. /* Excluded from this release type: __constructor */
  4689. static _create(type: 'startAt' | 'startAfter', _docOrFields: Array<unknown | DocumentSnapshot_2<unknown>>, _inclusive: boolean): QueryStartAtConstraint;
  4690. _apply<T>(query: Query<T>): Query<T>;
  4691. }
  4692. /** The different states of a watch target. */
  4693. declare type QueryTargetState = 'not-current' | 'current' | 'rejected';
  4694. /**
  4695. * Returns true if the provided references are equal.
  4696. *
  4697. * @param left - A reference to compare.
  4698. * @param right - A reference to compare.
  4699. * @returns true if the references point to the same location in the same
  4700. * Firestore database.
  4701. */
  4702. export declare function refEqual<T>(left: DocumentReference<T> | CollectionReference<T>, right: DocumentReference<T> | CollectionReference<T>): boolean;
  4703. /**
  4704. * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This
  4705. * includes being added to a target, being removed from a target, being subject to mutation, and
  4706. * being mutated by the user.
  4707. *
  4708. * Different implementations may do different things with each of these events. Not every
  4709. * implementation needs to do something with every lifecycle hook.
  4710. *
  4711. * PORTING NOTE: since sequence numbers are attached to transactions in this
  4712. * client, the ReferenceDelegate does not need to deal in transactional
  4713. * semantics (onTransactionStarted/Committed()), nor does it need to track and
  4714. * generate sequence numbers (getCurrentSequenceNumber()).
  4715. */
  4716. declare interface ReferenceDelegate {
  4717. /** Notify the delegate that the given document was added to a target. */
  4718. addReference(txn: PersistenceTransaction, targetId: TargetId, doc: _DocumentKey): PersistencePromise<void>;
  4719. /** Notify the delegate that the given document was removed from a target. */
  4720. removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: _DocumentKey): PersistencePromise<void>;
  4721. /**
  4722. * Notify the delegate that a target was removed. The delegate may, but is not obligated to,
  4723. * actually delete the target and associated data.
  4724. */
  4725. removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
  4726. /**
  4727. * Notify the delegate that a document may no longer be part of any views or
  4728. * have any mutations associated.
  4729. */
  4730. markPotentiallyOrphaned(txn: PersistenceTransaction, doc: _DocumentKey): PersistencePromise<void>;
  4731. /** Notify the delegate that a limbo document was updated. */
  4732. updateLimboDocument(txn: PersistenceTransaction, doc: _DocumentKey): PersistencePromise<void>;
  4733. }
  4734. declare type RejectedHandler<R> = ((reason: Error) => R | PersistencePromise<R>) | null;
  4735. declare type Rejector = (error: Error) => void;
  4736. /**
  4737. * Represents cached documents received from the remote backend.
  4738. *
  4739. * The cache is keyed by DocumentKey and entries in the cache are
  4740. * MutableDocuments, meaning we can cache both actual documents as well as
  4741. * documents that are known to not exist.
  4742. */
  4743. declare interface RemoteDocumentCache {
  4744. /** Sets the index manager to use for managing the collectionGroup index. */
  4745. setIndexManager(indexManager: IndexManager): void;
  4746. /**
  4747. * Looks up an entry in the cache.
  4748. *
  4749. * @param documentKey - The key of the entry to look up.*
  4750. * @returns The cached document entry. Returns an invalid document if the
  4751. * document is not cached.
  4752. */
  4753. getEntry(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutableDocument>;
  4754. /**
  4755. * Looks up a set of entries in the cache.
  4756. *
  4757. * @param documentKeys - The keys of the entries to look up.
  4758. * @returns The cached document entries indexed by key. If an entry is not
  4759. * cached, the corresponding key will be mapped to an invalid document.
  4760. */
  4761. getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<MutableDocumentMap>;
  4762. /**
  4763. * Returns the documents matching the given query
  4764. *
  4765. * @param query - The query to match documents against.
  4766. * @param offset - The offset to start the scan at (exclusive).
  4767. * @returns The set of matching documents.
  4768. */
  4769. getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, mutatedDocs: OverlayMap): PersistencePromise<MutableDocumentMap>;
  4770. /**
  4771. * Looks up the next `limit` documents for a collection group based on the
  4772. * provided offset. The ordering is based on the document's read time and key.
  4773. *
  4774. * @param collectionGroup - The collection group to scan.
  4775. * @param offset - The offset to start the scan at (exclusive).
  4776. * @param limit - The maximum number of results to return.
  4777. * @returns The set of matching documents.
  4778. */
  4779. getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise<MutableDocumentMap>;
  4780. /**
  4781. * Provides access to add or update the contents of the cache. The buffer
  4782. * handles proper size accounting for the change.
  4783. *
  4784. * Multi-Tab Note: This should only be called by the primary client.
  4785. *
  4786. * @param options - Specify `trackRemovals` to create sentinel entries for
  4787. * removed documents, which allows removals to be tracked by
  4788. * `getNewDocumentChanges()`.
  4789. */
  4790. newChangeBuffer(options?: {
  4791. trackRemovals: boolean;
  4792. }): RemoteDocumentChangeBuffer;
  4793. /**
  4794. * Get an estimate of the size of the document cache. Note that for eager
  4795. * garbage collection, we don't track sizes so this will return 0.
  4796. */
  4797. getSize(transaction: PersistenceTransaction): PersistencePromise<number>;
  4798. }
  4799. /**
  4800. * An in-memory buffer of entries to be written to a RemoteDocumentCache.
  4801. * It can be used to batch up a set of changes to be written to the cache, but
  4802. * additionally supports reading entries back with the `getEntry()` method,
  4803. * falling back to the underlying RemoteDocumentCache if no entry is
  4804. * buffered.
  4805. *
  4806. * Entries added to the cache *must* be read first. This is to facilitate
  4807. * calculating the size delta of the pending changes.
  4808. *
  4809. * PORTING NOTE: This class was implemented then removed from other platforms.
  4810. * If byte-counting ends up being needed on the other platforms, consider
  4811. * porting this class as part of that implementation work.
  4812. */
  4813. declare abstract class RemoteDocumentChangeBuffer {
  4814. protected changes: ObjectMap<_DocumentKey, MutableDocument>;
  4815. private changesApplied;
  4816. protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutableDocument>;
  4817. protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<MutableDocumentMap>;
  4818. protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise<void>;
  4819. /**
  4820. * Buffers a `RemoteDocumentCache.addEntry()` call.
  4821. *
  4822. * You can only modify documents that have already been retrieved via
  4823. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  4824. */
  4825. addEntry(document: MutableDocument): void;
  4826. /**
  4827. * Buffers a `RemoteDocumentCache.removeEntry()` call.
  4828. *
  4829. * You can only remove documents that have already been retrieved via
  4830. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  4831. */
  4832. removeEntry(key: _DocumentKey, readTime: SnapshotVersion): void;
  4833. /**
  4834. * Looks up an entry in the cache. The buffered changes will first be checked,
  4835. * and if no buffered change applies, this will forward to
  4836. * `RemoteDocumentCache.getEntry()`.
  4837. *
  4838. * @param transaction - The transaction in which to perform any persistence
  4839. * operations.
  4840. * @param documentKey - The key of the entry to look up.
  4841. * @returns The cached document or an invalid document if we have nothing
  4842. * cached.
  4843. */
  4844. getEntry(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise<MutableDocument>;
  4845. /**
  4846. * Looks up several entries in the cache, forwarding to
  4847. * `RemoteDocumentCache.getEntry()`.
  4848. *
  4849. * @param transaction - The transaction in which to perform any persistence
  4850. * operations.
  4851. * @param documentKeys - The keys of the entries to look up.
  4852. * @returns A map of cached documents, indexed by key. If an entry cannot be
  4853. * found, the corresponding key will be mapped to an invalid document.
  4854. */
  4855. getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise<MutableDocumentMap>;
  4856. /**
  4857. * Applies buffered changes to the underlying RemoteDocumentCache, using
  4858. * the provided transaction.
  4859. */
  4860. apply(transaction: PersistenceTransaction): PersistencePromise<void>;
  4861. /** Helper to assert this.changes is not null */
  4862. protected assertNotApplied(): void;
  4863. }
  4864. /**
  4865. * An event from the RemoteStore. It is split into targetChanges (changes to the
  4866. * state or the set of documents in our watched targets) and documentUpdates
  4867. * (changes to the actual documents).
  4868. */
  4869. declare class RemoteEvent {
  4870. /**
  4871. * The snapshot version this event brings us up to, or MIN if not set.
  4872. */
  4873. readonly snapshotVersion: SnapshotVersion;
  4874. /**
  4875. * A map from target to changes to the target. See TargetChange.
  4876. */
  4877. readonly targetChanges: Map<TargetId, TargetChange>;
  4878. /**
  4879. * A map of targets that is known to be inconsistent, and the purpose for
  4880. * re-listening. Listens for these targets should be re-established without
  4881. * resume tokens.
  4882. */
  4883. readonly targetMismatches: SortedMap<TargetId, TargetPurpose>;
  4884. /**
  4885. * A set of which documents have changed or been deleted, along with the
  4886. * doc's new values (if not deleted).
  4887. */
  4888. readonly documentUpdates: MutableDocumentMap;
  4889. /**
  4890. * A set of which document updates are due only to limbo resolution targets.
  4891. */
  4892. readonly resolvedLimboDocuments: DocumentKeySet;
  4893. constructor(
  4894. /**
  4895. * The snapshot version this event brings us up to, or MIN if not set.
  4896. */
  4897. snapshotVersion: SnapshotVersion,
  4898. /**
  4899. * A map from target to changes to the target. See TargetChange.
  4900. */
  4901. targetChanges: Map<TargetId, TargetChange>,
  4902. /**
  4903. * A map of targets that is known to be inconsistent, and the purpose for
  4904. * re-listening. Listens for these targets should be re-established without
  4905. * resume tokens.
  4906. */
  4907. targetMismatches: SortedMap<TargetId, TargetPurpose>,
  4908. /**
  4909. * A set of which documents have changed or been deleted, along with the
  4910. * doc's new values (if not deleted).
  4911. */
  4912. documentUpdates: MutableDocumentMap,
  4913. /**
  4914. * A set of which document updates are due only to limbo resolution targets.
  4915. */
  4916. resolvedLimboDocuments: DocumentKeySet);
  4917. /**
  4918. * HACK: Views require RemoteEvents in order to determine whether the view is
  4919. * CURRENT, but secondary tabs don't receive remote events. So this method is
  4920. * used to create a synthesized RemoteEvent that can be used to apply a
  4921. * CURRENT status change to a View, for queries executed in a different tab.
  4922. */
  4923. static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: _ByteString): RemoteEvent;
  4924. }
  4925. /**
  4926. * RemoteStore - An interface to remotely stored data, basically providing a
  4927. * wrapper around the Datastore that is more reliable for the rest of the
  4928. * system.
  4929. *
  4930. * RemoteStore is responsible for maintaining the connection to the server.
  4931. * - maintaining a list of active listens.
  4932. * - reconnecting when the connection is dropped.
  4933. * - resuming all the active listens on reconnect.
  4934. *
  4935. * RemoteStore handles all incoming events from the Datastore.
  4936. * - listening to the watch stream and repackaging the events as RemoteEvents
  4937. * - notifying SyncEngine of any changes to the active listens.
  4938. *
  4939. * RemoteStore takes writes from other components and handles them reliably.
  4940. * - pulling pending mutations from LocalStore and sending them to Datastore.
  4941. * - retrying mutations that failed because of network problems.
  4942. * - acking mutations to the SyncEngine once they are accepted or rejected.
  4943. */
  4944. declare interface RemoteStore {
  4945. /**
  4946. * SyncEngine to notify of watch and write events. This must be set
  4947. * immediately after construction.
  4948. */
  4949. remoteSyncer: RemoteSyncer;
  4950. }
  4951. /**
  4952. * An interface that describes the actions the RemoteStore needs to perform on
  4953. * a cooperating synchronization engine.
  4954. */
  4955. declare interface RemoteSyncer {
  4956. /**
  4957. * Applies one remote event to the sync engine, notifying any views of the
  4958. * changes, and releasing any pending mutation batches that would become
  4959. * visible because of the snapshot version the remote event contains.
  4960. */
  4961. applyRemoteEvent?(remoteEvent: RemoteEvent): Promise<void>;
  4962. /**
  4963. * Rejects the listen for the given targetID. This can be triggered by the
  4964. * backend for any active target.
  4965. *
  4966. * @param targetId - The targetID corresponds to one previously initiated by
  4967. * the user as part of TargetData passed to listen() on RemoteStore.
  4968. * @param error - A description of the condition that has forced the rejection.
  4969. * Nearly always this will be an indication that the user is no longer
  4970. * authorized to see the data matching the target.
  4971. */
  4972. rejectListen?(targetId: TargetId, error: FirestoreError): Promise<void>;
  4973. /**
  4974. * Applies the result of a successful write of a mutation batch to the sync
  4975. * engine, emitting snapshots in any views that the mutation applies to, and
  4976. * removing the batch from the mutation queue.
  4977. */
  4978. applySuccessfulWrite?(result: MutationBatchResult): Promise<void>;
  4979. /**
  4980. * Rejects the batch, removing the batch from the mutation queue, recomputing
  4981. * the local view of any documents affected by the batch and then, emitting
  4982. * snapshots with the reverted value.
  4983. */
  4984. rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise<void>;
  4985. /**
  4986. * Returns the set of remote document keys for the given target ID. This list
  4987. * includes the documents that were assigned to the target when we received
  4988. * the last snapshot.
  4989. */
  4990. getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet;
  4991. /**
  4992. * Updates all local state to match the pending mutations for the given user.
  4993. * May be called repeatedly for the same user.
  4994. */
  4995. handleCredentialChange?(user: User): Promise<void>;
  4996. }
  4997. declare type Resolver<T> = (value?: T) => void;
  4998. /* Excluded from this release type: _ResourcePath */
  4999. /**
  5000. * Executes the given `updateFunction` and then attempts to commit the changes
  5001. * applied within the transaction. If any document read within the transaction
  5002. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  5003. * commit after 5 attempts, the transaction fails.
  5004. *
  5005. * The maximum number of writes allowed in a single transaction is 500.
  5006. *
  5007. * @param firestore - A reference to the Firestore database to run this
  5008. * transaction against.
  5009. * @param updateFunction - The function to execute within the transaction
  5010. * context.
  5011. * @param options - An options object to configure maximum number of attempts to
  5012. * commit.
  5013. * @returns If the transaction completed successfully or was explicitly aborted
  5014. * (the `updateFunction` returned a failed promise), the promise returned by the
  5015. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  5016. * rejected promise with the corresponding failure error is returned.
  5017. */
  5018. export declare function runTransaction<T>(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise<T>, options?: TransactionOptions): Promise<T>;
  5019. /**
  5020. * Interface to schedule periodic tasks within SDK.
  5021. */
  5022. declare interface Scheduler {
  5023. readonly started: boolean;
  5024. start(): void;
  5025. stop(): void;
  5026. }
  5027. /** Base interface for the Serializer implementation. */
  5028. declare interface Serializer {
  5029. readonly useProto3Json: boolean;
  5030. }
  5031. /**
  5032. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  5033. * include a server-generated timestamp in the written data.
  5034. */
  5035. export declare function serverTimestamp(): FieldValue;
  5036. declare type ServerTimestampBehavior = 'estimate' | 'previous' | 'none';
  5037. /**
  5038. * Writes to the document referred to by this `DocumentReference`. If the
  5039. * document does not yet exist, it will be created.
  5040. *
  5041. * @param reference - A reference to the document to write.
  5042. * @param data - A map of the fields and values for the document.
  5043. * @returns A `Promise` resolved once the data has been successfully written
  5044. * to the backend (note that it won't resolve while you're offline).
  5045. */
  5046. export declare function setDoc<T>(reference: DocumentReference<T>, data: WithFieldValue<T>): Promise<void>;
  5047. /**
  5048. * Writes to the document referred to by the specified `DocumentReference`. If
  5049. * the document does not yet exist, it will be created. If you provide `merge`
  5050. * or `mergeFields`, the provided data can be merged into an existing document.
  5051. *
  5052. * @param reference - A reference to the document to write.
  5053. * @param data - A map of the fields and values for the document.
  5054. * @param options - An object to configure the set behavior.
  5055. * @returns A Promise resolved once the data has been successfully written
  5056. * to the backend (note that it won't resolve while you're offline).
  5057. */
  5058. export declare function setDoc<T>(reference: DocumentReference<T>, data: PartialWithFieldValue<T>, options: SetOptions): Promise<void>;
  5059. /**
  5060. * Configures indexing for local query execution. Any previous index
  5061. * configuration is overridden. The `Promise` resolves once the index
  5062. * configuration has been persisted.
  5063. *
  5064. * The index entries themselves are created asynchronously. You can continue to
  5065. * use queries that require indexing even if the indices are not yet available.
  5066. * Query execution will automatically start using the index once the index
  5067. * entries have been written.
  5068. *
  5069. * Indexes are only supported with IndexedDb persistence. If IndexedDb is not
  5070. * enabled, any index configuration is ignored.
  5071. *
  5072. * @param firestore - The {@link Firestore} instance to configure indexes for.
  5073. * @param configuration -The index definition.
  5074. * @throws FirestoreError if the JSON format is invalid.
  5075. * @returns A `Promise` that resolves once all indices are successfully
  5076. * configured.
  5077. * @beta
  5078. */
  5079. export declare function setIndexConfiguration(firestore: Firestore, configuration: IndexConfiguration): Promise<void>;
  5080. /**
  5081. * Configures indexing for local query execution. Any previous index
  5082. * configuration is overridden. The `Promise` resolves once the index
  5083. * configuration has been persisted.
  5084. *
  5085. * The index entries themselves are created asynchronously. You can continue to
  5086. * use queries that require indexing even if the indices are not yet available.
  5087. * Query execution will automatically start using the index once the index
  5088. * entries have been written.
  5089. *
  5090. * Indexes are only supported with IndexedDb persistence. Invoke either
  5091. * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`
  5092. * before setting an index configuration. If IndexedDb is not enabled, any
  5093. * index configuration is ignored.
  5094. *
  5095. * The method accepts the JSON format exported by the Firebase CLI (`firebase
  5096. * firestore:indexes`). If the JSON format is invalid, this method throws an
  5097. * error.
  5098. *
  5099. * @param firestore - The {@link Firestore} instance to configure indexes for.
  5100. * @param json -The JSON format exported by the Firebase CLI.
  5101. * @throws FirestoreError if the JSON format is invalid.
  5102. * @returns A `Promise` that resolves once all indices are successfully
  5103. * configured.
  5104. * @beta
  5105. */
  5106. export declare function setIndexConfiguration(firestore: Firestore, json: string): Promise<void>;
  5107. /**
  5108. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  5109. *
  5110. * @param logLevel - The verbosity you set for activity and error logging. Can
  5111. * be any of the following values:
  5112. *
  5113. * <ul>
  5114. * <li>`debug` for the most verbose logging level, primarily for
  5115. * debugging.</li>
  5116. * <li>`error` to log errors only.</li>
  5117. * <li><code>`silent` to turn off logging.</li>
  5118. * </ul>
  5119. */
  5120. export declare function setLogLevel(logLevel: LogLevel): void;
  5121. /**
  5122. * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link
  5123. * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be
  5124. * configured to perform granular merges instead of overwriting the target
  5125. * documents in their entirety by providing a `SetOptions` with `merge: true`.
  5126. *
  5127. * @param merge - Changes the behavior of a `setDoc()` call to only replace the
  5128. * values specified in its data argument. Fields omitted from the `setDoc()`
  5129. * call remain untouched. If your input sets any field to an empty map, all
  5130. * nested fields are overwritten.
  5131. * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace
  5132. * the specified field paths. Any field path that is not specified is ignored
  5133. * and remains untouched. If your input sets any field to an empty map, all
  5134. * nested fields are overwritten.
  5135. */
  5136. export declare type SetOptions = {
  5137. readonly merge?: boolean;
  5138. } | {
  5139. readonly mergeFields?: Array<string | FieldPath>;
  5140. };
  5141. /**
  5142. * A `SharedClientState` keeps track of the global state of the mutations
  5143. * and query targets for all active clients with the same persistence key (i.e.
  5144. * project ID and FirebaseApp name). It relays local changes to other clients
  5145. * and updates its local state as new state is observed.
  5146. *
  5147. * `SharedClientState` is primarily used for synchronization in Multi-Tab
  5148. * environments. Each tab is responsible for registering its active query
  5149. * targets and mutations. `SharedClientState` will then notify the listener
  5150. * assigned to `.syncEngine` for updates to mutations and queries that
  5151. * originated in other clients.
  5152. *
  5153. * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be
  5154. * assigned before calling `start()`.
  5155. */
  5156. declare interface SharedClientState {
  5157. onlineStateHandler: ((onlineState: OnlineState) => void) | null;
  5158. sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null;
  5159. /** Registers the Mutation Batch ID of a newly pending mutation. */
  5160. addPendingMutation(batchId: BatchId): void;
  5161. /**
  5162. * Records that a pending mutation has been acknowledged or rejected.
  5163. * Called by the primary client to notify secondary clients of mutation
  5164. * results as they come back from the backend.
  5165. */
  5166. updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void;
  5167. /**
  5168. * Associates a new Query Target ID with the local Firestore client. Returns
  5169. * the new query state for the query (which can be 'current' if the query is
  5170. * already associated with another tab).
  5171. *
  5172. * If the target id is already associated with local client, the method simply
  5173. * returns its `QueryTargetState`.
  5174. */
  5175. addLocalQueryTarget(targetId: TargetId): QueryTargetState;
  5176. /** Removes the Query Target ID association from the local client. */
  5177. removeLocalQueryTarget(targetId: TargetId): void;
  5178. /** Checks whether the target is associated with the local client. */
  5179. isLocalQueryTarget(targetId: TargetId): boolean;
  5180. /**
  5181. * Processes an update to a query target.
  5182. *
  5183. * Called by the primary client to notify secondary clients of document
  5184. * changes or state transitions that affect the provided query target.
  5185. */
  5186. updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void;
  5187. /**
  5188. * Removes the target's metadata entry.
  5189. *
  5190. * Called by the primary client when all clients stopped listening to a query
  5191. * target.
  5192. */
  5193. clearQueryState(targetId: TargetId): void;
  5194. /**
  5195. * Gets the active Query Targets IDs for all active clients.
  5196. *
  5197. * The implementation for this may require O(n) runtime, where 'n' is the size
  5198. * of the result set.
  5199. */
  5200. getAllActiveQueryTargets(): SortedSet<TargetId>;
  5201. /**
  5202. * Checks whether the provided target ID is currently being listened to by
  5203. * any of the active clients.
  5204. *
  5205. * The implementation may require O(n*log m) runtime, where 'n' is the number
  5206. * of clients and 'm' the number of targets.
  5207. */
  5208. isActiveQueryTarget(targetId: TargetId): boolean;
  5209. /**
  5210. * Starts the SharedClientState, reads existing client data and registers
  5211. * listeners for updates to new and existing clients.
  5212. */
  5213. start(): Promise<void>;
  5214. /** Shuts down the `SharedClientState` and its listeners. */
  5215. shutdown(): void;
  5216. /**
  5217. * Changes the active user and removes all existing user-specific data. The
  5218. * user change does not call back into SyncEngine (for example, no mutations
  5219. * will be marked as removed).
  5220. */
  5221. handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void;
  5222. /** Changes the shared online state of all clients. */
  5223. setOnlineState(onlineState: OnlineState): void;
  5224. writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;
  5225. /**
  5226. * Notifies other clients when remote documents have changed due to loading
  5227. * a bundle.
  5228. *
  5229. * @param collectionGroups The collection groups affected by this bundle.
  5230. */
  5231. notifyBundleLoaded(collectionGroups: Set<string>): void;
  5232. }
  5233. /**
  5234. * Returns true if the provided snapshots are equal.
  5235. *
  5236. * @param left - A snapshot to compare.
  5237. * @param right - A snapshot to compare.
  5238. * @returns true if the snapshots are equal.
  5239. */
  5240. export declare function snapshotEqual<T>(left: DocumentSnapshot<T> | QuerySnapshot<T>, right: DocumentSnapshot<T> | QuerySnapshot<T>): boolean;
  5241. /**
  5242. * An options object that can be passed to {@link (onSnapshot:1)} and {@link
  5243. * QuerySnapshot.docChanges} to control which types of changes to include in the
  5244. * result set.
  5245. */
  5246. export declare interface SnapshotListenOptions {
  5247. /**
  5248. * Include a change even if only the metadata of the query or of a document
  5249. * changed. Default is false.
  5250. */
  5251. readonly includeMetadataChanges?: boolean;
  5252. }
  5253. /**
  5254. * Metadata about a snapshot, describing the state of the snapshot.
  5255. */
  5256. export declare class SnapshotMetadata {
  5257. /**
  5258. * True if the snapshot contains the result of local writes (for example
  5259. * `set()` or `update()` calls) that have not yet been committed to the
  5260. * backend. If your listener has opted into metadata updates (via
  5261. * `SnapshotListenOptions`) you will receive another snapshot with
  5262. * `hasPendingWrites` equal to false once the writes have been committed to
  5263. * the backend.
  5264. */
  5265. readonly hasPendingWrites: boolean;
  5266. /**
  5267. * True if the snapshot was created from cached data rather than guaranteed
  5268. * up-to-date server data. If your listener has opted into metadata updates
  5269. * (via `SnapshotListenOptions`) you will receive another snapshot with
  5270. * `fromCache` set to false once the client has received up-to-date data from
  5271. * the backend.
  5272. */
  5273. readonly fromCache: boolean;
  5274. /** @hideconstructor */
  5275. constructor(hasPendingWrites: boolean, fromCache: boolean);
  5276. /**
  5277. * Returns true if this `SnapshotMetadata` is equal to the provided one.
  5278. *
  5279. * @param other - The `SnapshotMetadata` to compare against.
  5280. * @returns true if this `SnapshotMetadata` is equal to the provided one.
  5281. */
  5282. isEqual(other: SnapshotMetadata): boolean;
  5283. }
  5284. /**
  5285. * Options that configure how data is retrieved from a `DocumentSnapshot` (for
  5286. * example the desired behavior for server timestamps that have not yet been set
  5287. * to their final value).
  5288. */
  5289. export declare interface SnapshotOptions {
  5290. /**
  5291. * If set, controls the return value for server timestamps that have not yet
  5292. * been set to their final value.
  5293. *
  5294. * By specifying 'estimate', pending server timestamps return an estimate
  5295. * based on the local clock. This estimate will differ from the final value
  5296. * and cause these values to change once the server result becomes available.
  5297. *
  5298. * By specifying 'previous', pending timestamps will be ignored and return
  5299. * their previous value instead.
  5300. *
  5301. * If omitted or set to 'none', `null` will be returned by default until the
  5302. * server value becomes available.
  5303. */
  5304. readonly serverTimestamps?: 'estimate' | 'previous' | 'none';
  5305. }
  5306. /**
  5307. * A version of a document in Firestore. This corresponds to the version
  5308. * timestamp, such as update_time or read_time.
  5309. */
  5310. declare class SnapshotVersion {
  5311. private timestamp;
  5312. static fromTimestamp(value: Timestamp): SnapshotVersion;
  5313. static min(): SnapshotVersion;
  5314. static max(): SnapshotVersion;
  5315. private constructor();
  5316. compareTo(other: SnapshotVersion): number;
  5317. isEqual(other: SnapshotVersion): boolean;
  5318. /** Returns a number representation of the version for use in spec tests. */
  5319. toMicroseconds(): number;
  5320. toString(): string;
  5321. toTimestamp(): Timestamp;
  5322. }
  5323. declare class SortedMap<K, V> {
  5324. comparator: Comparator<K>;
  5325. root: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
  5326. constructor(comparator: Comparator<K>, root?: LLRBNode<K, V> | LLRBEmptyNode<K, V>);
  5327. insert(key: K, value: V): SortedMap<K, V>;
  5328. remove(key: K): SortedMap<K, V>;
  5329. get(key: K): V | null;
  5330. indexOf(key: K): number;
  5331. isEmpty(): boolean;
  5332. get size(): number;
  5333. minKey(): K | null;
  5334. maxKey(): K | null;
  5335. inorderTraversal<T>(action: (k: K, v: V) => T): T;
  5336. forEach(fn: (k: K, v: V) => void): void;
  5337. toString(): string;
  5338. reverseTraversal<T>(action: (k: K, v: V) => T): T;
  5339. getIterator(): SortedMapIterator<K, V>;
  5340. getIteratorFrom(key: K): SortedMapIterator<K, V>;
  5341. getReverseIterator(): SortedMapIterator<K, V>;
  5342. getReverseIteratorFrom(key: K): SortedMapIterator<K, V>;
  5343. }
  5344. declare class SortedMapIterator<K, V> {
  5345. private isReverse;
  5346. private nodeStack;
  5347. constructor(node: LLRBNode<K, V> | LLRBEmptyNode<K, V>, startKey: K | null, comparator: Comparator<K>, isReverse: boolean);
  5348. getNext(): Entry<K, V>;
  5349. hasNext(): boolean;
  5350. peek(): Entry<K, V> | null;
  5351. }
  5352. /**
  5353. * SortedSet is an immutable (copy-on-write) collection that holds elements
  5354. * in order specified by the provided comparator.
  5355. *
  5356. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  5357. * be equal!
  5358. */
  5359. declare class SortedSet<T> {
  5360. private comparator;
  5361. private data;
  5362. constructor(comparator: (left: T, right: T) => number);
  5363. has(elem: T): boolean;
  5364. first(): T | null;
  5365. last(): T | null;
  5366. get size(): number;
  5367. indexOf(elem: T): number;
  5368. /** Iterates elements in order defined by "comparator" */
  5369. forEach(cb: (elem: T) => void): void;
  5370. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
  5371. forEachInRange(range: [T, T], cb: (elem: T) => void): void;
  5372. /**
  5373. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  5374. */
  5375. forEachWhile(cb: (elem: T) => boolean, start?: T): void;
  5376. /** Finds the least element greater than or equal to `elem`. */
  5377. firstAfterOrEqual(elem: T): T | null;
  5378. getIterator(): SortedSetIterator<T>;
  5379. getIteratorFrom(key: T): SortedSetIterator<T>;
  5380. /** Inserts or updates an element */
  5381. add(elem: T): SortedSet<T>;
  5382. /** Deletes an element */
  5383. delete(elem: T): SortedSet<T>;
  5384. isEmpty(): boolean;
  5385. unionWith(other: SortedSet<T>): SortedSet<T>;
  5386. isEqual(other: SortedSet<T>): boolean;
  5387. toArray(): T[];
  5388. toString(): string;
  5389. private copy;
  5390. }
  5391. declare class SortedSetIterator<T> {
  5392. private iter;
  5393. constructor(iter: SortedMapIterator<T, boolean>);
  5394. getNext(): T;
  5395. hasNext(): boolean;
  5396. }
  5397. /**
  5398. * Creates a {@link QueryStartAtConstraint} that modifies the result set to
  5399. * start after the provided document (exclusive). The starting position is
  5400. * relative to the order of the query. The document must contain all of the
  5401. * fields provided in the orderBy of the query.
  5402. *
  5403. * @param snapshot - The snapshot of the document to start after.
  5404. * @returns A {@link QueryStartAtConstraint} to pass to `query()`
  5405. */
  5406. export declare function startAfter(snapshot: DocumentSnapshot_2<unknown>): QueryStartAtConstraint;
  5407. /**
  5408. * Creates a {@link QueryStartAtConstraint} that modifies the result set to
  5409. * start after the provided fields relative to the order of the query. The order
  5410. * of the field values must match the order of the order by clauses of the query.
  5411. *
  5412. * @param fieldValues - The field values to start this query after, in order
  5413. * of the query's order by.
  5414. * @returns A {@link QueryStartAtConstraint} to pass to `query()`
  5415. */
  5416. export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;
  5417. /**
  5418. * Creates a {@link QueryStartAtConstraint} that modifies the result set to
  5419. * start at the provided document (inclusive). The starting position is relative
  5420. * to the order of the query. The document must contain all of the fields
  5421. * provided in the `orderBy` of this query.
  5422. *
  5423. * @param snapshot - The snapshot of the document to start at.
  5424. * @returns A {@link QueryStartAtConstraint} to pass to `query()`.
  5425. */
  5426. export declare function startAt(snapshot: DocumentSnapshot_2<unknown>): QueryStartAtConstraint;
  5427. /**
  5428. * Creates a {@link QueryStartAtConstraint} that modifies the result set to
  5429. * start at the provided fields relative to the order of the query. The order of
  5430. * the field values must match the order of the order by clauses of the query.
  5431. *
  5432. * @param fieldValues - The field values to start this query at, in order
  5433. * of the query's order by.
  5434. * @returns A {@link QueryStartAtConstraint} to pass to `query()`.
  5435. */
  5436. export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;
  5437. declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery;
  5438. /* Excluded from this release type: sum */
  5439. /**
  5440. * @license
  5441. * Copyright 2017 Google LLC
  5442. *
  5443. * Licensed under the Apache License, Version 2.0 (the "License");
  5444. * you may not use this file except in compliance with the License.
  5445. * You may obtain a copy of the License at
  5446. *
  5447. * http://www.apache.org/licenses/LICENSE-2.0
  5448. *
  5449. * Unless required by applicable law or agreed to in writing, software
  5450. * distributed under the License is distributed on an "AS IS" BASIS,
  5451. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5452. * See the License for the specific language governing permissions and
  5453. * limitations under the License.
  5454. */
  5455. /**
  5456. * SyncEngine is the central controller in the client SDK architecture. It is
  5457. * the glue code between the EventManager, LocalStore, and RemoteStore. Some of
  5458. * SyncEngine's responsibilities include:
  5459. * 1. Coordinating client requests and remote events between the EventManager
  5460. * and the local and remote data stores.
  5461. * 2. Managing a View object for each query, providing the unified view between
  5462. * the local and remote data stores.
  5463. * 3. Notifying the RemoteStore when the LocalStore has new mutations in its
  5464. * queue that need sending to the backend.
  5465. *
  5466. * The SyncEngine’s methods should only ever be called by methods running in the
  5467. * global async queue.
  5468. *
  5469. * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe()
  5470. * function. Instead, it directly depends on EventManager's tree-shakeable API
  5471. * (via `ensureWatchStream()`).
  5472. */
  5473. declare interface SyncEngine {
  5474. isPrimaryClient: boolean;
  5475. }
  5476. /**
  5477. * A Target represents the WatchTarget representation of a Query, which is used
  5478. * by the LocalStore and the RemoteStore to keep track of and to execute
  5479. * backend queries. While a Query can represent multiple Targets, each Targets
  5480. * maps to a single WatchTarget in RemoteStore and a single TargetData entry
  5481. * in persistence.
  5482. */
  5483. declare interface Target {
  5484. readonly path: _ResourcePath;
  5485. readonly collectionGroup: string | null;
  5486. readonly orderBy: OrderBy[];
  5487. readonly filters: Filter[];
  5488. readonly limit: number | null;
  5489. readonly startAt: Bound | null;
  5490. readonly endAt: Bound | null;
  5491. }
  5492. /**
  5493. * Represents cached targets received from the remote backend.
  5494. *
  5495. * The cache is keyed by `Target` and entries in the cache are `TargetData`
  5496. * instances.
  5497. */
  5498. declare interface TargetCache {
  5499. /**
  5500. * A global snapshot version representing the last consistent snapshot we
  5501. * received from the backend. This is monotonically increasing and any
  5502. * snapshots received from the backend prior to this version (e.g. for targets
  5503. * resumed with a resume_token) should be suppressed (buffered) until the
  5504. * backend has caught up to this snapshot version again. This prevents our
  5505. * cache from ever going backwards in time.
  5506. *
  5507. * This is updated whenever our we get a TargetChange with a read_time and
  5508. * empty target_ids.
  5509. */
  5510. getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise<SnapshotVersion>;
  5511. /**
  5512. * @returns The highest sequence number observed, including any that might be
  5513. * persisted on-disk.
  5514. */
  5515. getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise<ListenSequenceNumber>;
  5516. /**
  5517. * Call provided function with each `TargetData` that we have cached.
  5518. */
  5519. forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise<void>;
  5520. /**
  5521. * Set the highest listen sequence number and optionally updates the
  5522. * snapshot version of the last consistent snapshot received from the backend
  5523. * (see getLastRemoteSnapshotVersion() for more details).
  5524. *
  5525. * @param highestListenSequenceNumber - The new maximum listen sequence number.
  5526. * @param lastRemoteSnapshotVersion - The new snapshot version. Optional.
  5527. */
  5528. setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise<void>;
  5529. /**
  5530. * Adds an entry in the cache.
  5531. *
  5532. * The cache key is extracted from `targetData.target`. The key must not already
  5533. * exist in the cache.
  5534. *
  5535. * @param targetData - A TargetData instance to put in the cache.
  5536. */
  5537. addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
  5538. /**
  5539. * Updates an entry in the cache.
  5540. *
  5541. * The cache key is extracted from `targetData.target`. The entry must already
  5542. * exist in the cache, and it will be replaced.
  5543. * @param targetData - The TargetData to be replaced into the cache.
  5544. */
  5545. updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
  5546. /**
  5547. * Removes the cached entry for the given target data. It is an error to remove
  5548. * a target data that does not exist.
  5549. *
  5550. * Multi-Tab Note: This operation should only be called by the primary client.
  5551. */
  5552. removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise<void>;
  5553. /**
  5554. * The number of targets currently in the cache.
  5555. */
  5556. getTargetCount(transaction: PersistenceTransaction): PersistencePromise<number>;
  5557. /**
  5558. * Looks up a TargetData entry by target.
  5559. *
  5560. * @param target - The query target corresponding to the entry to look up.
  5561. * @returns The cached TargetData entry, or null if the cache has no entry for
  5562. * the target.
  5563. */
  5564. getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise<TargetData | null>;
  5565. /**
  5566. * Adds the given document keys to cached query results of the given target
  5567. * ID.
  5568. *
  5569. * Multi-Tab Note: This operation should only be called by the primary client.
  5570. */
  5571. addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise<void>;
  5572. /**
  5573. * Removes the given document keys from the cached query results of the
  5574. * given target ID.
  5575. *
  5576. * Multi-Tab Note: This operation should only be called by the primary client.
  5577. */
  5578. removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise<void>;
  5579. /**
  5580. * Removes all the keys in the query results of the given target ID.
  5581. *
  5582. * Multi-Tab Note: This operation should only be called by the primary client.
  5583. */
  5584. removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise<void>;
  5585. /**
  5586. * Returns the document keys that match the provided target ID.
  5587. */
  5588. getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise<DocumentKeySet>;
  5589. /**
  5590. * Returns a new target ID that is higher than any query in the cache. If
  5591. * there are no queries in the cache, returns the first valid target ID.
  5592. * Allocated target IDs are persisted and `allocateTargetId()` will never
  5593. * return the same ID twice.
  5594. */
  5595. allocateTargetId(transaction: PersistenceTransaction): PersistencePromise<TargetId>;
  5596. containsKey(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise<boolean>;
  5597. }
  5598. /**
  5599. * A TargetChange specifies the set of changes for a specific target as part of
  5600. * a RemoteEvent. These changes track which documents are added, modified or
  5601. * removed, as well as the target's resume token and whether the target is
  5602. * marked CURRENT.
  5603. * The actual changes *to* documents are not part of the TargetChange since
  5604. * documents may be part of multiple targets.
  5605. */
  5606. declare class TargetChange {
  5607. /**
  5608. * An opaque, server-assigned token that allows watching a query to be resumed
  5609. * after disconnecting without retransmitting all the data that matches the
  5610. * query. The resume token essentially identifies a point in time from which
  5611. * the server should resume sending results.
  5612. */
  5613. readonly resumeToken: _ByteString;
  5614. /**
  5615. * The "current" (synced) status of this target. Note that "current"
  5616. * has special meaning in the RPC protocol that implies that a target is
  5617. * both up-to-date and consistent with the rest of the watch stream.
  5618. */
  5619. readonly current: boolean;
  5620. /**
  5621. * The set of documents that were newly assigned to this target as part of
  5622. * this remote event.
  5623. */
  5624. readonly addedDocuments: DocumentKeySet;
  5625. /**
  5626. * The set of documents that were already assigned to this target but received
  5627. * an update during this remote event.
  5628. */
  5629. readonly modifiedDocuments: DocumentKeySet;
  5630. /**
  5631. * The set of documents that were removed from this target as part of this
  5632. * remote event.
  5633. */
  5634. readonly removedDocuments: DocumentKeySet;
  5635. constructor(
  5636. /**
  5637. * An opaque, server-assigned token that allows watching a query to be resumed
  5638. * after disconnecting without retransmitting all the data that matches the
  5639. * query. The resume token essentially identifies a point in time from which
  5640. * the server should resume sending results.
  5641. */
  5642. resumeToken: _ByteString,
  5643. /**
  5644. * The "current" (synced) status of this target. Note that "current"
  5645. * has special meaning in the RPC protocol that implies that a target is
  5646. * both up-to-date and consistent with the rest of the watch stream.
  5647. */
  5648. current: boolean,
  5649. /**
  5650. * The set of documents that were newly assigned to this target as part of
  5651. * this remote event.
  5652. */
  5653. addedDocuments: DocumentKeySet,
  5654. /**
  5655. * The set of documents that were already assigned to this target but received
  5656. * an update during this remote event.
  5657. */
  5658. modifiedDocuments: DocumentKeySet,
  5659. /**
  5660. * The set of documents that were removed from this target as part of this
  5661. * remote event.
  5662. */
  5663. removedDocuments: DocumentKeySet);
  5664. /**
  5665. * This method is used to create a synthesized TargetChanges that can be used to
  5666. * apply a CURRENT status change to a View (for queries executed in a different
  5667. * tab) or for new queries (to raise snapshots with correct CURRENT status).
  5668. */
  5669. static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: _ByteString): TargetChange;
  5670. }
  5671. declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET';
  5672. /**
  5673. * An immutable set of metadata that the local store tracks for each target.
  5674. */
  5675. declare class TargetData {
  5676. /** The target being listened to. */
  5677. readonly target: Target;
  5678. /**
  5679. * The target ID to which the target corresponds; Assigned by the
  5680. * LocalStore for user listens and by the SyncEngine for limbo watches.
  5681. */
  5682. readonly targetId: TargetId;
  5683. /** The purpose of the target. */
  5684. readonly purpose: TargetPurpose;
  5685. /**
  5686. * The sequence number of the last transaction during which this target data
  5687. * was modified.
  5688. */
  5689. readonly sequenceNumber: ListenSequenceNumber;
  5690. /** The latest snapshot version seen for this target. */
  5691. readonly snapshotVersion: SnapshotVersion;
  5692. /**
  5693. * The maximum snapshot version at which the associated view
  5694. * contained no limbo documents.
  5695. */
  5696. readonly lastLimboFreeSnapshotVersion: SnapshotVersion;
  5697. /**
  5698. * An opaque, server-assigned token that allows watching a target to be
  5699. * resumed after disconnecting without retransmitting all the data that
  5700. * matches the target. The resume token essentially identifies a point in
  5701. * time from which the server should resume sending results.
  5702. */
  5703. readonly resumeToken: _ByteString;
  5704. /**
  5705. * The number of documents that last matched the query at the resume token or
  5706. * read time. Documents are counted only when making a listen request with
  5707. * resume token or read time, otherwise, keep it null.
  5708. */
  5709. readonly expectedCount: number | null;
  5710. constructor(
  5711. /** The target being listened to. */
  5712. target: Target,
  5713. /**
  5714. * The target ID to which the target corresponds; Assigned by the
  5715. * LocalStore for user listens and by the SyncEngine for limbo watches.
  5716. */
  5717. targetId: TargetId,
  5718. /** The purpose of the target. */
  5719. purpose: TargetPurpose,
  5720. /**
  5721. * The sequence number of the last transaction during which this target data
  5722. * was modified.
  5723. */
  5724. sequenceNumber: ListenSequenceNumber,
  5725. /** The latest snapshot version seen for this target. */
  5726. snapshotVersion?: SnapshotVersion,
  5727. /**
  5728. * The maximum snapshot version at which the associated view
  5729. * contained no limbo documents.
  5730. */
  5731. lastLimboFreeSnapshotVersion?: SnapshotVersion,
  5732. /**
  5733. * An opaque, server-assigned token that allows watching a target to be
  5734. * resumed after disconnecting without retransmitting all the data that
  5735. * matches the target. The resume token essentially identifies a point in
  5736. * time from which the server should resume sending results.
  5737. */
  5738. resumeToken?: _ByteString,
  5739. /**
  5740. * The number of documents that last matched the query at the resume token or
  5741. * read time. Documents are counted only when making a listen request with
  5742. * resume token or read time, otherwise, keep it null.
  5743. */
  5744. expectedCount?: number | null);
  5745. /** Creates a new target data instance with an updated sequence number. */
  5746. withSequenceNumber(sequenceNumber: number): TargetData;
  5747. /**
  5748. * Creates a new target data instance with an updated resume token and
  5749. * snapshot version.
  5750. */
  5751. withResumeToken(resumeToken: _ByteString, snapshotVersion: SnapshotVersion): TargetData;
  5752. /**
  5753. * Creates a new target data instance with an updated expected count.
  5754. */
  5755. withExpectedCount(expectedCount: number): TargetData;
  5756. /**
  5757. * Creates a new target data instance with an updated last limbo free
  5758. * snapshot version number.
  5759. */
  5760. withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData;
  5761. }
  5762. /**
  5763. * A locally-assigned ID used to refer to a target being watched via the
  5764. * Watch service.
  5765. */
  5766. declare type TargetId = number;
  5767. /** An enumeration of the different purposes we have for targets. */
  5768. declare const enum TargetPurpose {
  5769. /** A regular, normal query target. */
  5770. Listen = "TargetPurposeListen",
  5771. /**
  5772. * The query target was used to refill a query after an existence filter
  5773. * mismatch.
  5774. */
  5775. ExistenceFilterMismatch = "TargetPurposeExistenceFilterMismatch",
  5776. /**
  5777. * The query target was used if the query is the result of a false positive in
  5778. * the bloom filter.
  5779. */
  5780. ExistenceFilterMismatchBloom = "TargetPurposeExistenceFilterMismatchBloom",
  5781. /** The query target was used to resolve a limbo document. */
  5782. LimboResolution = "TargetPurposeLimboResolution"
  5783. }
  5784. /**
  5785. * Represents the state of bundle loading tasks.
  5786. *
  5787. * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will
  5788. * be no more updates after they are reported.
  5789. */
  5790. export declare type TaskState = 'Error' | 'Running' | 'Success';
  5791. /**
  5792. * Terminates the provided {@link Firestore} instance.
  5793. *
  5794. * After calling `terminate()` only the `clearIndexedDbPersistence()` function
  5795. * may be used. Any other function will throw a `FirestoreError`.
  5796. *
  5797. * To restart after termination, create a new instance of FirebaseFirestore with
  5798. * {@link (getFirestore:1)}.
  5799. *
  5800. * Termination does not cancel any pending writes, and any promises that are
  5801. * awaiting a response from the server will not be resolved. If you have
  5802. * persistence enabled, the next time you start this instance, it will resume
  5803. * sending these writes to the server.
  5804. *
  5805. * Note: Under normal circumstances, calling `terminate()` is not required. This
  5806. * function is useful only when you want to force this instance to release all
  5807. * of its resources or in combination with `clearIndexedDbPersistence()` to
  5808. * ensure that all local state is destroyed between test runs.
  5809. *
  5810. * @returns A `Promise` that is resolved when the instance has been successfully
  5811. * terminated.
  5812. */
  5813. export declare function terminate(firestore: Firestore): Promise<void>;
  5814. /* Excluded from this release type: _TestingHooks */
  5815. /**
  5816. * Wellknown "timer" IDs used when scheduling delayed operations on the
  5817. * AsyncQueue. These IDs can then be used from tests to check for the presence
  5818. * of operations or to run them early.
  5819. *
  5820. * The string values are used when encoding these timer IDs in JSON spec tests.
  5821. */
  5822. declare const enum TimerId {
  5823. /** All can be used with runDelayedOperationsEarly() to run all timers. */
  5824. All = "all",
  5825. /**
  5826. * The following 5 timers are used in persistent_stream.ts for the listen and
  5827. * write streams. The "Idle" timer is used to close the stream due to
  5828. * inactivity. The "ConnectionBackoff" timer is used to restart a stream once
  5829. * the appropriate backoff delay has elapsed. The health check is used to mark
  5830. * a stream healthy if it has not received an error during its initial setup.
  5831. */
  5832. ListenStreamIdle = "listen_stream_idle",
  5833. ListenStreamConnectionBackoff = "listen_stream_connection_backoff",
  5834. WriteStreamIdle = "write_stream_idle",
  5835. WriteStreamConnectionBackoff = "write_stream_connection_backoff",
  5836. HealthCheckTimeout = "health_check_timeout",
  5837. /**
  5838. * A timer used in online_state_tracker.ts to transition from
  5839. * OnlineState.Unknown to Offline after a set timeout, rather than waiting
  5840. * indefinitely for success or failure.
  5841. */
  5842. OnlineStateTimeout = "online_state_timeout",
  5843. /**
  5844. * A timer used to update the client metadata in IndexedDb, which is used
  5845. * to determine the primary leaseholder.
  5846. */
  5847. ClientMetadataRefresh = "client_metadata_refresh",
  5848. /** A timer used to periodically attempt LRU Garbage collection */
  5849. LruGarbageCollection = "lru_garbage_collection",
  5850. /**
  5851. * A timer used to retry transactions. Since there can be multiple concurrent
  5852. * transactions, multiple of these may be in the queue at a given time.
  5853. */
  5854. TransactionRetry = "transaction_retry",
  5855. /**
  5856. * A timer used to retry operations scheduled via retryable AsyncQueue
  5857. * operations.
  5858. */
  5859. AsyncQueueRetry = "async_queue_retry",
  5860. /**
  5861. * A timer used to periodically attempt index backfill.
  5862. */
  5863. IndexBackfill = "index_backfill"
  5864. }
  5865. /**
  5866. * @license
  5867. * Copyright 2017 Google LLC
  5868. *
  5869. * Licensed under the Apache License, Version 2.0 (the "License");
  5870. * you may not use this file except in compliance with the License.
  5871. * You may obtain a copy of the License at
  5872. *
  5873. * http://www.apache.org/licenses/LICENSE-2.0
  5874. *
  5875. * Unless required by applicable law or agreed to in writing, software
  5876. * distributed under the License is distributed on an "AS IS" BASIS,
  5877. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5878. * See the License for the specific language governing permissions and
  5879. * limitations under the License.
  5880. */
  5881. /**
  5882. * A `Timestamp` represents a point in time independent of any time zone or
  5883. * calendar, represented as seconds and fractions of seconds at nanosecond
  5884. * resolution in UTC Epoch time.
  5885. *
  5886. * It is encoded using the Proleptic Gregorian Calendar which extends the
  5887. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  5888. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  5889. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  5890. * 9999-12-31T23:59:59.999999999Z.
  5891. *
  5892. * For examples and further specifications, refer to the
  5893. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  5894. */
  5895. export declare class Timestamp {
  5896. /**
  5897. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  5898. */
  5899. readonly seconds: number;
  5900. /**
  5901. * The fractions of a second at nanosecond resolution.*
  5902. */
  5903. readonly nanoseconds: number;
  5904. /**
  5905. * Creates a new timestamp with the current date, with millisecond precision.
  5906. *
  5907. * @returns a new timestamp representing the current date.
  5908. */
  5909. static now(): Timestamp;
  5910. /**
  5911. * Creates a new timestamp from the given date.
  5912. *
  5913. * @param date - The date to initialize the `Timestamp` from.
  5914. * @returns A new `Timestamp` representing the same point in time as the given
  5915. * date.
  5916. */
  5917. static fromDate(date: Date): Timestamp;
  5918. /**
  5919. * Creates a new timestamp from the given number of milliseconds.
  5920. *
  5921. * @param milliseconds - Number of milliseconds since Unix epoch
  5922. * 1970-01-01T00:00:00Z.
  5923. * @returns A new `Timestamp` representing the same point in time as the given
  5924. * number of milliseconds.
  5925. */
  5926. static fromMillis(milliseconds: number): Timestamp;
  5927. /**
  5928. * Creates a new timestamp.
  5929. *
  5930. * @param seconds - The number of seconds of UTC time since Unix epoch
  5931. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  5932. * 9999-12-31T23:59:59Z inclusive.
  5933. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  5934. * resolution. Negative second values with fractions must still have
  5935. * non-negative nanoseconds values that count forward in time. Must be
  5936. * from 0 to 999,999,999 inclusive.
  5937. */
  5938. constructor(
  5939. /**
  5940. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  5941. */
  5942. seconds: number,
  5943. /**
  5944. * The fractions of a second at nanosecond resolution.*
  5945. */
  5946. nanoseconds: number);
  5947. /**
  5948. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  5949. * causes a loss of precision since `Date` objects only support millisecond
  5950. * precision.
  5951. *
  5952. * @returns JavaScript `Date` object representing the same point in time as
  5953. * this `Timestamp`, with millisecond precision.
  5954. */
  5955. toDate(): Date;
  5956. /**
  5957. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  5958. * epoch). This operation causes a loss of precision.
  5959. *
  5960. * @returns The point in time corresponding to this timestamp, represented as
  5961. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  5962. */
  5963. toMillis(): number;
  5964. _compareTo(other: Timestamp): number;
  5965. /**
  5966. * Returns true if this `Timestamp` is equal to the provided one.
  5967. *
  5968. * @param other - The `Timestamp` to compare against.
  5969. * @returns true if this `Timestamp` is equal to the provided one.
  5970. */
  5971. isEqual(other: Timestamp): boolean;
  5972. /** Returns a textual representation of this `Timestamp`. */
  5973. toString(): string;
  5974. /** Returns a JSON-serializable representation of this `Timestamp`. */
  5975. toJSON(): {
  5976. seconds: number;
  5977. nanoseconds: number;
  5978. };
  5979. /**
  5980. * Converts this object to a primitive string, which allows `Timestamp` objects
  5981. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  5982. */
  5983. valueOf(): string;
  5984. }
  5985. declare type Timestamp_2 = string | {
  5986. seconds?: string | number;
  5987. nanos?: number;
  5988. };
  5989. declare interface Token {
  5990. /** Type of token. */
  5991. type: TokenType;
  5992. /**
  5993. * The user with which the token is associated (used for persisting user
  5994. * state on disk, etc.).
  5995. * This will be null for Tokens of the type 'AppCheck'.
  5996. */
  5997. user?: User;
  5998. /** Header values to set for this token */
  5999. headers: Map<string, string>;
  6000. }
  6001. declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck';
  6002. /**
  6003. * A reference to a transaction.
  6004. *
  6005. * The `Transaction` object passed to a transaction's `updateFunction` provides
  6006. * the methods to read and write data within the transaction context. See
  6007. * {@link runTransaction}.
  6008. */
  6009. export declare class Transaction extends Transaction_2 {
  6010. protected readonly _firestore: Firestore;
  6011. /** @hideconstructor */
  6012. constructor(_firestore: Firestore, _transaction: Transaction_3);
  6013. /**
  6014. * Reads the document referenced by the provided {@link DocumentReference}.
  6015. *
  6016. * @param documentRef - A reference to the document to be read.
  6017. * @returns A `DocumentSnapshot` with the read data.
  6018. */
  6019. get<T>(documentRef: DocumentReference<T>): Promise<DocumentSnapshot<T>>;
  6020. }
  6021. /**
  6022. * A reference to a transaction.
  6023. *
  6024. * The `Transaction` object passed to a transaction's `updateFunction` provides
  6025. * the methods to read and write data within the transaction context. See
  6026. * {@link runTransaction}.
  6027. */
  6028. declare class Transaction_2 {
  6029. protected readonly _firestore: Firestore_2;
  6030. private readonly _transaction;
  6031. private readonly _dataReader;
  6032. /** @hideconstructor */
  6033. constructor(_firestore: Firestore_2, _transaction: Transaction_3);
  6034. /**
  6035. * Reads the document referenced by the provided {@link DocumentReference}.
  6036. *
  6037. * @param documentRef - A reference to the document to be read.
  6038. * @returns A `DocumentSnapshot` with the read data.
  6039. */
  6040. get<T>(documentRef: DocumentReference<T>): Promise<DocumentSnapshot_2<T>>;
  6041. /**
  6042. * Writes to the document referred to by the provided {@link
  6043. * DocumentReference}. If the document does not exist yet, it will be created.
  6044. *
  6045. * @param documentRef - A reference to the document to be set.
  6046. * @param data - An object of the fields and values for the document.
  6047. * @throws Error - If the provided input is not a valid Firestore document.
  6048. * @returns This `Transaction` instance. Used for chaining method calls.
  6049. */
  6050. set<T>(documentRef: DocumentReference<T>, data: WithFieldValue<T>): this;
  6051. /**
  6052. * Writes to the document referred to by the provided {@link
  6053. * DocumentReference}. If the document does not exist yet, it will be created.
  6054. * If you provide `merge` or `mergeFields`, the provided data can be merged
  6055. * into an existing document.
  6056. *
  6057. * @param documentRef - A reference to the document to be set.
  6058. * @param data - An object of the fields and values for the document.
  6059. * @param options - An object to configure the set behavior.
  6060. * @throws Error - If the provided input is not a valid Firestore document.
  6061. * @returns This `Transaction` instance. Used for chaining method calls.
  6062. */
  6063. set<T>(documentRef: DocumentReference<T>, data: PartialWithFieldValue<T>, options: SetOptions): this;
  6064. /**
  6065. * Updates fields in the document referred to by the provided {@link
  6066. * DocumentReference}. The update will fail if applied to a document that does
  6067. * not exist.
  6068. *
  6069. * @param documentRef - A reference to the document to be updated.
  6070. * @param data - An object containing the fields and values with which to
  6071. * update the document. Fields can contain dots to reference nested fields
  6072. * within the document.
  6073. * @throws Error - If the provided input is not valid Firestore data.
  6074. * @returns This `Transaction` instance. Used for chaining method calls.
  6075. */
  6076. update<T>(documentRef: DocumentReference<T>, data: UpdateData<T>): this;
  6077. /**
  6078. * Updates fields in the document referred to by the provided {@link
  6079. * DocumentReference}. The update will fail if applied to a document that does
  6080. * not exist.
  6081. *
  6082. * Nested fields can be updated by providing dot-separated field path
  6083. * strings or by providing `FieldPath` objects.
  6084. *
  6085. * @param documentRef - A reference to the document to be updated.
  6086. * @param field - The first field to update.
  6087. * @param value - The first value.
  6088. * @param moreFieldsAndValues - Additional key/value pairs.
  6089. * @throws Error - If the provided input is not valid Firestore data.
  6090. * @returns This `Transaction` instance. Used for chaining method calls.
  6091. */
  6092. update(documentRef: DocumentReference<unknown>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this;
  6093. /**
  6094. * Deletes the document referred to by the provided {@link DocumentReference}.
  6095. *
  6096. * @param documentRef - A reference to the document to be deleted.
  6097. * @returns This `Transaction` instance. Used for chaining method calls.
  6098. */
  6099. delete(documentRef: DocumentReference<unknown>): this;
  6100. }
  6101. /**
  6102. * Internal transaction object responsible for accumulating the mutations to
  6103. * perform and the base versions for any documents read.
  6104. */
  6105. declare class Transaction_3 {
  6106. private datastore;
  6107. private readVersions;
  6108. private mutations;
  6109. private committed;
  6110. /**
  6111. * A deferred usage error that occurred previously in this transaction that
  6112. * will cause the transaction to fail once it actually commits.
  6113. */
  6114. private lastWriteError;
  6115. /**
  6116. * Set of documents that have been written in the transaction.
  6117. *
  6118. * When there's more than one write to the same key in a transaction, any
  6119. * writes after the first are handled differently.
  6120. */
  6121. private writtenDocs;
  6122. constructor(datastore: Datastore);
  6123. lookup(keys: _DocumentKey[]): Promise<Document_2[]>;
  6124. set(key: _DocumentKey, data: ParsedSetData): void;
  6125. update(key: _DocumentKey, data: ParsedUpdateData): void;
  6126. delete(key: _DocumentKey): void;
  6127. commit(): Promise<void>;
  6128. private recordVersion;
  6129. /**
  6130. * Returns the version of this document when it was read in this transaction,
  6131. * as a precondition, or no precondition if it was not read.
  6132. */
  6133. private precondition;
  6134. /**
  6135. * Returns the precondition for a document if the operation is an update.
  6136. */
  6137. private preconditionForUpdate;
  6138. private write;
  6139. private ensureCommitNotCalled;
  6140. }
  6141. /**
  6142. * @license
  6143. * Copyright 2022 Google LLC
  6144. *
  6145. * Licensed under the Apache License, Version 2.0 (the "License");
  6146. * you may not use this file except in compliance with the License.
  6147. * You may obtain a copy of the License at
  6148. *
  6149. * http://www.apache.org/licenses/LICENSE-2.0
  6150. *
  6151. * Unless required by applicable law or agreed to in writing, software
  6152. * distributed under the License is distributed on an "AS IS" BASIS,
  6153. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6154. * See the License for the specific language governing permissions and
  6155. * limitations under the License.
  6156. */
  6157. /**
  6158. * Options to customize transaction behavior.
  6159. */
  6160. export declare interface TransactionOptions {
  6161. /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */
  6162. readonly maxAttempts?: number;
  6163. }
  6164. /** Used to represent a field transform on a mutation. */
  6165. declare class TransformOperation {
  6166. private _;
  6167. }
  6168. declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL';
  6169. /**
  6170. * Given a union type `U = T1 | T2 | ...`, returns an intersected type
  6171. * `(T1 & T2 & ...)`.
  6172. *
  6173. * Uses distributive conditional types and inference from conditional types.
  6174. * This works because multiple candidates for the same type variable in
  6175. * contra-variant positions causes an intersection type to be inferred.
  6176. * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types
  6177. * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type
  6178. */
  6179. export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
  6180. /**
  6181. * A function returned by `onSnapshot()` that removes the listener when invoked.
  6182. */
  6183. export declare interface Unsubscribe {
  6184. /** Removes the listener when invoked. */
  6185. (): void;
  6186. }
  6187. /**
  6188. * An untyped Firestore Data Converter interface that is shared between the
  6189. * lite, firestore-exp and classic SDK.
  6190. */
  6191. declare interface UntypedFirestoreDataConverter<T> {
  6192. toFirestore(modelObject: WithFieldValue<T>): DocumentData_2;
  6193. toFirestore(modelObject: PartialWithFieldValue<T>, options: SetOptions_2): DocumentData_2;
  6194. fromFirestore(snapshot: unknown, options?: unknown): T;
  6195. }
  6196. /**
  6197. * Update data (for use with {@link (updateDoc:1)}) that consists of field paths
  6198. * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots
  6199. * reference nested fields within the document. FieldValues can be passed in
  6200. * as property values.
  6201. */
  6202. export declare type UpdateData<T> = T extends Primitive ? T : T extends {} ? {
  6203. [K in keyof T]?: UpdateData<T[K]> | FieldValue;
  6204. } & NestedUpdateFields<T> : Partial<T>;
  6205. /**
  6206. * Updates fields in the document referred to by the specified
  6207. * `DocumentReference`. The update will fail if applied to a document that does
  6208. * not exist.
  6209. *
  6210. * @param reference - A reference to the document to update.
  6211. * @param data - An object containing the fields and values with which to
  6212. * update the document. Fields can contain dots to reference nested fields
  6213. * within the document.
  6214. * @returns A `Promise` resolved once the data has been successfully written
  6215. * to the backend (note that it won't resolve while you're offline).
  6216. */
  6217. export declare function updateDoc<T>(reference: DocumentReference<T>, data: UpdateData<T>): Promise<void>;
  6218. /**
  6219. * Updates fields in the document referred to by the specified
  6220. * `DocumentReference` The update will fail if applied to a document that does
  6221. * not exist.
  6222. *
  6223. * Nested fields can be updated by providing dot-separated field path
  6224. * strings or by providing `FieldPath` objects.
  6225. *
  6226. * @param reference - A reference to the document to update.
  6227. * @param field - The first field to update.
  6228. * @param value - The first value.
  6229. * @param moreFieldsAndValues - Additional key value pairs.
  6230. * @returns A `Promise` resolved once the data has been successfully written
  6231. * to the backend (note that it won't resolve while you're offline).
  6232. */
  6233. export declare function updateDoc(reference: DocumentReference<unknown>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise<void>;
  6234. /**
  6235. * @license
  6236. * Copyright 2017 Google LLC
  6237. *
  6238. * Licensed under the Apache License, Version 2.0 (the "License");
  6239. * you may not use this file except in compliance with the License.
  6240. * You may obtain a copy of the License at
  6241. *
  6242. * http://www.apache.org/licenses/LICENSE-2.0
  6243. *
  6244. * Unless required by applicable law or agreed to in writing, software
  6245. * distributed under the License is distributed on an "AS IS" BASIS,
  6246. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6247. * See the License for the specific language governing permissions and
  6248. * limitations under the License.
  6249. */
  6250. /**
  6251. * Simple wrapper around a nullable UID. Mostly exists to make code more
  6252. * readable.
  6253. */
  6254. declare class User {
  6255. readonly uid: string | null;
  6256. /** A user with a null UID. */
  6257. static readonly UNAUTHENTICATED: User;
  6258. static readonly GOOGLE_CREDENTIALS: User;
  6259. static readonly FIRST_PARTY: User;
  6260. static readonly MOCK_USER: User;
  6261. constructor(uid: string | null);
  6262. isAuthenticated(): boolean;
  6263. /**
  6264. * Returns a key representing this user, suitable for inclusion in a
  6265. * dictionary.
  6266. */
  6267. toKey(): string;
  6268. isEqual(otherUser: User): boolean;
  6269. }
  6270. /* Excluded from this release type: _validateIsNotUsedTogether */
  6271. declare type Value = firestoreV1ApiClientInterfaces.Value;
  6272. declare type ValueNullValue = 'NULL_VALUE';
  6273. declare class ViewSnapshot {
  6274. readonly query: Query_2;
  6275. readonly docs: DocumentSet;
  6276. readonly oldDocs: DocumentSet;
  6277. readonly docChanges: DocumentViewChange[];
  6278. readonly mutatedKeys: DocumentKeySet;
  6279. readonly fromCache: boolean;
  6280. readonly syncStateChanged: boolean;
  6281. readonly excludesMetadataChanges: boolean;
  6282. readonly hasCachedResults: boolean;
  6283. constructor(query: Query_2, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean);
  6284. /** Returns a view snapshot as if all documents in the snapshot were added. */
  6285. static fromInitialDocuments(query: Query_2, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot;
  6286. get hasPendingWrites(): boolean;
  6287. isEqual(other: ViewSnapshot): boolean;
  6288. }
  6289. /**
  6290. * Waits until all currently pending writes for the active user have been
  6291. * acknowledged by the backend.
  6292. *
  6293. * The returned promise resolves immediately if there are no outstanding writes.
  6294. * Otherwise, the promise waits for all previously issued writes (including
  6295. * those written in a previous app session), but it does not wait for writes
  6296. * that were added after the function is called. If you want to wait for
  6297. * additional writes, call `waitForPendingWrites()` again.
  6298. *
  6299. * Any outstanding `waitForPendingWrites()` promises are rejected during user
  6300. * changes.
  6301. *
  6302. * @returns A `Promise` which resolves when all currently pending writes have been
  6303. * acknowledged by the backend.
  6304. */
  6305. export declare function waitForPendingWrites(firestore: Firestore): Promise<void>;
  6306. /**
  6307. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  6308. * must contain the specified field and that the value should satisfy the
  6309. * relation constraint provided.
  6310. *
  6311. * @param fieldPath - The path to compare
  6312. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  6313. * "&lt;=", "!=").
  6314. * @param value - The value for comparison
  6315. * @returns The created {@link QueryFieldFilterConstraint}.
  6316. */
  6317. export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint;
  6318. /**
  6319. * Filter conditions in a {@link where} clause are specified using the
  6320. * strings '&lt;', '&lt;=', '==', '!=', '&gt;=', '&gt;', 'array-contains', 'in',
  6321. * 'array-contains-any', and 'not-in'.
  6322. */
  6323. export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in';
  6324. /**
  6325. * Allows FieldValues to be passed in as a property value while maintaining
  6326. * type safety.
  6327. */
  6328. export declare type WithFieldValue<T> = T | (T extends Primitive ? T : T extends {} ? {
  6329. [K in keyof T]: WithFieldValue<T[K]> | FieldValue;
  6330. } : never);
  6331. /**
  6332. * A write batch, used to perform multiple writes as a single atomic unit.
  6333. *
  6334. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  6335. * provides methods for adding writes to the write batch. None of the writes
  6336. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  6337. * called.
  6338. */
  6339. export declare class WriteBatch {
  6340. private readonly _firestore;
  6341. private readonly _commitHandler;
  6342. private readonly _dataReader;
  6343. private _mutations;
  6344. private _committed;
  6345. /** @hideconstructor */
  6346. constructor(_firestore: Firestore_2, _commitHandler: (m: Mutation[]) => Promise<void>);
  6347. /**
  6348. * Writes to the document referred to by the provided {@link
  6349. * DocumentReference}. If the document does not exist yet, it will be created.
  6350. *
  6351. * @param documentRef - A reference to the document to be set.
  6352. * @param data - An object of the fields and values for the document.
  6353. * @returns This `WriteBatch` instance. Used for chaining method calls.
  6354. */
  6355. set<T>(documentRef: DocumentReference<T>, data: WithFieldValue<T>): WriteBatch;
  6356. /**
  6357. * Writes to the document referred to by the provided {@link
  6358. * DocumentReference}. If the document does not exist yet, it will be created.
  6359. * If you provide `merge` or `mergeFields`, the provided data can be merged
  6360. * into an existing document.
  6361. *
  6362. * @param documentRef - A reference to the document to be set.
  6363. * @param data - An object of the fields and values for the document.
  6364. * @param options - An object to configure the set behavior.
  6365. * @throws Error - If the provided input is not a valid Firestore document.
  6366. * @returns This `WriteBatch` instance. Used for chaining method calls.
  6367. */
  6368. set<T>(documentRef: DocumentReference<T>, data: PartialWithFieldValue<T>, options: SetOptions): WriteBatch;
  6369. /**
  6370. * Updates fields in the document referred to by the provided {@link
  6371. * DocumentReference}. The update will fail if applied to a document that does
  6372. * not exist.
  6373. *
  6374. * @param documentRef - A reference to the document to be updated.
  6375. * @param data - An object containing the fields and values with which to
  6376. * update the document. Fields can contain dots to reference nested fields
  6377. * within the document.
  6378. * @throws Error - If the provided input is not valid Firestore data.
  6379. * @returns This `WriteBatch` instance. Used for chaining method calls.
  6380. */
  6381. update<T>(documentRef: DocumentReference<T>, data: UpdateData<T>): WriteBatch;
  6382. /**
  6383. * Updates fields in the document referred to by this {@link
  6384. * DocumentReference}. The update will fail if applied to a document that does
  6385. * not exist.
  6386. *
  6387. * Nested fields can be update by providing dot-separated field path strings
  6388. * or by providing `FieldPath` objects.
  6389. *
  6390. * @param documentRef - A reference to the document to be updated.
  6391. * @param field - The first field to update.
  6392. * @param value - The first value.
  6393. * @param moreFieldsAndValues - Additional key value pairs.
  6394. * @throws Error - If the provided input is not valid Firestore data.
  6395. * @returns This `WriteBatch` instance. Used for chaining method calls.
  6396. */
  6397. update(documentRef: DocumentReference<unknown>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch;
  6398. /**
  6399. * Deletes the document referred to by the provided {@link DocumentReference}.
  6400. *
  6401. * @param documentRef - A reference to the document to be deleted.
  6402. * @returns This `WriteBatch` instance. Used for chaining method calls.
  6403. */
  6404. delete(documentRef: DocumentReference<unknown>): WriteBatch;
  6405. /**
  6406. * Commits all of the writes in this write batch as a single atomic unit.
  6407. *
  6408. * The result of these writes will only be reflected in document reads that
  6409. * occur after the returned promise resolves. If the client is offline, the
  6410. * write fails. If you would like to see local modifications or buffer writes
  6411. * until the client is online, use the full Firestore SDK.
  6412. *
  6413. * @returns A `Promise` resolved once all of the writes in the batch have been
  6414. * successfully written to the backend as an atomic unit (note that it won't
  6415. * resolve while you're offline).
  6416. */
  6417. commit(): Promise<void>;
  6418. private _verifyNotCommitted;
  6419. }
  6420. /**
  6421. * Creates a write batch, used for performing multiple writes as a single
  6422. * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}
  6423. * is 500.
  6424. *
  6425. * Unlike transactions, write batches are persisted offline and therefore are
  6426. * preferable when you don't need to condition your writes on read data.
  6427. *
  6428. * @returns A {@link WriteBatch} that can be used to atomically execute multiple
  6429. * writes.
  6430. */
  6431. export declare function writeBatch(firestore: Firestore): WriteBatch;
  6432. export { }