parse.js 549 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687
  1. /**
  2. * Parse JavaScript SDK v2.6.0
  3. *
  4. * The source tree of this library can be found at
  5. * https://github.com/ParsePlatform/Parse-SDK-JS
  6. */
  7. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Parse = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
  8. "use strict";
  9. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  10. Object.defineProperty(exports, "__esModule", {
  11. value: true
  12. });
  13. exports.track = track;
  14. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  15. /**
  16. * Copyright (c) 2015-present, Parse, LLC.
  17. * All rights reserved.
  18. *
  19. * This source code is licensed under the BSD-style license found in the
  20. * LICENSE file in the root directory of this source tree. An additional grant
  21. * of patent rights can be found in the PATENTS file in the same directory.
  22. *
  23. * @flow
  24. */
  25. /**
  26. * Parse.Analytics provides an interface to Parse's logging and analytics
  27. * backend.
  28. *
  29. * @class Parse.Analytics
  30. * @static
  31. * @hideconstructor
  32. */
  33. /**
  34. * Tracks the occurrence of a custom event with additional dimensions.
  35. * Parse will store a data point at the time of invocation with the given
  36. * event name.
  37. *
  38. * Dimensions will allow segmentation of the occurrences of this custom
  39. * event. Keys and values should be {@code String}s, and will throw
  40. * otherwise.
  41. *
  42. * To track a user signup along with additional metadata, consider the
  43. * following:
  44. * <pre>
  45. * var dimensions = {
  46. * gender: 'm',
  47. * source: 'web',
  48. * dayType: 'weekend'
  49. * };
  50. * Parse.Analytics.track('signup', dimensions);
  51. * </pre>
  52. *
  53. * There is a default limit of 8 dimensions per event tracked.
  54. *
  55. * @method track
  56. * @name Parse.Analytics.track
  57. * @param {String} name The name of the custom event to report to Parse as
  58. * having happened.
  59. * @param {Object} dimensions The dictionary of information by which to
  60. * segment this event.
  61. * @return {Promise} A promise that is resolved when the round-trip
  62. * to the server completes.
  63. */
  64. function track(name
  65. /*: string*/
  66. , dimensions
  67. /*: { [key: string]: string }*/
  68. )
  69. /*: Promise*/
  70. {
  71. name = name || '';
  72. name = name.replace(/^\s*/, '');
  73. name = name.replace(/\s*$/, '');
  74. if (name.length === 0) {
  75. throw new TypeError('A name for the custom event must be provided');
  76. }
  77. for (var _key in dimensions) {
  78. if (typeof _key !== 'string' || typeof dimensions[_key] !== 'string') {
  79. throw new TypeError('track() dimensions expects keys and values of type "string".');
  80. }
  81. }
  82. return _CoreManager.default.getAnalyticsController().track(name, dimensions);
  83. }
  84. var DefaultController = {
  85. track: function (name, dimensions) {
  86. var RESTController = _CoreManager.default.getRESTController();
  87. return RESTController.request('POST', 'events/' + name, {
  88. dimensions: dimensions
  89. });
  90. }
  91. };
  92. _CoreManager.default.setAnalyticsController(DefaultController);
  93. },{"./CoreManager":4,"@babel/runtime/helpers/interopRequireDefault":61}],2:[function(_dereq_,module,exports){
  94. "use strict";
  95. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  96. Object.defineProperty(exports, "__esModule", {
  97. value: true
  98. });
  99. exports.default = void 0;
  100. var _ParseUser = _interopRequireDefault(_dereq_("./ParseUser"));
  101. /**
  102. * Copyright (c) 2015-present, Parse, LLC.
  103. * All rights reserved.
  104. *
  105. * This source code is licensed under the BSD-style license found in the
  106. * LICENSE file in the root directory of this source tree. An additional grant
  107. * of patent rights can be found in the PATENTS file in the same directory.
  108. *
  109. * @flow-weak
  110. */
  111. var uuidv4 = _dereq_('uuid/v4');
  112. /*:: import type { RequestOptions } from './RESTController';*/
  113. var registered = false;
  114. /**
  115. * Provides utility functions for working with Anonymously logged-in users. <br />
  116. * Anonymous users have some unique characteristics:
  117. * <ul>
  118. * <li>Anonymous users don't need a user name or password.</li>
  119. * <ul>
  120. * <li>Once logged out, an anonymous user cannot be recovered.</li>
  121. * </ul>
  122. * <li>signUp converts an anonymous user to a standard user with the given username and password.</li>
  123. * <ul>
  124. * <li>Data associated with the anonymous user is retained.</li>
  125. * </ul>
  126. * <li>logIn switches users without converting the anonymous user.</li>
  127. * <ul>
  128. * <li>Data associated with the anonymous user will be lost.</li>
  129. * </ul>
  130. * <li>Service logIn (e.g. Facebook, Twitter) will attempt to convert
  131. * the anonymous user into a standard user by linking it to the service.</li>
  132. * <ul>
  133. * <li>If a user already exists that is linked to the service, it will instead switch to the existing user.</li>
  134. * </ul>
  135. * <li>Service linking (e.g. Facebook, Twitter) will convert the anonymous user
  136. * into a standard user by linking it to the service.</li>
  137. * </ul>
  138. * @class Parse.AnonymousUtils
  139. * @static
  140. */
  141. var AnonymousUtils = {
  142. /**
  143. * Gets whether the user has their account linked to anonymous user.
  144. *
  145. * @method isLinked
  146. * @name Parse.AnonymousUtils.isLinked
  147. * @param {Parse.User} user User to check for.
  148. * The user must be logged in on this device.
  149. * @return {Boolean} <code>true</code> if the user has their account
  150. * linked to an anonymous user.
  151. * @static
  152. */
  153. isLinked: function (user
  154. /*: ParseUser*/
  155. ) {
  156. var provider = this._getAuthProvider();
  157. return user._isLinked(provider.getAuthType());
  158. },
  159. /**
  160. * Logs in a user Anonymously.
  161. *
  162. * @method logIn
  163. * @name Parse.AnonymousUtils.logIn
  164. * @param {Object} options MasterKey / SessionToken.
  165. * @returns {Promise}
  166. * @static
  167. */
  168. logIn: function (options
  169. /*:: ?: RequestOptions*/
  170. ) {
  171. var provider = this._getAuthProvider();
  172. return _ParseUser.default._logInWith(provider.getAuthType(), provider.getAuthData(), options);
  173. },
  174. /**
  175. * Links Anonymous User to an existing PFUser.
  176. *
  177. * @method link
  178. * @name Parse.AnonymousUtils.link
  179. * @param {Parse.User} user User to link. This must be the current user.
  180. * @param {Object} options MasterKey / SessionToken.
  181. * @returns {Promise}
  182. * @static
  183. */
  184. link: function (user
  185. /*: ParseUser*/
  186. , options
  187. /*:: ?: RequestOptions*/
  188. ) {
  189. var provider = this._getAuthProvider();
  190. return user._linkWith(provider.getAuthType(), provider.getAuthData(), options);
  191. },
  192. _getAuthProvider: function () {
  193. var provider = {
  194. restoreAuthentication: function () {
  195. return true;
  196. },
  197. getAuthType: function () {
  198. return 'anonymous';
  199. },
  200. getAuthData: function () {
  201. return {
  202. authData: {
  203. id: uuidv4()
  204. }
  205. };
  206. }
  207. };
  208. if (!registered) {
  209. _ParseUser.default._registerAuthenticationProvider(provider);
  210. registered = true;
  211. }
  212. return provider;
  213. }
  214. };
  215. var _default = AnonymousUtils;
  216. exports.default = _default;
  217. },{"./ParseUser":31,"@babel/runtime/helpers/interopRequireDefault":61,"uuid/v4":81}],3:[function(_dereq_,module,exports){
  218. "use strict";
  219. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  220. Object.defineProperty(exports, "__esModule", {
  221. value: true
  222. });
  223. exports.run = run;
  224. exports.getJobsData = getJobsData;
  225. exports.startJob = startJob;
  226. exports.getJobStatus = getJobStatus;
  227. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  228. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  229. var _decode = _interopRequireDefault(_dereq_("./decode"));
  230. var _encode = _interopRequireDefault(_dereq_("./encode"));
  231. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  232. var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
  233. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  234. /**
  235. * Copyright (c) 2015-present, Parse, LLC.
  236. * All rights reserved.
  237. *
  238. * This source code is licensed under the BSD-style license found in the
  239. * LICENSE file in the root directory of this source tree. An additional grant
  240. * of patent rights can be found in the PATENTS file in the same directory.
  241. *
  242. * @flow
  243. */
  244. /**
  245. * Contains functions for calling and declaring
  246. * <a href="/docs/cloud_code_guide#functions">cloud functions</a>.
  247. * <p><strong><em>
  248. * Some functions are only available from Cloud Code.
  249. * </em></strong></p>
  250. *
  251. * @class Parse.Cloud
  252. * @static
  253. * @hideconstructor
  254. */
  255. /**
  256. * Makes a call to a cloud function.
  257. * @method run
  258. * @name Parse.Cloud.run
  259. * @param {String} name The function name.
  260. * @param {Object} data The parameters to send to the cloud function.
  261. * @param {Object} options
  262. * @return {Promise} A promise that will be resolved with the result
  263. * of the function.
  264. */
  265. function run(name
  266. /*: string*/
  267. , data
  268. /*: mixed*/
  269. , options
  270. /*: RequestOptions*/
  271. )
  272. /*: Promise<mixed>*/
  273. {
  274. options = options || {};
  275. if (typeof name !== 'string' || name.length === 0) {
  276. throw new TypeError('Cloud function name must be a string.');
  277. }
  278. var requestOptions = {};
  279. if (options.useMasterKey) {
  280. requestOptions.useMasterKey = options.useMasterKey;
  281. }
  282. if (options.sessionToken) {
  283. requestOptions.sessionToken = options.sessionToken;
  284. }
  285. return _CoreManager.default.getCloudController().run(name, data, requestOptions);
  286. }
  287. /**
  288. * Gets data for the current set of cloud jobs.
  289. * @method getJobsData
  290. * @name Parse.Cloud.getJobsData
  291. * @return {Promise} A promise that will be resolved with the result
  292. * of the function.
  293. */
  294. function getJobsData()
  295. /*: Promise<Object>*/
  296. {
  297. return _CoreManager.default.getCloudController().getJobsData({
  298. useMasterKey: true
  299. });
  300. }
  301. /**
  302. * Starts a given cloud job, which will process asynchronously.
  303. * @method startJob
  304. * @name Parse.Cloud.startJob
  305. * @param {String} name The function name.
  306. * @param {Object} data The parameters to send to the cloud function.
  307. * @return {Promise} A promise that will be resolved with the jobStatusId
  308. * of the job.
  309. */
  310. function startJob(name
  311. /*: string*/
  312. , data
  313. /*: mixed*/
  314. )
  315. /*: Promise<string>*/
  316. {
  317. if (typeof name !== 'string' || name.length === 0) {
  318. throw new TypeError('Cloud job name must be a string.');
  319. }
  320. return _CoreManager.default.getCloudController().startJob(name, data, {
  321. useMasterKey: true
  322. });
  323. }
  324. /**
  325. * Gets job status by Id
  326. * @method getJobStatus
  327. * @name Parse.Cloud.getJobStatus
  328. * @param {String} jobStatusId The Id of Job Status.
  329. * @return {Parse.Object} Status of Job.
  330. */
  331. function getJobStatus(jobStatusId
  332. /*: string*/
  333. )
  334. /*: Promise<ParseObject>*/
  335. {
  336. var query = new _ParseQuery.default('_JobStatus');
  337. return query.get(jobStatusId, {
  338. useMasterKey: true
  339. });
  340. }
  341. var DefaultController = {
  342. run: function (name, data, options
  343. /*: RequestOptions*/
  344. ) {
  345. var RESTController = _CoreManager.default.getRESTController();
  346. var payload = (0, _encode.default)(data, true);
  347. var request = RESTController.request('POST', 'functions/' + name, payload, options);
  348. return request.then(function (res) {
  349. if ((0, _typeof2.default)(res) === 'object' && Object.keys(res).length > 0 && !res.hasOwnProperty('result')) {
  350. throw new _ParseError.default(_ParseError.default.INVALID_JSON, 'The server returned an invalid response.');
  351. }
  352. var decoded = (0, _decode.default)(res);
  353. if (decoded && decoded.hasOwnProperty('result')) {
  354. return Promise.resolve(decoded.result);
  355. }
  356. return Promise.resolve(undefined);
  357. });
  358. },
  359. getJobsData: function (options
  360. /*: RequestOptions*/
  361. ) {
  362. var RESTController = _CoreManager.default.getRESTController();
  363. return RESTController.request('GET', 'cloud_code/jobs/data', null, options);
  364. },
  365. startJob: function (name, data, options
  366. /*: RequestOptions*/
  367. ) {
  368. var RESTController = _CoreManager.default.getRESTController();
  369. var payload = (0, _encode.default)(data, true);
  370. return RESTController.request('POST', 'jobs/' + name, payload, options);
  371. }
  372. };
  373. _CoreManager.default.setCloudController(DefaultController);
  374. },{"./CoreManager":4,"./ParseError":18,"./ParseObject":23,"./ParseQuery":26,"./decode":41,"./encode":42,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],4:[function(_dereq_,module,exports){
  375. (function (process){
  376. /*:: import type { AttributeMap, ObjectCache, OpsMap, State } from './ObjectStateMutations';*/
  377. /*:: import type ParseFile from './ParseFile';*/
  378. /*:: import type { FileSource } from './ParseFile';*/
  379. /*:: import type { Op } from './ParseOp';*/
  380. /*:: import type ParseObject from './ParseObject';*/
  381. /*:: import type { QueryJSON } from './ParseQuery';*/
  382. /*:: import type ParseUser from './ParseUser';*/
  383. /*:: import type { AuthData } from './ParseUser';*/
  384. /*:: import type { PushData } from './Push';*/
  385. /*:: import type { RequestOptions, FullOptions } from './RESTController';*/
  386. /*:: type AnalyticsController = {
  387. track: (name: string, dimensions: { [key: string]: string }) => Promise;
  388. };*/
  389. /*:: type CloudController = {
  390. run: (name: string, data: mixed, options: RequestOptions) => Promise;
  391. getJobsData: (options: RequestOptions) => Promise;
  392. startJob: (name: string, data: mixed, options: RequestOptions) => Promise;
  393. };*/
  394. /*:: type ConfigController = {
  395. current: () => Promise;
  396. get: () => Promise;
  397. save: (attrs: { [key: string]: any }) => Promise;
  398. };*/
  399. /*:: type FileController = {
  400. saveFile: (name: string, source: FileSource, options: FullOptions) => Promise;
  401. saveBase64: (name: string, source: FileSource, options: FullOptions) => Promise;
  402. download: (uri: string) => Promise;
  403. };*/
  404. /*:: type InstallationController = {
  405. currentInstallationId: () => Promise;
  406. };*/
  407. /*:: type ObjectController = {
  408. fetch: (object: ParseObject | Array<ParseObject>, forceFetch: boolean, options: RequestOptions) => Promise;
  409. save: (object: ParseObject | Array<ParseObject | ParseFile>, options: RequestOptions) => Promise;
  410. destroy: (object: ParseObject | Array<ParseObject>, options: RequestOptions) => Promise;
  411. };*/
  412. /*:: type ObjectStateController = {
  413. getState: (obj: any) => ?State;
  414. initializeState: (obj: any, initial?: State) => State;
  415. removeState: (obj: any) => ?State;
  416. getServerData: (obj: any) => AttributeMap;
  417. setServerData: (obj: any, attributes: AttributeMap) => void;
  418. getPendingOps: (obj: any) => Array<OpsMap>;
  419. setPendingOp: (obj: any, attr: string, op: ?Op) => void;
  420. pushPendingState: (obj: any) => void;
  421. popPendingState: (obj: any) => OpsMap;
  422. mergeFirstPendingState: (obj: any) => void;
  423. getObjectCache: (obj: any) => ObjectCache;
  424. estimateAttribute: (obj: any, attr: string) => mixed;
  425. estimateAttributes: (obj: any) => AttributeMap;
  426. commitServerChanges: (obj: any, changes: AttributeMap) => void;
  427. enqueueTask: (obj: any, task: () => Promise) => Promise;
  428. clearAllState: () => void;
  429. duplicateState: (source: any, dest: any) => void;
  430. };*/
  431. /*:: type PushController = {
  432. send: (data: PushData, options: RequestOptions) => Promise;
  433. };*/
  434. /*:: type QueryController = {
  435. find: (className: string, params: QueryJSON, options: RequestOptions) => Promise;
  436. aggregate: (className: string, params: any, options: RequestOptions) => Promise;
  437. };*/
  438. /*:: type RESTController = {
  439. request: (method: string, path: string, data: mixed, options: RequestOptions) => Promise;
  440. ajax: (method: string, url: string, data: any, headers?: any, options: FullOptions) => Promise;
  441. };*/
  442. /*:: type SchemaController = {
  443. purge: (className: string) => Promise;
  444. get: (className: string, options: RequestOptions) => Promise;
  445. delete: (className: string, options: RequestOptions) => Promise;
  446. create: (className: string, params: any, options: RequestOptions) => Promise;
  447. update: (className: string, params: any, options: RequestOptions) => Promise;
  448. send(className: string, method: string, params: any, options: RequestOptions): Promise;
  449. };*/
  450. /*:: type SessionController = {
  451. getSession: (token: RequestOptions) => Promise;
  452. };*/
  453. /*:: type StorageController = {
  454. async: 0;
  455. getItem: (path: string) => ?string;
  456. setItem: (path: string, value: string) => void;
  457. removeItem: (path: string) => void;
  458. getItemAsync?: (path: string) => Promise;
  459. setItemAsync?: (path: string, value: string) => Promise;
  460. removeItemAsync?: (path: string) => Promise;
  461. clear: () => void;
  462. } | {
  463. async: 1;
  464. getItem?: (path: string) => ?string;
  465. setItem?: (path: string, value: string) => void;
  466. removeItem?: (path: string) => void;
  467. getItemAsync: (path: string) => Promise;
  468. setItemAsync: (path: string, value: string) => Promise;
  469. removeItemAsync: (path: string) => Promise;
  470. clear: () => void;
  471. };*/
  472. /*:: type LocalDatastoreController = {
  473. fromPinWithName: (name: string) => ?any;
  474. pinWithName: (name: string, objects: any) => void;
  475. unPinWithName: (name: string) => void;
  476. getAllContents: () => ?any;
  477. clear: () => void;
  478. };*/
  479. /*:: type UserController = {
  480. setCurrentUser: (user: ParseUser) => Promise;
  481. currentUser: () => ?ParseUser;
  482. currentUserAsync: () => Promise;
  483. signUp: (user: ParseUser, attrs: AttributeMap, options: RequestOptions) => Promise;
  484. logIn: (user: ParseUser, options: RequestOptions) => Promise;
  485. become: (options: RequestOptions) => Promise;
  486. hydrate: (userJSON: AttributeMap) => Promise;
  487. logOut: (options: RequestOptions) => Promise;
  488. me: (options: RequestOptions) => Promise;
  489. requestPasswordReset: (email: string, options: RequestOptions) => Promise;
  490. updateUserOnDisk: (user: ParseUser) => Promise;
  491. upgradeToRevocableSession: (user: ParseUser, options: RequestOptions) => Promise;
  492. linkWith: (user: ParseUser, authData: AuthData) => Promise;
  493. removeUserFromDisk: () => Promise;
  494. };*/
  495. /*:: type HooksController = {
  496. get: (type: string, functionName?: string, triggerName?: string) => Promise;
  497. create: (hook: mixed) => Promise;
  498. delete: (hook: mixed) => Promise;
  499. update: (hook: mixed) => Promise;
  500. send: (method: string, path: string, body?: mixed) => Promise;
  501. };*/
  502. /*:: type WebSocketController = {
  503. onopen: () => void;
  504. onmessage: (message: any) => void;
  505. onclose: () => void;
  506. onerror: (error: any) => void;
  507. send: (data: any) => void;
  508. close: () => void;
  509. }*/
  510. /*:: type Config = {
  511. AnalyticsController?: AnalyticsController,
  512. CloudController?: CloudController,
  513. ConfigController?: ConfigController,
  514. FileController?: FileController,
  515. InstallationController?: InstallationController,
  516. ObjectController?: ObjectController,
  517. ObjectStateController?: ObjectStateController,
  518. PushController?: PushController,
  519. QueryController?: QueryController,
  520. RESTController?: RESTController,
  521. SchemaController?: SchemaController,
  522. SessionController?: SessionController,
  523. StorageController?: StorageController,
  524. LocalDatastoreController?: LocalDatastoreController,
  525. UserController?: UserController,
  526. HooksController?: HooksController,
  527. WebSocketController?: WebSocketController,
  528. };*/
  529. "use strict";
  530. /*
  531. * Copyright (c) 2015-present, Parse, LLC.
  532. * All rights reserved.
  533. *
  534. * This source code is licensed under the BSD-style license found in the
  535. * LICENSE file in the root directory of this source tree. An additional grant
  536. * of patent rights can be found in the PATENTS file in the same directory.
  537. *
  538. * @flow
  539. */
  540. var config
  541. /*: Config & { [key: string]: mixed }*/
  542. = {
  543. // Defaults
  544. IS_NODE: typeof process !== 'undefined' && !!process.versions && !!process.versions.node && !process.versions.electron,
  545. REQUEST_ATTEMPT_LIMIT: 5,
  546. SERVER_URL: 'https://api.parse.com/1',
  547. SERVER_AUTH_TYPE: null,
  548. SERVER_AUTH_TOKEN: null,
  549. LIVEQUERY_SERVER_URL: null,
  550. VERSION: 'js' + "2.6.0",
  551. APPLICATION_ID: null,
  552. JAVASCRIPT_KEY: null,
  553. MASTER_KEY: null,
  554. USE_MASTER_KEY: false,
  555. PERFORM_USER_REWRITE: true,
  556. FORCE_REVOCABLE_SESSION: false
  557. };
  558. function requireMethods(name
  559. /*: string*/
  560. , methods
  561. /*: Array<string>*/
  562. , controller
  563. /*: any*/
  564. ) {
  565. methods.forEach(function (func) {
  566. if (typeof controller[func] !== 'function') {
  567. throw new Error("".concat(name, " must implement ").concat(func, "()"));
  568. }
  569. });
  570. }
  571. module.exports = {
  572. get: function (key
  573. /*: string*/
  574. )
  575. /*: any*/
  576. {
  577. if (config.hasOwnProperty(key)) {
  578. return config[key];
  579. }
  580. throw new Error('Configuration key not found: ' + key);
  581. },
  582. set: function (key
  583. /*: string*/
  584. , value
  585. /*: any*/
  586. )
  587. /*: void*/
  588. {
  589. config[key] = value;
  590. },
  591. /* Specialized Controller Setters/Getters */
  592. setAnalyticsController: function (controller
  593. /*: AnalyticsController*/
  594. ) {
  595. requireMethods('AnalyticsController', ['track'], controller);
  596. config['AnalyticsController'] = controller;
  597. },
  598. getAnalyticsController: function ()
  599. /*: AnalyticsController*/
  600. {
  601. return config['AnalyticsController'];
  602. },
  603. setCloudController: function (controller
  604. /*: CloudController*/
  605. ) {
  606. requireMethods('CloudController', ['run', 'getJobsData', 'startJob'], controller);
  607. config['CloudController'] = controller;
  608. },
  609. getCloudController: function ()
  610. /*: CloudController*/
  611. {
  612. return config['CloudController'];
  613. },
  614. setConfigController: function (controller
  615. /*: ConfigController*/
  616. ) {
  617. requireMethods('ConfigController', ['current', 'get', 'save'], controller);
  618. config['ConfigController'] = controller;
  619. },
  620. getConfigController: function ()
  621. /*: ConfigController*/
  622. {
  623. return config['ConfigController'];
  624. },
  625. setFileController: function (controller
  626. /*: FileController*/
  627. ) {
  628. requireMethods('FileController', ['saveFile', 'saveBase64'], controller);
  629. config['FileController'] = controller;
  630. },
  631. getFileController: function ()
  632. /*: FileController*/
  633. {
  634. return config['FileController'];
  635. },
  636. setInstallationController: function (controller
  637. /*: InstallationController*/
  638. ) {
  639. requireMethods('InstallationController', ['currentInstallationId'], controller);
  640. config['InstallationController'] = controller;
  641. },
  642. getInstallationController: function ()
  643. /*: InstallationController*/
  644. {
  645. return config['InstallationController'];
  646. },
  647. setObjectController: function (controller
  648. /*: ObjectController*/
  649. ) {
  650. requireMethods('ObjectController', ['save', 'fetch', 'destroy'], controller);
  651. config['ObjectController'] = controller;
  652. },
  653. getObjectController: function ()
  654. /*: ObjectController*/
  655. {
  656. return config['ObjectController'];
  657. },
  658. setObjectStateController: function (controller
  659. /*: ObjectStateController*/
  660. ) {
  661. requireMethods('ObjectStateController', ['getState', 'initializeState', 'removeState', 'getServerData', 'setServerData', 'getPendingOps', 'setPendingOp', 'pushPendingState', 'popPendingState', 'mergeFirstPendingState', 'getObjectCache', 'estimateAttribute', 'estimateAttributes', 'commitServerChanges', 'enqueueTask', 'clearAllState'], controller);
  662. config['ObjectStateController'] = controller;
  663. },
  664. getObjectStateController: function ()
  665. /*: ObjectStateController*/
  666. {
  667. return config['ObjectStateController'];
  668. },
  669. setPushController: function (controller
  670. /*: PushController*/
  671. ) {
  672. requireMethods('PushController', ['send'], controller);
  673. config['PushController'] = controller;
  674. },
  675. getPushController: function ()
  676. /*: PushController*/
  677. {
  678. return config['PushController'];
  679. },
  680. setQueryController: function (controller
  681. /*: QueryController*/
  682. ) {
  683. requireMethods('QueryController', ['find', 'aggregate'], controller);
  684. config['QueryController'] = controller;
  685. },
  686. getQueryController: function ()
  687. /*: QueryController*/
  688. {
  689. return config['QueryController'];
  690. },
  691. setRESTController: function (controller
  692. /*: RESTController*/
  693. ) {
  694. requireMethods('RESTController', ['request', 'ajax'], controller);
  695. config['RESTController'] = controller;
  696. },
  697. getRESTController: function ()
  698. /*: RESTController*/
  699. {
  700. return config['RESTController'];
  701. },
  702. setSchemaController: function (controller
  703. /*: SchemaController*/
  704. ) {
  705. requireMethods('SchemaController', ['get', 'create', 'update', 'delete', 'send', 'purge'], controller);
  706. config['SchemaController'] = controller;
  707. },
  708. getSchemaController: function ()
  709. /*: SchemaController*/
  710. {
  711. return config['SchemaController'];
  712. },
  713. setSessionController: function (controller
  714. /*: SessionController*/
  715. ) {
  716. requireMethods('SessionController', ['getSession'], controller);
  717. config['SessionController'] = controller;
  718. },
  719. getSessionController: function ()
  720. /*: SessionController*/
  721. {
  722. return config['SessionController'];
  723. },
  724. setStorageController: function (controller
  725. /*: StorageController*/
  726. ) {
  727. if (controller.async) {
  728. requireMethods('An async StorageController', ['getItemAsync', 'setItemAsync', 'removeItemAsync'], controller);
  729. } else {
  730. requireMethods('A synchronous StorageController', ['getItem', 'setItem', 'removeItem'], controller);
  731. }
  732. config['StorageController'] = controller;
  733. },
  734. setLocalDatastoreController: function (controller
  735. /*: LocalDatastoreController*/
  736. ) {
  737. requireMethods('LocalDatastoreController', ['pinWithName', 'fromPinWithName', 'unPinWithName', 'getAllContents', 'clear'], controller);
  738. config['LocalDatastoreController'] = controller;
  739. },
  740. getLocalDatastoreController: function ()
  741. /*: LocalDatastoreController*/
  742. {
  743. return config['LocalDatastoreController'];
  744. },
  745. setLocalDatastore: function (store
  746. /*: any*/
  747. ) {
  748. config['LocalDatastore'] = store;
  749. },
  750. getLocalDatastore: function () {
  751. return config['LocalDatastore'];
  752. },
  753. getStorageController: function ()
  754. /*: StorageController*/
  755. {
  756. return config['StorageController'];
  757. },
  758. setAsyncStorage: function (storage
  759. /*: any*/
  760. ) {
  761. config['AsyncStorage'] = storage;
  762. },
  763. getAsyncStorage: function () {
  764. return config['AsyncStorage'];
  765. },
  766. setWebSocketController: function (controller
  767. /*: WebSocketController*/
  768. ) {
  769. config['WebSocketController'] = controller;
  770. },
  771. getWebSocketController: function ()
  772. /*: WebSocketController*/
  773. {
  774. return config['WebSocketController'];
  775. },
  776. setUserController: function (controller
  777. /*: UserController*/
  778. ) {
  779. requireMethods('UserController', ['setCurrentUser', 'currentUser', 'currentUserAsync', 'signUp', 'logIn', 'become', 'logOut', 'me', 'requestPasswordReset', 'upgradeToRevocableSession', 'linkWith'], controller);
  780. config['UserController'] = controller;
  781. },
  782. getUserController: function ()
  783. /*: UserController*/
  784. {
  785. return config['UserController'];
  786. },
  787. setLiveQueryController: function (controller
  788. /*: any*/
  789. ) {
  790. requireMethods('LiveQueryController', ['setDefaultLiveQueryClient', 'getDefaultLiveQueryClient', '_clearCachedDefaultClient'], controller);
  791. config['LiveQueryController'] = controller;
  792. },
  793. getLiveQueryController: function ()
  794. /*: any*/
  795. {
  796. return config['LiveQueryController'];
  797. },
  798. setHooksController: function (controller
  799. /*: HooksController*/
  800. ) {
  801. requireMethods('HooksController', ['create', 'get', 'update', 'remove'], controller);
  802. config['HooksController'] = controller;
  803. },
  804. getHooksController: function ()
  805. /*: HooksController*/
  806. {
  807. return config['HooksController'];
  808. }
  809. };
  810. }).call(this,_dereq_('_process'))
  811. },{"_process":77}],5:[function(_dereq_,module,exports){
  812. "use strict";
  813. /**
  814. * Copyright (c) 2015-present, Parse, LLC.
  815. * All rights reserved.
  816. *
  817. * This source code is licensed under the BSD-style license found in the
  818. * LICENSE file in the root directory of this source tree. An additional grant
  819. * of patent rights can be found in the PATENTS file in the same directory.
  820. *
  821. * This is a simple wrapper to unify EventEmitter implementations across platforms.
  822. */
  823. module.exports = _dereq_('events').EventEmitter;
  824. var EventEmitter;
  825. },{"events":78}],6:[function(_dereq_,module,exports){
  826. "use strict";
  827. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  828. Object.defineProperty(exports, "__esModule", {
  829. value: true
  830. });
  831. exports.default = void 0;
  832. var _ParseUser = _interopRequireDefault(_dereq_("./ParseUser"));
  833. /**
  834. * Copyright (c) 2015-present, Parse, LLC.
  835. * All rights reserved.
  836. *
  837. * This source code is licensed under the BSD-style license found in the
  838. * LICENSE file in the root directory of this source tree. An additional grant
  839. * of patent rights can be found in the PATENTS file in the same directory.
  840. *
  841. * @flow-weak
  842. */
  843. /* global FB */
  844. var initialized = false;
  845. var requestedPermissions;
  846. var initOptions;
  847. var provider = {
  848. authenticate: function (options) {
  849. var _this = this;
  850. if (typeof FB === 'undefined') {
  851. options.error(this, 'Facebook SDK not found.');
  852. }
  853. FB.login(function (response) {
  854. if (response.authResponse) {
  855. if (options.success) {
  856. options.success(_this, {
  857. id: response.authResponse.userID,
  858. access_token: response.authResponse.accessToken,
  859. expiration_date: new Date(response.authResponse.expiresIn * 1000 + new Date().getTime()).toJSON()
  860. });
  861. }
  862. } else {
  863. if (options.error) {
  864. options.error(_this, response);
  865. }
  866. }
  867. }, {
  868. scope: requestedPermissions
  869. });
  870. },
  871. restoreAuthentication: function (authData) {
  872. if (authData) {
  873. var newOptions = {};
  874. if (initOptions) {
  875. for (var key in initOptions) {
  876. newOptions[key] = initOptions[key];
  877. }
  878. } // Suppress checks for login status from the browser.
  879. newOptions.status = false; // If the user doesn't match the one known by the FB SDK, log out.
  880. // Most of the time, the users will match -- it's only in cases where
  881. // the FB SDK knows of a different user than the one being restored
  882. // from a Parse User that logged in with username/password.
  883. var existingResponse = FB.getAuthResponse();
  884. if (existingResponse && existingResponse.userID !== authData.id) {
  885. FB.logout();
  886. }
  887. FB.init(newOptions);
  888. }
  889. return true;
  890. },
  891. getAuthType: function () {
  892. return 'facebook';
  893. },
  894. deauthenticate: function () {
  895. this.restoreAuthentication(null);
  896. }
  897. };
  898. /**
  899. * Provides a set of utilities for using Parse with Facebook.
  900. * @class Parse.FacebookUtils
  901. * @static
  902. * @hideconstructor
  903. */
  904. var FacebookUtils = {
  905. /**
  906. * Initializes Parse Facebook integration. Call this function after you
  907. * have loaded the Facebook Javascript SDK with the same parameters
  908. * as you would pass to<code>
  909. * <a href=
  910. * "https://developers.facebook.com/docs/reference/javascript/FB.init/">
  911. * FB.init()</a></code>. Parse.FacebookUtils will invoke FB.init() for you
  912. * with these arguments.
  913. *
  914. * @method init
  915. * @name Parse.FacebookUtils.init
  916. * @param {Object} options Facebook options argument as described here:
  917. * <a href=
  918. * "https://developers.facebook.com/docs/reference/javascript/FB.init/">
  919. * FB.init()</a>. The status flag will be coerced to 'false' because it
  920. * interferes with Parse Facebook integration. Call FB.getLoginStatus()
  921. * explicitly if this behavior is required by your application.
  922. */
  923. init: function (options) {
  924. if (typeof FB === 'undefined') {
  925. throw new Error('The Facebook JavaScript SDK must be loaded before calling init.');
  926. }
  927. initOptions = {};
  928. if (options) {
  929. for (var key in options) {
  930. initOptions[key] = options[key];
  931. }
  932. }
  933. if (initOptions.status && typeof console !== 'undefined') {
  934. var warn = console.warn || console.log || function () {}; // eslint-disable-line no-console
  935. warn.call(console, 'The "status" flag passed into' + ' FB.init, when set to true, can interfere with Parse Facebook' + ' integration, so it has been suppressed. Please call' + ' FB.getLoginStatus() explicitly if you require this behavior.');
  936. }
  937. initOptions.status = false;
  938. FB.init(initOptions);
  939. _ParseUser.default._registerAuthenticationProvider(provider);
  940. initialized = true;
  941. },
  942. /**
  943. * Gets whether the user has their account linked to Facebook.
  944. *
  945. * @method isLinked
  946. * @name Parse.FacebookUtils.isLinked
  947. * @param {Parse.User} user User to check for a facebook link.
  948. * The user must be logged in on this device.
  949. * @return {Boolean} <code>true</code> if the user has their account
  950. * linked to Facebook.
  951. */
  952. isLinked: function (user) {
  953. return user._isLinked('facebook');
  954. },
  955. /**
  956. * Logs in a user using Facebook. This method delegates to the Facebook
  957. * SDK to authenticate the user, and then automatically logs in (or
  958. * creates, in the case where it is a new user) a Parse.User.
  959. *
  960. * Standard API:
  961. *
  962. * <code>logIn(permission: string, authData: Object);</code>
  963. *
  964. * Advanced API: Used for handling your own oAuth tokens
  965. * {@link https://docs.parseplatform.org/rest/guide/#linking-users}
  966. *
  967. * <code>logIn(authData: Object, options?: Object);</code>
  968. *
  969. * @method logIn
  970. * @name Parse.FacebookUtils.logIn
  971. * @param {(String|Object)} permissions The permissions required for Facebook
  972. * log in. This is a comma-separated string of permissions.
  973. * Alternatively, supply a Facebook authData object as described in our
  974. * REST API docs if you want to handle getting facebook auth tokens
  975. * yourself.
  976. * @param {Object} options MasterKey / SessionToken. Alternatively can be used for authData if permissions is a string
  977. * @returns {Promise}
  978. */
  979. logIn: function (permissions, options) {
  980. if (!permissions || typeof permissions === 'string') {
  981. if (!initialized) {
  982. throw new Error('You must initialize FacebookUtils before calling logIn.');
  983. }
  984. requestedPermissions = permissions;
  985. return _ParseUser.default._logInWith('facebook', options);
  986. }
  987. return _ParseUser.default._logInWith('facebook', {
  988. authData: permissions
  989. }, options);
  990. },
  991. /**
  992. * Links Facebook to an existing PFUser. This method delegates to the
  993. * Facebook SDK to authenticate the user, and then automatically links
  994. * the account to the Parse.User.
  995. *
  996. * Standard API:
  997. *
  998. * <code>link(user: Parse.User, permission: string, authData?: Object);</code>
  999. *
  1000. * Advanced API: Used for handling your own oAuth tokens
  1001. * {@link https://docs.parseplatform.org/rest/guide/#linking-users}
  1002. *
  1003. * <code>link(user: Parse.User, authData: Object, options?: FullOptions);</code>
  1004. *
  1005. * @method link
  1006. * @name Parse.FacebookUtils.link
  1007. * @param {Parse.User} user User to link to Facebook. This must be the
  1008. * current user.
  1009. * @param {(String|Object)} permissions The permissions required for Facebook
  1010. * log in. This is a comma-separated string of permissions.
  1011. * Alternatively, supply a Facebook authData object as described in our
  1012. * REST API docs if you want to handle getting facebook auth tokens
  1013. * yourself.
  1014. * @param {Object} options MasterKey / SessionToken. Alternatively can be used for authData if permissions is a string
  1015. * @returns {Promise}
  1016. */
  1017. link: function (user, permissions, options) {
  1018. if (!permissions || typeof permissions === 'string') {
  1019. if (!initialized) {
  1020. throw new Error('You must initialize FacebookUtils before calling link.');
  1021. }
  1022. requestedPermissions = permissions;
  1023. return user._linkWith('facebook', options);
  1024. }
  1025. return user._linkWith('facebook', {
  1026. authData: permissions
  1027. }, options);
  1028. },
  1029. /**
  1030. * Unlinks the Parse.User from a Facebook account.
  1031. *
  1032. * @method unlink
  1033. * @name Parse.FacebookUtils.unlink
  1034. * @param {Parse.User} user User to unlink from Facebook. This must be the
  1035. * current user.
  1036. * @param {Object} options Standard options object with success and error
  1037. * callbacks.
  1038. * @returns {Promise}
  1039. */
  1040. unlink: function (user, options) {
  1041. if (!initialized) {
  1042. throw new Error('You must initialize FacebookUtils before calling unlink.');
  1043. }
  1044. return user._unlinkFrom('facebook', options);
  1045. },
  1046. // Used for testing purposes
  1047. _getAuthProvider: function () {
  1048. return provider;
  1049. }
  1050. };
  1051. var _default = FacebookUtils;
  1052. exports.default = _default;
  1053. },{"./ParseUser":31,"@babel/runtime/helpers/interopRequireDefault":61}],7:[function(_dereq_,module,exports){
  1054. "use strict";
  1055. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  1056. var _Storage = _interopRequireDefault(_dereq_("./Storage"));
  1057. /**
  1058. * Copyright (c) 2015-present, Parse, LLC.
  1059. * All rights reserved.
  1060. *
  1061. * This source code is licensed under the BSD-style license found in the
  1062. * LICENSE file in the root directory of this source tree. An additional grant
  1063. * of patent rights can be found in the PATENTS file in the same directory.
  1064. *
  1065. * @flow
  1066. */
  1067. var iidCache = null;
  1068. function hexOctet() {
  1069. return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  1070. }
  1071. function generateId() {
  1072. return hexOctet() + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + hexOctet() + hexOctet();
  1073. }
  1074. var InstallationController = {
  1075. currentInstallationId: function ()
  1076. /*: Promise<string>*/
  1077. {
  1078. if (typeof iidCache === 'string') {
  1079. return Promise.resolve(iidCache);
  1080. }
  1081. var path = _Storage.default.generatePath('installationId');
  1082. return _Storage.default.getItemAsync(path).then(function (iid) {
  1083. if (!iid) {
  1084. iid = generateId();
  1085. return _Storage.default.setItemAsync(path, iid).then(function () {
  1086. iidCache = iid;
  1087. return iid;
  1088. });
  1089. }
  1090. iidCache = iid;
  1091. return iid;
  1092. });
  1093. },
  1094. _clearCache: function () {
  1095. iidCache = null;
  1096. },
  1097. _setInstallationIdCache: function (iid
  1098. /*: string*/
  1099. ) {
  1100. iidCache = iid;
  1101. }
  1102. };
  1103. module.exports = InstallationController;
  1104. },{"./Storage":35,"@babel/runtime/helpers/interopRequireDefault":61}],8:[function(_dereq_,module,exports){
  1105. "use strict";
  1106. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  1107. Object.defineProperty(exports, "__esModule", {
  1108. value: true
  1109. });
  1110. exports.default = void 0;
  1111. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  1112. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  1113. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  1114. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  1115. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  1116. var _assertThisInitialized2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/assertThisInitialized"));
  1117. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  1118. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  1119. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  1120. var _EventEmitter2 = _interopRequireDefault(_dereq_("./EventEmitter"));
  1121. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  1122. var _LiveQuerySubscription = _interopRequireDefault(_dereq_("./LiveQuerySubscription"));
  1123. var _promiseUtils = _dereq_("./promiseUtils");
  1124. /**
  1125. * Copyright (c) 2015-present, Parse, LLC.
  1126. * All rights reserved.
  1127. *
  1128. * This source code is licensed under the BSD-style license found in the
  1129. * LICENSE file in the root directory of this source tree. An additional grant
  1130. * of patent rights can be found in the PATENTS file in the same directory.
  1131. *
  1132. */
  1133. /* global WebSocket */
  1134. // The LiveQuery client inner state
  1135. var CLIENT_STATE = {
  1136. INITIALIZED: 'initialized',
  1137. CONNECTING: 'connecting',
  1138. CONNECTED: 'connected',
  1139. CLOSED: 'closed',
  1140. RECONNECTING: 'reconnecting',
  1141. DISCONNECTED: 'disconnected'
  1142. }; // The event type the LiveQuery client should sent to server
  1143. var OP_TYPES = {
  1144. CONNECT: 'connect',
  1145. SUBSCRIBE: 'subscribe',
  1146. UNSUBSCRIBE: 'unsubscribe',
  1147. ERROR: 'error'
  1148. }; // The event we get back from LiveQuery server
  1149. var OP_EVENTS = {
  1150. CONNECTED: 'connected',
  1151. SUBSCRIBED: 'subscribed',
  1152. UNSUBSCRIBED: 'unsubscribed',
  1153. ERROR: 'error',
  1154. CREATE: 'create',
  1155. UPDATE: 'update',
  1156. ENTER: 'enter',
  1157. LEAVE: 'leave',
  1158. DELETE: 'delete'
  1159. }; // The event the LiveQuery client should emit
  1160. var CLIENT_EMMITER_TYPES = {
  1161. CLOSE: 'close',
  1162. ERROR: 'error',
  1163. OPEN: 'open'
  1164. }; // The event the LiveQuery subscription should emit
  1165. var SUBSCRIPTION_EMMITER_TYPES = {
  1166. OPEN: 'open',
  1167. CLOSE: 'close',
  1168. ERROR: 'error',
  1169. CREATE: 'create',
  1170. UPDATE: 'update',
  1171. ENTER: 'enter',
  1172. LEAVE: 'leave',
  1173. DELETE: 'delete'
  1174. };
  1175. var generateInterval = function (k) {
  1176. return Math.random() * Math.min(30, Math.pow(2, k) - 1) * 1000;
  1177. };
  1178. /**
  1179. * Creates a new LiveQueryClient.
  1180. * Extends events.EventEmitter
  1181. * <a href="https://nodejs.org/api/events.html#events_class_eventemitter">cloud functions</a>.
  1182. *
  1183. * A wrapper of a standard WebSocket client. We add several useful methods to
  1184. * help you connect/disconnect to LiveQueryServer, subscribe/unsubscribe a ParseQuery easily.
  1185. *
  1186. * javascriptKey and masterKey are used for verifying the LiveQueryClient when it tries
  1187. * to connect to the LiveQuery server
  1188. *
  1189. * We expose three events to help you monitor the status of the LiveQueryClient.
  1190. *
  1191. * <pre>
  1192. * let Parse = require('parse/node');
  1193. * let LiveQueryClient = Parse.LiveQueryClient;
  1194. * let client = new LiveQueryClient({
  1195. * applicationId: '',
  1196. * serverURL: '',
  1197. * javascriptKey: '',
  1198. * masterKey: ''
  1199. * });
  1200. * </pre>
  1201. *
  1202. * Open - When we establish the WebSocket connection to the LiveQuery server, you'll get this event.
  1203. * <pre>
  1204. * client.on('open', () => {
  1205. *
  1206. * });</pre>
  1207. *
  1208. * Close - When we lose the WebSocket connection to the LiveQuery server, you'll get this event.
  1209. * <pre>
  1210. * client.on('close', () => {
  1211. *
  1212. * });</pre>
  1213. *
  1214. * Error - When some network error or LiveQuery server error happens, you'll get this event.
  1215. * <pre>
  1216. * client.on('error', (error) => {
  1217. *
  1218. * });</pre>
  1219. * @alias Parse.LiveQueryClient
  1220. */
  1221. var LiveQueryClient =
  1222. /*#__PURE__*/
  1223. function (_EventEmitter) {
  1224. (0, _inherits2.default)(LiveQueryClient, _EventEmitter);
  1225. /**
  1226. * @param {Object} options
  1227. * @param {string} options.applicationId - applicationId of your Parse app
  1228. * @param {string} options.serverURL - <b>the URL of your LiveQuery server</b>
  1229. * @param {string} options.javascriptKey (optional)
  1230. * @param {string} options.masterKey (optional) Your Parse Master Key. (Node.js only!)
  1231. * @param {string} options.sessionToken (optional)
  1232. */
  1233. function LiveQueryClient(_ref) {
  1234. var _this;
  1235. var applicationId = _ref.applicationId,
  1236. serverURL = _ref.serverURL,
  1237. javascriptKey = _ref.javascriptKey,
  1238. masterKey = _ref.masterKey,
  1239. sessionToken = _ref.sessionToken;
  1240. (0, _classCallCheck2.default)(this, LiveQueryClient);
  1241. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(LiveQueryClient).call(this));
  1242. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "attempts", void 0);
  1243. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "id", void 0);
  1244. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "requestId", void 0);
  1245. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "applicationId", void 0);
  1246. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "serverURL", void 0);
  1247. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "javascriptKey", void 0);
  1248. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "masterKey", void 0);
  1249. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "sessionToken", void 0);
  1250. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "connectPromise", void 0);
  1251. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "subscriptions", void 0);
  1252. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "socket", void 0);
  1253. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "state", void 0);
  1254. if (!serverURL || serverURL.indexOf('ws') !== 0) {
  1255. throw new Error('You need to set a proper Parse LiveQuery server url before using LiveQueryClient');
  1256. }
  1257. _this.reconnectHandle = null;
  1258. _this.attempts = 1;
  1259. _this.id = 0;
  1260. _this.requestId = 1;
  1261. _this.serverURL = serverURL;
  1262. _this.applicationId = applicationId;
  1263. _this.javascriptKey = javascriptKey;
  1264. _this.masterKey = masterKey;
  1265. _this.sessionToken = sessionToken;
  1266. _this.connectPromise = (0, _promiseUtils.resolvingPromise)();
  1267. _this.subscriptions = new Map();
  1268. _this.state = CLIENT_STATE.INITIALIZED;
  1269. return _this;
  1270. }
  1271. (0, _createClass2.default)(LiveQueryClient, [{
  1272. key: "shouldOpen",
  1273. value: function ()
  1274. /*: any*/
  1275. {
  1276. return this.state === CLIENT_STATE.INITIALIZED || this.state === CLIENT_STATE.DISCONNECTED;
  1277. }
  1278. /**
  1279. * Subscribes to a ParseQuery
  1280. *
  1281. * If you provide the sessionToken, when the LiveQuery server gets ParseObject's
  1282. * updates from parse server, it'll try to check whether the sessionToken fulfills
  1283. * the ParseObject's ACL. The LiveQuery server will only send updates to clients whose
  1284. * sessionToken is fit for the ParseObject's ACL. You can check the LiveQuery protocol
  1285. * <a href="https://github.com/parse-community/parse-server/wiki/Parse-LiveQuery-Protocol-Specification">here</a> for more details. The subscription you get is the same subscription you get
  1286. * from our Standard API.
  1287. *
  1288. * @param {Object} query - the ParseQuery you want to subscribe to
  1289. * @param {string} sessionToken (optional)
  1290. * @return {Object} subscription
  1291. */
  1292. }, {
  1293. key: "subscribe",
  1294. value: function (query
  1295. /*: Object*/
  1296. , sessionToken
  1297. /*: ?string*/
  1298. )
  1299. /*: Object*/
  1300. {
  1301. var _this2 = this;
  1302. if (!query) {
  1303. return;
  1304. }
  1305. var className = query.className;
  1306. var queryJSON = query.toJSON();
  1307. var where = queryJSON.where;
  1308. var fields = queryJSON.keys ? queryJSON.keys.split(',') : undefined;
  1309. var subscribeRequest = {
  1310. op: OP_TYPES.SUBSCRIBE,
  1311. requestId: this.requestId,
  1312. query: {
  1313. className: className,
  1314. where: where,
  1315. fields: fields
  1316. }
  1317. };
  1318. if (sessionToken) {
  1319. subscribeRequest.sessionToken = sessionToken;
  1320. }
  1321. var subscription = new _LiveQuerySubscription.default(this.requestId, query, sessionToken);
  1322. this.subscriptions.set(this.requestId, subscription);
  1323. this.requestId += 1;
  1324. this.connectPromise.then(function () {
  1325. _this2.socket.send(JSON.stringify(subscribeRequest));
  1326. });
  1327. return subscription;
  1328. }
  1329. /**
  1330. * After calling unsubscribe you'll stop receiving events from the subscription object.
  1331. *
  1332. * @param {Object} subscription - subscription you would like to unsubscribe from.
  1333. */
  1334. }, {
  1335. key: "unsubscribe",
  1336. value: function (subscription
  1337. /*: Object*/
  1338. ) {
  1339. var _this3 = this;
  1340. if (!subscription) {
  1341. return;
  1342. }
  1343. this.subscriptions.delete(subscription.id);
  1344. var unsubscribeRequest = {
  1345. op: OP_TYPES.UNSUBSCRIBE,
  1346. requestId: subscription.id
  1347. };
  1348. this.connectPromise.then(function () {
  1349. _this3.socket.send(JSON.stringify(unsubscribeRequest));
  1350. });
  1351. }
  1352. /**
  1353. * After open is called, the LiveQueryClient will try to send a connect request
  1354. * to the LiveQuery server.
  1355. *
  1356. */
  1357. }, {
  1358. key: "open",
  1359. value: function () {
  1360. var _this4 = this;
  1361. var WebSocketImplementation = _CoreManager.default.getWebSocketController();
  1362. if (!WebSocketImplementation) {
  1363. this.emit(CLIENT_EMMITER_TYPES.ERROR, 'Can not find WebSocket implementation');
  1364. return;
  1365. }
  1366. if (this.state !== CLIENT_STATE.RECONNECTING) {
  1367. this.state = CLIENT_STATE.CONNECTING;
  1368. }
  1369. this.socket = new WebSocketImplementation(this.serverURL); // Bind WebSocket callbacks
  1370. this.socket.onopen = function () {
  1371. _this4._handleWebSocketOpen();
  1372. };
  1373. this.socket.onmessage = function (event) {
  1374. _this4._handleWebSocketMessage(event);
  1375. };
  1376. this.socket.onclose = function () {
  1377. _this4._handleWebSocketClose();
  1378. };
  1379. this.socket.onerror = function (error) {
  1380. _this4._handleWebSocketError(error);
  1381. };
  1382. }
  1383. }, {
  1384. key: "resubscribe",
  1385. value: function () {
  1386. var _this5 = this;
  1387. this.subscriptions.forEach(function (subscription, requestId) {
  1388. var query = subscription.query;
  1389. var queryJSON = query.toJSON();
  1390. var where = queryJSON.where;
  1391. var fields = queryJSON.keys ? queryJSON.keys.split(',') : undefined;
  1392. var className = query.className;
  1393. var sessionToken = subscription.sessionToken;
  1394. var subscribeRequest = {
  1395. op: OP_TYPES.SUBSCRIBE,
  1396. requestId: requestId,
  1397. query: {
  1398. className: className,
  1399. where: where,
  1400. fields: fields
  1401. }
  1402. };
  1403. if (sessionToken) {
  1404. subscribeRequest.sessionToken = sessionToken;
  1405. }
  1406. _this5.connectPromise.then(function () {
  1407. _this5.socket.send(JSON.stringify(subscribeRequest));
  1408. });
  1409. });
  1410. }
  1411. /**
  1412. * This method will close the WebSocket connection to this LiveQueryClient,
  1413. * cancel the auto reconnect and unsubscribe all subscriptions based on it.
  1414. *
  1415. */
  1416. }, {
  1417. key: "close",
  1418. value: function () {
  1419. if (this.state === CLIENT_STATE.INITIALIZED || this.state === CLIENT_STATE.DISCONNECTED) {
  1420. return;
  1421. }
  1422. this.state = CLIENT_STATE.DISCONNECTED;
  1423. this.socket.close(); // Notify each subscription about the close
  1424. var _iteratorNormalCompletion = true;
  1425. var _didIteratorError = false;
  1426. var _iteratorError = undefined;
  1427. try {
  1428. for (var _iterator = this.subscriptions.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  1429. var subscription = _step.value;
  1430. subscription.emit(SUBSCRIPTION_EMMITER_TYPES.CLOSE);
  1431. }
  1432. } catch (err) {
  1433. _didIteratorError = true;
  1434. _iteratorError = err;
  1435. } finally {
  1436. try {
  1437. if (!_iteratorNormalCompletion && _iterator.return != null) {
  1438. _iterator.return();
  1439. }
  1440. } finally {
  1441. if (_didIteratorError) {
  1442. throw _iteratorError;
  1443. }
  1444. }
  1445. }
  1446. this._handleReset();
  1447. this.emit(CLIENT_EMMITER_TYPES.CLOSE);
  1448. } // ensure we start with valid state if connect is called again after close
  1449. }, {
  1450. key: "_handleReset",
  1451. value: function () {
  1452. this.attempts = 1;
  1453. this.id = 0;
  1454. this.requestId = 1;
  1455. this.connectPromise = (0, _promiseUtils.resolvingPromise)();
  1456. this.subscriptions = new Map();
  1457. }
  1458. }, {
  1459. key: "_handleWebSocketOpen",
  1460. value: function () {
  1461. this.attempts = 1;
  1462. var connectRequest = {
  1463. op: OP_TYPES.CONNECT,
  1464. applicationId: this.applicationId,
  1465. javascriptKey: this.javascriptKey,
  1466. masterKey: this.masterKey,
  1467. sessionToken: this.sessionToken
  1468. };
  1469. this.socket.send(JSON.stringify(connectRequest));
  1470. }
  1471. }, {
  1472. key: "_handleWebSocketMessage",
  1473. value: function (event
  1474. /*: any*/
  1475. ) {
  1476. var data = event.data;
  1477. if (typeof data === 'string') {
  1478. data = JSON.parse(data);
  1479. }
  1480. var subscription = null;
  1481. if (data.requestId) {
  1482. subscription = this.subscriptions.get(data.requestId);
  1483. }
  1484. switch (data.op) {
  1485. case OP_EVENTS.CONNECTED:
  1486. if (this.state === CLIENT_STATE.RECONNECTING) {
  1487. this.resubscribe();
  1488. }
  1489. this.emit(CLIENT_EMMITER_TYPES.OPEN);
  1490. this.id = data.clientId;
  1491. this.connectPromise.resolve();
  1492. this.state = CLIENT_STATE.CONNECTED;
  1493. break;
  1494. case OP_EVENTS.SUBSCRIBED:
  1495. if (subscription) {
  1496. subscription.emit(SUBSCRIPTION_EMMITER_TYPES.OPEN);
  1497. }
  1498. break;
  1499. case OP_EVENTS.ERROR:
  1500. if (data.requestId) {
  1501. if (subscription) {
  1502. subscription.emit(SUBSCRIPTION_EMMITER_TYPES.ERROR, data.error);
  1503. }
  1504. } else {
  1505. this.emit(CLIENT_EMMITER_TYPES.ERROR, data.error);
  1506. }
  1507. break;
  1508. case OP_EVENTS.UNSUBSCRIBED:
  1509. // We have already deleted subscription in unsubscribe(), do nothing here
  1510. break;
  1511. default:
  1512. {
  1513. // create, update, enter, leave, delete cases
  1514. if (!subscription) {
  1515. break;
  1516. }
  1517. var override = false;
  1518. if (data.original) {
  1519. override = true;
  1520. delete data.original.__type; // Check for removed fields
  1521. for (var field in data.original) {
  1522. if (!(field in data.object)) {
  1523. data.object[field] = undefined;
  1524. }
  1525. }
  1526. data.original = _ParseObject.default.fromJSON(data.original, false);
  1527. }
  1528. delete data.object.__type;
  1529. var parseObject = _ParseObject.default.fromJSON(data.object, override);
  1530. subscription.emit(data.op, parseObject, data.original);
  1531. var localDatastore = _CoreManager.default.getLocalDatastore();
  1532. if (override && localDatastore.isEnabled) {
  1533. localDatastore._updateObjectIfPinned(parseObject).then(function () {});
  1534. }
  1535. }
  1536. }
  1537. }
  1538. }, {
  1539. key: "_handleWebSocketClose",
  1540. value: function () {
  1541. if (this.state === CLIENT_STATE.DISCONNECTED) {
  1542. return;
  1543. }
  1544. this.state = CLIENT_STATE.CLOSED;
  1545. this.emit(CLIENT_EMMITER_TYPES.CLOSE); // Notify each subscription about the close
  1546. var _iteratorNormalCompletion2 = true;
  1547. var _didIteratorError2 = false;
  1548. var _iteratorError2 = undefined;
  1549. try {
  1550. for (var _iterator2 = this.subscriptions.values()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  1551. var subscription = _step2.value;
  1552. subscription.emit(SUBSCRIPTION_EMMITER_TYPES.CLOSE);
  1553. }
  1554. } catch (err) {
  1555. _didIteratorError2 = true;
  1556. _iteratorError2 = err;
  1557. } finally {
  1558. try {
  1559. if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
  1560. _iterator2.return();
  1561. }
  1562. } finally {
  1563. if (_didIteratorError2) {
  1564. throw _iteratorError2;
  1565. }
  1566. }
  1567. }
  1568. this._handleReconnect();
  1569. }
  1570. }, {
  1571. key: "_handleWebSocketError",
  1572. value: function (error
  1573. /*: any*/
  1574. ) {
  1575. this.emit(CLIENT_EMMITER_TYPES.ERROR, error);
  1576. var _iteratorNormalCompletion3 = true;
  1577. var _didIteratorError3 = false;
  1578. var _iteratorError3 = undefined;
  1579. try {
  1580. for (var _iterator3 = this.subscriptions.values()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
  1581. var subscription = _step3.value;
  1582. subscription.emit(SUBSCRIPTION_EMMITER_TYPES.ERROR);
  1583. }
  1584. } catch (err) {
  1585. _didIteratorError3 = true;
  1586. _iteratorError3 = err;
  1587. } finally {
  1588. try {
  1589. if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
  1590. _iterator3.return();
  1591. }
  1592. } finally {
  1593. if (_didIteratorError3) {
  1594. throw _iteratorError3;
  1595. }
  1596. }
  1597. }
  1598. this._handleReconnect();
  1599. }
  1600. }, {
  1601. key: "_handleReconnect",
  1602. value: function () {
  1603. var _this6 = this; // if closed or currently reconnecting we stop attempting to reconnect
  1604. if (this.state === CLIENT_STATE.DISCONNECTED) {
  1605. return;
  1606. }
  1607. this.state = CLIENT_STATE.RECONNECTING;
  1608. var time = generateInterval(this.attempts); // handle case when both close/error occur at frequent rates we ensure we do not reconnect unnecessarily.
  1609. // we're unable to distinguish different between close/error when we're unable to reconnect therefore
  1610. // we try to reonnect in both cases
  1611. // server side ws and browser WebSocket behave differently in when close/error get triggered
  1612. if (this.reconnectHandle) {
  1613. clearTimeout(this.reconnectHandle);
  1614. }
  1615. this.reconnectHandle = setTimeout(function () {
  1616. _this6.attempts++;
  1617. _this6.connectPromise = (0, _promiseUtils.resolvingPromise)();
  1618. _this6.open();
  1619. }.bind(this), time);
  1620. }
  1621. }]);
  1622. return LiveQueryClient;
  1623. }(_EventEmitter2.default);
  1624. _CoreManager.default.setWebSocketController(typeof WebSocket === 'function' || (typeof WebSocket === "undefined" ? "undefined" : (0, _typeof2.default)(WebSocket)) === 'object' ? WebSocket : null);
  1625. var _default = LiveQueryClient;
  1626. exports.default = _default;
  1627. },{"./CoreManager":4,"./EventEmitter":5,"./LiveQuerySubscription":9,"./ParseObject":23,"./promiseUtils":47,"@babel/runtime/helpers/assertThisInitialized":52,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/getPrototypeOf":59,"@babel/runtime/helpers/inherits":60,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/possibleConstructorReturn":68,"@babel/runtime/helpers/typeof":73}],9:[function(_dereq_,module,exports){
  1628. "use strict";
  1629. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  1630. Object.defineProperty(exports, "__esModule", {
  1631. value: true
  1632. });
  1633. exports.default = void 0;
  1634. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  1635. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  1636. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  1637. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  1638. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  1639. var _EventEmitter2 = _interopRequireDefault(_dereq_("./EventEmitter"));
  1640. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  1641. /*
  1642. * Copyright (c) 2015-present, Parse, LLC.
  1643. * All rights reserved.
  1644. *
  1645. * This source code is licensed under the BSD-style license found in the
  1646. * LICENSE file in the root directory of this source tree. An additional grant
  1647. * of patent rights can be found in the PATENTS file in the same directory.
  1648. *
  1649. */
  1650. /**
  1651. * Creates a new LiveQuery Subscription.
  1652. * Extends events.EventEmitter
  1653. * <a href="https://nodejs.org/api/events.html#events_class_eventemitter">cloud functions</a>.
  1654. *
  1655. *
  1656. * <p>Open Event - When you call query.subscribe(), we send a subscribe request to
  1657. * the LiveQuery server, when we get the confirmation from the LiveQuery server,
  1658. * this event will be emitted. When the client loses WebSocket connection to the
  1659. * LiveQuery server, we will try to auto reconnect the LiveQuery server. If we
  1660. * reconnect the LiveQuery server and successfully resubscribe the ParseQuery,
  1661. * you'll also get this event.
  1662. *
  1663. * <pre>
  1664. * subscription.on('open', () => {
  1665. *
  1666. * });</pre></p>
  1667. *
  1668. * <p>Create Event - When a new ParseObject is created and it fulfills the ParseQuery you subscribe,
  1669. * you'll get this event. The object is the ParseObject which is created.
  1670. *
  1671. * <pre>
  1672. * subscription.on('create', (object) => {
  1673. *
  1674. * });</pre></p>
  1675. *
  1676. * <p>Update Event - When an existing ParseObject (original) which fulfills the ParseQuery you subscribe
  1677. * is updated (The ParseObject fulfills the ParseQuery before and after changes),
  1678. * you'll get this event. The object is the ParseObject which is updated.
  1679. * Its content is the latest value of the ParseObject.
  1680. *
  1681. * Parse-Server 3.1.3+ Required for original object parameter
  1682. *
  1683. * <pre>
  1684. * subscription.on('update', (object, original) => {
  1685. *
  1686. * });</pre></p>
  1687. *
  1688. * <p>Enter Event - When an existing ParseObject's (original) old value doesn't fulfill the ParseQuery
  1689. * but its new value fulfills the ParseQuery, you'll get this event. The object is the
  1690. * ParseObject which enters the ParseQuery. Its content is the latest value of the ParseObject.
  1691. *
  1692. * Parse-Server 3.1.3+ Required for original object parameter
  1693. *
  1694. * <pre>
  1695. * subscription.on('enter', (object, original) => {
  1696. *
  1697. * });</pre></p>
  1698. *
  1699. *
  1700. * <p>Update Event - When an existing ParseObject's old value fulfills the ParseQuery but its new value
  1701. * doesn't fulfill the ParseQuery, you'll get this event. The object is the ParseObject
  1702. * which leaves the ParseQuery. Its content is the latest value of the ParseObject.
  1703. *
  1704. * <pre>
  1705. * subscription.on('leave', (object) => {
  1706. *
  1707. * });</pre></p>
  1708. *
  1709. *
  1710. * <p>Delete Event - When an existing ParseObject which fulfills the ParseQuery is deleted, you'll
  1711. * get this event. The object is the ParseObject which is deleted.
  1712. *
  1713. * <pre>
  1714. * subscription.on('delete', (object) => {
  1715. *
  1716. * });</pre></p>
  1717. *
  1718. *
  1719. * <p>Close Event - When the client loses the WebSocket connection to the LiveQuery
  1720. * server and we stop receiving events, you'll get this event.
  1721. *
  1722. * <pre>
  1723. * subscription.on('close', () => {
  1724. *
  1725. * });</pre></p>
  1726. *
  1727. * @alias Parse.LiveQuerySubscription
  1728. */
  1729. var Subscription =
  1730. /*#__PURE__*/
  1731. function (_EventEmitter) {
  1732. (0, _inherits2.default)(Subscription, _EventEmitter);
  1733. /*
  1734. * @param {string} id - subscription id
  1735. * @param {string} query - query to subscribe to
  1736. * @param {string} sessionToken - optional session token
  1737. */
  1738. function Subscription(id, query, sessionToken) {
  1739. var _this;
  1740. (0, _classCallCheck2.default)(this, Subscription);
  1741. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(Subscription).call(this));
  1742. _this.id = id;
  1743. _this.query = query;
  1744. _this.sessionToken = sessionToken; // adding listener so process does not crash
  1745. // best practice is for developer to register their own listener
  1746. _this.on('error', function () {});
  1747. return _this;
  1748. }
  1749. /**
  1750. * Close the subscription
  1751. */
  1752. (0, _createClass2.default)(Subscription, [{
  1753. key: "unsubscribe",
  1754. value: function ()
  1755. /*: Promise*/
  1756. {
  1757. var _this2 = this;
  1758. return _CoreManager.default.getLiveQueryController().getDefaultLiveQueryClient().then(function (liveQueryClient) {
  1759. liveQueryClient.unsubscribe(_this2);
  1760. _this2.emit('close');
  1761. });
  1762. }
  1763. }]);
  1764. return Subscription;
  1765. }(_EventEmitter2.default);
  1766. var _default = Subscription;
  1767. exports.default = _default;
  1768. },{"./CoreManager":4,"./EventEmitter":5,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/getPrototypeOf":59,"@babel/runtime/helpers/inherits":60,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/possibleConstructorReturn":68}],10:[function(_dereq_,module,exports){
  1769. "use strict";
  1770. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  1771. var _regenerator = _interopRequireDefault(_dereq_("@babel/runtime/regenerator"));
  1772. var _toConsumableArray2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/toConsumableArray"));
  1773. var _slicedToArray2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/slicedToArray"));
  1774. var _asyncToGenerator2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/asyncToGenerator"));
  1775. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  1776. var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
  1777. var _LocalDatastoreUtils = _dereq_("./LocalDatastoreUtils");
  1778. /**
  1779. * Copyright (c) 2015-present, Parse, LLC.
  1780. * All rights reserved.
  1781. *
  1782. * This source code is licensed under the BSD-style license found in the
  1783. * LICENSE file in the root directory of this source tree. An additional grant
  1784. * of patent rights can be found in the PATENTS file in the same directory.
  1785. *
  1786. * @flow
  1787. */
  1788. /**
  1789. * Provides a local datastore which can be used to store and retrieve <code>Parse.Object</code>. <br />
  1790. * To enable this functionality, call <code>Parse.enableLocalDatastore()</code>.
  1791. *
  1792. * Pin object to add to local datastore
  1793. *
  1794. * <pre>await object.pin();</pre>
  1795. * <pre>await object.pinWithName('pinName');</pre>
  1796. *
  1797. * Query pinned objects
  1798. *
  1799. * <pre>query.fromLocalDatastore();</pre>
  1800. * <pre>query.fromPin();</pre>
  1801. * <pre>query.fromPinWithName();</pre>
  1802. *
  1803. * <pre>const localObjects = await query.find();</pre>
  1804. *
  1805. * @class Parse.LocalDatastore
  1806. * @static
  1807. */
  1808. var LocalDatastore = {
  1809. isEnabled: false,
  1810. isSyncing: false,
  1811. fromPinWithName: function (name
  1812. /*: string*/
  1813. )
  1814. /*: Promise<Array<Object>>*/
  1815. {
  1816. var controller = _CoreManager.default.getLocalDatastoreController();
  1817. return controller.fromPinWithName(name);
  1818. },
  1819. pinWithName: function (name
  1820. /*: string*/
  1821. , value
  1822. /*: any*/
  1823. )
  1824. /*: Promise<void>*/
  1825. {
  1826. var controller = _CoreManager.default.getLocalDatastoreController();
  1827. return controller.pinWithName(name, value);
  1828. },
  1829. unPinWithName: function (name
  1830. /*: string*/
  1831. )
  1832. /*: Promise<void>*/
  1833. {
  1834. var controller = _CoreManager.default.getLocalDatastoreController();
  1835. return controller.unPinWithName(name);
  1836. },
  1837. _getAllContents: function ()
  1838. /*: Promise<Object>*/
  1839. {
  1840. var controller = _CoreManager.default.getLocalDatastoreController();
  1841. return controller.getAllContents();
  1842. },
  1843. // Use for testing
  1844. _getRawStorage: function ()
  1845. /*: Promise<Object>*/
  1846. {
  1847. var controller = _CoreManager.default.getLocalDatastoreController();
  1848. return controller.getRawStorage();
  1849. },
  1850. _clear: function ()
  1851. /*: Promise<void>*/
  1852. {
  1853. var controller = _CoreManager.default.getLocalDatastoreController();
  1854. return controller.clear();
  1855. },
  1856. // Pin the object and children recursively
  1857. // Saves the object and children key to Pin Name
  1858. _handlePinAllWithName: function () {
  1859. var _handlePinAllWithName2 = (0, _asyncToGenerator2.default)(
  1860. /*#__PURE__*/
  1861. _regenerator.default.mark(function _callee(name
  1862. /*: string*/
  1863. , objects
  1864. /*: Array<ParseObject>*/
  1865. ) {
  1866. var pinName, toPinPromises, objectKeys, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, parent, children, parentKey, json, objectKey, fromPinPromise, _ref, _ref2, pinned, toPin;
  1867. return _regenerator.default.wrap(function (_context) {
  1868. while (1) {
  1869. switch (_context.prev = _context.next) {
  1870. case 0:
  1871. pinName = this.getPinName(name);
  1872. toPinPromises = [];
  1873. objectKeys = [];
  1874. _iteratorNormalCompletion = true;
  1875. _didIteratorError = false;
  1876. _iteratorError = undefined;
  1877. _context.prev = 6;
  1878. for (_iterator = objects[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  1879. parent = _step.value;
  1880. children = this._getChildren(parent);
  1881. parentKey = this.getKeyForObject(parent);
  1882. json = parent._toFullJSON();
  1883. if (parent._localId) {
  1884. json._localId = parent._localId;
  1885. }
  1886. children[parentKey] = json;
  1887. for (objectKey in children) {
  1888. objectKeys.push(objectKey);
  1889. toPinPromises.push(this.pinWithName(objectKey, [children[objectKey]]));
  1890. }
  1891. }
  1892. _context.next = 14;
  1893. break;
  1894. case 10:
  1895. _context.prev = 10;
  1896. _context.t0 = _context["catch"](6);
  1897. _didIteratorError = true;
  1898. _iteratorError = _context.t0;
  1899. case 14:
  1900. _context.prev = 14;
  1901. _context.prev = 15;
  1902. if (!_iteratorNormalCompletion && _iterator.return != null) {
  1903. _iterator.return();
  1904. }
  1905. case 17:
  1906. _context.prev = 17;
  1907. if (!_didIteratorError) {
  1908. _context.next = 20;
  1909. break;
  1910. }
  1911. throw _iteratorError;
  1912. case 20:
  1913. return _context.finish(17);
  1914. case 21:
  1915. return _context.finish(14);
  1916. case 22:
  1917. fromPinPromise = this.fromPinWithName(pinName);
  1918. _context.next = 25;
  1919. return Promise.all([fromPinPromise, toPinPromises]);
  1920. case 25:
  1921. _ref = _context.sent;
  1922. _ref2 = (0, _slicedToArray2.default)(_ref, 1);
  1923. pinned = _ref2[0];
  1924. toPin = (0, _toConsumableArray2.default)(new Set([].concat((0, _toConsumableArray2.default)(pinned || []), objectKeys)));
  1925. return _context.abrupt("return", this.pinWithName(pinName, toPin));
  1926. case 30:
  1927. case "end":
  1928. return _context.stop();
  1929. }
  1930. }
  1931. }, _callee, this, [[6, 10, 14, 22], [15,, 17, 21]]);
  1932. }));
  1933. return function () {
  1934. return _handlePinAllWithName2.apply(this, arguments);
  1935. };
  1936. }(),
  1937. // Removes object and children keys from pin name
  1938. // Keeps the object and children pinned
  1939. _handleUnPinAllWithName: function () {
  1940. var _handleUnPinAllWithName2 = (0, _asyncToGenerator2.default)(
  1941. /*#__PURE__*/
  1942. _regenerator.default.mark(function _callee2(name
  1943. /*: string*/
  1944. , objects
  1945. /*: Array<ParseObject>*/
  1946. ) {
  1947. var localDatastore, pinName, promises, objectKeys, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, _objectKeys, parent, children, parentKey, pinned, _iteratorNormalCompletion3, _didIteratorError3, _iteratorError3, _iterator3, _step3, objectKey, hasReference, key, pinnedObjects;
  1948. return _regenerator.default.wrap(function (_context2) {
  1949. while (1) {
  1950. switch (_context2.prev = _context2.next) {
  1951. case 0:
  1952. _context2.next = 2;
  1953. return this._getAllContents();
  1954. case 2:
  1955. localDatastore = _context2.sent;
  1956. pinName = this.getPinName(name);
  1957. promises = [];
  1958. objectKeys = [];
  1959. _iteratorNormalCompletion2 = true;
  1960. _didIteratorError2 = false;
  1961. _iteratorError2 = undefined;
  1962. _context2.prev = 9;
  1963. for (_iterator2 = objects[Symbol.iterator](); !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  1964. parent = _step2.value;
  1965. children = this._getChildren(parent);
  1966. parentKey = this.getKeyForObject(parent);
  1967. (_objectKeys = objectKeys).push.apply(_objectKeys, [parentKey].concat((0, _toConsumableArray2.default)(Object.keys(children))));
  1968. }
  1969. _context2.next = 17;
  1970. break;
  1971. case 13:
  1972. _context2.prev = 13;
  1973. _context2.t0 = _context2["catch"](9);
  1974. _didIteratorError2 = true;
  1975. _iteratorError2 = _context2.t0;
  1976. case 17:
  1977. _context2.prev = 17;
  1978. _context2.prev = 18;
  1979. if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
  1980. _iterator2.return();
  1981. }
  1982. case 20:
  1983. _context2.prev = 20;
  1984. if (!_didIteratorError2) {
  1985. _context2.next = 23;
  1986. break;
  1987. }
  1988. throw _iteratorError2;
  1989. case 23:
  1990. return _context2.finish(20);
  1991. case 24:
  1992. return _context2.finish(17);
  1993. case 25:
  1994. objectKeys = (0, _toConsumableArray2.default)(new Set(objectKeys));
  1995. pinned = localDatastore[pinName] || [];
  1996. pinned = pinned.filter(function (item) {
  1997. return !objectKeys.includes(item);
  1998. });
  1999. if (pinned.length == 0) {
  2000. promises.push(this.unPinWithName(pinName));
  2001. delete localDatastore[pinName];
  2002. } else {
  2003. promises.push(this.pinWithName(pinName, pinned));
  2004. localDatastore[pinName] = pinned;
  2005. }
  2006. _iteratorNormalCompletion3 = true;
  2007. _didIteratorError3 = false;
  2008. _iteratorError3 = undefined;
  2009. _context2.prev = 32;
  2010. _iterator3 = objectKeys[Symbol.iterator]();
  2011. case 34:
  2012. if (_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done) {
  2013. _context2.next = 51;
  2014. break;
  2015. }
  2016. objectKey = _step3.value;
  2017. hasReference = false;
  2018. _context2.t1 = _regenerator.default.keys(localDatastore);
  2019. case 38:
  2020. if ((_context2.t2 = _context2.t1()).done) {
  2021. _context2.next = 47;
  2022. break;
  2023. }
  2024. key = _context2.t2.value;
  2025. if (!(key === _LocalDatastoreUtils.DEFAULT_PIN || key.startsWith(_LocalDatastoreUtils.PIN_PREFIX))) {
  2026. _context2.next = 45;
  2027. break;
  2028. }
  2029. pinnedObjects = localDatastore[key] || [];
  2030. if (!pinnedObjects.includes(objectKey)) {
  2031. _context2.next = 45;
  2032. break;
  2033. }
  2034. hasReference = true;
  2035. return _context2.abrupt("break", 47);
  2036. case 45:
  2037. _context2.next = 38;
  2038. break;
  2039. case 47:
  2040. if (!hasReference) {
  2041. promises.push(this.unPinWithName(objectKey));
  2042. }
  2043. case 48:
  2044. _iteratorNormalCompletion3 = true;
  2045. _context2.next = 34;
  2046. break;
  2047. case 51:
  2048. _context2.next = 57;
  2049. break;
  2050. case 53:
  2051. _context2.prev = 53;
  2052. _context2.t3 = _context2["catch"](32);
  2053. _didIteratorError3 = true;
  2054. _iteratorError3 = _context2.t3;
  2055. case 57:
  2056. _context2.prev = 57;
  2057. _context2.prev = 58;
  2058. if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
  2059. _iterator3.return();
  2060. }
  2061. case 60:
  2062. _context2.prev = 60;
  2063. if (!_didIteratorError3) {
  2064. _context2.next = 63;
  2065. break;
  2066. }
  2067. throw _iteratorError3;
  2068. case 63:
  2069. return _context2.finish(60);
  2070. case 64:
  2071. return _context2.finish(57);
  2072. case 65:
  2073. return _context2.abrupt("return", Promise.all(promises));
  2074. case 66:
  2075. case "end":
  2076. return _context2.stop();
  2077. }
  2078. }
  2079. }, _callee2, this, [[9, 13, 17, 25], [18,, 20, 24], [32, 53, 57, 65], [58,, 60, 64]]);
  2080. }));
  2081. return function () {
  2082. return _handleUnPinAllWithName2.apply(this, arguments);
  2083. };
  2084. }(),
  2085. // Retrieve all pointer fields from object recursively
  2086. _getChildren: function (object
  2087. /*: ParseObject*/
  2088. ) {
  2089. var encountered = {};
  2090. var json = object._toFullJSON();
  2091. for (var key in json) {
  2092. if (json[key] && json[key].__type && json[key].__type === 'Object') {
  2093. this._traverse(json[key], encountered);
  2094. }
  2095. }
  2096. return encountered;
  2097. },
  2098. _traverse: function (object
  2099. /*: any*/
  2100. , encountered
  2101. /*: any*/
  2102. ) {
  2103. if (!object.objectId) {
  2104. return;
  2105. } else {
  2106. var objectKey = this.getKeyForObject(object);
  2107. if (encountered[objectKey]) {
  2108. return;
  2109. }
  2110. encountered[objectKey] = object;
  2111. }
  2112. for (var key in object) {
  2113. var json = object[key];
  2114. if (!object[key]) {
  2115. json = object;
  2116. }
  2117. if (json.__type && json.__type === 'Object') {
  2118. this._traverse(json, encountered);
  2119. }
  2120. }
  2121. },
  2122. // Transform keys in pin name to objects
  2123. _serializeObjectsFromPinName: function () {
  2124. var _serializeObjectsFromPinName2 = (0, _asyncToGenerator2.default)(
  2125. /*#__PURE__*/
  2126. _regenerator.default.mark(function _callee3(name
  2127. /*: string*/
  2128. ) {
  2129. var _this = this,
  2130. _ref3;
  2131. var localDatastore, allObjects, key, pinName, pinned, promises, objects;
  2132. return _regenerator.default.wrap(function (_context3) {
  2133. while (1) {
  2134. switch (_context3.prev = _context3.next) {
  2135. case 0:
  2136. _context3.next = 2;
  2137. return this._getAllContents();
  2138. case 2:
  2139. localDatastore = _context3.sent;
  2140. allObjects = [];
  2141. for (key in localDatastore) {
  2142. if (key.startsWith(_LocalDatastoreUtils.OBJECT_PREFIX)) {
  2143. allObjects.push(localDatastore[key][0]);
  2144. }
  2145. }
  2146. if (name) {
  2147. _context3.next = 7;
  2148. break;
  2149. }
  2150. return _context3.abrupt("return", allObjects);
  2151. case 7:
  2152. pinName = this.getPinName(name);
  2153. pinned = localDatastore[pinName];
  2154. if (Array.isArray(pinned)) {
  2155. _context3.next = 11;
  2156. break;
  2157. }
  2158. return _context3.abrupt("return", []);
  2159. case 11:
  2160. promises = pinned.map(function (objectKey) {
  2161. return _this.fromPinWithName(objectKey);
  2162. });
  2163. _context3.next = 14;
  2164. return Promise.all(promises);
  2165. case 14:
  2166. objects = _context3.sent;
  2167. objects = (_ref3 = []).concat.apply(_ref3, (0, _toConsumableArray2.default)(objects));
  2168. return _context3.abrupt("return", objects.filter(function (object) {
  2169. return object != null;
  2170. }));
  2171. case 17:
  2172. case "end":
  2173. return _context3.stop();
  2174. }
  2175. }
  2176. }, _callee3, this);
  2177. }));
  2178. return function () {
  2179. return _serializeObjectsFromPinName2.apply(this, arguments);
  2180. };
  2181. }(),
  2182. // Replaces object pointers with pinned pointers
  2183. // The object pointers may contain old data
  2184. // Uses Breadth First Search Algorithm
  2185. _serializeObject: function () {
  2186. var _serializeObject2 = (0, _asyncToGenerator2.default)(
  2187. /*#__PURE__*/
  2188. _regenerator.default.mark(function _callee4(objectKey
  2189. /*: string*/
  2190. , localDatastore
  2191. /*: any*/
  2192. ) {
  2193. var LDS, root, queue, meta, uniqueId, nodeId, subTreeRoot, field, value, key, pointer;
  2194. return _regenerator.default.wrap(function (_context4) {
  2195. while (1) {
  2196. switch (_context4.prev = _context4.next) {
  2197. case 0:
  2198. LDS = localDatastore;
  2199. if (LDS) {
  2200. _context4.next = 5;
  2201. break;
  2202. }
  2203. _context4.next = 4;
  2204. return this._getAllContents();
  2205. case 4:
  2206. LDS = _context4.sent;
  2207. case 5:
  2208. if (!(!LDS[objectKey] || LDS[objectKey].length === 0)) {
  2209. _context4.next = 7;
  2210. break;
  2211. }
  2212. return _context4.abrupt("return", null);
  2213. case 7:
  2214. root = LDS[objectKey][0];
  2215. queue = [];
  2216. meta = {};
  2217. uniqueId = 0;
  2218. meta[uniqueId] = root;
  2219. queue.push(uniqueId);
  2220. while (queue.length !== 0) {
  2221. nodeId = queue.shift();
  2222. subTreeRoot = meta[nodeId];
  2223. for (field in subTreeRoot) {
  2224. value = subTreeRoot[field];
  2225. if (value.__type && value.__type === 'Object') {
  2226. key = this.getKeyForObject(value);
  2227. if (LDS[key] && LDS[key].length > 0) {
  2228. pointer = LDS[key][0];
  2229. uniqueId++;
  2230. meta[uniqueId] = pointer;
  2231. subTreeRoot[field] = pointer;
  2232. queue.push(uniqueId);
  2233. }
  2234. }
  2235. }
  2236. }
  2237. return _context4.abrupt("return", root);
  2238. case 15:
  2239. case "end":
  2240. return _context4.stop();
  2241. }
  2242. }
  2243. }, _callee4, this);
  2244. }));
  2245. return function () {
  2246. return _serializeObject2.apply(this, arguments);
  2247. };
  2248. }(),
  2249. // Called when an object is save / fetched
  2250. // Update object pin value
  2251. _updateObjectIfPinned: function () {
  2252. var _updateObjectIfPinned2 = (0, _asyncToGenerator2.default)(
  2253. /*#__PURE__*/
  2254. _regenerator.default.mark(function _callee5(object
  2255. /*: ParseObject*/
  2256. ) {
  2257. var objectKey, pinned;
  2258. return _regenerator.default.wrap(function (_context5) {
  2259. while (1) {
  2260. switch (_context5.prev = _context5.next) {
  2261. case 0:
  2262. if (this.isEnabled) {
  2263. _context5.next = 2;
  2264. break;
  2265. }
  2266. return _context5.abrupt("return");
  2267. case 2:
  2268. objectKey = this.getKeyForObject(object);
  2269. _context5.next = 5;
  2270. return this.fromPinWithName(objectKey);
  2271. case 5:
  2272. pinned = _context5.sent;
  2273. if (!(!pinned || pinned.length === 0)) {
  2274. _context5.next = 8;
  2275. break;
  2276. }
  2277. return _context5.abrupt("return");
  2278. case 8:
  2279. return _context5.abrupt("return", this.pinWithName(objectKey, [object._toFullJSON()]));
  2280. case 9:
  2281. case "end":
  2282. return _context5.stop();
  2283. }
  2284. }
  2285. }, _callee5, this);
  2286. }));
  2287. return function () {
  2288. return _updateObjectIfPinned2.apply(this, arguments);
  2289. };
  2290. }(),
  2291. // Called when object is destroyed
  2292. // Unpin object and remove all references from pin names
  2293. // TODO: Destroy children?
  2294. _destroyObjectIfPinned: function () {
  2295. var _destroyObjectIfPinned2 = (0, _asyncToGenerator2.default)(
  2296. /*#__PURE__*/
  2297. _regenerator.default.mark(function _callee6(object
  2298. /*: ParseObject*/
  2299. ) {
  2300. var localDatastore, objectKey, pin, promises, key, pinned;
  2301. return _regenerator.default.wrap(function (_context6) {
  2302. while (1) {
  2303. switch (_context6.prev = _context6.next) {
  2304. case 0:
  2305. if (this.isEnabled) {
  2306. _context6.next = 2;
  2307. break;
  2308. }
  2309. return _context6.abrupt("return");
  2310. case 2:
  2311. _context6.next = 4;
  2312. return this._getAllContents();
  2313. case 4:
  2314. localDatastore = _context6.sent;
  2315. objectKey = this.getKeyForObject(object);
  2316. pin = localDatastore[objectKey];
  2317. if (pin) {
  2318. _context6.next = 9;
  2319. break;
  2320. }
  2321. return _context6.abrupt("return");
  2322. case 9:
  2323. promises = [this.unPinWithName(objectKey)];
  2324. delete localDatastore[objectKey];
  2325. for (key in localDatastore) {
  2326. if (key === _LocalDatastoreUtils.DEFAULT_PIN || key.startsWith(_LocalDatastoreUtils.PIN_PREFIX)) {
  2327. pinned = localDatastore[key] || [];
  2328. if (pinned.includes(objectKey)) {
  2329. pinned = pinned.filter(function (item) {
  2330. return item !== objectKey;
  2331. });
  2332. if (pinned.length == 0) {
  2333. promises.push(this.unPinWithName(key));
  2334. delete localDatastore[key];
  2335. } else {
  2336. promises.push(this.pinWithName(key, pinned));
  2337. localDatastore[key] = pinned;
  2338. }
  2339. }
  2340. }
  2341. }
  2342. return _context6.abrupt("return", Promise.all(promises));
  2343. case 13:
  2344. case "end":
  2345. return _context6.stop();
  2346. }
  2347. }
  2348. }, _callee6, this);
  2349. }));
  2350. return function () {
  2351. return _destroyObjectIfPinned2.apply(this, arguments);
  2352. };
  2353. }(),
  2354. // Update pin and references of the unsaved object
  2355. _updateLocalIdForObject: function () {
  2356. var _updateLocalIdForObject2 = (0, _asyncToGenerator2.default)(
  2357. /*#__PURE__*/
  2358. _regenerator.default.mark(function _callee7(localId
  2359. /*: string*/
  2360. , object
  2361. /*: ParseObject*/
  2362. ) {
  2363. var localKey, objectKey, unsaved, promises, localDatastore, key, pinned;
  2364. return _regenerator.default.wrap(function (_context7) {
  2365. while (1) {
  2366. switch (_context7.prev = _context7.next) {
  2367. case 0:
  2368. if (this.isEnabled) {
  2369. _context7.next = 2;
  2370. break;
  2371. }
  2372. return _context7.abrupt("return");
  2373. case 2:
  2374. localKey = "".concat(_LocalDatastoreUtils.OBJECT_PREFIX).concat(object.className, "_").concat(localId);
  2375. objectKey = this.getKeyForObject(object);
  2376. _context7.next = 6;
  2377. return this.fromPinWithName(localKey);
  2378. case 6:
  2379. unsaved = _context7.sent;
  2380. if (!(!unsaved || unsaved.length === 0)) {
  2381. _context7.next = 9;
  2382. break;
  2383. }
  2384. return _context7.abrupt("return");
  2385. case 9:
  2386. promises = [this.unPinWithName(localKey), this.pinWithName(objectKey, unsaved)];
  2387. _context7.next = 12;
  2388. return this._getAllContents();
  2389. case 12:
  2390. localDatastore = _context7.sent;
  2391. for (key in localDatastore) {
  2392. if (key === _LocalDatastoreUtils.DEFAULT_PIN || key.startsWith(_LocalDatastoreUtils.PIN_PREFIX)) {
  2393. pinned = localDatastore[key] || [];
  2394. if (pinned.includes(localKey)) {
  2395. pinned = pinned.filter(function (item) {
  2396. return item !== localKey;
  2397. });
  2398. pinned.push(objectKey);
  2399. promises.push(this.pinWithName(key, pinned));
  2400. localDatastore[key] = pinned;
  2401. }
  2402. }
  2403. }
  2404. return _context7.abrupt("return", Promise.all(promises));
  2405. case 15:
  2406. case "end":
  2407. return _context7.stop();
  2408. }
  2409. }
  2410. }, _callee7, this);
  2411. }));
  2412. return function () {
  2413. return _updateLocalIdForObject2.apply(this, arguments);
  2414. };
  2415. }(),
  2416. /**
  2417. * Updates Local Datastore from Server
  2418. *
  2419. * <pre>
  2420. * await Parse.LocalDatastore.updateFromServer();
  2421. * </pre>
  2422. * @method updateFromServer
  2423. * @name Parse.LocalDatastore.updateFromServer
  2424. * @static
  2425. */
  2426. updateFromServer: function () {
  2427. var _updateFromServer = (0, _asyncToGenerator2.default)(
  2428. /*#__PURE__*/
  2429. _regenerator.default.mark(function _callee8() {
  2430. var _this2 = this;
  2431. var localDatastore, keys, key, pointersHash, _i, _keys, _key, _key$split, _key$split2, className, objectId, queryPromises, responses, objects, pinPromises;
  2432. return _regenerator.default.wrap(function (_context8) {
  2433. while (1) {
  2434. switch (_context8.prev = _context8.next) {
  2435. case 0:
  2436. if (!(!this.checkIfEnabled() || this.isSyncing)) {
  2437. _context8.next = 2;
  2438. break;
  2439. }
  2440. return _context8.abrupt("return");
  2441. case 2:
  2442. _context8.next = 4;
  2443. return this._getAllContents();
  2444. case 4:
  2445. localDatastore = _context8.sent;
  2446. keys = [];
  2447. for (key in localDatastore) {
  2448. if (key.startsWith(_LocalDatastoreUtils.OBJECT_PREFIX)) {
  2449. keys.push(key);
  2450. }
  2451. }
  2452. if (!(keys.length === 0)) {
  2453. _context8.next = 9;
  2454. break;
  2455. }
  2456. return _context8.abrupt("return");
  2457. case 9:
  2458. this.isSyncing = true;
  2459. pointersHash = {};
  2460. _i = 0, _keys = keys;
  2461. case 12:
  2462. if (!(_i < _keys.length)) {
  2463. _context8.next = 23;
  2464. break;
  2465. }
  2466. _key = _keys[_i]; // Ignore the OBJECT_PREFIX
  2467. _key$split = _key.split('_'), _key$split2 = (0, _slicedToArray2.default)(_key$split, 4), className = _key$split2[2], objectId = _key$split2[3]; // User key is split into [ 'Parse', 'LDS', '', 'User', 'objectId' ]
  2468. if (_key.split('_').length === 5 && _key.split('_')[3] === 'User') {
  2469. className = '_User';
  2470. objectId = _key.split('_')[4];
  2471. }
  2472. if (!objectId.startsWith('local')) {
  2473. _context8.next = 18;
  2474. break;
  2475. }
  2476. return _context8.abrupt("continue", 20);
  2477. case 18:
  2478. if (!(className in pointersHash)) {
  2479. pointersHash[className] = new Set();
  2480. }
  2481. pointersHash[className].add(objectId);
  2482. case 20:
  2483. _i++;
  2484. _context8.next = 12;
  2485. break;
  2486. case 23:
  2487. queryPromises = Object.keys(pointersHash).map(function (className) {
  2488. var objectIds = Array.from(pointersHash[className]);
  2489. var query = new _ParseQuery.default(className);
  2490. query.limit(objectIds.length);
  2491. if (objectIds.length === 1) {
  2492. query.equalTo('objectId', objectIds[0]);
  2493. } else {
  2494. query.containedIn('objectId', objectIds);
  2495. }
  2496. return query.find();
  2497. });
  2498. _context8.prev = 24;
  2499. _context8.next = 27;
  2500. return Promise.all(queryPromises);
  2501. case 27:
  2502. responses = _context8.sent;
  2503. objects = [].concat.apply([], responses);
  2504. pinPromises = objects.map(function (object) {
  2505. var objectKey = _this2.getKeyForObject(object);
  2506. return _this2.pinWithName(objectKey, object._toFullJSON());
  2507. });
  2508. _context8.next = 32;
  2509. return Promise.all(pinPromises);
  2510. case 32:
  2511. this.isSyncing = false;
  2512. _context8.next = 39;
  2513. break;
  2514. case 35:
  2515. _context8.prev = 35;
  2516. _context8.t0 = _context8["catch"](24);
  2517. console.error('Error syncing LocalDatastore: ', _context8.t0);
  2518. this.isSyncing = false;
  2519. case 39:
  2520. case "end":
  2521. return _context8.stop();
  2522. }
  2523. }
  2524. }, _callee8, this, [[24, 35]]);
  2525. }));
  2526. return function () {
  2527. return _updateFromServer.apply(this, arguments);
  2528. };
  2529. }(),
  2530. getKeyForObject: function (object
  2531. /*: any*/
  2532. ) {
  2533. var objectId = object.objectId || object._getId();
  2534. return "".concat(_LocalDatastoreUtils.OBJECT_PREFIX).concat(object.className, "_").concat(objectId);
  2535. },
  2536. getPinName: function (pinName
  2537. /*: ?string*/
  2538. ) {
  2539. if (!pinName || pinName === _LocalDatastoreUtils.DEFAULT_PIN) {
  2540. return _LocalDatastoreUtils.DEFAULT_PIN;
  2541. }
  2542. return _LocalDatastoreUtils.PIN_PREFIX + pinName;
  2543. },
  2544. checkIfEnabled: function () {
  2545. if (!this.isEnabled) {
  2546. console.error('Parse.enableLocalDatastore() must be called first');
  2547. }
  2548. return this.isEnabled;
  2549. }
  2550. };
  2551. module.exports = LocalDatastore;
  2552. _CoreManager.default.setLocalDatastoreController(_dereq_('./LocalDatastoreController.browser'));
  2553. _CoreManager.default.setLocalDatastore(LocalDatastore);
  2554. },{"./CoreManager":4,"./LocalDatastoreController.browser":11,"./LocalDatastoreUtils":12,"./ParseQuery":26,"@babel/runtime/helpers/asyncToGenerator":53,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/slicedToArray":70,"@babel/runtime/helpers/toConsumableArray":72,"@babel/runtime/regenerator":76}],11:[function(_dereq_,module,exports){
  2555. "use strict";
  2556. var _LocalDatastoreUtils = _dereq_("./LocalDatastoreUtils");
  2557. /**
  2558. * Copyright (c) 2015-present, Parse, LLC.
  2559. * All rights reserved.
  2560. *
  2561. * This source code is licensed under the BSD-style license found in the
  2562. * LICENSE file in the root directory of this source tree. An additional grant
  2563. * of patent rights can be found in the PATENTS file in the same directory.
  2564. *
  2565. * @flow
  2566. */
  2567. /* global localStorage */
  2568. var LocalDatastoreController = {
  2569. fromPinWithName: function (name
  2570. /*: string*/
  2571. )
  2572. /*: Array<Object>*/
  2573. {
  2574. var values = localStorage.getItem(name);
  2575. if (!values) {
  2576. return [];
  2577. }
  2578. var objects = JSON.parse(values);
  2579. return objects;
  2580. },
  2581. pinWithName: function (name
  2582. /*: string*/
  2583. , value
  2584. /*: any*/
  2585. ) {
  2586. try {
  2587. var values = JSON.stringify(value);
  2588. localStorage.setItem(name, values);
  2589. } catch (e) {
  2590. // Quota exceeded, possibly due to Safari Private Browsing mode
  2591. console.log(e.message);
  2592. }
  2593. },
  2594. unPinWithName: function (name
  2595. /*: string*/
  2596. ) {
  2597. localStorage.removeItem(name);
  2598. },
  2599. getAllContents: function ()
  2600. /*: Object*/
  2601. {
  2602. var LDS = {};
  2603. for (var i = 0; i < localStorage.length; i += 1) {
  2604. var key = localStorage.key(i);
  2605. if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
  2606. var value = localStorage.getItem(key);
  2607. try {
  2608. LDS[key] = JSON.parse(value);
  2609. } catch (error) {
  2610. console.error('Error getAllContents: ', error);
  2611. }
  2612. }
  2613. }
  2614. return LDS;
  2615. },
  2616. getRawStorage: function ()
  2617. /*: Object*/
  2618. {
  2619. var storage = {};
  2620. for (var i = 0; i < localStorage.length; i += 1) {
  2621. var key = localStorage.key(i);
  2622. var value = localStorage.getItem(key);
  2623. storage[key] = value;
  2624. }
  2625. return storage;
  2626. },
  2627. clear: function ()
  2628. /*: Promise*/
  2629. {
  2630. var toRemove = [];
  2631. for (var i = 0; i < localStorage.length; i += 1) {
  2632. var key = localStorage.key(i);
  2633. if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
  2634. toRemove.push(key);
  2635. }
  2636. }
  2637. var promises = toRemove.map(this.unPinWithName);
  2638. return Promise.all(promises);
  2639. }
  2640. };
  2641. module.exports = LocalDatastoreController;
  2642. },{"./LocalDatastoreUtils":12}],12:[function(_dereq_,module,exports){
  2643. "use strict";
  2644. Object.defineProperty(exports, "__esModule", {
  2645. value: true
  2646. });
  2647. exports.isLocalDatastoreKey = isLocalDatastoreKey;
  2648. exports.OBJECT_PREFIX = exports.PIN_PREFIX = exports.DEFAULT_PIN = void 0;
  2649. /**
  2650. * Copyright (c) 2015-present, Parse, LLC.
  2651. * All rights reserved.
  2652. *
  2653. * This source code is licensed under the BSD-style license found in the
  2654. * LICENSE file in the root directory of this source tree. An additional grant
  2655. * of patent rights can be found in the PATENTS file in the same directory.
  2656. *
  2657. * @flow
  2658. */
  2659. var DEFAULT_PIN = '_default';
  2660. exports.DEFAULT_PIN = DEFAULT_PIN;
  2661. var PIN_PREFIX = 'parsePin_';
  2662. exports.PIN_PREFIX = PIN_PREFIX;
  2663. var OBJECT_PREFIX = 'Parse_LDS_';
  2664. exports.OBJECT_PREFIX = OBJECT_PREFIX;
  2665. function isLocalDatastoreKey(key
  2666. /*: string*/
  2667. )
  2668. /*: boolean*/
  2669. {
  2670. return !!(key && (key === DEFAULT_PIN || key.startsWith(PIN_PREFIX) || key.startsWith(OBJECT_PREFIX)));
  2671. }
  2672. },{}],13:[function(_dereq_,module,exports){
  2673. "use strict";
  2674. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  2675. Object.defineProperty(exports, "__esModule", {
  2676. value: true
  2677. });
  2678. exports.defaultState = defaultState;
  2679. exports.setServerData = setServerData;
  2680. exports.setPendingOp = setPendingOp;
  2681. exports.pushPendingState = pushPendingState;
  2682. exports.popPendingState = popPendingState;
  2683. exports.mergeFirstPendingState = mergeFirstPendingState;
  2684. exports.estimateAttribute = estimateAttribute;
  2685. exports.estimateAttributes = estimateAttributes;
  2686. exports.commitServerChanges = commitServerChanges;
  2687. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  2688. var _encode = _interopRequireDefault(_dereq_("./encode"));
  2689. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  2690. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  2691. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  2692. var _TaskQueue = _interopRequireDefault(_dereq_("./TaskQueue"));
  2693. var _ParseOp = _dereq_("./ParseOp");
  2694. /**
  2695. * Copyright (c) 2015-present, Parse, LLC.
  2696. * All rights reserved.
  2697. *
  2698. * This source code is licensed under the BSD-style license found in the
  2699. * LICENSE file in the root directory of this source tree. An additional grant
  2700. * of patent rights can be found in the PATENTS file in the same directory.
  2701. *
  2702. * @flow
  2703. */
  2704. function defaultState()
  2705. /*: State*/
  2706. {
  2707. return {
  2708. serverData: {},
  2709. pendingOps: [{}],
  2710. objectCache: {},
  2711. tasks: new _TaskQueue.default(),
  2712. existed: false
  2713. };
  2714. }
  2715. function setServerData(serverData
  2716. /*: AttributeMap*/
  2717. , attributes
  2718. /*: AttributeMap*/
  2719. ) {
  2720. for (var _attr in attributes) {
  2721. if (typeof attributes[_attr] !== 'undefined') {
  2722. serverData[_attr] = attributes[_attr];
  2723. } else {
  2724. delete serverData[_attr];
  2725. }
  2726. }
  2727. }
  2728. function setPendingOp(pendingOps
  2729. /*: Array<OpsMap>*/
  2730. , attr
  2731. /*: string*/
  2732. , op
  2733. /*: ?Op*/
  2734. ) {
  2735. var last = pendingOps.length - 1;
  2736. if (op) {
  2737. pendingOps[last][attr] = op;
  2738. } else {
  2739. delete pendingOps[last][attr];
  2740. }
  2741. }
  2742. function pushPendingState(pendingOps
  2743. /*: Array<OpsMap>*/
  2744. ) {
  2745. pendingOps.push({});
  2746. }
  2747. function popPendingState(pendingOps
  2748. /*: Array<OpsMap>*/
  2749. )
  2750. /*: OpsMap*/
  2751. {
  2752. var first = pendingOps.shift();
  2753. if (!pendingOps.length) {
  2754. pendingOps[0] = {};
  2755. }
  2756. return first;
  2757. }
  2758. function mergeFirstPendingState(pendingOps
  2759. /*: Array<OpsMap>*/
  2760. ) {
  2761. var first = popPendingState(pendingOps);
  2762. var next = pendingOps[0];
  2763. for (var _attr2 in first) {
  2764. if (next[_attr2] && first[_attr2]) {
  2765. var merged = next[_attr2].mergeWith(first[_attr2]);
  2766. if (merged) {
  2767. next[_attr2] = merged;
  2768. }
  2769. } else {
  2770. next[_attr2] = first[_attr2];
  2771. }
  2772. }
  2773. }
  2774. function estimateAttribute(serverData
  2775. /*: AttributeMap*/
  2776. , pendingOps
  2777. /*: Array<OpsMap>*/
  2778. , className
  2779. /*: string*/
  2780. , id
  2781. /*: ?string*/
  2782. , attr
  2783. /*: string*/
  2784. )
  2785. /*: mixed*/
  2786. {
  2787. var value = serverData[attr];
  2788. for (var i = 0; i < pendingOps.length; i++) {
  2789. if (pendingOps[i][attr]) {
  2790. if (pendingOps[i][attr] instanceof _ParseOp.RelationOp) {
  2791. if (id) {
  2792. value = pendingOps[i][attr].applyTo(value, {
  2793. className: className,
  2794. id: id
  2795. }, attr);
  2796. }
  2797. } else {
  2798. value = pendingOps[i][attr].applyTo(value);
  2799. }
  2800. }
  2801. }
  2802. return value;
  2803. }
  2804. function estimateAttributes(serverData
  2805. /*: AttributeMap*/
  2806. , pendingOps
  2807. /*: Array<OpsMap>*/
  2808. , className
  2809. /*: string*/
  2810. , id
  2811. /*: ?string*/
  2812. )
  2813. /*: AttributeMap*/
  2814. {
  2815. var data = {};
  2816. for (var attr in serverData) {
  2817. data[attr] = serverData[attr];
  2818. }
  2819. for (var i = 0; i < pendingOps.length; i++) {
  2820. for (attr in pendingOps[i]) {
  2821. if (pendingOps[i][attr] instanceof _ParseOp.RelationOp) {
  2822. if (id) {
  2823. data[attr] = pendingOps[i][attr].applyTo(data[attr], {
  2824. className: className,
  2825. id: id
  2826. }, attr);
  2827. }
  2828. } else {
  2829. if (attr.includes('.')) {
  2830. // convert a.b.c into { a: { b: { c: value } } }
  2831. var fields = attr.split('.');
  2832. var last = fields[fields.length - 1];
  2833. var object = Object.assign({}, data);
  2834. for (var _i = 0; _i < fields.length - 1; _i++) {
  2835. object = object[fields[_i]];
  2836. }
  2837. object[last] = pendingOps[i][attr].applyTo(object[last]);
  2838. } else {
  2839. data[attr] = pendingOps[i][attr].applyTo(data[attr]);
  2840. }
  2841. }
  2842. }
  2843. }
  2844. return data;
  2845. }
  2846. function commitServerChanges(serverData
  2847. /*: AttributeMap*/
  2848. , objectCache
  2849. /*: ObjectCache*/
  2850. , changes
  2851. /*: AttributeMap*/
  2852. ) {
  2853. for (var _attr3 in changes) {
  2854. var val = changes[_attr3];
  2855. serverData[_attr3] = val;
  2856. if (val && (0, _typeof2.default)(val) === 'object' && !(val instanceof _ParseObject.default) && !(val instanceof _ParseFile.default) && !(val instanceof _ParseRelation.default)) {
  2857. var json = (0, _encode.default)(val, false, true);
  2858. objectCache[_attr3] = JSON.stringify(json);
  2859. }
  2860. }
  2861. }
  2862. },{"./ParseFile":19,"./ParseObject":23,"./ParseOp":24,"./ParseRelation":27,"./TaskQueue":37,"./encode":42,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],14:[function(_dereq_,module,exports){
  2863. "use strict";
  2864. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  2865. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  2866. var equalObjects = _dereq_('./equals').default;
  2867. var decode = _dereq_('./decode').default;
  2868. var ParseError = _dereq_('./ParseError').default;
  2869. var ParsePolygon = _dereq_('./ParsePolygon').default;
  2870. var ParseGeoPoint = _dereq_('./ParseGeoPoint').default;
  2871. /**
  2872. * contains -- Determines if an object is contained in a list with special handling for Parse pointers.
  2873. */
  2874. function contains(haystack, needle) {
  2875. if (needle && needle.__type && (needle.__type === 'Pointer' || needle.__type === 'Object')) {
  2876. for (var i in haystack) {
  2877. var ptr = haystack[i];
  2878. if (typeof ptr === 'string' && ptr === needle.objectId) {
  2879. return true;
  2880. }
  2881. if (ptr.className === needle.className && ptr.objectId === needle.objectId) {
  2882. return true;
  2883. }
  2884. }
  2885. return false;
  2886. }
  2887. return haystack.indexOf(needle) > -1;
  2888. }
  2889. function transformObject(object) {
  2890. if (object._toFullJSON) {
  2891. return object._toFullJSON();
  2892. }
  2893. return object;
  2894. }
  2895. /**
  2896. * matchesQuery -- Determines if an object would be returned by a Parse Query
  2897. * It's a lightweight, where-clause only implementation of a full query engine.
  2898. * Since we find queries that match objects, rather than objects that match
  2899. * queries, we can avoid building a full-blown query tool.
  2900. */
  2901. function matchesQuery(className, object, objects, query) {
  2902. if (object.className !== className) {
  2903. return false;
  2904. }
  2905. var obj = object;
  2906. var q = query;
  2907. if (object.toJSON) {
  2908. obj = object.toJSON();
  2909. }
  2910. if (query.toJSON) {
  2911. q = query.toJSON().where;
  2912. }
  2913. obj.className = className;
  2914. for (var field in q) {
  2915. if (!matchesKeyConstraints(className, obj, objects, field, q[field])) {
  2916. return false;
  2917. }
  2918. }
  2919. return true;
  2920. }
  2921. function equalObjectsGeneric(obj, compareTo, eqlFn) {
  2922. if (Array.isArray(obj)) {
  2923. for (var i = 0; i < obj.length; i++) {
  2924. if (eqlFn(obj[i], compareTo)) {
  2925. return true;
  2926. }
  2927. }
  2928. return false;
  2929. }
  2930. return eqlFn(obj, compareTo);
  2931. }
  2932. /**
  2933. * Determines whether an object matches a single key's constraints
  2934. */
  2935. function matchesKeyConstraints(className, object, objects, key, constraints) {
  2936. if (constraints === null) {
  2937. return false;
  2938. }
  2939. if (key.indexOf('.') >= 0) {
  2940. // Key references a subobject
  2941. var keyComponents = key.split('.');
  2942. var subObjectKey = keyComponents[0];
  2943. var keyRemainder = keyComponents.slice(1).join('.');
  2944. return matchesKeyConstraints(className, object[subObjectKey] || {}, objects, keyRemainder, constraints);
  2945. }
  2946. var i;
  2947. if (key === '$or') {
  2948. for (i = 0; i < constraints.length; i++) {
  2949. if (matchesQuery(className, object, objects, constraints[i])) {
  2950. return true;
  2951. }
  2952. }
  2953. return false;
  2954. }
  2955. if (key === '$and') {
  2956. for (i = 0; i < constraints.length; i++) {
  2957. if (!matchesQuery(className, object, objects, constraints[i])) {
  2958. return false;
  2959. }
  2960. }
  2961. return true;
  2962. }
  2963. if (key === '$nor') {
  2964. for (i = 0; i < constraints.length; i++) {
  2965. if (matchesQuery(className, object, objects, constraints[i])) {
  2966. return false;
  2967. }
  2968. }
  2969. return true;
  2970. }
  2971. if (key === '$relatedTo') {
  2972. // Bail! We can't handle relational queries locally
  2973. return false;
  2974. }
  2975. if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(key)) {
  2976. throw new ParseError(ParseError.INVALID_KEY_NAME, "Invalid Key: ".concat(key));
  2977. } // Equality (or Array contains) cases
  2978. if ((0, _typeof2.default)(constraints) !== 'object') {
  2979. if (Array.isArray(object[key])) {
  2980. return object[key].indexOf(constraints) > -1;
  2981. }
  2982. return object[key] === constraints;
  2983. }
  2984. var compareTo;
  2985. if (constraints.__type) {
  2986. if (constraints.__type === 'Pointer') {
  2987. return equalObjectsGeneric(object[key], constraints, function (obj, ptr) {
  2988. return typeof obj !== 'undefined' && ptr.className === obj.className && ptr.objectId === obj.objectId;
  2989. });
  2990. }
  2991. return equalObjectsGeneric(decode(object[key]), decode(constraints), equalObjects);
  2992. } // More complex cases
  2993. for (var condition in constraints) {
  2994. compareTo = constraints[condition];
  2995. if (compareTo.__type) {
  2996. compareTo = decode(compareTo);
  2997. } // Compare Date Object or Date String
  2998. if (toString.call(compareTo) === '[object Date]' || typeof compareTo === 'string' && new Date(compareTo) !== 'Invalid Date' && !isNaN(new Date(compareTo))) {
  2999. object[key] = new Date(object[key].iso ? object[key].iso : object[key]);
  3000. }
  3001. switch (condition) {
  3002. case '$lt':
  3003. if (object[key] >= compareTo) {
  3004. return false;
  3005. }
  3006. break;
  3007. case '$lte':
  3008. if (object[key] > compareTo) {
  3009. return false;
  3010. }
  3011. break;
  3012. case '$gt':
  3013. if (object[key] <= compareTo) {
  3014. return false;
  3015. }
  3016. break;
  3017. case '$gte':
  3018. if (object[key] < compareTo) {
  3019. return false;
  3020. }
  3021. break;
  3022. case '$ne':
  3023. if (equalObjects(object[key], compareTo)) {
  3024. return false;
  3025. }
  3026. break;
  3027. case '$in':
  3028. if (!contains(compareTo, object[key])) {
  3029. return false;
  3030. }
  3031. break;
  3032. case '$nin':
  3033. if (contains(compareTo, object[key])) {
  3034. return false;
  3035. }
  3036. break;
  3037. case '$all':
  3038. for (i = 0; i < compareTo.length; i++) {
  3039. if (object[key].indexOf(compareTo[i]) < 0) {
  3040. return false;
  3041. }
  3042. }
  3043. break;
  3044. case '$exists':
  3045. {
  3046. var propertyExists = typeof object[key] !== 'undefined';
  3047. var existenceIsRequired = constraints['$exists'];
  3048. if (typeof constraints['$exists'] !== 'boolean') {
  3049. // The SDK will never submit a non-boolean for $exists, but if someone
  3050. // tries to submit a non-boolean for $exits outside the SDKs, just ignore it.
  3051. break;
  3052. }
  3053. if (!propertyExists && existenceIsRequired || propertyExists && !existenceIsRequired) {
  3054. return false;
  3055. }
  3056. break;
  3057. }
  3058. case '$regex':
  3059. {
  3060. if ((0, _typeof2.default)(compareTo) === 'object') {
  3061. return compareTo.test(object[key]);
  3062. } // JS doesn't support perl-style escaping
  3063. var expString = '';
  3064. var escapeEnd = -2;
  3065. var escapeStart = compareTo.indexOf('\\Q');
  3066. while (escapeStart > -1) {
  3067. // Add the unescaped portion
  3068. expString += compareTo.substring(escapeEnd + 2, escapeStart);
  3069. escapeEnd = compareTo.indexOf('\\E', escapeStart);
  3070. if (escapeEnd > -1) {
  3071. expString += compareTo.substring(escapeStart + 2, escapeEnd).replace(/\\\\\\\\E/g, '\\E').replace(/\W/g, '\\$&');
  3072. }
  3073. escapeStart = compareTo.indexOf('\\Q', escapeEnd);
  3074. }
  3075. expString += compareTo.substring(Math.max(escapeStart, escapeEnd + 2));
  3076. var modifiers = constraints.$options || '';
  3077. modifiers = modifiers.replace('x', '').replace('s', ''); // Parse Server / Mongo support x and s modifiers but JS RegExp doesn't
  3078. var exp = new RegExp(expString, modifiers);
  3079. if (!exp.test(object[key])) {
  3080. return false;
  3081. }
  3082. break;
  3083. }
  3084. case '$nearSphere':
  3085. {
  3086. if (!compareTo || !object[key]) {
  3087. return false;
  3088. }
  3089. var distance = compareTo.radiansTo(object[key]);
  3090. var max = constraints.$maxDistance || Infinity;
  3091. return distance <= max;
  3092. }
  3093. case '$within':
  3094. {
  3095. if (!compareTo || !object[key]) {
  3096. return false;
  3097. }
  3098. var southWest = compareTo.$box[0];
  3099. var northEast = compareTo.$box[1];
  3100. if (southWest.latitude > northEast.latitude || southWest.longitude > northEast.longitude) {
  3101. // Invalid box, crosses the date line
  3102. return false;
  3103. }
  3104. return object[key].latitude > southWest.latitude && object[key].latitude < northEast.latitude && object[key].longitude > southWest.longitude && object[key].longitude < northEast.longitude;
  3105. }
  3106. case '$options':
  3107. // Not a query type, but a way to add options to $regex. Ignore and
  3108. // avoid the default
  3109. break;
  3110. case '$maxDistance':
  3111. // Not a query type, but a way to add a cap to $nearSphere. Ignore and
  3112. // avoid the default
  3113. break;
  3114. case '$select':
  3115. {
  3116. var subQueryObjects = objects.filter(function (obj, index, arr) {
  3117. return matchesQuery(compareTo.query.className, obj, arr, compareTo.query.where);
  3118. });
  3119. for (var _i = 0; _i < subQueryObjects.length; _i += 1) {
  3120. var subObject = transformObject(subQueryObjects[_i]);
  3121. return equalObjects(object[key], subObject[compareTo.key]);
  3122. }
  3123. return false;
  3124. }
  3125. case '$dontSelect':
  3126. {
  3127. var _subQueryObjects = objects.filter(function (obj, index, arr) {
  3128. return matchesQuery(compareTo.query.className, obj, arr, compareTo.query.where);
  3129. });
  3130. for (var _i2 = 0; _i2 < _subQueryObjects.length; _i2 += 1) {
  3131. var _subObject = transformObject(_subQueryObjects[_i2]);
  3132. return !equalObjects(object[key], _subObject[compareTo.key]);
  3133. }
  3134. return false;
  3135. }
  3136. case '$inQuery':
  3137. {
  3138. var _subQueryObjects2 = objects.filter(function (obj, index, arr) {
  3139. return matchesQuery(compareTo.className, obj, arr, compareTo.where);
  3140. });
  3141. for (var _i3 = 0; _i3 < _subQueryObjects2.length; _i3 += 1) {
  3142. var _subObject2 = transformObject(_subQueryObjects2[_i3]);
  3143. if (object[key].className === _subObject2.className && object[key].objectId === _subObject2.objectId) {
  3144. return true;
  3145. }
  3146. }
  3147. return false;
  3148. }
  3149. case '$notInQuery':
  3150. {
  3151. var _subQueryObjects3 = objects.filter(function (obj, index, arr) {
  3152. return matchesQuery(compareTo.className, obj, arr, compareTo.where);
  3153. });
  3154. for (var _i4 = 0; _i4 < _subQueryObjects3.length; _i4 += 1) {
  3155. var _subObject3 = transformObject(_subQueryObjects3[_i4]);
  3156. if (object[key].className === _subObject3.className && object[key].objectId === _subObject3.objectId) {
  3157. return false;
  3158. }
  3159. }
  3160. return true;
  3161. }
  3162. case '$containedBy':
  3163. {
  3164. var _iteratorNormalCompletion = true;
  3165. var _didIteratorError = false;
  3166. var _iteratorError = undefined;
  3167. try {
  3168. for (var _iterator = object[key][Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  3169. var value = _step.value;
  3170. if (!contains(compareTo, value)) {
  3171. return false;
  3172. }
  3173. }
  3174. } catch (err) {
  3175. _didIteratorError = true;
  3176. _iteratorError = err;
  3177. } finally {
  3178. try {
  3179. if (!_iteratorNormalCompletion && _iterator.return != null) {
  3180. _iterator.return();
  3181. }
  3182. } finally {
  3183. if (_didIteratorError) {
  3184. throw _iteratorError;
  3185. }
  3186. }
  3187. }
  3188. return true;
  3189. }
  3190. case '$geoWithin':
  3191. {
  3192. var points = compareTo.$polygon.map(function (geoPoint) {
  3193. return [geoPoint.latitude, geoPoint.longitude];
  3194. });
  3195. var polygon = new ParsePolygon(points);
  3196. return polygon.containsPoint(object[key]);
  3197. }
  3198. case '$geoIntersects':
  3199. {
  3200. var _polygon = new ParsePolygon(object[key].coordinates);
  3201. var point = new ParseGeoPoint(compareTo.$point);
  3202. return _polygon.containsPoint(point);
  3203. }
  3204. default:
  3205. return false;
  3206. }
  3207. }
  3208. return true;
  3209. }
  3210. function validateQuery(query
  3211. /*: any*/
  3212. ) {
  3213. var q = query;
  3214. if (query.toJSON) {
  3215. q = query.toJSON().where;
  3216. }
  3217. var specialQuerykeys = ['$and', '$or', '$nor', '_rperm', '_wperm', '_perishable_token', '_email_verify_token', '_email_verify_token_expires_at', '_account_lockout_expires_at', '_failed_login_count'];
  3218. Object.keys(q).forEach(function (key) {
  3219. if (q && q[key] && q[key].$regex) {
  3220. if (typeof q[key].$options === 'string') {
  3221. if (!q[key].$options.match(/^[imxs]+$/)) {
  3222. throw new ParseError(ParseError.INVALID_QUERY, "Bad $options value for query: ".concat(q[key].$options));
  3223. }
  3224. }
  3225. }
  3226. if (specialQuerykeys.indexOf(key) < 0 && !key.match(/^[a-zA-Z][a-zA-Z0-9_\.]*$/)) {
  3227. throw new ParseError(ParseError.INVALID_KEY_NAME, "Invalid key name: ".concat(key));
  3228. }
  3229. });
  3230. }
  3231. var OfflineQuery = {
  3232. matchesQuery: matchesQuery,
  3233. validateQuery: validateQuery
  3234. };
  3235. module.exports = OfflineQuery;
  3236. },{"./ParseError":18,"./ParseGeoPoint":20,"./ParsePolygon":25,"./decode":41,"./equals":43,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],15:[function(_dereq_,module,exports){
  3237. (function (process){
  3238. "use strict";
  3239. var _interopRequireWildcard = _dereq_("@babel/runtime/helpers/interopRequireWildcard");
  3240. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  3241. var _decode = _interopRequireDefault(_dereq_("./decode"));
  3242. var _encode = _interopRequireDefault(_dereq_("./encode"));
  3243. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  3244. var _InstallationController = _interopRequireDefault(_dereq_("./InstallationController"));
  3245. var ParseOp = _interopRequireWildcard(_dereq_("./ParseOp"));
  3246. var _RESTController = _interopRequireDefault(_dereq_("./RESTController"));
  3247. /**
  3248. * Copyright (c) 2015-present, Parse, LLC.
  3249. * All rights reserved.
  3250. *
  3251. * This source code is licensed under the BSD-style license found in the
  3252. * LICENSE file in the root directory of this source tree. An additional grant
  3253. * of patent rights can be found in the PATENTS file in the same directory.
  3254. */
  3255. /**
  3256. * Contains all Parse API classes and functions.
  3257. * @static
  3258. * @global
  3259. * @class
  3260. * @hideconstructor
  3261. */
  3262. var Parse = {
  3263. /**
  3264. * Call this method first to set up your authentication tokens for Parse.
  3265. * You can get your keys from the Data Browser on parse.com.
  3266. * @param {String} applicationId Your Parse Application ID.
  3267. * @param {String} javaScriptKey (optional) Your Parse JavaScript Key (Not needed for parse-server)
  3268. * @param {String} masterKey (optional) Your Parse Master Key. (Node.js only!)
  3269. * @static
  3270. */
  3271. initialize: function (applicationId
  3272. /*: string*/
  3273. , javaScriptKey
  3274. /*: string*/
  3275. ) {
  3276. if ("browser" === 'browser' && _CoreManager.default.get('IS_NODE') && !process.env.SERVER_RENDERING) {
  3277. /* eslint-disable no-console */
  3278. console.log('It looks like you\'re using the browser version of the SDK in a ' + 'node.js environment. You should require(\'parse/node\') instead.');
  3279. /* eslint-enable no-console */
  3280. }
  3281. Parse._initialize(applicationId, javaScriptKey);
  3282. },
  3283. _initialize: function (applicationId
  3284. /*: string*/
  3285. , javaScriptKey
  3286. /*: string*/
  3287. , masterKey
  3288. /*: string*/
  3289. ) {
  3290. _CoreManager.default.set('APPLICATION_ID', applicationId);
  3291. _CoreManager.default.set('JAVASCRIPT_KEY', javaScriptKey);
  3292. _CoreManager.default.set('MASTER_KEY', masterKey);
  3293. _CoreManager.default.set('USE_MASTER_KEY', false);
  3294. },
  3295. /**
  3296. * Call this method to set your AsyncStorage engine
  3297. * Starting Parse@1.11, the ParseSDK do not provide a React AsyncStorage as the ReactNative module
  3298. * is not provided at a stable path and changes over versions.
  3299. * @param {AsyncStorage} storage a react native async storage.
  3300. * @static
  3301. */
  3302. setAsyncStorage: function (storage
  3303. /*: any*/
  3304. ) {
  3305. _CoreManager.default.setAsyncStorage(storage);
  3306. },
  3307. /**
  3308. * Call this method to set your LocalDatastoreStorage engine
  3309. * If using React-Native use {@link Parse.setAsyncStorage Parse.setAsyncStorage()}
  3310. * @param {LocalDatastoreController} controller a data storage.
  3311. * @static
  3312. */
  3313. setLocalDatastoreController: function (controller
  3314. /*: any*/
  3315. ) {
  3316. _CoreManager.default.setLocalDatastoreController(controller);
  3317. }
  3318. };
  3319. /** These legacy setters may eventually be deprecated **/
  3320. /**
  3321. * @member Parse.applicationId
  3322. * @type string
  3323. * @static
  3324. */
  3325. Object.defineProperty(Parse, 'applicationId', {
  3326. get: function () {
  3327. return _CoreManager.default.get('APPLICATION_ID');
  3328. },
  3329. set: function (value) {
  3330. _CoreManager.default.set('APPLICATION_ID', value);
  3331. }
  3332. });
  3333. /**
  3334. * @member Parse.javaScriptKey
  3335. * @type string
  3336. * @static
  3337. */
  3338. Object.defineProperty(Parse, 'javaScriptKey', {
  3339. get: function () {
  3340. return _CoreManager.default.get('JAVASCRIPT_KEY');
  3341. },
  3342. set: function (value) {
  3343. _CoreManager.default.set('JAVASCRIPT_KEY', value);
  3344. }
  3345. });
  3346. /**
  3347. * @member Parse.masterKey
  3348. * @type string
  3349. * @static
  3350. */
  3351. Object.defineProperty(Parse, 'masterKey', {
  3352. get: function () {
  3353. return _CoreManager.default.get('MASTER_KEY');
  3354. },
  3355. set: function (value) {
  3356. _CoreManager.default.set('MASTER_KEY', value);
  3357. }
  3358. });
  3359. /**
  3360. * @member Parse.serverURL
  3361. * @type string
  3362. * @static
  3363. */
  3364. Object.defineProperty(Parse, 'serverURL', {
  3365. get: function () {
  3366. return _CoreManager.default.get('SERVER_URL');
  3367. },
  3368. set: function (value) {
  3369. _CoreManager.default.set('SERVER_URL', value);
  3370. }
  3371. });
  3372. /**
  3373. * @member Parse.serverAuthToken
  3374. * @type string
  3375. * @static
  3376. */
  3377. Object.defineProperty(Parse, 'serverAuthToken', {
  3378. get: function () {
  3379. return _CoreManager.default.get('SERVER_AUTH_TOKEN');
  3380. },
  3381. set: function (value) {
  3382. _CoreManager.default.set('SERVER_AUTH_TOKEN', value);
  3383. }
  3384. });
  3385. /**
  3386. * @member Parse.serverAuthType
  3387. * @type string
  3388. * @static
  3389. */
  3390. Object.defineProperty(Parse, 'serverAuthType', {
  3391. get: function () {
  3392. return _CoreManager.default.get('SERVER_AUTH_TYPE');
  3393. },
  3394. set: function (value) {
  3395. _CoreManager.default.set('SERVER_AUTH_TYPE', value);
  3396. }
  3397. });
  3398. /**
  3399. * @member Parse.liveQueryServerURL
  3400. * @type string
  3401. * @static
  3402. */
  3403. Object.defineProperty(Parse, 'liveQueryServerURL', {
  3404. get: function () {
  3405. return _CoreManager.default.get('LIVEQUERY_SERVER_URL');
  3406. },
  3407. set: function (value) {
  3408. _CoreManager.default.set('LIVEQUERY_SERVER_URL', value);
  3409. }
  3410. });
  3411. /* End setters */
  3412. Parse.ACL = _dereq_('./ParseACL').default;
  3413. Parse.Analytics = _dereq_('./Analytics');
  3414. Parse.AnonymousUtils = _dereq_('./AnonymousUtils').default;
  3415. Parse.Cloud = _dereq_('./Cloud');
  3416. Parse.CoreManager = _dereq_('./CoreManager');
  3417. Parse.Config = _dereq_('./ParseConfig').default;
  3418. Parse.Error = _dereq_('./ParseError').default;
  3419. Parse.FacebookUtils = _dereq_('./FacebookUtils').default;
  3420. Parse.File = _dereq_('./ParseFile').default;
  3421. Parse.GeoPoint = _dereq_('./ParseGeoPoint').default;
  3422. Parse.Polygon = _dereq_('./ParsePolygon').default;
  3423. Parse.Installation = _dereq_('./ParseInstallation').default;
  3424. Parse.LocalDatastore = _dereq_('./LocalDatastore');
  3425. Parse.Object = _dereq_('./ParseObject').default;
  3426. Parse.Op = {
  3427. Set: ParseOp.SetOp,
  3428. Unset: ParseOp.UnsetOp,
  3429. Increment: ParseOp.IncrementOp,
  3430. Add: ParseOp.AddOp,
  3431. Remove: ParseOp.RemoveOp,
  3432. AddUnique: ParseOp.AddUniqueOp,
  3433. Relation: ParseOp.RelationOp
  3434. };
  3435. Parse.Push = _dereq_('./Push');
  3436. Parse.Query = _dereq_('./ParseQuery').default;
  3437. Parse.Relation = _dereq_('./ParseRelation').default;
  3438. Parse.Role = _dereq_('./ParseRole').default;
  3439. Parse.Schema = _dereq_('./ParseSchema').default;
  3440. Parse.Session = _dereq_('./ParseSession').default;
  3441. Parse.Storage = _dereq_('./Storage');
  3442. Parse.User = _dereq_('./ParseUser').default;
  3443. Parse.LiveQuery = _dereq_('./ParseLiveQuery').default;
  3444. Parse.LiveQueryClient = _dereq_('./LiveQueryClient').default;
  3445. Parse._request = function () {
  3446. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3447. args[_key] = arguments[_key];
  3448. }
  3449. return _CoreManager.default.getRESTController().request.apply(null, args);
  3450. };
  3451. Parse._ajax = function () {
  3452. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  3453. args[_key2] = arguments[_key2];
  3454. }
  3455. return _CoreManager.default.getRESTController().ajax.apply(null, args);
  3456. }; // We attempt to match the signatures of the legacy versions of these methods
  3457. Parse._decode = function (_, value) {
  3458. return (0, _decode.default)(value);
  3459. };
  3460. Parse._encode = function (value, _, disallowObjects) {
  3461. return (0, _encode.default)(value, disallowObjects);
  3462. };
  3463. Parse._getInstallationId = function () {
  3464. return _CoreManager.default.getInstallationController().currentInstallationId();
  3465. };
  3466. /**
  3467. * Enable pinning in your application.
  3468. * This must be called before your application can use pinning.
  3469. *
  3470. * @static
  3471. */
  3472. Parse.enableLocalDatastore = function () {
  3473. Parse.LocalDatastore.isEnabled = true;
  3474. };
  3475. /**
  3476. * Flag that indicates whether Local Datastore is enabled.
  3477. *
  3478. * @static
  3479. */
  3480. Parse.isLocalDatastoreEnabled = function () {
  3481. return Parse.LocalDatastore.isEnabled;
  3482. };
  3483. /**
  3484. * Gets all contents from Local Datastore
  3485. *
  3486. * <pre>
  3487. * await Parse.dumpLocalDatastore();
  3488. * </pre>
  3489. *
  3490. * @static
  3491. */
  3492. Parse.dumpLocalDatastore = function () {
  3493. if (!Parse.LocalDatastore.isEnabled) {
  3494. console.log('Parse.enableLocalDatastore() must be called first'); // eslint-disable-line no-console
  3495. return Promise.resolve({});
  3496. } else {
  3497. return Parse.LocalDatastore._getAllContents();
  3498. }
  3499. };
  3500. _CoreManager.default.setInstallationController(_InstallationController.default);
  3501. _CoreManager.default.setRESTController(_RESTController.default);
  3502. // For legacy requires, of the form `var Parse = require('parse').Parse`
  3503. Parse.Parse = Parse;
  3504. module.exports = Parse;
  3505. }).call(this,_dereq_('_process'))
  3506. },{"./Analytics":1,"./AnonymousUtils":2,"./Cloud":3,"./CoreManager":4,"./FacebookUtils":6,"./InstallationController":7,"./LiveQueryClient":8,"./LocalDatastore":10,"./ParseACL":16,"./ParseConfig":17,"./ParseError":18,"./ParseFile":19,"./ParseGeoPoint":20,"./ParseInstallation":21,"./ParseLiveQuery":22,"./ParseObject":23,"./ParseOp":24,"./ParsePolygon":25,"./ParseQuery":26,"./ParseRelation":27,"./ParseRole":28,"./ParseSchema":29,"./ParseSession":30,"./ParseUser":31,"./Push":32,"./RESTController":33,"./Storage":35,"./decode":41,"./encode":42,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/interopRequireWildcard":62,"_process":77}],16:[function(_dereq_,module,exports){
  3507. "use strict";
  3508. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  3509. Object.defineProperty(exports, "__esModule", {
  3510. value: true
  3511. });
  3512. exports.default = void 0;
  3513. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  3514. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  3515. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  3516. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  3517. var _ParseRole = _interopRequireDefault(_dereq_("./ParseRole"));
  3518. var _ParseUser = _interopRequireDefault(_dereq_("./ParseUser"));
  3519. /**
  3520. * Copyright (c) 2015-present, Parse, LLC.
  3521. * All rights reserved.
  3522. *
  3523. * This source code is licensed under the BSD-style license found in the
  3524. * LICENSE file in the root directory of this source tree. An additional grant
  3525. * of patent rights can be found in the PATENTS file in the same directory.
  3526. *
  3527. * @flow
  3528. */
  3529. var PUBLIC_KEY = '*';
  3530. /**
  3531. * Creates a new ACL.
  3532. * If no argument is given, the ACL has no permissions for anyone.
  3533. * If the argument is a Parse.User, the ACL will have read and write
  3534. * permission for only that user.
  3535. * If the argument is any other JSON object, that object will be interpretted
  3536. * as a serialized ACL created with toJSON().
  3537. *
  3538. * <p>An ACL, or Access Control List can be added to any
  3539. * <code>Parse.Object</code> to restrict access to only a subset of users
  3540. * of your application.</p>
  3541. * @alias Parse.ACL
  3542. */
  3543. var ParseACL =
  3544. /*#__PURE__*/
  3545. function () {
  3546. /**
  3547. * @param {(Parse.User|Object)} user The user to initialize the ACL for
  3548. */
  3549. function ParseACL(arg1
  3550. /*: ParseUser | ByIdMap*/
  3551. ) {
  3552. (0, _classCallCheck2.default)(this, ParseACL);
  3553. (0, _defineProperty2.default)(this, "permissionsById", void 0);
  3554. this.permissionsById = {};
  3555. if (arg1 && (0, _typeof2.default)(arg1) === 'object') {
  3556. if (arg1 instanceof _ParseUser.default) {
  3557. this.setReadAccess(arg1, true);
  3558. this.setWriteAccess(arg1, true);
  3559. } else {
  3560. for (var _userId in arg1) {
  3561. var accessList = arg1[_userId];
  3562. if (typeof _userId !== 'string') {
  3563. throw new TypeError('Tried to create an ACL with an invalid user id.');
  3564. }
  3565. this.permissionsById[_userId] = {};
  3566. for (var _permission in accessList) {
  3567. var allowed = accessList[_permission];
  3568. if (_permission !== 'read' && _permission !== 'write') {
  3569. throw new TypeError('Tried to create an ACL with an invalid permission type.');
  3570. }
  3571. if (typeof allowed !== 'boolean') {
  3572. throw new TypeError('Tried to create an ACL with an invalid permission value.');
  3573. }
  3574. this.permissionsById[_userId][_permission] = allowed;
  3575. }
  3576. }
  3577. }
  3578. } else if (typeof arg1 === 'function') {
  3579. throw new TypeError('ParseACL constructed with a function. Did you forget ()?');
  3580. }
  3581. }
  3582. /**
  3583. * Returns a JSON-encoded version of the ACL.
  3584. * @return {Object}
  3585. */
  3586. (0, _createClass2.default)(ParseACL, [{
  3587. key: "toJSON",
  3588. value: function ()
  3589. /*: ByIdMap*/
  3590. {
  3591. var permissions = {};
  3592. for (var p in this.permissionsById) {
  3593. permissions[p] = this.permissionsById[p];
  3594. }
  3595. return permissions;
  3596. }
  3597. /**
  3598. * Returns whether this ACL is equal to another object
  3599. * @param other The other object to compare to
  3600. * @return {Boolean}
  3601. */
  3602. }, {
  3603. key: "equals",
  3604. value: function (other
  3605. /*: ParseACL*/
  3606. )
  3607. /*: boolean*/
  3608. {
  3609. if (!(other instanceof ParseACL)) {
  3610. return false;
  3611. }
  3612. var users = Object.keys(this.permissionsById);
  3613. var otherUsers = Object.keys(other.permissionsById);
  3614. if (users.length !== otherUsers.length) {
  3615. return false;
  3616. }
  3617. for (var u in this.permissionsById) {
  3618. if (!other.permissionsById[u]) {
  3619. return false;
  3620. }
  3621. if (this.permissionsById[u].read !== other.permissionsById[u].read) {
  3622. return false;
  3623. }
  3624. if (this.permissionsById[u].write !== other.permissionsById[u].write) {
  3625. return false;
  3626. }
  3627. }
  3628. return true;
  3629. }
  3630. }, {
  3631. key: "_setAccess",
  3632. value: function (accessType
  3633. /*: string*/
  3634. , userId
  3635. /*: ParseUser | ParseRole | string*/
  3636. , allowed
  3637. /*: boolean*/
  3638. ) {
  3639. if (userId instanceof _ParseUser.default) {
  3640. userId = userId.id;
  3641. } else if (userId instanceof _ParseRole.default) {
  3642. var name = userId.getName();
  3643. if (!name) {
  3644. throw new TypeError('Role must have a name');
  3645. }
  3646. userId = 'role:' + name;
  3647. }
  3648. if (typeof userId !== 'string') {
  3649. throw new TypeError('userId must be a string.');
  3650. }
  3651. if (typeof allowed !== 'boolean') {
  3652. throw new TypeError('allowed must be either true or false.');
  3653. }
  3654. var permissions = this.permissionsById[userId];
  3655. if (!permissions) {
  3656. if (!allowed) {
  3657. // The user already doesn't have this permission, so no action is needed
  3658. return;
  3659. } else {
  3660. permissions = {};
  3661. this.permissionsById[userId] = permissions;
  3662. }
  3663. }
  3664. if (allowed) {
  3665. this.permissionsById[userId][accessType] = true;
  3666. } else {
  3667. delete permissions[accessType];
  3668. if (Object.keys(permissions).length === 0) {
  3669. delete this.permissionsById[userId];
  3670. }
  3671. }
  3672. }
  3673. }, {
  3674. key: "_getAccess",
  3675. value: function (accessType
  3676. /*: string*/
  3677. , userId
  3678. /*: ParseUser | ParseRole | string*/
  3679. )
  3680. /*: boolean*/
  3681. {
  3682. if (userId instanceof _ParseUser.default) {
  3683. userId = userId.id;
  3684. if (!userId) {
  3685. throw new Error('Cannot get access for a ParseUser without an ID');
  3686. }
  3687. } else if (userId instanceof _ParseRole.default) {
  3688. var name = userId.getName();
  3689. if (!name) {
  3690. throw new TypeError('Role must have a name');
  3691. }
  3692. userId = 'role:' + name;
  3693. }
  3694. var permissions = this.permissionsById[userId];
  3695. if (!permissions) {
  3696. return false;
  3697. }
  3698. return !!permissions[accessType];
  3699. }
  3700. /**
  3701. * Sets whether the given user is allowed to read this object.
  3702. * @param userId An instance of Parse.User or its objectId.
  3703. * @param {Boolean} allowed Whether that user should have read access.
  3704. */
  3705. }, {
  3706. key: "setReadAccess",
  3707. value: function (userId
  3708. /*: ParseUser | ParseRole | string*/
  3709. , allowed
  3710. /*: boolean*/
  3711. ) {
  3712. this._setAccess('read', userId, allowed);
  3713. }
  3714. /**
  3715. * Get whether the given user id is *explicitly* allowed to read this object.
  3716. * Even if this returns false, the user may still be able to access it if
  3717. * getPublicReadAccess returns true or a role that the user belongs to has
  3718. * write access.
  3719. * @param userId An instance of Parse.User or its objectId, or a Parse.Role.
  3720. * @return {Boolean}
  3721. */
  3722. }, {
  3723. key: "getReadAccess",
  3724. value: function (userId
  3725. /*: ParseUser | ParseRole | string*/
  3726. )
  3727. /*: boolean*/
  3728. {
  3729. return this._getAccess('read', userId);
  3730. }
  3731. /**
  3732. * Sets whether the given user id is allowed to write this object.
  3733. * @param userId An instance of Parse.User or its objectId, or a Parse.Role..
  3734. * @param {Boolean} allowed Whether that user should have write access.
  3735. */
  3736. }, {
  3737. key: "setWriteAccess",
  3738. value: function (userId
  3739. /*: ParseUser | ParseRole | string*/
  3740. , allowed
  3741. /*: boolean*/
  3742. ) {
  3743. this._setAccess('write', userId, allowed);
  3744. }
  3745. /**
  3746. * Gets whether the given user id is *explicitly* allowed to write this object.
  3747. * Even if this returns false, the user may still be able to write it if
  3748. * getPublicWriteAccess returns true or a role that the user belongs to has
  3749. * write access.
  3750. * @param userId An instance of Parse.User or its objectId, or a Parse.Role.
  3751. * @return {Boolean}
  3752. */
  3753. }, {
  3754. key: "getWriteAccess",
  3755. value: function (userId
  3756. /*: ParseUser | ParseRole | string*/
  3757. )
  3758. /*: boolean*/
  3759. {
  3760. return this._getAccess('write', userId);
  3761. }
  3762. /**
  3763. * Sets whether the public is allowed to read this object.
  3764. * @param {Boolean} allowed
  3765. */
  3766. }, {
  3767. key: "setPublicReadAccess",
  3768. value: function (allowed
  3769. /*: boolean*/
  3770. ) {
  3771. this.setReadAccess(PUBLIC_KEY, allowed);
  3772. }
  3773. /**
  3774. * Gets whether the public is allowed to read this object.
  3775. * @return {Boolean}
  3776. */
  3777. }, {
  3778. key: "getPublicReadAccess",
  3779. value: function ()
  3780. /*: boolean*/
  3781. {
  3782. return this.getReadAccess(PUBLIC_KEY);
  3783. }
  3784. /**
  3785. * Sets whether the public is allowed to write this object.
  3786. * @param {Boolean} allowed
  3787. */
  3788. }, {
  3789. key: "setPublicWriteAccess",
  3790. value: function (allowed
  3791. /*: boolean*/
  3792. ) {
  3793. this.setWriteAccess(PUBLIC_KEY, allowed);
  3794. }
  3795. /**
  3796. * Gets whether the public is allowed to write this object.
  3797. * @return {Boolean}
  3798. */
  3799. }, {
  3800. key: "getPublicWriteAccess",
  3801. value: function ()
  3802. /*: boolean*/
  3803. {
  3804. return this.getWriteAccess(PUBLIC_KEY);
  3805. }
  3806. /**
  3807. * Gets whether users belonging to the given role are allowed
  3808. * to read this object. Even if this returns false, the role may
  3809. * still be able to write it if a parent role has read access.
  3810. *
  3811. * @param role The name of the role, or a Parse.Role object.
  3812. * @return {Boolean} true if the role has read access. false otherwise.
  3813. * @throws {TypeError} If role is neither a Parse.Role nor a String.
  3814. */
  3815. }, {
  3816. key: "getRoleReadAccess",
  3817. value: function (role
  3818. /*: ParseRole | string*/
  3819. )
  3820. /*: boolean*/
  3821. {
  3822. if (role instanceof _ParseRole.default) {
  3823. // Normalize to the String name
  3824. role = role.getName();
  3825. }
  3826. if (typeof role !== 'string') {
  3827. throw new TypeError('role must be a ParseRole or a String');
  3828. }
  3829. return this.getReadAccess('role:' + role);
  3830. }
  3831. /**
  3832. * Gets whether users belonging to the given role are allowed
  3833. * to write this object. Even if this returns false, the role may
  3834. * still be able to write it if a parent role has write access.
  3835. *
  3836. * @param role The name of the role, or a Parse.Role object.
  3837. * @return {Boolean} true if the role has write access. false otherwise.
  3838. * @throws {TypeError} If role is neither a Parse.Role nor a String.
  3839. */
  3840. }, {
  3841. key: "getRoleWriteAccess",
  3842. value: function (role
  3843. /*: ParseRole | string*/
  3844. )
  3845. /*: boolean*/
  3846. {
  3847. if (role instanceof _ParseRole.default) {
  3848. // Normalize to the String name
  3849. role = role.getName();
  3850. }
  3851. if (typeof role !== 'string') {
  3852. throw new TypeError('role must be a ParseRole or a String');
  3853. }
  3854. return this.getWriteAccess('role:' + role);
  3855. }
  3856. /**
  3857. * Sets whether users belonging to the given role are allowed
  3858. * to read this object.
  3859. *
  3860. * @param role The name of the role, or a Parse.Role object.
  3861. * @param {Boolean} allowed Whether the given role can read this object.
  3862. * @throws {TypeError} If role is neither a Parse.Role nor a String.
  3863. */
  3864. }, {
  3865. key: "setRoleReadAccess",
  3866. value: function (role
  3867. /*: ParseRole | string*/
  3868. , allowed
  3869. /*: boolean*/
  3870. ) {
  3871. if (role instanceof _ParseRole.default) {
  3872. // Normalize to the String name
  3873. role = role.getName();
  3874. }
  3875. if (typeof role !== 'string') {
  3876. throw new TypeError('role must be a ParseRole or a String');
  3877. }
  3878. this.setReadAccess('role:' + role, allowed);
  3879. }
  3880. /**
  3881. * Sets whether users belonging to the given role are allowed
  3882. * to write this object.
  3883. *
  3884. * @param role The name of the role, or a Parse.Role object.
  3885. * @param {Boolean} allowed Whether the given role can write this object.
  3886. * @throws {TypeError} If role is neither a Parse.Role nor a String.
  3887. */
  3888. }, {
  3889. key: "setRoleWriteAccess",
  3890. value: function (role
  3891. /*: ParseRole | string*/
  3892. , allowed
  3893. /*: boolean*/
  3894. ) {
  3895. if (role instanceof _ParseRole.default) {
  3896. // Normalize to the String name
  3897. role = role.getName();
  3898. }
  3899. if (typeof role !== 'string') {
  3900. throw new TypeError('role must be a ParseRole or a String');
  3901. }
  3902. this.setWriteAccess('role:' + role, allowed);
  3903. }
  3904. }]);
  3905. return ParseACL;
  3906. }();
  3907. var _default = ParseACL;
  3908. exports.default = _default;
  3909. },{"./ParseRole":28,"./ParseUser":31,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],17:[function(_dereq_,module,exports){
  3910. "use strict";
  3911. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  3912. Object.defineProperty(exports, "__esModule", {
  3913. value: true
  3914. });
  3915. exports.default = void 0;
  3916. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  3917. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  3918. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  3919. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  3920. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  3921. var _decode = _interopRequireDefault(_dereq_("./decode"));
  3922. var _encode = _interopRequireDefault(_dereq_("./encode"));
  3923. var _escape2 = _interopRequireDefault(_dereq_("./escape"));
  3924. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  3925. var _Storage = _interopRequireDefault(_dereq_("./Storage"));
  3926. /**
  3927. * Copyright (c) 2015-present, Parse, LLC.
  3928. * All rights reserved.
  3929. *
  3930. * This source code is licensed under the BSD-style license found in the
  3931. * LICENSE file in the root directory of this source tree. An additional grant
  3932. * of patent rights can be found in the PATENTS file in the same directory.
  3933. *
  3934. * @flow
  3935. */
  3936. /**
  3937. * Parse.Config is a local representation of configuration data that
  3938. * can be set from the Parse dashboard.
  3939. *
  3940. * @alias Parse.Config
  3941. */
  3942. var ParseConfig =
  3943. /*#__PURE__*/
  3944. function () {
  3945. function ParseConfig() {
  3946. (0, _classCallCheck2.default)(this, ParseConfig);
  3947. (0, _defineProperty2.default)(this, "attributes", void 0);
  3948. (0, _defineProperty2.default)(this, "_escapedAttributes", void 0);
  3949. this.attributes = {};
  3950. this._escapedAttributes = {};
  3951. }
  3952. /**
  3953. * Gets the value of an attribute.
  3954. * @param {String} attr The name of an attribute.
  3955. */
  3956. (0, _createClass2.default)(ParseConfig, [{
  3957. key: "get",
  3958. value: function (attr
  3959. /*: string*/
  3960. )
  3961. /*: any*/
  3962. {
  3963. return this.attributes[attr];
  3964. }
  3965. /**
  3966. * Gets the HTML-escaped value of an attribute.
  3967. * @param {String} attr The name of an attribute.
  3968. */
  3969. }, {
  3970. key: "escape",
  3971. value: function (attr
  3972. /*: string*/
  3973. )
  3974. /*: string*/
  3975. {
  3976. var html = this._escapedAttributes[attr];
  3977. if (html) {
  3978. return html;
  3979. }
  3980. var val = this.attributes[attr];
  3981. var escaped = '';
  3982. if (val != null) {
  3983. escaped = (0, _escape2.default)(val.toString());
  3984. }
  3985. this._escapedAttributes[attr] = escaped;
  3986. return escaped;
  3987. }
  3988. /**
  3989. * Retrieves the most recently-fetched configuration object, either from
  3990. * memory or from local storage if necessary.
  3991. *
  3992. * @static
  3993. * @return {Config} The most recently-fetched Parse.Config if it
  3994. * exists, else an empty Parse.Config.
  3995. */
  3996. }], [{
  3997. key: "current",
  3998. value: function () {
  3999. var controller = _CoreManager.default.getConfigController();
  4000. return controller.current();
  4001. }
  4002. /**
  4003. * Gets a new configuration object from the server.
  4004. * @static
  4005. * @return {Promise} A promise that is resolved with a newly-created
  4006. * configuration object when the get completes.
  4007. */
  4008. }, {
  4009. key: "get",
  4010. value: function () {
  4011. var controller = _CoreManager.default.getConfigController();
  4012. return controller.get();
  4013. }
  4014. /**
  4015. * Save value keys to the server.
  4016. * @static
  4017. * @return {Promise} A promise that is resolved with a newly-created
  4018. * configuration object or with the current with the update.
  4019. */
  4020. }, {
  4021. key: "save",
  4022. value: function (attrs
  4023. /*: { [key: string]: any }*/
  4024. ) {
  4025. var controller = _CoreManager.default.getConfigController(); //To avoid a mismatch with the local and the cloud config we get a new version
  4026. return controller.save(attrs).then(function () {
  4027. return controller.get();
  4028. }, function (error) {
  4029. return Promise.reject(error);
  4030. });
  4031. }
  4032. }]);
  4033. return ParseConfig;
  4034. }();
  4035. var currentConfig = null;
  4036. var CURRENT_CONFIG_KEY = 'currentConfig';
  4037. function decodePayload(data) {
  4038. try {
  4039. var json = JSON.parse(data);
  4040. if (json && (0, _typeof2.default)(json) === 'object') {
  4041. return (0, _decode.default)(json);
  4042. }
  4043. } catch (e) {
  4044. return null;
  4045. }
  4046. }
  4047. var DefaultController = {
  4048. current: function () {
  4049. if (currentConfig) {
  4050. return currentConfig;
  4051. }
  4052. var config = new ParseConfig();
  4053. var storagePath = _Storage.default.generatePath(CURRENT_CONFIG_KEY);
  4054. var configData;
  4055. if (!_Storage.default.async()) {
  4056. configData = _Storage.default.getItem(storagePath);
  4057. if (configData) {
  4058. var attributes = decodePayload(configData);
  4059. if (attributes) {
  4060. config.attributes = attributes;
  4061. currentConfig = config;
  4062. }
  4063. }
  4064. return config;
  4065. } // Return a promise for async storage controllers
  4066. return _Storage.default.getItemAsync(storagePath).then(function (configData) {
  4067. if (configData) {
  4068. var _attributes = decodePayload(configData);
  4069. if (_attributes) {
  4070. config.attributes = _attributes;
  4071. currentConfig = config;
  4072. }
  4073. }
  4074. return config;
  4075. });
  4076. },
  4077. get: function () {
  4078. var RESTController = _CoreManager.default.getRESTController();
  4079. return RESTController.request('GET', 'config', {}, {}).then(function (response) {
  4080. if (!response || !response.params) {
  4081. var error = new _ParseError.default(_ParseError.default.INVALID_JSON, 'Config JSON response invalid.');
  4082. return Promise.reject(error);
  4083. }
  4084. var config = new ParseConfig();
  4085. config.attributes = {};
  4086. for (var attr in response.params) {
  4087. config.attributes[attr] = (0, _decode.default)(response.params[attr]);
  4088. }
  4089. currentConfig = config;
  4090. return _Storage.default.setItemAsync(_Storage.default.generatePath(CURRENT_CONFIG_KEY), JSON.stringify(response.params)).then(function () {
  4091. return config;
  4092. });
  4093. });
  4094. },
  4095. save: function (attrs
  4096. /*: { [key: string]: any }*/
  4097. ) {
  4098. var RESTController = _CoreManager.default.getRESTController();
  4099. var encodedAttrs = {};
  4100. for (var _key in attrs) {
  4101. encodedAttrs[_key] = (0, _encode.default)(attrs[_key]);
  4102. }
  4103. return RESTController.request('PUT', 'config', {
  4104. params: encodedAttrs
  4105. }, {
  4106. useMasterKey: true
  4107. }).then(function (response) {
  4108. if (response && response.result) {
  4109. return Promise.resolve();
  4110. } else {
  4111. var error = new _ParseError.default(_ParseError.default.INTERNAL_SERVER_ERROR, 'Error occured updating Config.');
  4112. return Promise.reject(error);
  4113. }
  4114. });
  4115. }
  4116. };
  4117. _CoreManager.default.setConfigController(DefaultController);
  4118. var _default = ParseConfig;
  4119. exports.default = _default;
  4120. },{"./CoreManager":4,"./ParseError":18,"./Storage":35,"./decode":41,"./encode":42,"./escape":44,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],18:[function(_dereq_,module,exports){
  4121. "use strict";
  4122. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  4123. Object.defineProperty(exports, "__esModule", {
  4124. value: true
  4125. });
  4126. exports.default = void 0;
  4127. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  4128. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  4129. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  4130. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  4131. var _assertThisInitialized2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/assertThisInitialized"));
  4132. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  4133. var _wrapNativeSuper2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/wrapNativeSuper"));
  4134. /**
  4135. * Copyright (c) 2015-present, Parse, LLC.
  4136. * All rights reserved.
  4137. *
  4138. * This source code is licensed under the BSD-style license found in the
  4139. * LICENSE file in the root directory of this source tree. An additional grant
  4140. * of patent rights can be found in the PATENTS file in the same directory.
  4141. */
  4142. /**
  4143. * Constructs a new Parse.Error object with the given code and message.
  4144. * @alias Parse.Error
  4145. */
  4146. var ParseError =
  4147. /*#__PURE__*/
  4148. function (_Error) {
  4149. (0, _inherits2.default)(ParseError, _Error);
  4150. /**
  4151. * @param {Number} code An error code constant from <code>Parse.Error</code>.
  4152. * @param {String} message A detailed description of the error.
  4153. */
  4154. function ParseError(code, message) {
  4155. var _this;
  4156. (0, _classCallCheck2.default)(this, ParseError);
  4157. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(ParseError).call(this, message));
  4158. _this.code = code;
  4159. Object.defineProperty((0, _assertThisInitialized2.default)(_this), 'message', {
  4160. enumerable: true,
  4161. value: message
  4162. });
  4163. return _this;
  4164. }
  4165. (0, _createClass2.default)(ParseError, [{
  4166. key: "toString",
  4167. value: function () {
  4168. return 'ParseError: ' + this.code + ' ' + this.message;
  4169. }
  4170. }]);
  4171. return ParseError;
  4172. }((0, _wrapNativeSuper2.default)(Error));
  4173. /**
  4174. * Error code indicating some error other than those enumerated here.
  4175. * @property OTHER_CAUSE
  4176. * @static
  4177. * @final
  4178. */
  4179. ParseError.OTHER_CAUSE = -1;
  4180. /**
  4181. * Error code indicating that something has gone wrong with the server.
  4182. * If you get this error code, it is Parse's fault. Contact us at
  4183. * https://parse.com/help
  4184. * @property INTERNAL_SERVER_ERROR
  4185. * @static
  4186. * @final
  4187. */
  4188. ParseError.INTERNAL_SERVER_ERROR = 1;
  4189. /**
  4190. * Error code indicating the connection to the Parse servers failed.
  4191. * @property CONNECTION_FAILED
  4192. * @static
  4193. * @final
  4194. */
  4195. ParseError.CONNECTION_FAILED = 100;
  4196. /**
  4197. * Error code indicating the specified object doesn't exist.
  4198. * @property OBJECT_NOT_FOUND
  4199. * @static
  4200. * @final
  4201. */
  4202. ParseError.OBJECT_NOT_FOUND = 101;
  4203. /**
  4204. * Error code indicating you tried to query with a datatype that doesn't
  4205. * support it, like exact matching an array or object.
  4206. * @property INVALID_QUERY
  4207. * @static
  4208. * @final
  4209. */
  4210. ParseError.INVALID_QUERY = 102;
  4211. /**
  4212. * Error code indicating a missing or invalid classname. Classnames are
  4213. * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the
  4214. * only valid characters.
  4215. * @property INVALID_CLASS_NAME
  4216. * @static
  4217. * @final
  4218. */
  4219. ParseError.INVALID_CLASS_NAME = 103;
  4220. /**
  4221. * Error code indicating an unspecified object id.
  4222. * @property MISSING_OBJECT_ID
  4223. * @static
  4224. * @final
  4225. */
  4226. ParseError.MISSING_OBJECT_ID = 104;
  4227. /**
  4228. * Error code indicating an invalid key name. Keys are case-sensitive. They
  4229. * must start with a letter, and a-zA-Z0-9_ are the only valid characters.
  4230. * @property INVALID_KEY_NAME
  4231. * @static
  4232. * @final
  4233. */
  4234. ParseError.INVALID_KEY_NAME = 105;
  4235. /**
  4236. * Error code indicating a malformed pointer. You should not see this unless
  4237. * you have been mucking about changing internal Parse code.
  4238. * @property INVALID_POINTER
  4239. * @static
  4240. * @final
  4241. */
  4242. ParseError.INVALID_POINTER = 106;
  4243. /**
  4244. * Error code indicating that badly formed JSON was received upstream. This
  4245. * either indicates you have done something unusual with modifying how
  4246. * things encode to JSON, or the network is failing badly.
  4247. * @property INVALID_JSON
  4248. * @static
  4249. * @final
  4250. */
  4251. ParseError.INVALID_JSON = 107;
  4252. /**
  4253. * Error code indicating that the feature you tried to access is only
  4254. * available internally for testing purposes.
  4255. * @property COMMAND_UNAVAILABLE
  4256. * @static
  4257. * @final
  4258. */
  4259. ParseError.COMMAND_UNAVAILABLE = 108;
  4260. /**
  4261. * You must call Parse.initialize before using the Parse library.
  4262. * @property NOT_INITIALIZED
  4263. * @static
  4264. * @final
  4265. */
  4266. ParseError.NOT_INITIALIZED = 109;
  4267. /**
  4268. * Error code indicating that a field was set to an inconsistent type.
  4269. * @property INCORRECT_TYPE
  4270. * @static
  4271. * @final
  4272. */
  4273. ParseError.INCORRECT_TYPE = 111;
  4274. /**
  4275. * Error code indicating an invalid channel name. A channel name is either
  4276. * an empty string (the broadcast channel) or contains only a-zA-Z0-9_
  4277. * characters and starts with a letter.
  4278. * @property INVALID_CHANNEL_NAME
  4279. * @static
  4280. * @final
  4281. */
  4282. ParseError.INVALID_CHANNEL_NAME = 112;
  4283. /**
  4284. * Error code indicating that push is misconfigured.
  4285. * @property PUSH_MISCONFIGURED
  4286. * @static
  4287. * @final
  4288. */
  4289. ParseError.PUSH_MISCONFIGURED = 115;
  4290. /**
  4291. * Error code indicating that the object is too large.
  4292. * @property OBJECT_TOO_LARGE
  4293. * @static
  4294. * @final
  4295. */
  4296. ParseError.OBJECT_TOO_LARGE = 116;
  4297. /**
  4298. * Error code indicating that the operation isn't allowed for clients.
  4299. * @property OPERATION_FORBIDDEN
  4300. * @static
  4301. * @final
  4302. */
  4303. ParseError.OPERATION_FORBIDDEN = 119;
  4304. /**
  4305. * Error code indicating the result was not found in the cache.
  4306. * @property CACHE_MISS
  4307. * @static
  4308. * @final
  4309. */
  4310. ParseError.CACHE_MISS = 120;
  4311. /**
  4312. * Error code indicating that an invalid key was used in a nested
  4313. * JSONObject.
  4314. * @property INVALID_NESTED_KEY
  4315. * @static
  4316. * @final
  4317. */
  4318. ParseError.INVALID_NESTED_KEY = 121;
  4319. /**
  4320. * Error code indicating that an invalid filename was used for ParseFile.
  4321. * A valid file name contains only a-zA-Z0-9_. characters and is between 1
  4322. * and 128 characters.
  4323. * @property INVALID_FILE_NAME
  4324. * @static
  4325. * @final
  4326. */
  4327. ParseError.INVALID_FILE_NAME = 122;
  4328. /**
  4329. * Error code indicating an invalid ACL was provided.
  4330. * @property INVALID_ACL
  4331. * @static
  4332. * @final
  4333. */
  4334. ParseError.INVALID_ACL = 123;
  4335. /**
  4336. * Error code indicating that the request timed out on the server. Typically
  4337. * this indicates that the request is too expensive to run.
  4338. * @property TIMEOUT
  4339. * @static
  4340. * @final
  4341. */
  4342. ParseError.TIMEOUT = 124;
  4343. /**
  4344. * Error code indicating that the email address was invalid.
  4345. * @property INVALID_EMAIL_ADDRESS
  4346. * @static
  4347. * @final
  4348. */
  4349. ParseError.INVALID_EMAIL_ADDRESS = 125;
  4350. /**
  4351. * Error code indicating a missing content type.
  4352. * @property MISSING_CONTENT_TYPE
  4353. * @static
  4354. * @final
  4355. */
  4356. ParseError.MISSING_CONTENT_TYPE = 126;
  4357. /**
  4358. * Error code indicating a missing content length.
  4359. * @property MISSING_CONTENT_LENGTH
  4360. * @static
  4361. * @final
  4362. */
  4363. ParseError.MISSING_CONTENT_LENGTH = 127;
  4364. /**
  4365. * Error code indicating an invalid content length.
  4366. * @property INVALID_CONTENT_LENGTH
  4367. * @static
  4368. * @final
  4369. */
  4370. ParseError.INVALID_CONTENT_LENGTH = 128;
  4371. /**
  4372. * Error code indicating a file that was too large.
  4373. * @property FILE_TOO_LARGE
  4374. * @static
  4375. * @final
  4376. */
  4377. ParseError.FILE_TOO_LARGE = 129;
  4378. /**
  4379. * Error code indicating an error saving a file.
  4380. * @property FILE_SAVE_ERROR
  4381. * @static
  4382. * @final
  4383. */
  4384. ParseError.FILE_SAVE_ERROR = 130;
  4385. /**
  4386. * Error code indicating that a unique field was given a value that is
  4387. * already taken.
  4388. * @property DUPLICATE_VALUE
  4389. * @static
  4390. * @final
  4391. */
  4392. ParseError.DUPLICATE_VALUE = 137;
  4393. /**
  4394. * Error code indicating that a role's name is invalid.
  4395. * @property INVALID_ROLE_NAME
  4396. * @static
  4397. * @final
  4398. */
  4399. ParseError.INVALID_ROLE_NAME = 139;
  4400. /**
  4401. * Error code indicating that an application quota was exceeded. Upgrade to
  4402. * resolve.
  4403. * @property EXCEEDED_QUOTA
  4404. * @static
  4405. * @final
  4406. */
  4407. ParseError.EXCEEDED_QUOTA = 140;
  4408. /**
  4409. * Error code indicating that a Cloud Code script failed.
  4410. * @property SCRIPT_FAILED
  4411. * @static
  4412. * @final
  4413. */
  4414. ParseError.SCRIPT_FAILED = 141;
  4415. /**
  4416. * Error code indicating that a Cloud Code validation failed.
  4417. * @property VALIDATION_ERROR
  4418. * @static
  4419. * @final
  4420. */
  4421. ParseError.VALIDATION_ERROR = 142;
  4422. /**
  4423. * Error code indicating that invalid image data was provided.
  4424. * @property INVALID_IMAGE_DATA
  4425. * @static
  4426. * @final
  4427. */
  4428. ParseError.INVALID_IMAGE_DATA = 143;
  4429. /**
  4430. * Error code indicating an unsaved file.
  4431. * @property UNSAVED_FILE_ERROR
  4432. * @static
  4433. * @final
  4434. */
  4435. ParseError.UNSAVED_FILE_ERROR = 151;
  4436. /**
  4437. * Error code indicating an invalid push time.
  4438. * @property INVALID_PUSH_TIME_ERROR
  4439. * @static
  4440. * @final
  4441. */
  4442. ParseError.INVALID_PUSH_TIME_ERROR = 152;
  4443. /**
  4444. * Error code indicating an error deleting a file.
  4445. * @property FILE_DELETE_ERROR
  4446. * @static
  4447. * @final
  4448. */
  4449. ParseError.FILE_DELETE_ERROR = 153;
  4450. /**
  4451. * Error code indicating that the application has exceeded its request
  4452. * limit.
  4453. * @property REQUEST_LIMIT_EXCEEDED
  4454. * @static
  4455. * @final
  4456. */
  4457. ParseError.REQUEST_LIMIT_EXCEEDED = 155;
  4458. /**
  4459. * Error code indicating an invalid event name.
  4460. * @property INVALID_EVENT_NAME
  4461. * @static
  4462. * @final
  4463. */
  4464. ParseError.INVALID_EVENT_NAME = 160;
  4465. /**
  4466. * Error code indicating that the username is missing or empty.
  4467. * @property USERNAME_MISSING
  4468. * @static
  4469. * @final
  4470. */
  4471. ParseError.USERNAME_MISSING = 200;
  4472. /**
  4473. * Error code indicating that the password is missing or empty.
  4474. * @property PASSWORD_MISSING
  4475. * @static
  4476. * @final
  4477. */
  4478. ParseError.PASSWORD_MISSING = 201;
  4479. /**
  4480. * Error code indicating that the username has already been taken.
  4481. * @property USERNAME_TAKEN
  4482. * @static
  4483. * @final
  4484. */
  4485. ParseError.USERNAME_TAKEN = 202;
  4486. /**
  4487. * Error code indicating that the email has already been taken.
  4488. * @property EMAIL_TAKEN
  4489. * @static
  4490. * @final
  4491. */
  4492. ParseError.EMAIL_TAKEN = 203;
  4493. /**
  4494. * Error code indicating that the email is missing, but must be specified.
  4495. * @property EMAIL_MISSING
  4496. * @static
  4497. * @final
  4498. */
  4499. ParseError.EMAIL_MISSING = 204;
  4500. /**
  4501. * Error code indicating that a user with the specified email was not found.
  4502. * @property EMAIL_NOT_FOUND
  4503. * @static
  4504. * @final
  4505. */
  4506. ParseError.EMAIL_NOT_FOUND = 205;
  4507. /**
  4508. * Error code indicating that a user object without a valid session could
  4509. * not be altered.
  4510. * @property SESSION_MISSING
  4511. * @static
  4512. * @final
  4513. */
  4514. ParseError.SESSION_MISSING = 206;
  4515. /**
  4516. * Error code indicating that a user can only be created through signup.
  4517. * @property MUST_CREATE_USER_THROUGH_SIGNUP
  4518. * @static
  4519. * @final
  4520. */
  4521. ParseError.MUST_CREATE_USER_THROUGH_SIGNUP = 207;
  4522. /**
  4523. * Error code indicating that an an account being linked is already linked
  4524. * to another user.
  4525. * @property ACCOUNT_ALREADY_LINKED
  4526. * @static
  4527. * @final
  4528. */
  4529. ParseError.ACCOUNT_ALREADY_LINKED = 208;
  4530. /**
  4531. * Error code indicating that the current session token is invalid.
  4532. * @property INVALID_SESSION_TOKEN
  4533. * @static
  4534. * @final
  4535. */
  4536. ParseError.INVALID_SESSION_TOKEN = 209;
  4537. /**
  4538. * Error code indicating that a user cannot be linked to an account because
  4539. * that account's id could not be found.
  4540. * @property LINKED_ID_MISSING
  4541. * @static
  4542. * @final
  4543. */
  4544. ParseError.LINKED_ID_MISSING = 250;
  4545. /**
  4546. * Error code indicating that a user with a linked (e.g. Facebook) account
  4547. * has an invalid session.
  4548. * @property INVALID_LINKED_SESSION
  4549. * @static
  4550. * @final
  4551. */
  4552. ParseError.INVALID_LINKED_SESSION = 251;
  4553. /**
  4554. * Error code indicating that a service being linked (e.g. Facebook or
  4555. * Twitter) is unsupported.
  4556. * @property UNSUPPORTED_SERVICE
  4557. * @static
  4558. * @final
  4559. */
  4560. ParseError.UNSUPPORTED_SERVICE = 252;
  4561. /**
  4562. * Error code indicating an invalid operation occured on schema
  4563. * @property INVALID_SCHEMA_OPERATION
  4564. * @static
  4565. * @final
  4566. */
  4567. ParseError.INVALID_SCHEMA_OPERATION = 255;
  4568. /**
  4569. * Error code indicating that there were multiple errors. Aggregate errors
  4570. * have an "errors" property, which is an array of error objects with more
  4571. * detail about each error that occurred.
  4572. * @property AGGREGATE_ERROR
  4573. * @static
  4574. * @final
  4575. */
  4576. ParseError.AGGREGATE_ERROR = 600;
  4577. /**
  4578. * Error code indicating the client was unable to read an input file.
  4579. * @property FILE_READ_ERROR
  4580. * @static
  4581. * @final
  4582. */
  4583. ParseError.FILE_READ_ERROR = 601;
  4584. /**
  4585. * Error code indicating a real error code is unavailable because
  4586. * we had to use an XDomainRequest object to allow CORS requests in
  4587. * Internet Explorer, which strips the body from HTTP responses that have
  4588. * a non-2XX status code.
  4589. * @property X_DOMAIN_REQUEST
  4590. * @static
  4591. * @final
  4592. */
  4593. ParseError.X_DOMAIN_REQUEST = 602;
  4594. var _default = ParseError;
  4595. exports.default = _default;
  4596. },{"@babel/runtime/helpers/assertThisInitialized":52,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/getPrototypeOf":59,"@babel/runtime/helpers/inherits":60,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/possibleConstructorReturn":68,"@babel/runtime/helpers/wrapNativeSuper":74}],19:[function(_dereq_,module,exports){
  4597. "use strict";
  4598. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  4599. Object.defineProperty(exports, "__esModule", {
  4600. value: true
  4601. });
  4602. exports.default = void 0;
  4603. var _regenerator = _interopRequireDefault(_dereq_("@babel/runtime/regenerator"));
  4604. var _asyncToGenerator2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/asyncToGenerator"));
  4605. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  4606. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  4607. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  4608. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  4609. /**
  4610. * Copyright (c) 2015-present, Parse, LLC.
  4611. * All rights reserved.
  4612. *
  4613. * This source code is licensed under the BSD-style license found in the
  4614. * LICENSE file in the root directory of this source tree. An additional grant
  4615. * of patent rights can be found in the PATENTS file in the same directory.
  4616. *
  4617. * @flow
  4618. */
  4619. /* global XMLHttpRequest, Blob */
  4620. var XHR = null;
  4621. if (typeof XMLHttpRequest !== 'undefined') {
  4622. XHR = XMLHttpRequest;
  4623. }
  4624. /*:: type Base64 = { base64: string };*/
  4625. /*:: type Uri = { uri: string };*/
  4626. /*:: type FileData = Array<number> | Base64 | Blob | Uri;*/
  4627. /*:: export type FileSource = {
  4628. format: 'file';
  4629. file: Blob;
  4630. type: string
  4631. } | {
  4632. format: 'base64';
  4633. base64: string;
  4634. type: string
  4635. } | {
  4636. format: 'uri';
  4637. uri: string;
  4638. type: string
  4639. };*/
  4640. var dataUriRegexp = /^data:([a-zA-Z]+\/[-a-zA-Z0-9+.]+)(;charset=[a-zA-Z0-9\-\/]*)?;base64,/;
  4641. function b64Digit(number
  4642. /*: number*/
  4643. )
  4644. /*: string*/
  4645. {
  4646. if (number < 26) {
  4647. return String.fromCharCode(65 + number);
  4648. }
  4649. if (number < 52) {
  4650. return String.fromCharCode(97 + (number - 26));
  4651. }
  4652. if (number < 62) {
  4653. return String.fromCharCode(48 + (number - 52));
  4654. }
  4655. if (number === 62) {
  4656. return '+';
  4657. }
  4658. if (number === 63) {
  4659. return '/';
  4660. }
  4661. throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
  4662. }
  4663. /**
  4664. * A Parse.File is a local representation of a file that is saved to the Parse
  4665. * cloud.
  4666. * @alias Parse.File
  4667. */
  4668. var ParseFile =
  4669. /*#__PURE__*/
  4670. function () {
  4671. /**
  4672. * @param name {String} The file's name. This will be prefixed by a unique
  4673. * value once the file has finished saving. The file name must begin with
  4674. * an alphanumeric character, and consist of alphanumeric characters,
  4675. * periods, spaces, underscores, or dashes.
  4676. * @param data {Array} The data for the file, as either:
  4677. * 1. an Array of byte value Numbers, or
  4678. * 2. an Object like { base64: "..." } with a base64-encoded String.
  4679. * 3. an Object like { uri: "..." } with a uri String.
  4680. * 4. a File object selected with a file upload control. (3) only works
  4681. * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
  4682. * For example:
  4683. * <pre>
  4684. * var fileUploadControl = $("#profilePhotoFileUpload")[0];
  4685. * if (fileUploadControl.files.length > 0) {
  4686. * var file = fileUploadControl.files[0];
  4687. * var name = "photo.jpg";
  4688. * var parseFile = new Parse.File(name, file);
  4689. * parseFile.save().then(function() {
  4690. * // The file has been saved to Parse.
  4691. * }, function(error) {
  4692. * // The file either could not be read, or could not be saved to Parse.
  4693. * });
  4694. * }</pre>
  4695. * @param type {String} Optional Content-Type header to use for the file. If
  4696. * this is omitted, the content type will be inferred from the name's
  4697. * extension.
  4698. */
  4699. function ParseFile(name
  4700. /*: string*/
  4701. , data
  4702. /*:: ?: FileData*/
  4703. , type
  4704. /*:: ?: string*/
  4705. ) {
  4706. (0, _classCallCheck2.default)(this, ParseFile);
  4707. (0, _defineProperty2.default)(this, "_name", void 0);
  4708. (0, _defineProperty2.default)(this, "_url", void 0);
  4709. (0, _defineProperty2.default)(this, "_source", void 0);
  4710. (0, _defineProperty2.default)(this, "_previousSave", void 0);
  4711. (0, _defineProperty2.default)(this, "_data", void 0);
  4712. var specifiedType = type || '';
  4713. this._name = name;
  4714. if (data !== undefined) {
  4715. if (Array.isArray(data)) {
  4716. this._data = ParseFile.encodeBase64(data);
  4717. this._source = {
  4718. format: 'base64',
  4719. base64: this._data,
  4720. type: specifiedType
  4721. };
  4722. } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
  4723. this._source = {
  4724. format: 'file',
  4725. file: data,
  4726. type: specifiedType
  4727. };
  4728. } else if (data && typeof data.uri === 'string' && data.uri !== undefined) {
  4729. this._source = {
  4730. format: 'uri',
  4731. uri: data.uri,
  4732. type: specifiedType
  4733. };
  4734. } else if (data && typeof data.base64 === 'string') {
  4735. var base64 = data.base64;
  4736. var commaIndex = base64.indexOf(',');
  4737. if (commaIndex !== -1) {
  4738. var matches = dataUriRegexp.exec(base64.slice(0, commaIndex + 1)); // if data URI with type and charset, there will be 4 matches.
  4739. this._data = base64.slice(commaIndex + 1);
  4740. this._source = {
  4741. format: 'base64',
  4742. base64: this._data,
  4743. type: matches[1]
  4744. };
  4745. } else {
  4746. this._data = base64;
  4747. this._source = {
  4748. format: 'base64',
  4749. base64: base64,
  4750. type: specifiedType
  4751. };
  4752. }
  4753. } else {
  4754. throw new TypeError('Cannot create a Parse.File with that data.');
  4755. }
  4756. }
  4757. }
  4758. /**
  4759. * Return the data for the file, downloading it if not already present.
  4760. * Data is present if initialized with Byte Array, Base64 or Saved with Uri.
  4761. * Data is cleared if saved with File object selected with a file upload control
  4762. *
  4763. * @return {Promise} Promise that is resolve with base64 data
  4764. */
  4765. (0, _createClass2.default)(ParseFile, [{
  4766. key: "getData",
  4767. value: function () {
  4768. var _getData = (0, _asyncToGenerator2.default)(
  4769. /*#__PURE__*/
  4770. _regenerator.default.mark(function _callee() {
  4771. var controller, result;
  4772. return _regenerator.default.wrap(function (_context) {
  4773. while (1) {
  4774. switch (_context.prev = _context.next) {
  4775. case 0:
  4776. if (!this._data) {
  4777. _context.next = 2;
  4778. break;
  4779. }
  4780. return _context.abrupt("return", this._data);
  4781. case 2:
  4782. if (this._url) {
  4783. _context.next = 4;
  4784. break;
  4785. }
  4786. throw new Error('Cannot retrieve data for unsaved ParseFile.');
  4787. case 4:
  4788. controller = _CoreManager.default.getFileController();
  4789. _context.next = 7;
  4790. return controller.download(this._url);
  4791. case 7:
  4792. result = _context.sent;
  4793. this._data = result.base64;
  4794. return _context.abrupt("return", this._data);
  4795. case 10:
  4796. case "end":
  4797. return _context.stop();
  4798. }
  4799. }
  4800. }, _callee, this);
  4801. }));
  4802. return function () {
  4803. return _getData.apply(this, arguments);
  4804. };
  4805. }()
  4806. /**
  4807. * Gets the name of the file. Before save is called, this is the filename
  4808. * given by the user. After save is called, that name gets prefixed with a
  4809. * unique identifier.
  4810. * @return {String}
  4811. */
  4812. }, {
  4813. key: "name",
  4814. value: function ()
  4815. /*: string*/
  4816. {
  4817. return this._name;
  4818. }
  4819. /**
  4820. * Gets the url of the file. It is only available after you save the file or
  4821. * after you get the file from a Parse.Object.
  4822. * @param {Object} options An object to specify url options
  4823. * @return {String}
  4824. */
  4825. }, {
  4826. key: "url",
  4827. value: function (options
  4828. /*:: ?: { forceSecure?: boolean }*/
  4829. )
  4830. /*: ?string*/
  4831. {
  4832. options = options || {};
  4833. if (!this._url) {
  4834. return;
  4835. }
  4836. if (options.forceSecure) {
  4837. return this._url.replace(/^http:\/\//i, 'https://');
  4838. } else {
  4839. return this._url;
  4840. }
  4841. }
  4842. /**
  4843. * Saves the file to the Parse cloud.
  4844. * @param {Object} options
  4845. * * Valid options are:<ul>
  4846. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  4847. * be used for this request.
  4848. * <li>progress: In Browser only, callback for upload progress
  4849. * </ul>
  4850. * @return {Promise} Promise that is resolved when the save finishes.
  4851. */
  4852. }, {
  4853. key: "save",
  4854. value: function (options
  4855. /*:: ?: FullOptions*/
  4856. ) {
  4857. var _this = this;
  4858. options = options || {};
  4859. var controller = _CoreManager.default.getFileController();
  4860. if (!this._previousSave) {
  4861. if (this._source.format === 'file') {
  4862. this._previousSave = controller.saveFile(this._name, this._source, options).then(function (res) {
  4863. _this._name = res.name;
  4864. _this._url = res.url;
  4865. _this._data = null;
  4866. return _this;
  4867. });
  4868. } else if (this._source.format === 'uri') {
  4869. this._previousSave = controller.download(this._source.uri).then(function (result) {
  4870. var newSource = {
  4871. format: 'base64',
  4872. base64: result.base64,
  4873. type: result.contentType
  4874. };
  4875. _this._data = result.base64;
  4876. return controller.saveBase64(_this._name, newSource, options);
  4877. }).then(function (res) {
  4878. _this._name = res.name;
  4879. _this._url = res.url;
  4880. return _this;
  4881. });
  4882. } else {
  4883. this._previousSave = controller.saveBase64(this._name, this._source, options).then(function (res) {
  4884. _this._name = res.name;
  4885. _this._url = res.url;
  4886. return _this;
  4887. });
  4888. }
  4889. }
  4890. if (this._previousSave) {
  4891. return this._previousSave;
  4892. }
  4893. }
  4894. }, {
  4895. key: "toJSON",
  4896. value: function ()
  4897. /*: { name: ?string, url: ?string }*/
  4898. {
  4899. return {
  4900. __type: 'File',
  4901. name: this._name,
  4902. url: this._url
  4903. };
  4904. }
  4905. }, {
  4906. key: "equals",
  4907. value: function (other
  4908. /*: mixed*/
  4909. )
  4910. /*: boolean*/
  4911. {
  4912. if (this === other) {
  4913. return true;
  4914. } // Unsaved Files are never equal, since they will be saved to different URLs
  4915. return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
  4916. }
  4917. }], [{
  4918. key: "fromJSON",
  4919. value: function (obj)
  4920. /*: ParseFile*/
  4921. {
  4922. if (obj.__type !== 'File') {
  4923. throw new TypeError('JSON object does not represent a ParseFile');
  4924. }
  4925. var file = new ParseFile(obj.name);
  4926. file._url = obj.url;
  4927. return file;
  4928. }
  4929. }, {
  4930. key: "encodeBase64",
  4931. value: function (bytes
  4932. /*: Array<number>*/
  4933. )
  4934. /*: string*/
  4935. {
  4936. var chunks = [];
  4937. chunks.length = Math.ceil(bytes.length / 3);
  4938. for (var i = 0; i < chunks.length; i++) {
  4939. var b1 = bytes[i * 3];
  4940. var b2 = bytes[i * 3 + 1] || 0;
  4941. var b3 = bytes[i * 3 + 2] || 0;
  4942. var has2 = i * 3 + 1 < bytes.length;
  4943. var has3 = i * 3 + 2 < bytes.length;
  4944. chunks[i] = [b64Digit(b1 >> 2 & 0x3F), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0F), has2 ? b64Digit(b2 << 2 & 0x3C | b3 >> 6 & 0x03) : '=', has3 ? b64Digit(b3 & 0x3F) : '='].join('');
  4945. }
  4946. return chunks.join('');
  4947. }
  4948. }]);
  4949. return ParseFile;
  4950. }();
  4951. var DefaultController = {
  4952. saveFile: function (name
  4953. /*: string*/
  4954. , source
  4955. /*: FileSource*/
  4956. , options
  4957. /*:: ?: FullOptions*/
  4958. ) {
  4959. if (source.format !== 'file') {
  4960. throw new Error('saveFile can only be used with File-type sources.');
  4961. } // To directly upload a File, we use a REST-style AJAX request
  4962. var headers = {
  4963. 'X-Parse-Application-ID': _CoreManager.default.get('APPLICATION_ID'),
  4964. 'Content-Type': source.type || (source.file ? source.file.type : null)
  4965. };
  4966. var jsKey = _CoreManager.default.get('JAVASCRIPT_KEY');
  4967. if (jsKey) {
  4968. headers['X-Parse-JavaScript-Key'] = jsKey;
  4969. }
  4970. var url = _CoreManager.default.get('SERVER_URL');
  4971. if (url[url.length - 1] !== '/') {
  4972. url += '/';
  4973. }
  4974. url += 'files/' + name;
  4975. return _CoreManager.default.getRESTController().ajax('POST', url, source.file, headers, options).then(function (res) {
  4976. return res.response;
  4977. });
  4978. },
  4979. saveBase64: function (name
  4980. /*: string*/
  4981. , source
  4982. /*: FileSource*/
  4983. , options
  4984. /*:: ?: FullOptions*/
  4985. ) {
  4986. if (source.format !== 'base64') {
  4987. throw new Error('saveBase64 can only be used with Base64-type sources.');
  4988. }
  4989. var data
  4990. /*: { base64: any; _ContentType?: any }*/
  4991. = {
  4992. base64: source.base64
  4993. };
  4994. if (source.type) {
  4995. data._ContentType = source.type;
  4996. }
  4997. return _CoreManager.default.getRESTController().request('POST', 'files/' + name, data, options);
  4998. },
  4999. download: function (uri) {
  5000. if (XHR) {
  5001. return this.downloadAjax(uri);
  5002. } else {
  5003. return Promise.reject('Cannot make a request: No definition of XMLHttpRequest was found.');
  5004. }
  5005. },
  5006. downloadAjax: function (uri) {
  5007. return new Promise(function (resolve, reject) {
  5008. var xhr = new XHR();
  5009. xhr.open('GET', uri, true);
  5010. xhr.responseType = 'arraybuffer';
  5011. xhr.onerror = function (e) {
  5012. reject(e);
  5013. };
  5014. xhr.onreadystatechange = function () {
  5015. if (xhr.readyState !== 4) {
  5016. return;
  5017. }
  5018. var bytes = new Uint8Array(this.response);
  5019. resolve({
  5020. base64: ParseFile.encodeBase64(bytes),
  5021. contentType: xhr.getResponseHeader('content-type')
  5022. });
  5023. };
  5024. xhr.send();
  5025. });
  5026. },
  5027. _setXHR: function (xhr
  5028. /*: any*/
  5029. ) {
  5030. XHR = xhr;
  5031. }
  5032. };
  5033. _CoreManager.default.setFileController(DefaultController);
  5034. var _default = ParseFile;
  5035. exports.default = _default;
  5036. },{"./CoreManager":4,"@babel/runtime/helpers/asyncToGenerator":53,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/regenerator":76}],20:[function(_dereq_,module,exports){
  5037. "use strict";
  5038. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  5039. Object.defineProperty(exports, "__esModule", {
  5040. value: true
  5041. });
  5042. exports.default = void 0;
  5043. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  5044. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  5045. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  5046. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  5047. /**
  5048. * Copyright (c) 2015-present, Parse, LLC.
  5049. * All rights reserved.
  5050. *
  5051. * This source code is licensed under the BSD-style license found in the
  5052. * LICENSE file in the root directory of this source tree. An additional grant
  5053. * of patent rights can be found in the PATENTS file in the same directory.
  5054. *
  5055. * @flow
  5056. */
  5057. /**
  5058. * Creates a new GeoPoint with any of the following forms:<br>
  5059. * <pre>
  5060. * new GeoPoint(otherGeoPoint)
  5061. * new GeoPoint(30, 30)
  5062. * new GeoPoint([30, 30])
  5063. * new GeoPoint({latitude: 30, longitude: 30})
  5064. * new GeoPoint() // defaults to (0, 0)
  5065. * </pre>
  5066. * <p>Represents a latitude / longitude point that may be associated
  5067. * with a key in a ParseObject or used as a reference point for geo queries.
  5068. * This allows proximity-based queries on the key.</p>
  5069. *
  5070. * <p>Only one key in a class may contain a GeoPoint.</p>
  5071. *
  5072. * <p>Example:<pre>
  5073. * var point = new Parse.GeoPoint(30.0, -20.0);
  5074. * var object = new Parse.Object("PlaceObject");
  5075. * object.set("location", point);
  5076. * object.save();</pre></p>
  5077. * @alias Parse.GeoPoint
  5078. */
  5079. /* global navigator */
  5080. var ParseGeoPoint =
  5081. /*#__PURE__*/
  5082. function () {
  5083. /**
  5084. * @param {(Number[]|Object|Number)} options Either a list of coordinate pairs, an object with `latitude`, `longitude`, or the latitude or the point.
  5085. * @param {Number} longitude The longitude of the GeoPoint
  5086. */
  5087. function ParseGeoPoint(arg1
  5088. /*: Array<number> |
  5089. { latitude: number; longitude: number } |
  5090. number*/
  5091. , arg2
  5092. /*:: ?: number*/
  5093. ) {
  5094. (0, _classCallCheck2.default)(this, ParseGeoPoint);
  5095. (0, _defineProperty2.default)(this, "_latitude", void 0);
  5096. (0, _defineProperty2.default)(this, "_longitude", void 0);
  5097. if (Array.isArray(arg1)) {
  5098. ParseGeoPoint._validate(arg1[0], arg1[1]);
  5099. this._latitude = arg1[0];
  5100. this._longitude = arg1[1];
  5101. } else if ((0, _typeof2.default)(arg1) === 'object') {
  5102. ParseGeoPoint._validate(arg1.latitude, arg1.longitude);
  5103. this._latitude = arg1.latitude;
  5104. this._longitude = arg1.longitude;
  5105. } else if (arg1 !== undefined && arg2 !== undefined) {
  5106. ParseGeoPoint._validate(arg1, arg2);
  5107. this._latitude = arg1;
  5108. this._longitude = arg2;
  5109. } else {
  5110. this._latitude = 0;
  5111. this._longitude = 0;
  5112. }
  5113. }
  5114. /**
  5115. * North-south portion of the coordinate, in range [-90, 90].
  5116. * Throws an exception if set out of range in a modern browser.
  5117. * @property latitude
  5118. * @type Number
  5119. */
  5120. (0, _createClass2.default)(ParseGeoPoint, [{
  5121. key: "toJSON",
  5122. /**
  5123. * Returns a JSON representation of the GeoPoint, suitable for Parse.
  5124. * @return {Object}
  5125. */
  5126. value: function ()
  5127. /*: { __type: string; latitude: number; longitude: number }*/
  5128. {
  5129. ParseGeoPoint._validate(this._latitude, this._longitude);
  5130. return {
  5131. __type: 'GeoPoint',
  5132. latitude: this._latitude,
  5133. longitude: this._longitude
  5134. };
  5135. }
  5136. }, {
  5137. key: "equals",
  5138. value: function (other
  5139. /*: mixed*/
  5140. )
  5141. /*: boolean*/
  5142. {
  5143. return other instanceof ParseGeoPoint && this.latitude === other.latitude && this.longitude === other.longitude;
  5144. }
  5145. /**
  5146. * Returns the distance from this GeoPoint to another in radians.
  5147. * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
  5148. * @return {Number}
  5149. */
  5150. }, {
  5151. key: "radiansTo",
  5152. value: function (point
  5153. /*: ParseGeoPoint*/
  5154. )
  5155. /*: number*/
  5156. {
  5157. var d2r = Math.PI / 180.0;
  5158. var lat1rad = this.latitude * d2r;
  5159. var long1rad = this.longitude * d2r;
  5160. var lat2rad = point.latitude * d2r;
  5161. var long2rad = point.longitude * d2r;
  5162. var sinDeltaLatDiv2 = Math.sin((lat1rad - lat2rad) / 2);
  5163. var sinDeltaLongDiv2 = Math.sin((long1rad - long2rad) / 2); // Square of half the straight line chord distance between both points.
  5164. var a = sinDeltaLatDiv2 * sinDeltaLatDiv2 + Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2;
  5165. a = Math.min(1.0, a);
  5166. return 2 * Math.asin(Math.sqrt(a));
  5167. }
  5168. /**
  5169. * Returns the distance from this GeoPoint to another in kilometers.
  5170. * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
  5171. * @return {Number}
  5172. */
  5173. }, {
  5174. key: "kilometersTo",
  5175. value: function (point
  5176. /*: ParseGeoPoint*/
  5177. )
  5178. /*: number*/
  5179. {
  5180. return this.radiansTo(point) * 6371.0;
  5181. }
  5182. /**
  5183. * Returns the distance from this GeoPoint to another in miles.
  5184. * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
  5185. * @return {Number}
  5186. */
  5187. }, {
  5188. key: "milesTo",
  5189. value: function (point
  5190. /*: ParseGeoPoint*/
  5191. )
  5192. /*: number*/
  5193. {
  5194. return this.radiansTo(point) * 3958.8;
  5195. }
  5196. /*
  5197. * Throws an exception if the given lat-long is out of bounds.
  5198. */
  5199. }, {
  5200. key: "latitude",
  5201. get: function ()
  5202. /*: number*/
  5203. {
  5204. return this._latitude;
  5205. },
  5206. set: function (val
  5207. /*: number*/
  5208. ) {
  5209. ParseGeoPoint._validate(val, this.longitude);
  5210. this._latitude = val;
  5211. }
  5212. /**
  5213. * East-west portion of the coordinate, in range [-180, 180].
  5214. * Throws if set out of range in a modern browser.
  5215. * @property longitude
  5216. * @type Number
  5217. */
  5218. }, {
  5219. key: "longitude",
  5220. get: function ()
  5221. /*: number*/
  5222. {
  5223. return this._longitude;
  5224. },
  5225. set: function (val
  5226. /*: number*/
  5227. ) {
  5228. ParseGeoPoint._validate(this.latitude, val);
  5229. this._longitude = val;
  5230. }
  5231. }], [{
  5232. key: "_validate",
  5233. value: function (latitude
  5234. /*: number*/
  5235. , longitude
  5236. /*: number*/
  5237. ) {
  5238. if (isNaN(latitude) || isNaN(longitude) || typeof latitude !== 'number' || typeof longitude !== 'number') {
  5239. throw new TypeError('GeoPoint latitude and longitude must be valid numbers');
  5240. }
  5241. if (latitude < -90.0) {
  5242. throw new TypeError('GeoPoint latitude out of bounds: ' + latitude + ' < -90.0.');
  5243. }
  5244. if (latitude > 90.0) {
  5245. throw new TypeError('GeoPoint latitude out of bounds: ' + latitude + ' > 90.0.');
  5246. }
  5247. if (longitude < -180.0) {
  5248. throw new TypeError('GeoPoint longitude out of bounds: ' + longitude + ' < -180.0.');
  5249. }
  5250. if (longitude > 180.0) {
  5251. throw new TypeError('GeoPoint longitude out of bounds: ' + longitude + ' > 180.0.');
  5252. }
  5253. }
  5254. /**
  5255. * Creates a GeoPoint with the user's current location, if available.
  5256. * Calls options.success with a new GeoPoint instance or calls options.error.
  5257. * @static
  5258. */
  5259. }, {
  5260. key: "current",
  5261. value: function () {
  5262. return navigator.geolocation.getCurrentPosition(function (location) {
  5263. return new ParseGeoPoint(location.coords.latitude, location.coords.longitude);
  5264. });
  5265. }
  5266. }]);
  5267. return ParseGeoPoint;
  5268. }();
  5269. var _default = ParseGeoPoint;
  5270. exports.default = _default;
  5271. },{"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],21:[function(_dereq_,module,exports){
  5272. "use strict";
  5273. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  5274. Object.defineProperty(exports, "__esModule", {
  5275. value: true
  5276. });
  5277. exports.default = void 0;
  5278. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  5279. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  5280. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  5281. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  5282. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  5283. var _ParseObject2 = _interopRequireDefault(_dereq_("./ParseObject"));
  5284. /**
  5285. * Copyright (c) 2015-present, Parse, LLC.
  5286. * All rights reserved.
  5287. *
  5288. * This source code is licensed under the BSD-style license found in the
  5289. * LICENSE file in the root directory of this source tree. An additional grant
  5290. * of patent rights can be found in the PATENTS file in the same directory.
  5291. *
  5292. * @flow
  5293. */
  5294. var Installation =
  5295. /*#__PURE__*/
  5296. function (_ParseObject) {
  5297. (0, _inherits2.default)(Installation, _ParseObject);
  5298. function Installation(attributes
  5299. /*: ?AttributeMap*/
  5300. ) {
  5301. var _this;
  5302. (0, _classCallCheck2.default)(this, Installation);
  5303. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(Installation).call(this, '_Installation'));
  5304. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  5305. if (!_this.set(attributes || {})) {
  5306. throw new Error('Can\'t create an invalid Session');
  5307. }
  5308. }
  5309. return _this;
  5310. }
  5311. return Installation;
  5312. }(_ParseObject2.default);
  5313. exports.default = Installation;
  5314. _ParseObject2.default.registerSubclass('_Installation', Installation);
  5315. },{"./ParseObject":23,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/getPrototypeOf":59,"@babel/runtime/helpers/inherits":60,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/possibleConstructorReturn":68,"@babel/runtime/helpers/typeof":73}],22:[function(_dereq_,module,exports){
  5316. "use strict";
  5317. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  5318. Object.defineProperty(exports, "__esModule", {
  5319. value: true
  5320. });
  5321. exports.default = void 0;
  5322. var _regenerator = _interopRequireDefault(_dereq_("@babel/runtime/regenerator"));
  5323. var _asyncToGenerator2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/asyncToGenerator"));
  5324. var _EventEmitter = _interopRequireDefault(_dereq_("./EventEmitter"));
  5325. var _LiveQueryClient = _interopRequireDefault(_dereq_("./LiveQueryClient"));
  5326. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  5327. /**
  5328. * Copyright (c) 2015-present, Parse, LLC.
  5329. * All rights reserved.
  5330. *
  5331. * This source code is licensed under the BSD-style license found in the
  5332. * LICENSE file in the root directory of this source tree. An additional grant
  5333. * of patent rights can be found in the PATENTS file in the same directory.
  5334. *
  5335. * @flow
  5336. */
  5337. function getLiveQueryClient()
  5338. /*: LiveQueryClient*/
  5339. {
  5340. return _CoreManager.default.getLiveQueryController().getDefaultLiveQueryClient();
  5341. }
  5342. /**
  5343. *
  5344. * We expose three events to help you monitor the status of the WebSocket connection:
  5345. *
  5346. * <p>Open - When we establish the WebSocket connection to the LiveQuery server, you'll get this event.
  5347. *
  5348. * <pre>
  5349. * Parse.LiveQuery.on('open', () => {
  5350. *
  5351. * });</pre></p>
  5352. *
  5353. * <p>Close - When we lose the WebSocket connection to the LiveQuery server, you'll get this event.
  5354. *
  5355. * <pre>
  5356. * Parse.LiveQuery.on('close', () => {
  5357. *
  5358. * });</pre></p>
  5359. *
  5360. * <p>Error - When some network error or LiveQuery server error happens, you'll get this event.
  5361. *
  5362. * <pre>
  5363. * Parse.LiveQuery.on('error', (error) => {
  5364. *
  5365. * });</pre></p>
  5366. *
  5367. * @class Parse.LiveQuery
  5368. * @static
  5369. *
  5370. */
  5371. var LiveQuery = new _EventEmitter.default();
  5372. /**
  5373. * After open is called, the LiveQuery will try to send a connect request
  5374. * to the LiveQuery server.
  5375. */
  5376. LiveQuery.open =
  5377. /*#__PURE__*/
  5378. (0, _asyncToGenerator2.default)(
  5379. /*#__PURE__*/
  5380. _regenerator.default.mark(function _callee() {
  5381. var liveQueryClient;
  5382. return _regenerator.default.wrap(function (_context) {
  5383. while (1) {
  5384. switch (_context.prev = _context.next) {
  5385. case 0:
  5386. _context.next = 2;
  5387. return getLiveQueryClient();
  5388. case 2:
  5389. liveQueryClient = _context.sent;
  5390. return _context.abrupt("return", liveQueryClient.open());
  5391. case 4:
  5392. case "end":
  5393. return _context.stop();
  5394. }
  5395. }
  5396. }, _callee);
  5397. }));
  5398. /**
  5399. * When you're done using LiveQuery, you can call Parse.LiveQuery.close().
  5400. * This function will close the WebSocket connection to the LiveQuery server,
  5401. * cancel the auto reconnect, and unsubscribe all subscriptions based on it.
  5402. * If you call query.subscribe() after this, we'll create a new WebSocket
  5403. * connection to the LiveQuery server.
  5404. */
  5405. LiveQuery.close =
  5406. /*#__PURE__*/
  5407. (0, _asyncToGenerator2.default)(
  5408. /*#__PURE__*/
  5409. _regenerator.default.mark(function _callee2() {
  5410. var liveQueryClient;
  5411. return _regenerator.default.wrap(function (_context2) {
  5412. while (1) {
  5413. switch (_context2.prev = _context2.next) {
  5414. case 0:
  5415. _context2.next = 2;
  5416. return getLiveQueryClient();
  5417. case 2:
  5418. liveQueryClient = _context2.sent;
  5419. return _context2.abrupt("return", liveQueryClient.close());
  5420. case 4:
  5421. case "end":
  5422. return _context2.stop();
  5423. }
  5424. }
  5425. }, _callee2);
  5426. })); // Register a default onError callback to make sure we do not crash on error
  5427. LiveQuery.on('error', function () {});
  5428. var _default = LiveQuery;
  5429. exports.default = _default;
  5430. var defaultLiveQueryClient;
  5431. var DefaultLiveQueryController = {
  5432. setDefaultLiveQueryClient: function (liveQueryClient
  5433. /*: LiveQueryClient*/
  5434. ) {
  5435. defaultLiveQueryClient = liveQueryClient;
  5436. },
  5437. getDefaultLiveQueryClient: function () {
  5438. var _getDefaultLiveQueryClient = (0, _asyncToGenerator2.default)(
  5439. /*#__PURE__*/
  5440. _regenerator.default.mark(function _callee3() {
  5441. var currentUser, sessionToken, liveQueryServerURL, serverURL, protocol, host, applicationId, javascriptKey, masterKey;
  5442. return _regenerator.default.wrap(function (_context3) {
  5443. while (1) {
  5444. switch (_context3.prev = _context3.next) {
  5445. case 0:
  5446. if (!defaultLiveQueryClient) {
  5447. _context3.next = 2;
  5448. break;
  5449. }
  5450. return _context3.abrupt("return", defaultLiveQueryClient);
  5451. case 2:
  5452. _context3.next = 4;
  5453. return _CoreManager.default.getUserController().currentUserAsync();
  5454. case 4:
  5455. currentUser = _context3.sent;
  5456. sessionToken = currentUser ? currentUser.getSessionToken() : undefined;
  5457. liveQueryServerURL = _CoreManager.default.get('LIVEQUERY_SERVER_URL');
  5458. if (!(liveQueryServerURL && liveQueryServerURL.indexOf('ws') !== 0)) {
  5459. _context3.next = 9;
  5460. break;
  5461. }
  5462. throw new Error('You need to set a proper Parse LiveQuery server url before using LiveQueryClient');
  5463. case 9:
  5464. // If we can not find Parse.liveQueryServerURL, we try to extract it from Parse.serverURL
  5465. if (!liveQueryServerURL) {
  5466. serverURL = _CoreManager.default.get('SERVER_URL');
  5467. protocol = serverURL.indexOf('https') === 0 ? 'wss://' : 'ws://';
  5468. host = serverURL.replace(/^https?:\/\//, '');
  5469. liveQueryServerURL = protocol + host;
  5470. _CoreManager.default.set('LIVEQUERY_SERVER_URL', liveQueryServerURL);
  5471. }
  5472. applicationId = _CoreManager.default.get('APPLICATION_ID');
  5473. javascriptKey = _CoreManager.default.get('JAVASCRIPT_KEY');
  5474. masterKey = _CoreManager.default.get('MASTER_KEY');
  5475. defaultLiveQueryClient = new _LiveQueryClient.default({
  5476. applicationId: applicationId,
  5477. serverURL: liveQueryServerURL,
  5478. javascriptKey: javascriptKey,
  5479. masterKey: masterKey,
  5480. sessionToken: sessionToken
  5481. });
  5482. defaultLiveQueryClient.on('error', function (error) {
  5483. LiveQuery.emit('error', error);
  5484. });
  5485. defaultLiveQueryClient.on('open', function () {
  5486. LiveQuery.emit('open');
  5487. });
  5488. defaultLiveQueryClient.on('close', function () {
  5489. LiveQuery.emit('close');
  5490. });
  5491. return _context3.abrupt("return", defaultLiveQueryClient);
  5492. case 18:
  5493. case "end":
  5494. return _context3.stop();
  5495. }
  5496. }
  5497. }, _callee3);
  5498. }));
  5499. return function () {
  5500. return _getDefaultLiveQueryClient.apply(this, arguments);
  5501. };
  5502. }(),
  5503. _clearCachedDefaultClient: function () {
  5504. defaultLiveQueryClient = null;
  5505. }
  5506. };
  5507. _CoreManager.default.setLiveQueryController(DefaultLiveQueryController);
  5508. },{"./CoreManager":4,"./EventEmitter":5,"./LiveQueryClient":8,"@babel/runtime/helpers/asyncToGenerator":53,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/regenerator":76}],23:[function(_dereq_,module,exports){
  5509. "use strict";
  5510. var _interopRequireWildcard = _dereq_("@babel/runtime/helpers/interopRequireWildcard");
  5511. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  5512. Object.defineProperty(exports, "__esModule", {
  5513. value: true
  5514. });
  5515. exports.default = void 0;
  5516. var _regenerator = _interopRequireDefault(_dereq_("@babel/runtime/regenerator"));
  5517. var _asyncToGenerator2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/asyncToGenerator"));
  5518. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  5519. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  5520. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  5521. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  5522. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  5523. var _canBeSerialized = _interopRequireDefault(_dereq_("./canBeSerialized"));
  5524. var _decode = _interopRequireDefault(_dereq_("./decode"));
  5525. var _encode = _interopRequireDefault(_dereq_("./encode"));
  5526. var _escape2 = _interopRequireDefault(_dereq_("./escape"));
  5527. var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
  5528. var _parseDate = _interopRequireDefault(_dereq_("./parseDate"));
  5529. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  5530. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  5531. var _promiseUtils = _dereq_("./promiseUtils");
  5532. var _LocalDatastoreUtils = _dereq_("./LocalDatastoreUtils");
  5533. var _ParseOp = _dereq_("./ParseOp");
  5534. var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
  5535. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  5536. var SingleInstanceStateController = _interopRequireWildcard(_dereq_("./SingleInstanceStateController"));
  5537. var _unique = _interopRequireDefault(_dereq_("./unique"));
  5538. var UniqueInstanceStateController = _interopRequireWildcard(_dereq_("./UniqueInstanceStateController"));
  5539. var _unsavedChildren = _interopRequireDefault(_dereq_("./unsavedChildren"));
  5540. /**
  5541. * Copyright (c) 2015-present, Parse, LLC.
  5542. * All rights reserved.
  5543. *
  5544. * This source code is licensed under the BSD-style license found in the
  5545. * LICENSE file in the root directory of this source tree. An additional grant
  5546. * of patent rights can be found in the PATENTS file in the same directory.
  5547. *
  5548. * @flow
  5549. */
  5550. var DEFAULT_BATCH_SIZE = 20; // Mapping of class names to constructors, so we can populate objects from the
  5551. // server with appropriate subclasses of ParseObject
  5552. var classMap = {}; // Global counter for generating unique local Ids
  5553. var localCount = 0; // Global counter for generating unique Ids for non-single-instance objects
  5554. var objectCount = 0; // On web clients, objects are single-instance: any two objects with the same Id
  5555. // will have the same attributes. However, this may be dangerous default
  5556. // behavior in a server scenario
  5557. var singleInstance = !_CoreManager.default.get('IS_NODE');
  5558. if (singleInstance) {
  5559. _CoreManager.default.setObjectStateController(SingleInstanceStateController);
  5560. } else {
  5561. _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
  5562. }
  5563. function getServerUrlPath() {
  5564. var serverUrl = _CoreManager.default.get('SERVER_URL');
  5565. if (serverUrl[serverUrl.length - 1] !== '/') {
  5566. serverUrl += '/';
  5567. }
  5568. var url = serverUrl.replace(/https?:\/\//, '');
  5569. return url.substr(url.indexOf('/'));
  5570. }
  5571. /**
  5572. * Creates a new model with defined attributes.
  5573. *
  5574. * <p>You won't normally call this method directly. It is recommended that
  5575. * you use a subclass of <code>Parse.Object</code> instead, created by calling
  5576. * <code>extend</code>.</p>
  5577. *
  5578. * <p>However, if you don't want to use a subclass, or aren't sure which
  5579. * subclass is appropriate, you can use this form:<pre>
  5580. * var object = new Parse.Object("ClassName");
  5581. * </pre>
  5582. * That is basically equivalent to:<pre>
  5583. * var MyClass = Parse.Object.extend("ClassName");
  5584. * var object = new MyClass();
  5585. * </pre></p>
  5586. *
  5587. * @alias Parse.Object
  5588. */
  5589. var ParseObject =
  5590. /*#__PURE__*/
  5591. function () {
  5592. /**
  5593. * @param {String} className The class name for the object
  5594. * @param {Object} attributes The initial set of data to store in the object.
  5595. * @param {Object} options The options for this object instance.
  5596. */
  5597. function ParseObject(className
  5598. /*: ?string | { className: string, [attr: string]: mixed }*/
  5599. , attributes
  5600. /*:: ?: { [attr: string]: mixed }*/
  5601. , options
  5602. /*:: ?: { ignoreValidation: boolean }*/
  5603. ) {
  5604. (0, _classCallCheck2.default)(this, ParseObject);
  5605. (0, _defineProperty2.default)(this, "id", void 0);
  5606. (0, _defineProperty2.default)(this, "_localId", void 0);
  5607. (0, _defineProperty2.default)(this, "_objCount", void 0);
  5608. (0, _defineProperty2.default)(this, "className", void 0); // Enable legacy initializers
  5609. if (typeof this.initialize === 'function') {
  5610. this.initialize.apply(this, arguments);
  5611. }
  5612. var toSet = null;
  5613. this._objCount = objectCount++;
  5614. if (typeof className === 'string') {
  5615. this.className = className;
  5616. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  5617. toSet = attributes;
  5618. }
  5619. } else if (className && (0, _typeof2.default)(className) === 'object') {
  5620. this.className = className.className;
  5621. toSet = {};
  5622. for (var _attr in className) {
  5623. if (_attr !== 'className') {
  5624. toSet[_attr] = className[_attr];
  5625. }
  5626. }
  5627. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  5628. options = attributes;
  5629. }
  5630. }
  5631. if (toSet && !this.set(toSet, options)) {
  5632. throw new Error('Can\'t create an invalid Parse Object');
  5633. }
  5634. }
  5635. /**
  5636. * The ID of this object, unique within its class.
  5637. * @property id
  5638. * @type String
  5639. */
  5640. (0, _createClass2.default)(ParseObject, [{
  5641. key: "_getId",
  5642. /** Private methods **/
  5643. /**
  5644. * Returns a local or server Id used uniquely identify this object
  5645. */
  5646. value: function ()
  5647. /*: string*/
  5648. {
  5649. if (typeof this.id === 'string') {
  5650. return this.id;
  5651. }
  5652. if (typeof this._localId === 'string') {
  5653. return this._localId;
  5654. }
  5655. var localId = 'local' + String(localCount++);
  5656. this._localId = localId;
  5657. return localId;
  5658. }
  5659. /**
  5660. * Returns a unique identifier used to pull data from the State Controller.
  5661. */
  5662. }, {
  5663. key: "_getStateIdentifier",
  5664. value: function ()
  5665. /*: ParseObject | {id: string, className: string}*/
  5666. {
  5667. if (singleInstance) {
  5668. var id = this.id;
  5669. if (!id) {
  5670. id = this._getId();
  5671. }
  5672. return {
  5673. id: id,
  5674. className: this.className
  5675. };
  5676. } else {
  5677. return this;
  5678. }
  5679. }
  5680. }, {
  5681. key: "_getServerData",
  5682. value: function ()
  5683. /*: AttributeMap*/
  5684. {
  5685. var stateController = _CoreManager.default.getObjectStateController();
  5686. return stateController.getServerData(this._getStateIdentifier());
  5687. }
  5688. }, {
  5689. key: "_clearServerData",
  5690. value: function () {
  5691. var serverData = this._getServerData();
  5692. var unset = {};
  5693. for (var _attr2 in serverData) {
  5694. unset[_attr2] = undefined;
  5695. }
  5696. var stateController = _CoreManager.default.getObjectStateController();
  5697. stateController.setServerData(this._getStateIdentifier(), unset);
  5698. }
  5699. }, {
  5700. key: "_getPendingOps",
  5701. value: function ()
  5702. /*: Array<OpsMap>*/
  5703. {
  5704. var stateController = _CoreManager.default.getObjectStateController();
  5705. return stateController.getPendingOps(this._getStateIdentifier());
  5706. }
  5707. /**
  5708. * @param {Array<string>} [keysToClear] - if specified, only ops matching
  5709. * these fields will be cleared
  5710. */
  5711. }, {
  5712. key: "_clearPendingOps",
  5713. value: function (keysToClear
  5714. /*:: ?: Array<string>*/
  5715. ) {
  5716. var pending = this._getPendingOps();
  5717. var latest = pending[pending.length - 1];
  5718. var keys = keysToClear || Object.keys(latest);
  5719. keys.forEach(function (key) {
  5720. delete latest[key];
  5721. });
  5722. }
  5723. }, {
  5724. key: "_getDirtyObjectAttributes",
  5725. value: function ()
  5726. /*: AttributeMap*/
  5727. {
  5728. var attributes = this.attributes;
  5729. var stateController = _CoreManager.default.getObjectStateController();
  5730. var objectCache = stateController.getObjectCache(this._getStateIdentifier());
  5731. var dirty = {};
  5732. for (var _attr3 in attributes) {
  5733. var val = attributes[_attr3];
  5734. if (val && (0, _typeof2.default)(val) === 'object' && !(val instanceof ParseObject) && !(val instanceof _ParseFile.default) && !(val instanceof _ParseRelation.default)) {
  5735. // Due to the way browsers construct maps, the key order will not change
  5736. // unless the object is changed
  5737. try {
  5738. var json = (0, _encode.default)(val, false, true);
  5739. var stringified = JSON.stringify(json);
  5740. if (objectCache[_attr3] !== stringified) {
  5741. dirty[_attr3] = val;
  5742. }
  5743. } catch (e) {
  5744. // Error occurred, possibly by a nested unsaved pointer in a mutable container
  5745. // No matter how it happened, it indicates a change in the attribute
  5746. dirty[_attr3] = val;
  5747. }
  5748. }
  5749. }
  5750. return dirty;
  5751. }
  5752. }, {
  5753. key: "_toFullJSON",
  5754. value: function (seen
  5755. /*:: ?: Array<any>*/
  5756. )
  5757. /*: AttributeMap*/
  5758. {
  5759. var json
  5760. /*: { [key: string]: mixed }*/
  5761. = this.toJSON(seen);
  5762. json.__type = 'Object';
  5763. json.className = this.className;
  5764. return json;
  5765. }
  5766. }, {
  5767. key: "_getSaveJSON",
  5768. value: function ()
  5769. /*: AttributeMap*/
  5770. {
  5771. var pending = this._getPendingOps();
  5772. var dirtyObjects = this._getDirtyObjectAttributes();
  5773. var json = {};
  5774. for (var attr in dirtyObjects) {
  5775. var isDotNotation = false;
  5776. for (var i = 0; i < pending.length; i += 1) {
  5777. for (var field in pending[i]) {
  5778. // Dot notation operations are handled later
  5779. if (field.includes('.')) {
  5780. var fieldName = field.split('.')[0];
  5781. if (fieldName === attr) {
  5782. isDotNotation = true;
  5783. break;
  5784. }
  5785. }
  5786. }
  5787. }
  5788. if (!isDotNotation) {
  5789. json[attr] = new _ParseOp.SetOp(dirtyObjects[attr]).toJSON();
  5790. }
  5791. }
  5792. for (attr in pending[0]) {
  5793. json[attr] = pending[0][attr].toJSON();
  5794. }
  5795. return json;
  5796. }
  5797. }, {
  5798. key: "_getSaveParams",
  5799. value: function ()
  5800. /*: SaveParams*/
  5801. {
  5802. var method = this.id ? 'PUT' : 'POST';
  5803. var body = this._getSaveJSON();
  5804. var path = 'classes/' + this.className;
  5805. if (this.id) {
  5806. path += '/' + this.id;
  5807. } else if (this.className === '_User') {
  5808. path = 'users';
  5809. }
  5810. return {
  5811. method: method,
  5812. body: body,
  5813. path: path
  5814. };
  5815. }
  5816. }, {
  5817. key: "_finishFetch",
  5818. value: function (serverData
  5819. /*: AttributeMap*/
  5820. ) {
  5821. if (!this.id && serverData.objectId) {
  5822. this.id = serverData.objectId;
  5823. }
  5824. var stateController = _CoreManager.default.getObjectStateController();
  5825. stateController.initializeState(this._getStateIdentifier());
  5826. var decoded = {};
  5827. for (var _attr4 in serverData) {
  5828. if (_attr4 === 'ACL') {
  5829. decoded[_attr4] = new _ParseACL.default(serverData[_attr4]);
  5830. } else if (_attr4 !== 'objectId') {
  5831. decoded[_attr4] = (0, _decode.default)(serverData[_attr4]);
  5832. if (decoded[_attr4] instanceof _ParseRelation.default) {
  5833. decoded[_attr4]._ensureParentAndKey(this, _attr4);
  5834. }
  5835. }
  5836. }
  5837. if (decoded.createdAt && typeof decoded.createdAt === 'string') {
  5838. decoded.createdAt = (0, _parseDate.default)(decoded.createdAt);
  5839. }
  5840. if (decoded.updatedAt && typeof decoded.updatedAt === 'string') {
  5841. decoded.updatedAt = (0, _parseDate.default)(decoded.updatedAt);
  5842. }
  5843. if (!decoded.updatedAt && decoded.createdAt) {
  5844. decoded.updatedAt = decoded.createdAt;
  5845. }
  5846. stateController.commitServerChanges(this._getStateIdentifier(), decoded);
  5847. }
  5848. }, {
  5849. key: "_setExisted",
  5850. value: function (existed
  5851. /*: boolean*/
  5852. ) {
  5853. var stateController = _CoreManager.default.getObjectStateController();
  5854. var state = stateController.getState(this._getStateIdentifier());
  5855. if (state) {
  5856. state.existed = existed;
  5857. }
  5858. }
  5859. }, {
  5860. key: "_migrateId",
  5861. value: function (serverId
  5862. /*: string*/
  5863. ) {
  5864. if (this._localId && serverId) {
  5865. if (singleInstance) {
  5866. var stateController = _CoreManager.default.getObjectStateController();
  5867. var oldState = stateController.removeState(this._getStateIdentifier());
  5868. this.id = serverId;
  5869. delete this._localId;
  5870. if (oldState) {
  5871. stateController.initializeState(this._getStateIdentifier(), oldState);
  5872. }
  5873. } else {
  5874. this.id = serverId;
  5875. delete this._localId;
  5876. }
  5877. }
  5878. }
  5879. }, {
  5880. key: "_handleSaveResponse",
  5881. value: function (response
  5882. /*: AttributeMap*/
  5883. , status
  5884. /*: number*/
  5885. ) {
  5886. var changes = {};
  5887. var stateController = _CoreManager.default.getObjectStateController();
  5888. var pending = stateController.popPendingState(this._getStateIdentifier());
  5889. for (var attr in pending) {
  5890. if (pending[attr] instanceof _ParseOp.RelationOp) {
  5891. changes[attr] = pending[attr].applyTo(undefined, this, attr);
  5892. } else if (!(attr in response)) {
  5893. // Only SetOps and UnsetOps should not come back with results
  5894. changes[attr] = pending[attr].applyTo(undefined);
  5895. }
  5896. }
  5897. for (attr in response) {
  5898. if ((attr === 'createdAt' || attr === 'updatedAt') && typeof response[attr] === 'string') {
  5899. changes[attr] = (0, _parseDate.default)(response[attr]);
  5900. } else if (attr === 'ACL') {
  5901. changes[attr] = new _ParseACL.default(response[attr]);
  5902. } else if (attr !== 'objectId') {
  5903. changes[attr] = (0, _decode.default)(response[attr]);
  5904. if (changes[attr] instanceof _ParseOp.UnsetOp) {
  5905. changes[attr] = undefined;
  5906. }
  5907. }
  5908. }
  5909. if (changes.createdAt && !changes.updatedAt) {
  5910. changes.updatedAt = changes.createdAt;
  5911. }
  5912. this._migrateId(response.objectId);
  5913. if (status !== 201) {
  5914. this._setExisted(true);
  5915. }
  5916. stateController.commitServerChanges(this._getStateIdentifier(), changes);
  5917. }
  5918. }, {
  5919. key: "_handleSaveError",
  5920. value: function () {
  5921. var stateController = _CoreManager.default.getObjectStateController();
  5922. stateController.mergeFirstPendingState(this._getStateIdentifier());
  5923. }
  5924. /** Public methods **/
  5925. }, {
  5926. key: "initialize",
  5927. value: function () {} // NOOP
  5928. /**
  5929. * Returns a JSON version of the object suitable for saving to Parse.
  5930. * @return {Object}
  5931. */
  5932. }, {
  5933. key: "toJSON",
  5934. value: function (seen
  5935. /*: Array<any> | void*/
  5936. )
  5937. /*: AttributeMap*/
  5938. {
  5939. var seenEntry = this.id ? this.className + ':' + this.id : this;
  5940. seen = seen || [seenEntry];
  5941. var json = {};
  5942. var attrs = this.attributes;
  5943. for (var _attr5 in attrs) {
  5944. if ((_attr5 === 'createdAt' || _attr5 === 'updatedAt') && attrs[_attr5].toJSON) {
  5945. json[_attr5] = attrs[_attr5].toJSON();
  5946. } else {
  5947. json[_attr5] = (0, _encode.default)(attrs[_attr5], false, false, seen);
  5948. }
  5949. }
  5950. var pending = this._getPendingOps();
  5951. for (var _attr6 in pending[0]) {
  5952. json[_attr6] = pending[0][_attr6].toJSON();
  5953. }
  5954. if (this.id) {
  5955. json.objectId = this.id;
  5956. }
  5957. return json;
  5958. }
  5959. /**
  5960. * Determines whether this ParseObject is equal to another ParseObject
  5961. * @param {Object} other - An other object ot compare
  5962. * @return {Boolean}
  5963. */
  5964. }, {
  5965. key: "equals",
  5966. value: function (other
  5967. /*: mixed*/
  5968. )
  5969. /*: boolean*/
  5970. {
  5971. if (this === other) {
  5972. return true;
  5973. }
  5974. return other instanceof ParseObject && this.className === other.className && this.id === other.id && typeof this.id !== 'undefined';
  5975. }
  5976. /**
  5977. * Returns true if this object has been modified since its last
  5978. * save/refresh. If an attribute is specified, it returns true only if that
  5979. * particular attribute has been modified since the last save/refresh.
  5980. * @param {String} attr An attribute name (optional).
  5981. * @return {Boolean}
  5982. */
  5983. }, {
  5984. key: "dirty",
  5985. value: function (attr
  5986. /*:: ?: string*/
  5987. )
  5988. /*: boolean*/
  5989. {
  5990. if (!this.id) {
  5991. return true;
  5992. }
  5993. var pendingOps = this._getPendingOps();
  5994. var dirtyObjects = this._getDirtyObjectAttributes();
  5995. if (attr) {
  5996. if (dirtyObjects.hasOwnProperty(attr)) {
  5997. return true;
  5998. }
  5999. for (var i = 0; i < pendingOps.length; i++) {
  6000. if (pendingOps[i].hasOwnProperty(attr)) {
  6001. return true;
  6002. }
  6003. }
  6004. return false;
  6005. }
  6006. if (Object.keys(pendingOps[0]).length !== 0) {
  6007. return true;
  6008. }
  6009. if (Object.keys(dirtyObjects).length !== 0) {
  6010. return true;
  6011. }
  6012. return false;
  6013. }
  6014. /**
  6015. * Returns an array of keys that have been modified since last save/refresh
  6016. * @return {String[]}
  6017. */
  6018. }, {
  6019. key: "dirtyKeys",
  6020. value: function ()
  6021. /*: Array<string>*/
  6022. {
  6023. var pendingOps = this._getPendingOps();
  6024. var keys = {};
  6025. for (var i = 0; i < pendingOps.length; i++) {
  6026. for (var _attr7 in pendingOps[i]) {
  6027. keys[_attr7] = true;
  6028. }
  6029. }
  6030. var dirtyObjects = this._getDirtyObjectAttributes();
  6031. for (var _attr8 in dirtyObjects) {
  6032. keys[_attr8] = true;
  6033. }
  6034. return Object.keys(keys);
  6035. }
  6036. /**
  6037. * Returns true if the object has been fetched.
  6038. * @return {Boolean}
  6039. */
  6040. }, {
  6041. key: "isDataAvailable",
  6042. value: function ()
  6043. /*: boolean*/
  6044. {
  6045. var serverData = this._getServerData();
  6046. return !!Object.keys(serverData).length;
  6047. }
  6048. /**
  6049. * Gets a Pointer referencing this Object.
  6050. * @return {Pointer}
  6051. */
  6052. }, {
  6053. key: "toPointer",
  6054. value: function ()
  6055. /*: Pointer*/
  6056. {
  6057. if (!this.id) {
  6058. throw new Error('Cannot create a pointer to an unsaved ParseObject');
  6059. }
  6060. return {
  6061. __type: 'Pointer',
  6062. className: this.className,
  6063. objectId: this.id
  6064. };
  6065. }
  6066. /**
  6067. * Gets the value of an attribute.
  6068. * @param {String} attr The string name of an attribute.
  6069. */
  6070. }, {
  6071. key: "get",
  6072. value: function (attr
  6073. /*: string*/
  6074. )
  6075. /*: mixed*/
  6076. {
  6077. return this.attributes[attr];
  6078. }
  6079. /**
  6080. * Gets a relation on the given class for the attribute.
  6081. * @param String attr The attribute to get the relation for.
  6082. * @return {Parse.Relation}
  6083. */
  6084. }, {
  6085. key: "relation",
  6086. value: function (attr
  6087. /*: string*/
  6088. )
  6089. /*: ParseRelation*/
  6090. {
  6091. var value = this.get(attr);
  6092. if (value) {
  6093. if (!(value instanceof _ParseRelation.default)) {
  6094. throw new Error('Called relation() on non-relation field ' + attr);
  6095. }
  6096. value._ensureParentAndKey(this, attr);
  6097. return value;
  6098. }
  6099. return new _ParseRelation.default(this, attr);
  6100. }
  6101. /**
  6102. * Gets the HTML-escaped value of an attribute.
  6103. * @param {String} attr The string name of an attribute.
  6104. */
  6105. }, {
  6106. key: "escape",
  6107. value: function (attr
  6108. /*: string*/
  6109. )
  6110. /*: string*/
  6111. {
  6112. var val = this.attributes[attr];
  6113. if (val == null) {
  6114. return '';
  6115. }
  6116. if (typeof val !== 'string') {
  6117. if (typeof val.toString !== 'function') {
  6118. return '';
  6119. }
  6120. val = val.toString();
  6121. }
  6122. return (0, _escape2.default)(val);
  6123. }
  6124. /**
  6125. * Returns <code>true</code> if the attribute contains a value that is not
  6126. * null or undefined.
  6127. * @param {String} attr The string name of the attribute.
  6128. * @return {Boolean}
  6129. */
  6130. }, {
  6131. key: "has",
  6132. value: function (attr
  6133. /*: string*/
  6134. )
  6135. /*: boolean*/
  6136. {
  6137. var attributes = this.attributes;
  6138. if (attributes.hasOwnProperty(attr)) {
  6139. return attributes[attr] != null;
  6140. }
  6141. return false;
  6142. }
  6143. /**
  6144. * Sets a hash of model attributes on the object.
  6145. *
  6146. * <p>You can call it with an object containing keys and values, with one
  6147. * key and value, or dot notation. For example:<pre>
  6148. * gameTurn.set({
  6149. * player: player1,
  6150. * diceRoll: 2
  6151. * }, {
  6152. * error: function(gameTurnAgain, error) {
  6153. * // The set failed validation.
  6154. * }
  6155. * });
  6156. *
  6157. * game.set("currentPlayer", player2, {
  6158. * error: function(gameTurnAgain, error) {
  6159. * // The set failed validation.
  6160. * }
  6161. * });
  6162. *
  6163. * game.set("finished", true);</pre></p>
  6164. *
  6165. * game.set("player.score", 10);</pre></p>
  6166. *
  6167. * @param {String} key The key to set.
  6168. * @param {} value The value to give it.
  6169. * @param {Object} options A set of options for the set.
  6170. * The only supported option is <code>error</code>.
  6171. * @return {(ParseObject|Boolean)} true if the set succeeded.
  6172. */
  6173. }, {
  6174. key: "set",
  6175. value: function (key
  6176. /*: mixed*/
  6177. , value
  6178. /*: mixed*/
  6179. , options
  6180. /*:: ?: mixed*/
  6181. )
  6182. /*: ParseObject | boolean*/
  6183. {
  6184. var changes = {};
  6185. var newOps = {};
  6186. if (key && (0, _typeof2.default)(key) === 'object') {
  6187. changes = key;
  6188. options = value;
  6189. } else if (typeof key === 'string') {
  6190. changes[key] = value;
  6191. } else {
  6192. return this;
  6193. }
  6194. options = options || {};
  6195. var readonly = [];
  6196. if (typeof this.constructor.readOnlyAttributes === 'function') {
  6197. readonly = readonly.concat(this.constructor.readOnlyAttributes());
  6198. }
  6199. for (var k in changes) {
  6200. if (k === 'createdAt' || k === 'updatedAt') {
  6201. // This property is read-only, but for legacy reasons we silently
  6202. // ignore it
  6203. continue;
  6204. }
  6205. if (readonly.indexOf(k) > -1) {
  6206. throw new Error('Cannot modify readonly attribute: ' + k);
  6207. }
  6208. if (options.unset) {
  6209. newOps[k] = new _ParseOp.UnsetOp();
  6210. } else if (changes[k] instanceof _ParseOp.Op) {
  6211. newOps[k] = changes[k];
  6212. } else if (changes[k] && (0, _typeof2.default)(changes[k]) === 'object' && typeof changes[k].__op === 'string') {
  6213. newOps[k] = (0, _ParseOp.opFromJSON)(changes[k]);
  6214. } else if (k === 'objectId' || k === 'id') {
  6215. if (typeof changes[k] === 'string') {
  6216. this.id = changes[k];
  6217. }
  6218. } else if (k === 'ACL' && (0, _typeof2.default)(changes[k]) === 'object' && !(changes[k] instanceof _ParseACL.default)) {
  6219. newOps[k] = new _ParseOp.SetOp(new _ParseACL.default(changes[k]));
  6220. } else if (changes[k] instanceof _ParseRelation.default) {
  6221. var relation = new _ParseRelation.default(this, k);
  6222. relation.targetClassName = changes[k].targetClassName;
  6223. newOps[k] = new _ParseOp.SetOp(relation);
  6224. } else {
  6225. newOps[k] = new _ParseOp.SetOp(changes[k]);
  6226. }
  6227. }
  6228. var currentAttributes = this.attributes; // Only set nested fields if exists
  6229. var serverData = this._getServerData();
  6230. if (typeof key === 'string' && key.includes('.')) {
  6231. var field = key.split('.')[0];
  6232. if (!serverData[field]) {
  6233. return this;
  6234. }
  6235. } // Calculate new values
  6236. var newValues = {};
  6237. for (var _attr9 in newOps) {
  6238. if (newOps[_attr9] instanceof _ParseOp.RelationOp) {
  6239. newValues[_attr9] = newOps[_attr9].applyTo(currentAttributes[_attr9], this, _attr9);
  6240. } else if (!(newOps[_attr9] instanceof _ParseOp.UnsetOp)) {
  6241. newValues[_attr9] = newOps[_attr9].applyTo(currentAttributes[_attr9]);
  6242. }
  6243. } // Validate changes
  6244. if (!options.ignoreValidation) {
  6245. var validation = this.validate(newValues);
  6246. if (validation) {
  6247. if (typeof options.error === 'function') {
  6248. options.error(this, validation);
  6249. }
  6250. return false;
  6251. }
  6252. } // Consolidate Ops
  6253. var pendingOps = this._getPendingOps();
  6254. var last = pendingOps.length - 1;
  6255. var stateController = _CoreManager.default.getObjectStateController();
  6256. for (var _attr10 in newOps) {
  6257. var nextOp = newOps[_attr10].mergeWith(pendingOps[last][_attr10]);
  6258. stateController.setPendingOp(this._getStateIdentifier(), _attr10, nextOp);
  6259. }
  6260. return this;
  6261. }
  6262. /**
  6263. * Remove an attribute from the model. This is a noop if the attribute doesn't
  6264. * exist.
  6265. * @param {String} attr The string name of an attribute.
  6266. * @return {(ParseObject|Boolean)}
  6267. */
  6268. }, {
  6269. key: "unset",
  6270. value: function (attr
  6271. /*: string*/
  6272. , options
  6273. /*:: ?: { [opt: string]: mixed }*/
  6274. )
  6275. /*: ParseObject | boolean*/
  6276. {
  6277. options = options || {};
  6278. options.unset = true;
  6279. return this.set(attr, null, options);
  6280. }
  6281. /**
  6282. * Atomically increments the value of the given attribute the next time the
  6283. * object is saved. If no amount is specified, 1 is used by default.
  6284. *
  6285. * @param attr {String} The key.
  6286. * @param amount {Number} The amount to increment by (optional).
  6287. * @return {(ParseObject|Boolean)}
  6288. */
  6289. }, {
  6290. key: "increment",
  6291. value: function (attr
  6292. /*: string*/
  6293. , amount
  6294. /*:: ?: number*/
  6295. )
  6296. /*: ParseObject | boolean*/
  6297. {
  6298. if (typeof amount === 'undefined') {
  6299. amount = 1;
  6300. }
  6301. if (typeof amount !== 'number') {
  6302. throw new Error('Cannot increment by a non-numeric amount.');
  6303. }
  6304. return this.set(attr, new _ParseOp.IncrementOp(amount));
  6305. }
  6306. /**
  6307. * Atomically add an object to the end of the array associated with a given
  6308. * key.
  6309. * @param attr {String} The key.
  6310. * @param item {} The item to add.
  6311. * @return {(ParseObject|Boolean)}
  6312. */
  6313. }, {
  6314. key: "add",
  6315. value: function (attr
  6316. /*: string*/
  6317. , item
  6318. /*: mixed*/
  6319. )
  6320. /*: ParseObject | boolean*/
  6321. {
  6322. return this.set(attr, new _ParseOp.AddOp([item]));
  6323. }
  6324. /**
  6325. * Atomically add the objects to the end of the array associated with a given
  6326. * key.
  6327. * @param attr {String} The key.
  6328. * @param items {Object[]} The items to add.
  6329. * @return {(ParseObject|Boolean)}
  6330. */
  6331. }, {
  6332. key: "addAll",
  6333. value: function (attr
  6334. /*: string*/
  6335. , items
  6336. /*: Array<mixed>*/
  6337. )
  6338. /*: ParseObject | boolean*/
  6339. {
  6340. return this.set(attr, new _ParseOp.AddOp(items));
  6341. }
  6342. /**
  6343. * Atomically add an object to the array associated with a given key, only
  6344. * if it is not already present in the array. The position of the insert is
  6345. * not guaranteed.
  6346. *
  6347. * @param attr {String} The key.
  6348. * @param item {} The object to add.
  6349. * @return {(ParseObject|Boolean)}
  6350. */
  6351. }, {
  6352. key: "addUnique",
  6353. value: function (attr
  6354. /*: string*/
  6355. , item
  6356. /*: mixed*/
  6357. )
  6358. /*: ParseObject | boolean*/
  6359. {
  6360. return this.set(attr, new _ParseOp.AddUniqueOp([item]));
  6361. }
  6362. /**
  6363. * Atomically add the objects to the array associated with a given key, only
  6364. * if it is not already present in the array. The position of the insert is
  6365. * not guaranteed.
  6366. *
  6367. * @param attr {String} The key.
  6368. * @param items {Object[]} The objects to add.
  6369. * @return {(ParseObject|Boolean)}
  6370. */
  6371. }, {
  6372. key: "addAllUnique",
  6373. value: function (attr
  6374. /*: string*/
  6375. , items
  6376. /*: Array<mixed>*/
  6377. )
  6378. /*: ParseObject | boolean*/
  6379. {
  6380. return this.set(attr, new _ParseOp.AddUniqueOp(items));
  6381. }
  6382. /**
  6383. * Atomically remove all instances of an object from the array associated
  6384. * with a given key.
  6385. *
  6386. * @param attr {String} The key.
  6387. * @param item {} The object to remove.
  6388. * @return {(ParseObject|Boolean)}
  6389. */
  6390. }, {
  6391. key: "remove",
  6392. value: function (attr
  6393. /*: string*/
  6394. , item
  6395. /*: mixed*/
  6396. )
  6397. /*: ParseObject | boolean*/
  6398. {
  6399. return this.set(attr, new _ParseOp.RemoveOp([item]));
  6400. }
  6401. /**
  6402. * Atomically remove all instances of the objects from the array associated
  6403. * with a given key.
  6404. *
  6405. * @param attr {String} The key.
  6406. * @param items {Object[]} The object to remove.
  6407. * @return {(ParseObject|Boolean)}
  6408. */
  6409. }, {
  6410. key: "removeAll",
  6411. value: function (attr
  6412. /*: string*/
  6413. , items
  6414. /*: Array<mixed>*/
  6415. )
  6416. /*: ParseObject | boolean*/
  6417. {
  6418. return this.set(attr, new _ParseOp.RemoveOp(items));
  6419. }
  6420. /**
  6421. * Returns an instance of a subclass of Parse.Op describing what kind of
  6422. * modification has been performed on this field since the last time it was
  6423. * saved. For example, after calling object.increment("x"), calling
  6424. * object.op("x") would return an instance of Parse.Op.Increment.
  6425. *
  6426. * @param attr {String} The key.
  6427. * @returns {Parse.Op} The operation, or undefined if none.
  6428. */
  6429. }, {
  6430. key: "op",
  6431. value: function (attr
  6432. /*: string*/
  6433. )
  6434. /*: ?Op*/
  6435. {
  6436. var pending = this._getPendingOps();
  6437. for (var i = pending.length; i--;) {
  6438. if (pending[i][attr]) {
  6439. return pending[i][attr];
  6440. }
  6441. }
  6442. }
  6443. /**
  6444. * Creates a new model with identical attributes to this one.
  6445. * @return {Parse.Object}
  6446. */
  6447. }, {
  6448. key: "clone",
  6449. value: function clone()
  6450. /*: any*/
  6451. {
  6452. var clone = new this.constructor();
  6453. if (!clone.className) {
  6454. clone.className = this.className;
  6455. }
  6456. var attributes = this.attributes;
  6457. if (typeof this.constructor.readOnlyAttributes === 'function') {
  6458. var readonly = this.constructor.readOnlyAttributes() || []; // Attributes are frozen, so we have to rebuild an object,
  6459. // rather than delete readonly keys
  6460. var copy = {};
  6461. for (var a in attributes) {
  6462. if (readonly.indexOf(a) < 0) {
  6463. copy[a] = attributes[a];
  6464. }
  6465. }
  6466. attributes = copy;
  6467. }
  6468. if (clone.set) {
  6469. clone.set(attributes);
  6470. }
  6471. return clone;
  6472. }
  6473. /**
  6474. * Creates a new instance of this object. Not to be confused with clone()
  6475. * @return {Parse.Object}
  6476. */
  6477. }, {
  6478. key: "newInstance",
  6479. value: function ()
  6480. /*: any*/
  6481. {
  6482. var clone = new this.constructor();
  6483. if (!clone.className) {
  6484. clone.className = this.className;
  6485. }
  6486. clone.id = this.id;
  6487. if (singleInstance) {
  6488. // Just return an object with the right id
  6489. return clone;
  6490. }
  6491. var stateController = _CoreManager.default.getObjectStateController();
  6492. if (stateController) {
  6493. stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier());
  6494. }
  6495. return clone;
  6496. }
  6497. /**
  6498. * Returns true if this object has never been saved to Parse.
  6499. * @return {Boolean}
  6500. */
  6501. }, {
  6502. key: "isNew",
  6503. value: function ()
  6504. /*: boolean*/
  6505. {
  6506. return !this.id;
  6507. }
  6508. /**
  6509. * Returns true if this object was created by the Parse server when the
  6510. * object might have already been there (e.g. in the case of a Facebook
  6511. * login)
  6512. * @return {Boolean}
  6513. */
  6514. }, {
  6515. key: "existed",
  6516. value: function ()
  6517. /*: boolean*/
  6518. {
  6519. if (!this.id) {
  6520. return false;
  6521. }
  6522. var stateController = _CoreManager.default.getObjectStateController();
  6523. var state = stateController.getState(this._getStateIdentifier());
  6524. if (state) {
  6525. return state.existed;
  6526. }
  6527. return false;
  6528. }
  6529. /**
  6530. * Checks if the model is currently in a valid state.
  6531. * @return {Boolean}
  6532. */
  6533. }, {
  6534. key: "isValid",
  6535. value: function ()
  6536. /*: boolean*/
  6537. {
  6538. return !this.validate(this.attributes);
  6539. }
  6540. /**
  6541. * You should not call this function directly unless you subclass
  6542. * <code>Parse.Object</code>, in which case you can override this method
  6543. * to provide additional validation on <code>set</code> and
  6544. * <code>save</code>. Your implementation should return
  6545. *
  6546. * @param {Object} attrs The current data to validate.
  6547. * @return {} False if the data is valid. An error object otherwise.
  6548. * @see Parse.Object#set
  6549. */
  6550. }, {
  6551. key: "validate",
  6552. value: function (attrs
  6553. /*: AttributeMap*/
  6554. )
  6555. /*: ParseError | boolean*/
  6556. {
  6557. if (attrs.hasOwnProperty('ACL') && !(attrs.ACL instanceof _ParseACL.default)) {
  6558. return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'ACL must be a Parse ACL.');
  6559. }
  6560. for (var _key in attrs) {
  6561. if (!/^[A-Za-z][0-9A-Za-z_.]*$/.test(_key)) {
  6562. return new _ParseError.default(_ParseError.default.INVALID_KEY_NAME);
  6563. }
  6564. }
  6565. return false;
  6566. }
  6567. /**
  6568. * Returns the ACL for this object.
  6569. * @returns {Parse.ACL} An instance of Parse.ACL.
  6570. * @see Parse.Object#get
  6571. */
  6572. }, {
  6573. key: "getACL",
  6574. value: function ()
  6575. /*: ?ParseACL*/
  6576. {
  6577. var acl = this.get('ACL');
  6578. if (acl instanceof _ParseACL.default) {
  6579. return acl;
  6580. }
  6581. return null;
  6582. }
  6583. /**
  6584. * Sets the ACL to be used for this object.
  6585. * @param {Parse.ACL} acl An instance of Parse.ACL.
  6586. * @param {Object} options
  6587. * @return {(ParseObject|Boolean)} Whether the set passed validation.
  6588. * @see Parse.Object#set
  6589. */
  6590. }, {
  6591. key: "setACL",
  6592. value: function (acl
  6593. /*: ParseACL*/
  6594. , options
  6595. /*:: ?: mixed*/
  6596. )
  6597. /*: ParseObject | boolean*/
  6598. {
  6599. return this.set('ACL', acl, options);
  6600. }
  6601. /**
  6602. * Clears any (or specific) changes to this object made since the last call to save()
  6603. * @param {string} [keys] - specify which fields to revert
  6604. */
  6605. }, {
  6606. key: "revert",
  6607. value: function ()
  6608. /*: void*/
  6609. {
  6610. var keysToRevert;
  6611. for (var _len = arguments.length, keys = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
  6612. keys[_key2] = arguments[_key2];
  6613. }
  6614. if (keys.length) {
  6615. keysToRevert = [];
  6616. for (var _i = 0, _keys = keys; _i < _keys.length; _i++) {
  6617. var _key3 = _keys[_i];
  6618. if (typeof _key3 === "string") {
  6619. keysToRevert.push(_key3);
  6620. } else {
  6621. throw new Error("Parse.Object#revert expects either no, or a list of string, arguments.");
  6622. }
  6623. }
  6624. }
  6625. this._clearPendingOps(keysToRevert);
  6626. }
  6627. /**
  6628. * Clears all attributes on a model
  6629. * @return {(ParseObject | boolean)}
  6630. */
  6631. }, {
  6632. key: "clear",
  6633. value: function ()
  6634. /*: ParseObject | boolean*/
  6635. {
  6636. var attributes = this.attributes;
  6637. var erasable = {};
  6638. var readonly = ['createdAt', 'updatedAt'];
  6639. if (typeof this.constructor.readOnlyAttributes === 'function') {
  6640. readonly = readonly.concat(this.constructor.readOnlyAttributes());
  6641. }
  6642. for (var _attr11 in attributes) {
  6643. if (readonly.indexOf(_attr11) < 0) {
  6644. erasable[_attr11] = true;
  6645. }
  6646. }
  6647. return this.set(erasable, {
  6648. unset: true
  6649. });
  6650. }
  6651. /**
  6652. * Fetch the model from the server. If the server's representation of the
  6653. * model differs from its current attributes, they will be overriden.
  6654. *
  6655. * @param {Object} options
  6656. * Valid options are:<ul>
  6657. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  6658. * be used for this request.
  6659. * <li>sessionToken: A valid session token, used for making a request on
  6660. * behalf of a specific user.
  6661. * <li>include: The name(s) of the key(s) to include. Can be a string, an array of strings,
  6662. * or an array of array of strings.
  6663. * </ul>
  6664. * @return {Promise} A promise that is fulfilled when the fetch
  6665. * completes.
  6666. */
  6667. }, {
  6668. key: "fetch",
  6669. value: function (options
  6670. /*: RequestOptions*/
  6671. )
  6672. /*: Promise*/
  6673. {
  6674. options = options || {};
  6675. var fetchOptions = {};
  6676. if (options.hasOwnProperty('useMasterKey')) {
  6677. fetchOptions.useMasterKey = options.useMasterKey;
  6678. }
  6679. if (options.hasOwnProperty('sessionToken')) {
  6680. fetchOptions.sessionToken = options.sessionToken;
  6681. }
  6682. if (options.hasOwnProperty('include')) {
  6683. fetchOptions.include = [];
  6684. if (Array.isArray(options.include)) {
  6685. options.include.forEach(function (key) {
  6686. if (Array.isArray(key)) {
  6687. fetchOptions.include = fetchOptions.include.concat(key);
  6688. } else {
  6689. fetchOptions.include.push(key);
  6690. }
  6691. });
  6692. } else {
  6693. fetchOptions.include.push(options.include);
  6694. }
  6695. }
  6696. var controller = _CoreManager.default.getObjectController();
  6697. return controller.fetch(this, true, fetchOptions);
  6698. }
  6699. /**
  6700. * Fetch the model from the server. If the server's representation of the
  6701. * model differs from its current attributes, they will be overriden.
  6702. *
  6703. * Includes nested Parse.Objects for the provided key. You can use dot
  6704. * notation to specify which fields in the included object are also fetched.
  6705. *
  6706. * @param {String|Array<string|Array<string>>} keys The name(s) of the key(s) to include.
  6707. * @param {Object} options
  6708. * Valid options are:<ul>
  6709. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  6710. * be used for this request.
  6711. * <li>sessionToken: A valid session token, used for making a request on
  6712. * behalf of a specific user.
  6713. * </ul>
  6714. * @return {Promise} A promise that is fulfilled when the fetch
  6715. * completes.
  6716. */
  6717. }, {
  6718. key: "fetchWithInclude",
  6719. value: function (keys
  6720. /*: String|Array<string|Array<string>>*/
  6721. , options
  6722. /*: RequestOptions*/
  6723. )
  6724. /*: Promise*/
  6725. {
  6726. options = options || {};
  6727. options.include = keys;
  6728. return this.fetch(options);
  6729. }
  6730. /**
  6731. * Set a hash of model attributes, and save the model to the server.
  6732. * updatedAt will be updated when the request returns.
  6733. * You can either call it as:<pre>
  6734. * object.save();</pre>
  6735. * or<pre>
  6736. * object.save(attrs);</pre>
  6737. * or<pre>
  6738. * object.save(null, options);</pre>
  6739. * or<pre>
  6740. * object.save(attrs, options);</pre>
  6741. * or<pre>
  6742. * object.save(key, value, options);</pre>
  6743. *
  6744. * For example, <pre>
  6745. * gameTurn.save({
  6746. * player: "Jake Cutter",
  6747. * diceRoll: 2
  6748. * }).then(function(gameTurnAgain) {
  6749. * // The save was successful.
  6750. * }, function(error) {
  6751. * // The save failed. Error is an instance of Parse.Error.
  6752. * });</pre>
  6753. *
  6754. * @param {String|Object|null} [attrs]
  6755. * Valid options are:<ul>
  6756. * <li>`Object` - Key/value pairs to update on the object.</li>
  6757. * <li>`String` Key - Key of attribute to update (requires arg2 to also be string)</li>
  6758. * <li>`null` - Passing null for arg1 allows you to save the object with options passed in arg2.</li>
  6759. * </ul>
  6760. *
  6761. * @param {String|Object} [options]
  6762. * <ul>
  6763. * <li>`String` Value - If arg1 was passed as a key, arg2 is the value that should be set on that key.</li>
  6764. * <li>`Object` Options - Valid options are:
  6765. * <ul>
  6766. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  6767. * be used for this request.
  6768. * <li>sessionToken: A valid session token, used for making a request on
  6769. * behalf of a specific user.
  6770. * </ul>
  6771. * </li>
  6772. * </ul>
  6773. *
  6774. * @param {Object} [options]
  6775. * Used to pass option parameters to method if arg1 and arg2 were both passed as strings.
  6776. * Valid options are:
  6777. * <ul>
  6778. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  6779. * be used for this request.
  6780. * <li>sessionToken: A valid session token, used for making a request on
  6781. * behalf of a specific user.
  6782. * </ul>
  6783. *
  6784. * @return {Promise} A promise that is fulfilled when the save
  6785. * completes.
  6786. */
  6787. }, {
  6788. key: "save",
  6789. value: function (arg1
  6790. /*: ?string | { [attr: string]: mixed }*/
  6791. , arg2
  6792. /*: FullOptions | mixed*/
  6793. , arg3
  6794. /*:: ?: FullOptions*/
  6795. )
  6796. /*: Promise*/
  6797. {
  6798. var _this = this;
  6799. var attrs;
  6800. var options;
  6801. if ((0, _typeof2.default)(arg1) === 'object' || typeof arg1 === 'undefined') {
  6802. attrs = arg1;
  6803. if ((0, _typeof2.default)(arg2) === 'object') {
  6804. options = arg2;
  6805. }
  6806. } else {
  6807. attrs = {};
  6808. attrs[arg1] = arg2;
  6809. options = arg3;
  6810. } // TODO: safely remove me
  6811. // Support save({ success: function() {}, error: function() {} })
  6812. if (!options && attrs) {
  6813. options = {};
  6814. if (typeof attrs.success === 'function') {
  6815. options.success = attrs.success;
  6816. delete attrs.success;
  6817. }
  6818. if (typeof attrs.error === 'function') {
  6819. options.error = attrs.error;
  6820. delete attrs.error;
  6821. }
  6822. }
  6823. if (attrs) {
  6824. var validation = this.validate(attrs);
  6825. if (validation) {
  6826. if (options && typeof options.error === 'function') {
  6827. options.error(this, validation);
  6828. }
  6829. return Promise.reject(validation);
  6830. }
  6831. this.set(attrs, options);
  6832. }
  6833. options = options || {};
  6834. var saveOptions = {};
  6835. if (options.hasOwnProperty('useMasterKey')) {
  6836. saveOptions.useMasterKey = !!options.useMasterKey;
  6837. }
  6838. if (options.hasOwnProperty('sessionToken') && typeof options.sessionToken === 'string') {
  6839. saveOptions.sessionToken = options.sessionToken;
  6840. }
  6841. var controller = _CoreManager.default.getObjectController();
  6842. var unsaved = (0, _unsavedChildren.default)(this);
  6843. return controller.save(unsaved, saveOptions).then(function () {
  6844. return controller.save(_this, saveOptions);
  6845. });
  6846. }
  6847. /**
  6848. * Destroy this model on the server if it was already persisted.
  6849. *
  6850. * @param {Object} options
  6851. * Valid options are:<ul>
  6852. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  6853. * be used for this request.
  6854. * <li>sessionToken: A valid session token, used for making a request on
  6855. * behalf of a specific user.
  6856. * </ul>
  6857. * @return {Promise} A promise that is fulfilled when the destroy
  6858. * completes.
  6859. */
  6860. }, {
  6861. key: "destroy",
  6862. value: function (options
  6863. /*: RequestOptions*/
  6864. )
  6865. /*: Promise*/
  6866. {
  6867. options = options || {};
  6868. var destroyOptions = {};
  6869. if (options.hasOwnProperty('useMasterKey')) {
  6870. destroyOptions.useMasterKey = options.useMasterKey;
  6871. }
  6872. if (options.hasOwnProperty('sessionToken')) {
  6873. destroyOptions.sessionToken = options.sessionToken;
  6874. }
  6875. if (!this.id) {
  6876. return Promise.resolve();
  6877. }
  6878. return _CoreManager.default.getObjectController().destroy(this, destroyOptions);
  6879. }
  6880. /**
  6881. * Asynchronously stores the object and every object it points to in the local datastore,
  6882. * recursively, using a default pin name: _default.
  6883. *
  6884. * If those other objects have not been fetched from Parse, they will not be stored.
  6885. * However, if they have changed data, all the changes will be retained.
  6886. *
  6887. * <pre>
  6888. * await object.pin();
  6889. * </pre>
  6890. *
  6891. * To retrieve object:
  6892. * <code>query.fromLocalDatastore()</code> or <code>query.fromPin()</code>
  6893. *
  6894. * @return {Promise} A promise that is fulfilled when the pin completes.
  6895. */
  6896. }, {
  6897. key: "pin",
  6898. value: function ()
  6899. /*: Promise<void>*/
  6900. {
  6901. return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
  6902. }
  6903. /**
  6904. * Asynchronously removes the object and every object it points to in the local datastore,
  6905. * recursively, using a default pin name: _default.
  6906. *
  6907. * <pre>
  6908. * await object.unPin();
  6909. * </pre>
  6910. *
  6911. * @return {Promise} A promise that is fulfilled when the unPin completes.
  6912. */
  6913. }, {
  6914. key: "unPin",
  6915. value: function ()
  6916. /*: Promise<void>*/
  6917. {
  6918. return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
  6919. }
  6920. /**
  6921. * Asynchronously returns if the object is pinned
  6922. *
  6923. * <pre>
  6924. * const isPinned = await object.isPinned();
  6925. * </pre>
  6926. *
  6927. * @return {Promise<boolean>} A boolean promise that is fulfilled if object is pinned.
  6928. */
  6929. }, {
  6930. key: "isPinned",
  6931. value: function () {
  6932. var _isPinned = (0, _asyncToGenerator2.default)(
  6933. /*#__PURE__*/
  6934. _regenerator.default.mark(function _callee() {
  6935. var localDatastore, objectKey, pin;
  6936. return _regenerator.default.wrap(function (_context) {
  6937. while (1) {
  6938. switch (_context.prev = _context.next) {
  6939. case 0:
  6940. localDatastore = _CoreManager.default.getLocalDatastore();
  6941. if (localDatastore.isEnabled) {
  6942. _context.next = 3;
  6943. break;
  6944. }
  6945. return _context.abrupt("return", Promise.reject('Parse.enableLocalDatastore() must be called first'));
  6946. case 3:
  6947. objectKey = localDatastore.getKeyForObject(this);
  6948. _context.next = 6;
  6949. return localDatastore.fromPinWithName(objectKey);
  6950. case 6:
  6951. pin = _context.sent;
  6952. return _context.abrupt("return", pin.length > 0);
  6953. case 8:
  6954. case "end":
  6955. return _context.stop();
  6956. }
  6957. }
  6958. }, _callee, this);
  6959. }));
  6960. return function () {
  6961. return _isPinned.apply(this, arguments);
  6962. };
  6963. }()
  6964. /**
  6965. * Asynchronously stores the objects and every object they point to in the local datastore, recursively.
  6966. *
  6967. * If those other objects have not been fetched from Parse, they will not be stored.
  6968. * However, if they have changed data, all the changes will be retained.
  6969. *
  6970. * <pre>
  6971. * await object.pinWithName(name);
  6972. * </pre>
  6973. *
  6974. * To retrieve object:
  6975. * <code>query.fromLocalDatastore()</code> or <code>query.fromPinWithName(name)</code>
  6976. *
  6977. * @param {String} name Name of Pin.
  6978. * @return {Promise} A promise that is fulfilled when the pin completes.
  6979. */
  6980. }, {
  6981. key: "pinWithName",
  6982. value: function (name
  6983. /*: string*/
  6984. )
  6985. /*: Promise<void>*/
  6986. {
  6987. return ParseObject.pinAllWithName(name, [this]);
  6988. }
  6989. /**
  6990. * Asynchronously removes the object and every object it points to in the local datastore, recursively.
  6991. *
  6992. * <pre>
  6993. * await object.unPinWithName(name);
  6994. * </pre>
  6995. *
  6996. * @param {String} name Name of Pin.
  6997. * @return {Promise} A promise that is fulfilled when the unPin completes.
  6998. */
  6999. }, {
  7000. key: "unPinWithName",
  7001. value: function (name
  7002. /*: string*/
  7003. )
  7004. /*: Promise<void>*/
  7005. {
  7006. return ParseObject.unPinAllWithName(name, [this]);
  7007. }
  7008. /**
  7009. * Asynchronously loads data from the local datastore into this object.
  7010. *
  7011. * <pre>
  7012. * await object.fetchFromLocalDatastore();
  7013. * </pre>
  7014. *
  7015. * You can create an unfetched pointer with <code>Parse.Object.createWithoutData()</code>
  7016. * and then call <code>fetchFromLocalDatastore()</code> on it.
  7017. *
  7018. * @return {Promise} A promise that is fulfilled when the fetch completes.
  7019. */
  7020. }, {
  7021. key: "fetchFromLocalDatastore",
  7022. value: function () {
  7023. var _fetchFromLocalDatastore = (0, _asyncToGenerator2.default)(
  7024. /*#__PURE__*/
  7025. _regenerator.default.mark(function _callee2() {
  7026. var localDatastore, objectKey, pinned, result;
  7027. return _regenerator.default.wrap(function (_context2) {
  7028. while (1) {
  7029. switch (_context2.prev = _context2.next) {
  7030. case 0:
  7031. localDatastore = _CoreManager.default.getLocalDatastore();
  7032. if (localDatastore.isEnabled) {
  7033. _context2.next = 3;
  7034. break;
  7035. }
  7036. throw new Error('Parse.enableLocalDatastore() must be called first');
  7037. case 3:
  7038. objectKey = localDatastore.getKeyForObject(this);
  7039. _context2.next = 6;
  7040. return localDatastore._serializeObject(objectKey);
  7041. case 6:
  7042. pinned = _context2.sent;
  7043. if (pinned) {
  7044. _context2.next = 9;
  7045. break;
  7046. }
  7047. throw new Error('Cannot fetch an unsaved ParseObject');
  7048. case 9:
  7049. result = ParseObject.fromJSON(pinned);
  7050. this._finishFetch(result.toJSON());
  7051. return _context2.abrupt("return", this);
  7052. case 12:
  7053. case "end":
  7054. return _context2.stop();
  7055. }
  7056. }
  7057. }, _callee2, this);
  7058. }));
  7059. return function () {
  7060. return _fetchFromLocalDatastore.apply(this, arguments);
  7061. };
  7062. }()
  7063. /** Static methods **/
  7064. }, {
  7065. key: "attributes",
  7066. /** Prototype getters / setters **/
  7067. get: function ()
  7068. /*: AttributeMap*/
  7069. {
  7070. var stateController = _CoreManager.default.getObjectStateController();
  7071. return Object.freeze(stateController.estimateAttributes(this._getStateIdentifier()));
  7072. }
  7073. /**
  7074. * The first time this object was saved on the server.
  7075. * @property createdAt
  7076. * @type Date
  7077. */
  7078. }, {
  7079. key: "createdAt",
  7080. get: function ()
  7081. /*: ?Date*/
  7082. {
  7083. return this._getServerData().createdAt;
  7084. }
  7085. /**
  7086. * The last time this object was updated on the server.
  7087. * @property updatedAt
  7088. * @type Date
  7089. */
  7090. }, {
  7091. key: "updatedAt",
  7092. get: function ()
  7093. /*: ?Date*/
  7094. {
  7095. return this._getServerData().updatedAt;
  7096. }
  7097. }], [{
  7098. key: "_clearAllState",
  7099. value: function () {
  7100. var stateController = _CoreManager.default.getObjectStateController();
  7101. stateController.clearAllState();
  7102. }
  7103. /**
  7104. * Fetches the given list of Parse.Object.
  7105. * If any error is encountered, stops and calls the error handler.
  7106. *
  7107. * <pre>
  7108. * Parse.Object.fetchAll([object1, object2, ...])
  7109. * .then((list) => {
  7110. * // All the objects were fetched.
  7111. * }, (error) => {
  7112. * // An error occurred while fetching one of the objects.
  7113. * });
  7114. * </pre>
  7115. *
  7116. * @param {Array} list A list of <code>Parse.Object</code>.
  7117. * @param {Object} options
  7118. * Valid options are:<ul>
  7119. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  7120. * be used for this request.
  7121. * <li>sessionToken: A valid session token, used for making a request on
  7122. * behalf of a specific user.
  7123. * <li>include: The name(s) of the key(s) to include. Can be a string, an array of strings,
  7124. * or an array of array of strings.
  7125. * </ul>
  7126. * @static
  7127. */
  7128. }, {
  7129. key: "fetchAll",
  7130. value: function (list
  7131. /*: Array<ParseObject>*/
  7132. ) {
  7133. var options
  7134. /*: RequestOptions*/
  7135. = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  7136. var queryOptions = {};
  7137. if (options.hasOwnProperty('useMasterKey')) {
  7138. queryOptions.useMasterKey = options.useMasterKey;
  7139. }
  7140. if (options.hasOwnProperty('sessionToken')) {
  7141. queryOptions.sessionToken = options.sessionToken;
  7142. }
  7143. if (options.hasOwnProperty('include')) {
  7144. queryOptions.include = [];
  7145. if (Array.isArray(options.include)) {
  7146. options.include.forEach(function (key) {
  7147. if (Array.isArray(key)) {
  7148. queryOptions.include = queryOptions.include.concat(key);
  7149. } else {
  7150. queryOptions.include.push(key);
  7151. }
  7152. });
  7153. } else {
  7154. queryOptions.include.push(options.include);
  7155. }
  7156. }
  7157. return _CoreManager.default.getObjectController().fetch(list, true, queryOptions);
  7158. }
  7159. /**
  7160. * Fetches the given list of Parse.Object.
  7161. *
  7162. * Includes nested Parse.Objects for the provided key. You can use dot
  7163. * notation to specify which fields in the included object are also fetched.
  7164. *
  7165. * If any error is encountered, stops and calls the error handler.
  7166. *
  7167. * <pre>
  7168. * Parse.Object.fetchAllWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
  7169. * .then((list) => {
  7170. * // All the objects were fetched.
  7171. * }, (error) => {
  7172. * // An error occurred while fetching one of the objects.
  7173. * });
  7174. * </pre>
  7175. *
  7176. * @param {Array} list A list of <code>Parse.Object</code>.
  7177. * @param {String|Array<string|Array<string>>} keys The name(s) of the key(s) to include.
  7178. * @param {Object} options
  7179. * Valid options are:<ul>
  7180. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  7181. * be used for this request.
  7182. * <li>sessionToken: A valid session token, used for making a request on
  7183. * behalf of a specific user.
  7184. * </ul>
  7185. * @static
  7186. */
  7187. }, {
  7188. key: "fetchAllWithInclude",
  7189. value: function (list
  7190. /*: Array<ParseObject>*/
  7191. , keys
  7192. /*: String|Array<string|Array<string>>*/
  7193. , options
  7194. /*: RequestOptions*/
  7195. ) {
  7196. options = options || {};
  7197. options.include = keys;
  7198. return ParseObject.fetchAll(list, options);
  7199. }
  7200. /**
  7201. * Fetches the given list of Parse.Object if needed.
  7202. * If any error is encountered, stops and calls the error handler.
  7203. *
  7204. * <pre>
  7205. * Parse.Object.fetchAllIfNeeded([object1, ...])
  7206. * .then((list) => {
  7207. * // Objects were fetched and updated.
  7208. * }, (error) => {
  7209. * // An error occurred while fetching one of the objects.
  7210. * });
  7211. * </pre>
  7212. *
  7213. * @param {Array} list A list of <code>Parse.Object</code>.
  7214. * @param {Object} options
  7215. * @static
  7216. */
  7217. }, {
  7218. key: "fetchAllIfNeeded",
  7219. value: function (list
  7220. /*: Array<ParseObject>*/
  7221. , options) {
  7222. options = options || {};
  7223. var queryOptions = {};
  7224. if (options.hasOwnProperty('useMasterKey')) {
  7225. queryOptions.useMasterKey = options.useMasterKey;
  7226. }
  7227. if (options.hasOwnProperty('sessionToken')) {
  7228. queryOptions.sessionToken = options.sessionToken;
  7229. }
  7230. return _CoreManager.default.getObjectController().fetch(list, false, queryOptions);
  7231. }
  7232. /**
  7233. * Destroy the given list of models on the server if it was already persisted.
  7234. *
  7235. * <p>Unlike saveAll, if an error occurs while deleting an individual model,
  7236. * this method will continue trying to delete the rest of the models if
  7237. * possible, except in the case of a fatal error like a connection error.
  7238. *
  7239. * <p>In particular, the Parse.Error object returned in the case of error may
  7240. * be one of two types:
  7241. *
  7242. * <ul>
  7243. * <li>A Parse.Error.AGGREGATE_ERROR. This object's "errors" property is an
  7244. * array of other Parse.Error objects. Each error object in this array
  7245. * has an "object" property that references the object that could not be
  7246. * deleted (for instance, because that object could not be found).</li>
  7247. * <li>A non-aggregate Parse.Error. This indicates a serious error that
  7248. * caused the delete operation to be aborted partway through (for
  7249. * instance, a connection failure in the middle of the delete).</li>
  7250. * </ul>
  7251. *
  7252. * <pre>
  7253. * Parse.Object.destroyAll([object1, object2, ...])
  7254. * .then((list) => {
  7255. * // All the objects were deleted.
  7256. * }, (error) => {
  7257. * // An error occurred while deleting one or more of the objects.
  7258. * // If this is an aggregate error, then we can inspect each error
  7259. * // object individually to determine the reason why a particular
  7260. * // object was not deleted.
  7261. * if (error.code === Parse.Error.AGGREGATE_ERROR) {
  7262. * for (var i = 0; i < error.errors.length; i++) {
  7263. * console.log("Couldn't delete " + error.errors[i].object.id +
  7264. * "due to " + error.errors[i].message);
  7265. * }
  7266. * } else {
  7267. * console.log("Delete aborted because of " + error.message);
  7268. * }
  7269. * });
  7270. * </pre>
  7271. *
  7272. * @param {Array} list A list of <code>Parse.Object</code>.
  7273. * @param {Object} options
  7274. * @static
  7275. * Valid options are:<ul>
  7276. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  7277. * be used for this request.
  7278. * <li>sessionToken: A valid session token, used for making a request on
  7279. * behalf of a specific user.
  7280. * <li>batchSize: Number of objects to process per request
  7281. * </ul>
  7282. * @return {Promise} A promise that is fulfilled when the destroyAll
  7283. * completes.
  7284. */
  7285. }, {
  7286. key: "destroyAll",
  7287. value: function (list
  7288. /*: Array<ParseObject>*/
  7289. ) {
  7290. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  7291. var destroyOptions = {};
  7292. if (options.hasOwnProperty('useMasterKey')) {
  7293. destroyOptions.useMasterKey = options.useMasterKey;
  7294. }
  7295. if (options.hasOwnProperty('sessionToken')) {
  7296. destroyOptions.sessionToken = options.sessionToken;
  7297. }
  7298. if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
  7299. destroyOptions.batchSize = options.batchSize;
  7300. }
  7301. return _CoreManager.default.getObjectController().destroy(list, destroyOptions);
  7302. }
  7303. /**
  7304. * Saves the given list of Parse.Object.
  7305. * If any error is encountered, stops and calls the error handler.
  7306. *
  7307. * <pre>
  7308. * Parse.Object.saveAll([object1, object2, ...])
  7309. * .then((list) => {
  7310. * // All the objects were saved.
  7311. * }, (error) => {
  7312. * // An error occurred while saving one of the objects.
  7313. * });
  7314. * </pre>
  7315. *
  7316. * @param {Array} list A list of <code>Parse.Object</code>.
  7317. * @param {Object} options
  7318. * @static
  7319. * Valid options are:<ul>
  7320. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  7321. * be used for this request.
  7322. * <li>sessionToken: A valid session token, used for making a request on
  7323. * behalf of a specific user.
  7324. * <li>batchSize: Number of objects to process per request
  7325. * </ul>
  7326. */
  7327. }, {
  7328. key: "saveAll",
  7329. value: function (list
  7330. /*: Array<ParseObject>*/
  7331. ) {
  7332. var options
  7333. /*: RequestOptions*/
  7334. = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  7335. var saveOptions = {};
  7336. if (options.hasOwnProperty('useMasterKey')) {
  7337. saveOptions.useMasterKey = options.useMasterKey;
  7338. }
  7339. if (options.hasOwnProperty('sessionToken')) {
  7340. saveOptions.sessionToken = options.sessionToken;
  7341. }
  7342. if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
  7343. saveOptions.batchSize = options.batchSize;
  7344. }
  7345. return _CoreManager.default.getObjectController().save(list, saveOptions);
  7346. }
  7347. /**
  7348. * Creates a reference to a subclass of Parse.Object with the given id. This
  7349. * does not exist on Parse.Object, only on subclasses.
  7350. *
  7351. * <p>A shortcut for: <pre>
  7352. * var Foo = Parse.Object.extend("Foo");
  7353. * var pointerToFoo = new Foo();
  7354. * pointerToFoo.id = "myObjectId";
  7355. * </pre>
  7356. *
  7357. * @param {String} id The ID of the object to create a reference to.
  7358. * @static
  7359. * @return {Parse.Object} A Parse.Object reference.
  7360. */
  7361. }, {
  7362. key: "createWithoutData",
  7363. value: function (id
  7364. /*: string*/
  7365. ) {
  7366. var obj = new this();
  7367. obj.id = id;
  7368. return obj;
  7369. }
  7370. /**
  7371. * Creates a new instance of a Parse Object from a JSON representation.
  7372. * @param {Object} json The JSON map of the Object's data
  7373. * @param {boolean} override In single instance mode, all old server data
  7374. * is overwritten if this is set to true
  7375. * @static
  7376. * @return {Parse.Object} A Parse.Object reference
  7377. */
  7378. }, {
  7379. key: "fromJSON",
  7380. value: function (json
  7381. /*: any*/
  7382. , override
  7383. /*:: ?: boolean*/
  7384. ) {
  7385. if (!json.className) {
  7386. throw new Error('Cannot create an object without a className');
  7387. }
  7388. var constructor = classMap[json.className];
  7389. var o = constructor ? new constructor() : new ParseObject(json.className);
  7390. var otherAttributes = {};
  7391. for (var _attr12 in json) {
  7392. if (_attr12 !== 'className' && _attr12 !== '__type') {
  7393. otherAttributes[_attr12] = json[_attr12];
  7394. }
  7395. }
  7396. if (override) {
  7397. // id needs to be set before clearServerData can work
  7398. if (otherAttributes.objectId) {
  7399. o.id = otherAttributes.objectId;
  7400. }
  7401. var preserved = null;
  7402. if (typeof o._preserveFieldsOnFetch === 'function') {
  7403. preserved = o._preserveFieldsOnFetch();
  7404. }
  7405. o._clearServerData();
  7406. if (preserved) {
  7407. o._finishFetch(preserved);
  7408. }
  7409. }
  7410. o._finishFetch(otherAttributes);
  7411. if (json.objectId) {
  7412. o._setExisted(true);
  7413. }
  7414. return o;
  7415. }
  7416. /**
  7417. * Registers a subclass of Parse.Object with a specific class name.
  7418. * When objects of that class are retrieved from a query, they will be
  7419. * instantiated with this subclass.
  7420. * This is only necessary when using ES6 subclassing.
  7421. * @param {String} className The class name of the subclass
  7422. * @param {Class} constructor The subclass
  7423. */
  7424. }, {
  7425. key: "registerSubclass",
  7426. value: function (className
  7427. /*: string*/
  7428. , constructor
  7429. /*: any*/
  7430. ) {
  7431. if (typeof className !== 'string') {
  7432. throw new TypeError('The first argument must be a valid class name.');
  7433. }
  7434. if (typeof constructor === 'undefined') {
  7435. throw new TypeError('You must supply a subclass constructor.');
  7436. }
  7437. if (typeof constructor !== 'function') {
  7438. throw new TypeError('You must register the subclass constructor. ' + 'Did you attempt to register an instance of the subclass?');
  7439. }
  7440. classMap[className] = constructor;
  7441. if (!constructor.className) {
  7442. constructor.className = className;
  7443. }
  7444. }
  7445. /**
  7446. * Creates a new subclass of Parse.Object for the given Parse class name.
  7447. *
  7448. * <p>Every extension of a Parse class will inherit from the most recent
  7449. * previous extension of that class. When a Parse.Object is automatically
  7450. * created by parsing JSON, it will use the most recent extension of that
  7451. * class.</p>
  7452. *
  7453. * <p>You should call either:<pre>
  7454. * var MyClass = Parse.Object.extend("MyClass", {
  7455. * <i>Instance methods</i>,
  7456. * initialize: function(attrs, options) {
  7457. * this.someInstanceProperty = [],
  7458. * <i>Other instance properties</i>
  7459. * }
  7460. * }, {
  7461. * <i>Class properties</i>
  7462. * });</pre>
  7463. * or, for Backbone compatibility:<pre>
  7464. * var MyClass = Parse.Object.extend({
  7465. * className: "MyClass",
  7466. * <i>Instance methods</i>,
  7467. * initialize: function(attrs, options) {
  7468. * this.someInstanceProperty = [],
  7469. * <i>Other instance properties</i>
  7470. * }
  7471. * }, {
  7472. * <i>Class properties</i>
  7473. * });</pre></p>
  7474. *
  7475. * @param {String} className The name of the Parse class backing this model.
  7476. * @param {Object} protoProps Instance properties to add to instances of the
  7477. * class returned from this method.
  7478. * @param {Object} classProps Class properties to add the class returned from
  7479. * this method.
  7480. * @return {Class} A new subclass of Parse.Object.
  7481. */
  7482. }, {
  7483. key: "extend",
  7484. value: function (className
  7485. /*: any*/
  7486. , protoProps
  7487. /*: any*/
  7488. , classProps
  7489. /*: any*/
  7490. ) {
  7491. if (typeof className !== 'string') {
  7492. if (className && typeof className.className === 'string') {
  7493. return ParseObject.extend(className.className, className, protoProps);
  7494. } else {
  7495. throw new Error('Parse.Object.extend\'s first argument should be the className.');
  7496. }
  7497. }
  7498. var adjustedClassName = className;
  7499. if (adjustedClassName === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
  7500. adjustedClassName = '_User';
  7501. }
  7502. var parentProto = ParseObject.prototype;
  7503. if (this.hasOwnProperty('__super__') && this.__super__) {
  7504. parentProto = this.prototype;
  7505. } else if (classMap[adjustedClassName]) {
  7506. parentProto = classMap[adjustedClassName].prototype;
  7507. }
  7508. var ParseObjectSubclass = function (attributes, options) {
  7509. this.className = adjustedClassName;
  7510. this._objCount = objectCount++; // Enable legacy initializers
  7511. if (typeof this.initialize === 'function') {
  7512. this.initialize.apply(this, arguments);
  7513. }
  7514. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  7515. if (!this.set(attributes || {}, options)) {
  7516. throw new Error('Can\'t create an invalid Parse Object');
  7517. }
  7518. }
  7519. };
  7520. ParseObjectSubclass.className = adjustedClassName;
  7521. ParseObjectSubclass.__super__ = parentProto;
  7522. ParseObjectSubclass.prototype = Object.create(parentProto, {
  7523. constructor: {
  7524. value: ParseObjectSubclass,
  7525. enumerable: false,
  7526. writable: true,
  7527. configurable: true
  7528. }
  7529. });
  7530. if (protoProps) {
  7531. for (var prop in protoProps) {
  7532. if (prop !== 'className') {
  7533. Object.defineProperty(ParseObjectSubclass.prototype, prop, {
  7534. value: protoProps[prop],
  7535. enumerable: false,
  7536. writable: true,
  7537. configurable: true
  7538. });
  7539. }
  7540. }
  7541. }
  7542. if (classProps) {
  7543. for (var _prop in classProps) {
  7544. if (_prop !== 'className') {
  7545. Object.defineProperty(ParseObjectSubclass, _prop, {
  7546. value: classProps[_prop],
  7547. enumerable: false,
  7548. writable: true,
  7549. configurable: true
  7550. });
  7551. }
  7552. }
  7553. }
  7554. ParseObjectSubclass.extend = function (name, protoProps, classProps) {
  7555. if (typeof name === 'string') {
  7556. return ParseObject.extend.call(ParseObjectSubclass, name, protoProps, classProps);
  7557. }
  7558. return ParseObject.extend.call(ParseObjectSubclass, adjustedClassName, name, protoProps);
  7559. };
  7560. ParseObjectSubclass.createWithoutData = ParseObject.createWithoutData;
  7561. classMap[adjustedClassName] = ParseObjectSubclass;
  7562. return ParseObjectSubclass;
  7563. }
  7564. /**
  7565. * Enable single instance objects, where any local objects with the same Id
  7566. * share the same attributes, and stay synchronized with each other.
  7567. * This is disabled by default in server environments, since it can lead to
  7568. * security issues.
  7569. * @static
  7570. */
  7571. }, {
  7572. key: "enableSingleInstance",
  7573. value: function () {
  7574. singleInstance = true;
  7575. _CoreManager.default.setObjectStateController(SingleInstanceStateController);
  7576. }
  7577. /**
  7578. * Disable single instance objects, where any local objects with the same Id
  7579. * share the same attributes, and stay synchronized with each other.
  7580. * When disabled, you can have two instances of the same object in memory
  7581. * without them sharing attributes.
  7582. * @static
  7583. */
  7584. }, {
  7585. key: "disableSingleInstance",
  7586. value: function () {
  7587. singleInstance = false;
  7588. _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
  7589. }
  7590. /**
  7591. * Asynchronously stores the objects and every object they point to in the local datastore,
  7592. * recursively, using a default pin name: _default.
  7593. *
  7594. * If those other objects have not been fetched from Parse, they will not be stored.
  7595. * However, if they have changed data, all the changes will be retained.
  7596. *
  7597. * <pre>
  7598. * await Parse.Object.pinAll([...]);
  7599. * </pre>
  7600. *
  7601. * To retrieve object:
  7602. * <code>query.fromLocalDatastore()</code> or <code>query.fromPin()</code>
  7603. *
  7604. * @param {Array} objects A list of <code>Parse.Object</code>.
  7605. * @return {Promise} A promise that is fulfilled when the pin completes.
  7606. * @static
  7607. */
  7608. }, {
  7609. key: "pinAll",
  7610. value: function (objects
  7611. /*: Array<ParseObject>*/
  7612. )
  7613. /*: Promise<void>*/
  7614. {
  7615. var localDatastore = _CoreManager.default.getLocalDatastore();
  7616. if (!localDatastore.isEnabled) {
  7617. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7618. }
  7619. return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
  7620. }
  7621. /**
  7622. * Asynchronously stores the objects and every object they point to in the local datastore, recursively.
  7623. *
  7624. * If those other objects have not been fetched from Parse, they will not be stored.
  7625. * However, if they have changed data, all the changes will be retained.
  7626. *
  7627. * <pre>
  7628. * await Parse.Object.pinAllWithName(name, [obj1, obj2, ...]);
  7629. * </pre>
  7630. *
  7631. * To retrieve object:
  7632. * <code>query.fromLocalDatastore()</code> or <code>query.fromPinWithName(name)</code>
  7633. *
  7634. * @param {String} name Name of Pin.
  7635. * @param {Array} objects A list of <code>Parse.Object</code>.
  7636. * @return {Promise} A promise that is fulfilled when the pin completes.
  7637. * @static
  7638. */
  7639. }, {
  7640. key: "pinAllWithName",
  7641. value: function (name
  7642. /*: string*/
  7643. , objects
  7644. /*: Array<ParseObject>*/
  7645. )
  7646. /*: Promise<void>*/
  7647. {
  7648. var localDatastore = _CoreManager.default.getLocalDatastore();
  7649. if (!localDatastore.isEnabled) {
  7650. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7651. }
  7652. return localDatastore._handlePinAllWithName(name, objects);
  7653. }
  7654. /**
  7655. * Asynchronously removes the objects and every object they point to in the local datastore,
  7656. * recursively, using a default pin name: _default.
  7657. *
  7658. * <pre>
  7659. * await Parse.Object.unPinAll([...]);
  7660. * </pre>
  7661. *
  7662. * @param {Array} objects A list of <code>Parse.Object</code>.
  7663. * @return {Promise} A promise that is fulfilled when the unPin completes.
  7664. * @static
  7665. */
  7666. }, {
  7667. key: "unPinAll",
  7668. value: function (objects
  7669. /*: Array<ParseObject>*/
  7670. )
  7671. /*: Promise<void>*/
  7672. {
  7673. var localDatastore = _CoreManager.default.getLocalDatastore();
  7674. if (!localDatastore.isEnabled) {
  7675. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7676. }
  7677. return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
  7678. }
  7679. /**
  7680. * Asynchronously removes the objects and every object they point to in the local datastore, recursively.
  7681. *
  7682. * <pre>
  7683. * await Parse.Object.unPinAllWithName(name, [obj1, obj2, ...]);
  7684. * </pre>
  7685. *
  7686. * @param {String} name Name of Pin.
  7687. * @param {Array} objects A list of <code>Parse.Object</code>.
  7688. * @return {Promise} A promise that is fulfilled when the unPin completes.
  7689. * @static
  7690. */
  7691. }, {
  7692. key: "unPinAllWithName",
  7693. value: function (name
  7694. /*: string*/
  7695. , objects
  7696. /*: Array<ParseObject>*/
  7697. )
  7698. /*: Promise<void>*/
  7699. {
  7700. var localDatastore = _CoreManager.default.getLocalDatastore();
  7701. if (!localDatastore.isEnabled) {
  7702. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7703. }
  7704. return localDatastore._handleUnPinAllWithName(name, objects);
  7705. }
  7706. /**
  7707. * Asynchronously removes all objects in the local datastore using a default pin name: _default.
  7708. *
  7709. * <pre>
  7710. * await Parse.Object.unPinAllObjects();
  7711. * </pre>
  7712. *
  7713. * @return {Promise} A promise that is fulfilled when the unPin completes.
  7714. * @static
  7715. */
  7716. }, {
  7717. key: "unPinAllObjects",
  7718. value: function ()
  7719. /*: Promise<void>*/
  7720. {
  7721. var localDatastore = _CoreManager.default.getLocalDatastore();
  7722. if (!localDatastore.isEnabled) {
  7723. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7724. }
  7725. return localDatastore.unPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
  7726. }
  7727. /**
  7728. * Asynchronously removes all objects with the specified pin name.
  7729. * Deletes the pin name also.
  7730. *
  7731. * <pre>
  7732. * await Parse.Object.unPinAllObjectsWithName(name);
  7733. * </pre>
  7734. *
  7735. * @param {String} name Name of Pin.
  7736. * @return {Promise} A promise that is fulfilled when the unPin completes.
  7737. * @static
  7738. */
  7739. }, {
  7740. key: "unPinAllObjectsWithName",
  7741. value: function (name
  7742. /*: string*/
  7743. )
  7744. /*: Promise<void>*/
  7745. {
  7746. var localDatastore = _CoreManager.default.getLocalDatastore();
  7747. if (!localDatastore.isEnabled) {
  7748. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7749. }
  7750. return localDatastore.unPinWithName(_LocalDatastoreUtils.PIN_PREFIX + name);
  7751. }
  7752. }]);
  7753. return ParseObject;
  7754. }();
  7755. var DefaultController = {
  7756. fetch: function (target
  7757. /*: ParseObject | Array<ParseObject>*/
  7758. , forceFetch
  7759. /*: boolean*/
  7760. , options
  7761. /*: RequestOptions*/
  7762. )
  7763. /*: Promise<Array<void> | ParseObject>*/
  7764. {
  7765. var localDatastore = _CoreManager.default.getLocalDatastore();
  7766. if (Array.isArray(target)) {
  7767. if (target.length < 1) {
  7768. return Promise.resolve([]);
  7769. }
  7770. var objs = [];
  7771. var ids = [];
  7772. var className = null;
  7773. var results = [];
  7774. var error = null;
  7775. target.forEach(function (el) {
  7776. if (error) {
  7777. return;
  7778. }
  7779. if (!className) {
  7780. className = el.className;
  7781. }
  7782. if (className !== el.className) {
  7783. error = new _ParseError.default(_ParseError.default.INVALID_CLASS_NAME, 'All objects should be of the same class');
  7784. }
  7785. if (!el.id) {
  7786. error = new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'All objects must have an ID');
  7787. }
  7788. if (forceFetch || !el.isDataAvailable()) {
  7789. ids.push(el.id);
  7790. objs.push(el);
  7791. }
  7792. results.push(el);
  7793. });
  7794. if (error) {
  7795. return Promise.reject(error);
  7796. }
  7797. var query = new _ParseQuery.default(className);
  7798. query.containedIn('objectId', ids);
  7799. if (options && options.include) {
  7800. query.include(options.include);
  7801. }
  7802. query._limit = ids.length;
  7803. return query.find(options).then(
  7804. /*#__PURE__*/
  7805. function () {
  7806. var _ref = (0, _asyncToGenerator2.default)(
  7807. /*#__PURE__*/
  7808. _regenerator.default.mark(function _callee3(objects) {
  7809. var idMap, i, obj, _i2, _obj, id, _i3, _results, object;
  7810. return _regenerator.default.wrap(function (_context3) {
  7811. while (1) {
  7812. switch (_context3.prev = _context3.next) {
  7813. case 0:
  7814. idMap = {};
  7815. objects.forEach(function (o) {
  7816. idMap[o.id] = o;
  7817. });
  7818. i = 0;
  7819. case 3:
  7820. if (!(i < objs.length)) {
  7821. _context3.next = 11;
  7822. break;
  7823. }
  7824. obj = objs[i];
  7825. if (!(!obj || !obj.id || !idMap[obj.id])) {
  7826. _context3.next = 8;
  7827. break;
  7828. }
  7829. if (!forceFetch) {
  7830. _context3.next = 8;
  7831. break;
  7832. }
  7833. return _context3.abrupt("return", Promise.reject(new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'All objects must exist on the server.')));
  7834. case 8:
  7835. i++;
  7836. _context3.next = 3;
  7837. break;
  7838. case 11:
  7839. if (!singleInstance) {
  7840. // If single instance objects are disabled, we need to replace the
  7841. for (_i2 = 0; _i2 < results.length; _i2++) {
  7842. _obj = results[_i2];
  7843. if (_obj && _obj.id && idMap[_obj.id]) {
  7844. id = _obj.id;
  7845. _obj._finishFetch(idMap[id].toJSON());
  7846. results[_i2] = idMap[id];
  7847. }
  7848. }
  7849. }
  7850. _i3 = 0, _results = results;
  7851. case 13:
  7852. if (!(_i3 < _results.length)) {
  7853. _context3.next = 20;
  7854. break;
  7855. }
  7856. object = _results[_i3];
  7857. _context3.next = 17;
  7858. return localDatastore._updateObjectIfPinned(object);
  7859. case 17:
  7860. _i3++;
  7861. _context3.next = 13;
  7862. break;
  7863. case 20:
  7864. return _context3.abrupt("return", Promise.resolve(results));
  7865. case 21:
  7866. case "end":
  7867. return _context3.stop();
  7868. }
  7869. }
  7870. }, _callee3);
  7871. }));
  7872. return function () {
  7873. return _ref.apply(this, arguments);
  7874. };
  7875. }());
  7876. } else {
  7877. var RESTController = _CoreManager.default.getRESTController();
  7878. var params = {};
  7879. if (options && options.include) {
  7880. params.include = options.include.join();
  7881. }
  7882. return RESTController.request('GET', 'classes/' + target.className + '/' + target._getId(), params, options).then(
  7883. /*#__PURE__*/
  7884. function () {
  7885. var _ref2 = (0, _asyncToGenerator2.default)(
  7886. /*#__PURE__*/
  7887. _regenerator.default.mark(function _callee4(response) {
  7888. return _regenerator.default.wrap(function (_context4) {
  7889. while (1) {
  7890. switch (_context4.prev = _context4.next) {
  7891. case 0:
  7892. if (target instanceof ParseObject) {
  7893. target._clearPendingOps();
  7894. target._clearServerData();
  7895. target._finishFetch(response);
  7896. }
  7897. _context4.next = 3;
  7898. return localDatastore._updateObjectIfPinned(target);
  7899. case 3:
  7900. return _context4.abrupt("return", target);
  7901. case 4:
  7902. case "end":
  7903. return _context4.stop();
  7904. }
  7905. }
  7906. }, _callee4);
  7907. }));
  7908. return function () {
  7909. return _ref2.apply(this, arguments);
  7910. };
  7911. }());
  7912. }
  7913. },
  7914. destroy: function () {
  7915. var _destroy = (0, _asyncToGenerator2.default)(
  7916. /*#__PURE__*/
  7917. _regenerator.default.mark(function _callee7(target
  7918. /*: ParseObject | Array<ParseObject>*/
  7919. , options
  7920. /*: RequestOptions*/
  7921. ) {
  7922. var batchSize, localDatastore, RESTController, batches, deleteCompleted, errors;
  7923. return _regenerator.default.wrap(function (_context7) {
  7924. while (1) {
  7925. switch (_context7.prev = _context7.next) {
  7926. case 0:
  7927. batchSize = options && options.batchSize ? options.batchSize : DEFAULT_BATCH_SIZE;
  7928. localDatastore = _CoreManager.default.getLocalDatastore();
  7929. RESTController = _CoreManager.default.getRESTController();
  7930. if (!Array.isArray(target)) {
  7931. _context7.next = 15;
  7932. break;
  7933. }
  7934. if (!(target.length < 1)) {
  7935. _context7.next = 6;
  7936. break;
  7937. }
  7938. return _context7.abrupt("return", Promise.resolve([]));
  7939. case 6:
  7940. batches = [[]];
  7941. target.forEach(function (obj) {
  7942. if (!obj.id) {
  7943. return;
  7944. }
  7945. batches[batches.length - 1].push(obj);
  7946. if (batches[batches.length - 1].length >= batchSize) {
  7947. batches.push([]);
  7948. }
  7949. });
  7950. if (batches[batches.length - 1].length === 0) {
  7951. // If the last batch is empty, remove it
  7952. batches.pop();
  7953. }
  7954. deleteCompleted = Promise.resolve();
  7955. errors = [];
  7956. batches.forEach(function (batch) {
  7957. deleteCompleted = deleteCompleted.then(function () {
  7958. return RESTController.request('POST', 'batch', {
  7959. requests: batch.map(function (obj) {
  7960. return {
  7961. method: 'DELETE',
  7962. path: getServerUrlPath() + 'classes/' + obj.className + '/' + obj._getId(),
  7963. body: {}
  7964. };
  7965. })
  7966. }, options).then(function (results) {
  7967. for (var i = 0; i < results.length; i++) {
  7968. if (results[i] && results[i].hasOwnProperty('error')) {
  7969. var err = new _ParseError.default(results[i].error.code, results[i].error.error);
  7970. err.object = batch[i];
  7971. errors.push(err);
  7972. }
  7973. }
  7974. });
  7975. });
  7976. });
  7977. return _context7.abrupt("return", deleteCompleted.then(
  7978. /*#__PURE__*/
  7979. (0, _asyncToGenerator2.default)(
  7980. /*#__PURE__*/
  7981. _regenerator.default.mark(function _callee5() {
  7982. var aggregate, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, object;
  7983. return _regenerator.default.wrap(function (_context5) {
  7984. while (1) {
  7985. switch (_context5.prev = _context5.next) {
  7986. case 0:
  7987. if (!errors.length) {
  7988. _context5.next = 4;
  7989. break;
  7990. }
  7991. aggregate = new _ParseError.default(_ParseError.default.AGGREGATE_ERROR);
  7992. aggregate.errors = errors;
  7993. return _context5.abrupt("return", Promise.reject(aggregate));
  7994. case 4:
  7995. _iteratorNormalCompletion = true;
  7996. _didIteratorError = false;
  7997. _iteratorError = undefined;
  7998. _context5.prev = 7;
  7999. _iterator = target[Symbol.iterator]();
  8000. case 9:
  8001. if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
  8002. _context5.next = 16;
  8003. break;
  8004. }
  8005. object = _step.value;
  8006. _context5.next = 13;
  8007. return localDatastore._destroyObjectIfPinned(object);
  8008. case 13:
  8009. _iteratorNormalCompletion = true;
  8010. _context5.next = 9;
  8011. break;
  8012. case 16:
  8013. _context5.next = 22;
  8014. break;
  8015. case 18:
  8016. _context5.prev = 18;
  8017. _context5.t0 = _context5["catch"](7);
  8018. _didIteratorError = true;
  8019. _iteratorError = _context5.t0;
  8020. case 22:
  8021. _context5.prev = 22;
  8022. _context5.prev = 23;
  8023. if (!_iteratorNormalCompletion && _iterator.return != null) {
  8024. _iterator.return();
  8025. }
  8026. case 25:
  8027. _context5.prev = 25;
  8028. if (!_didIteratorError) {
  8029. _context5.next = 28;
  8030. break;
  8031. }
  8032. throw _iteratorError;
  8033. case 28:
  8034. return _context5.finish(25);
  8035. case 29:
  8036. return _context5.finish(22);
  8037. case 30:
  8038. return _context5.abrupt("return", Promise.resolve(target));
  8039. case 31:
  8040. case "end":
  8041. return _context5.stop();
  8042. }
  8043. }
  8044. }, _callee5, null, [[7, 18, 22, 30], [23,, 25, 29]]);
  8045. }))));
  8046. case 15:
  8047. if (!(target instanceof ParseObject)) {
  8048. _context7.next = 17;
  8049. break;
  8050. }
  8051. return _context7.abrupt("return", RESTController.request('DELETE', 'classes/' + target.className + '/' + target._getId(), {}, options).then(
  8052. /*#__PURE__*/
  8053. (0, _asyncToGenerator2.default)(
  8054. /*#__PURE__*/
  8055. _regenerator.default.mark(function _callee6() {
  8056. return _regenerator.default.wrap(function (_context6) {
  8057. while (1) {
  8058. switch (_context6.prev = _context6.next) {
  8059. case 0:
  8060. _context6.next = 2;
  8061. return localDatastore._destroyObjectIfPinned(target);
  8062. case 2:
  8063. return _context6.abrupt("return", Promise.resolve(target));
  8064. case 3:
  8065. case "end":
  8066. return _context6.stop();
  8067. }
  8068. }
  8069. }, _callee6);
  8070. }))));
  8071. case 17:
  8072. _context7.next = 19;
  8073. return localDatastore._destroyObjectIfPinned(target);
  8074. case 19:
  8075. return _context7.abrupt("return", Promise.resolve(target));
  8076. case 20:
  8077. case "end":
  8078. return _context7.stop();
  8079. }
  8080. }
  8081. }, _callee7);
  8082. }));
  8083. return function () {
  8084. return _destroy.apply(this, arguments);
  8085. };
  8086. }(),
  8087. save: function (target
  8088. /*: ParseObject | Array<ParseObject | ParseFile>*/
  8089. , options
  8090. /*: RequestOptions*/
  8091. ) {
  8092. var batchSize = options && options.batchSize ? options.batchSize : DEFAULT_BATCH_SIZE;
  8093. var localDatastore = _CoreManager.default.getLocalDatastore();
  8094. var mapIdForPin = {};
  8095. var RESTController = _CoreManager.default.getRESTController();
  8096. var stateController = _CoreManager.default.getObjectStateController();
  8097. options = options || {};
  8098. options.returnStatus = options.returnStatus || true;
  8099. if (Array.isArray(target)) {
  8100. if (target.length < 1) {
  8101. return Promise.resolve([]);
  8102. }
  8103. var unsaved = target.concat();
  8104. for (var i = 0; i < target.length; i++) {
  8105. if (target[i] instanceof ParseObject) {
  8106. unsaved = unsaved.concat((0, _unsavedChildren.default)(target[i], true));
  8107. }
  8108. }
  8109. unsaved = (0, _unique.default)(unsaved);
  8110. var filesSaved = Promise.resolve();
  8111. var pending
  8112. /*: Array<ParseObject>*/
  8113. = [];
  8114. unsaved.forEach(function (el) {
  8115. if (el instanceof _ParseFile.default) {
  8116. filesSaved = filesSaved.then(function () {
  8117. return el.save();
  8118. });
  8119. } else if (el instanceof ParseObject) {
  8120. pending.push(el);
  8121. }
  8122. });
  8123. return filesSaved.then(function () {
  8124. var objectError = null;
  8125. return (0, _promiseUtils.continueWhile)(function () {
  8126. return pending.length > 0;
  8127. }, function () {
  8128. var batch = [];
  8129. var nextPending = [];
  8130. pending.forEach(function (el) {
  8131. if (batch.length < batchSize && (0, _canBeSerialized.default)(el)) {
  8132. batch.push(el);
  8133. } else {
  8134. nextPending.push(el);
  8135. }
  8136. });
  8137. pending = nextPending;
  8138. if (batch.length < 1) {
  8139. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Tried to save a batch with a cycle.'));
  8140. } // Queue up tasks for each object in the batch.
  8141. // When every task is ready, the API request will execute
  8142. var res, rej;
  8143. var batchReturned = new Promise(function (resolve, reject) {
  8144. res = resolve;
  8145. rej = reject;
  8146. });
  8147. batchReturned.resolve = res;
  8148. batchReturned.reject = rej;
  8149. var batchReady = [];
  8150. var batchTasks = [];
  8151. batch.forEach(function (obj, index) {
  8152. var res, rej;
  8153. var ready = new Promise(function (resolve, reject) {
  8154. res = resolve;
  8155. rej = reject;
  8156. });
  8157. ready.resolve = res;
  8158. ready.reject = rej;
  8159. batchReady.push(ready);
  8160. stateController.pushPendingState(obj._getStateIdentifier());
  8161. batchTasks.push(stateController.enqueueTask(obj._getStateIdentifier(), function () {
  8162. ready.resolve();
  8163. return batchReturned.then(function (responses) {
  8164. if (responses[index].hasOwnProperty('success')) {
  8165. var objectId = responses[index].success.objectId;
  8166. var status = responses[index]._status;
  8167. delete responses[index]._status;
  8168. mapIdForPin[objectId] = obj._localId;
  8169. obj._handleSaveResponse(responses[index].success, status);
  8170. } else {
  8171. if (!objectError && responses[index].hasOwnProperty('error')) {
  8172. var serverError = responses[index].error;
  8173. objectError = new _ParseError.default(serverError.code, serverError.error); // Cancel the rest of the save
  8174. pending = [];
  8175. }
  8176. obj._handleSaveError();
  8177. }
  8178. });
  8179. }));
  8180. });
  8181. (0, _promiseUtils.when)(batchReady).then(function () {
  8182. // Kick off the batch request
  8183. return RESTController.request('POST', 'batch', {
  8184. requests: batch.map(function (obj) {
  8185. var params = obj._getSaveParams();
  8186. params.path = getServerUrlPath() + params.path;
  8187. return params;
  8188. })
  8189. }, options);
  8190. }).then(batchReturned.resolve, function (error) {
  8191. batchReturned.reject(new _ParseError.default(_ParseError.default.INCORRECT_TYPE, error.message));
  8192. });
  8193. return (0, _promiseUtils.when)(batchTasks);
  8194. }).then(
  8195. /*#__PURE__*/
  8196. (0, _asyncToGenerator2.default)(
  8197. /*#__PURE__*/
  8198. _regenerator.default.mark(function _callee8() {
  8199. var _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, object;
  8200. return _regenerator.default.wrap(function (_context8) {
  8201. while (1) {
  8202. switch (_context8.prev = _context8.next) {
  8203. case 0:
  8204. if (!objectError) {
  8205. _context8.next = 2;
  8206. break;
  8207. }
  8208. return _context8.abrupt("return", Promise.reject(objectError));
  8209. case 2:
  8210. _iteratorNormalCompletion2 = true;
  8211. _didIteratorError2 = false;
  8212. _iteratorError2 = undefined;
  8213. _context8.prev = 5;
  8214. _iterator2 = target[Symbol.iterator]();
  8215. case 7:
  8216. if (_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done) {
  8217. _context8.next = 16;
  8218. break;
  8219. }
  8220. object = _step2.value;
  8221. _context8.next = 11;
  8222. return localDatastore._updateLocalIdForObject(mapIdForPin[object.id], object);
  8223. case 11:
  8224. _context8.next = 13;
  8225. return localDatastore._updateObjectIfPinned(object);
  8226. case 13:
  8227. _iteratorNormalCompletion2 = true;
  8228. _context8.next = 7;
  8229. break;
  8230. case 16:
  8231. _context8.next = 22;
  8232. break;
  8233. case 18:
  8234. _context8.prev = 18;
  8235. _context8.t0 = _context8["catch"](5);
  8236. _didIteratorError2 = true;
  8237. _iteratorError2 = _context8.t0;
  8238. case 22:
  8239. _context8.prev = 22;
  8240. _context8.prev = 23;
  8241. if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
  8242. _iterator2.return();
  8243. }
  8244. case 25:
  8245. _context8.prev = 25;
  8246. if (!_didIteratorError2) {
  8247. _context8.next = 28;
  8248. break;
  8249. }
  8250. throw _iteratorError2;
  8251. case 28:
  8252. return _context8.finish(25);
  8253. case 29:
  8254. return _context8.finish(22);
  8255. case 30:
  8256. return _context8.abrupt("return", Promise.resolve(target));
  8257. case 31:
  8258. case "end":
  8259. return _context8.stop();
  8260. }
  8261. }
  8262. }, _callee8, null, [[5, 18, 22, 30], [23,, 25, 29]]);
  8263. })));
  8264. });
  8265. } else if (target instanceof ParseObject) {
  8266. // copying target lets Flow guarantee the pointer isn't modified elsewhere
  8267. var localId = target._localId;
  8268. var targetCopy = target;
  8269. var task = function () {
  8270. var params = targetCopy._getSaveParams();
  8271. return RESTController.request(params.method, params.path, params.body, options).then(function (response) {
  8272. var status = response._status;
  8273. delete response._status;
  8274. targetCopy._handleSaveResponse(response, status);
  8275. }, function (error) {
  8276. targetCopy._handleSaveError();
  8277. return Promise.reject(error);
  8278. });
  8279. };
  8280. stateController.pushPendingState(target._getStateIdentifier());
  8281. return stateController.enqueueTask(target._getStateIdentifier(), task).then(
  8282. /*#__PURE__*/
  8283. (0, _asyncToGenerator2.default)(
  8284. /*#__PURE__*/
  8285. _regenerator.default.mark(function _callee9() {
  8286. return _regenerator.default.wrap(function (_context9) {
  8287. while (1) {
  8288. switch (_context9.prev = _context9.next) {
  8289. case 0:
  8290. _context9.next = 2;
  8291. return localDatastore._updateLocalIdForObject(localId, target);
  8292. case 2:
  8293. _context9.next = 4;
  8294. return localDatastore._updateObjectIfPinned(target);
  8295. case 4:
  8296. return _context9.abrupt("return", target);
  8297. case 5:
  8298. case "end":
  8299. return _context9.stop();
  8300. }
  8301. }
  8302. }, _callee9);
  8303. })), function (error) {
  8304. return Promise.reject(error);
  8305. });
  8306. }
  8307. return Promise.resolve();
  8308. }
  8309. };
  8310. _CoreManager.default.setObjectController(DefaultController);
  8311. var _default = ParseObject;
  8312. exports.default = _default;
  8313. },{"./CoreManager":4,"./LocalDatastoreUtils":12,"./ParseACL":16,"./ParseError":18,"./ParseFile":19,"./ParseOp":24,"./ParseQuery":26,"./ParseRelation":27,"./SingleInstanceStateController":34,"./UniqueInstanceStateController":38,"./canBeSerialized":40,"./decode":41,"./encode":42,"./escape":44,"./parseDate":46,"./promiseUtils":47,"./unique":48,"./unsavedChildren":49,"@babel/runtime/helpers/asyncToGenerator":53,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/interopRequireWildcard":62,"@babel/runtime/helpers/typeof":73,"@babel/runtime/regenerator":76}],24:[function(_dereq_,module,exports){
  8314. "use strict";
  8315. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  8316. Object.defineProperty(exports, "__esModule", {
  8317. value: true
  8318. });
  8319. exports.opFromJSON = opFromJSON;
  8320. exports.RelationOp = exports.RemoveOp = exports.AddUniqueOp = exports.AddOp = exports.IncrementOp = exports.UnsetOp = exports.SetOp = exports.Op = void 0;
  8321. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  8322. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  8323. var _assertThisInitialized2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/assertThisInitialized"));
  8324. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  8325. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  8326. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  8327. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  8328. var _arrayContainsObject = _interopRequireDefault(_dereq_("./arrayContainsObject"));
  8329. var _decode = _interopRequireDefault(_dereq_("./decode"));
  8330. var _encode = _interopRequireDefault(_dereq_("./encode"));
  8331. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  8332. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  8333. var _unique = _interopRequireDefault(_dereq_("./unique"));
  8334. /**
  8335. * Copyright (c) 2015-present, Parse, LLC.
  8336. * All rights reserved.
  8337. *
  8338. * This source code is licensed under the BSD-style license found in the
  8339. * LICENSE file in the root directory of this source tree. An additional grant
  8340. * of patent rights can be found in the PATENTS file in the same directory.
  8341. *
  8342. * @flow
  8343. */
  8344. function opFromJSON(json
  8345. /*: { [key: string]: any }*/
  8346. )
  8347. /*: ?Op*/
  8348. {
  8349. if (!json || !json.__op) {
  8350. return null;
  8351. }
  8352. switch (json.__op) {
  8353. case 'Delete':
  8354. return new UnsetOp();
  8355. case 'Increment':
  8356. return new IncrementOp(json.amount);
  8357. case 'Add':
  8358. return new AddOp((0, _decode.default)(json.objects));
  8359. case 'AddUnique':
  8360. return new AddUniqueOp((0, _decode.default)(json.objects));
  8361. case 'Remove':
  8362. return new RemoveOp((0, _decode.default)(json.objects));
  8363. case 'AddRelation':
  8364. {
  8365. var toAdd = (0, _decode.default)(json.objects);
  8366. if (!Array.isArray(toAdd)) {
  8367. return new RelationOp([], []);
  8368. }
  8369. return new RelationOp(toAdd, []);
  8370. }
  8371. case 'RemoveRelation':
  8372. {
  8373. var toRemove = (0, _decode.default)(json.objects);
  8374. if (!Array.isArray(toRemove)) {
  8375. return new RelationOp([], []);
  8376. }
  8377. return new RelationOp([], toRemove);
  8378. }
  8379. case 'Batch':
  8380. {
  8381. var _toAdd = [];
  8382. var _toRemove = [];
  8383. for (var i = 0; i < json.ops.length; i++) {
  8384. if (json.ops[i].__op === 'AddRelation') {
  8385. _toAdd = _toAdd.concat((0, _decode.default)(json.ops[i].objects));
  8386. } else if (json.ops[i].__op === 'RemoveRelation') {
  8387. _toRemove = _toRemove.concat((0, _decode.default)(json.ops[i].objects));
  8388. }
  8389. }
  8390. return new RelationOp(_toAdd, _toRemove);
  8391. }
  8392. }
  8393. return null;
  8394. }
  8395. var Op =
  8396. /*#__PURE__*/
  8397. function () {
  8398. function Op() {
  8399. (0, _classCallCheck2.default)(this, Op);
  8400. }
  8401. (0, _createClass2.default)(Op, [{
  8402. key: "applyTo",
  8403. // Empty parent class
  8404. value: function ()
  8405. /*: mixed*/
  8406. /*: mixed*/
  8407. {}
  8408. /* eslint-disable-line no-unused-vars */
  8409. }, {
  8410. key: "mergeWith",
  8411. value: function ()
  8412. /*: Op*/
  8413. /*: ?Op*/
  8414. {}
  8415. /* eslint-disable-line no-unused-vars */
  8416. }, {
  8417. key: "toJSON",
  8418. value: function ()
  8419. /*: mixed*/
  8420. {}
  8421. }]);
  8422. return Op;
  8423. }();
  8424. exports.Op = Op;
  8425. var SetOp =
  8426. /*#__PURE__*/
  8427. function (_Op) {
  8428. (0, _inherits2.default)(SetOp, _Op);
  8429. function SetOp(value
  8430. /*: mixed*/
  8431. ) {
  8432. var _this;
  8433. (0, _classCallCheck2.default)(this, SetOp);
  8434. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(SetOp).call(this));
  8435. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "_value", void 0);
  8436. _this._value = value;
  8437. return _this;
  8438. }
  8439. (0, _createClass2.default)(SetOp, [{
  8440. key: "applyTo",
  8441. value: function ()
  8442. /*: mixed*/
  8443. {
  8444. return this._value;
  8445. }
  8446. }, {
  8447. key: "mergeWith",
  8448. value: function ()
  8449. /*: SetOp*/
  8450. {
  8451. return new SetOp(this._value);
  8452. }
  8453. }, {
  8454. key: "toJSON",
  8455. value: function () {
  8456. return (0, _encode.default)(this._value, false, true);
  8457. }
  8458. }]);
  8459. return SetOp;
  8460. }(Op);
  8461. exports.SetOp = SetOp;
  8462. var UnsetOp =
  8463. /*#__PURE__*/
  8464. function (_Op2) {
  8465. (0, _inherits2.default)(UnsetOp, _Op2);
  8466. function UnsetOp() {
  8467. (0, _classCallCheck2.default)(this, UnsetOp);
  8468. return (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(UnsetOp).apply(this, arguments));
  8469. }
  8470. (0, _createClass2.default)(UnsetOp, [{
  8471. key: "applyTo",
  8472. value: function () {
  8473. return undefined;
  8474. }
  8475. }, {
  8476. key: "mergeWith",
  8477. value: function ()
  8478. /*: UnsetOp*/
  8479. {
  8480. return new UnsetOp();
  8481. }
  8482. }, {
  8483. key: "toJSON",
  8484. value: function ()
  8485. /*: { __op: string }*/
  8486. {
  8487. return {
  8488. __op: 'Delete'
  8489. };
  8490. }
  8491. }]);
  8492. return UnsetOp;
  8493. }(Op);
  8494. exports.UnsetOp = UnsetOp;
  8495. var IncrementOp =
  8496. /*#__PURE__*/
  8497. function (_Op3) {
  8498. (0, _inherits2.default)(IncrementOp, _Op3);
  8499. function IncrementOp(amount
  8500. /*: number*/
  8501. ) {
  8502. var _this2;
  8503. (0, _classCallCheck2.default)(this, IncrementOp);
  8504. _this2 = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(IncrementOp).call(this));
  8505. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this2), "_amount", void 0);
  8506. if (typeof amount !== 'number') {
  8507. throw new TypeError('Increment Op must be initialized with a numeric amount.');
  8508. }
  8509. _this2._amount = amount;
  8510. return _this2;
  8511. }
  8512. (0, _createClass2.default)(IncrementOp, [{
  8513. key: "applyTo",
  8514. value: function (value
  8515. /*: ?mixed*/
  8516. )
  8517. /*: number*/
  8518. {
  8519. if (typeof value === 'undefined') {
  8520. return this._amount;
  8521. }
  8522. if (typeof value !== 'number') {
  8523. throw new TypeError('Cannot increment a non-numeric value.');
  8524. }
  8525. return this._amount + value;
  8526. }
  8527. }, {
  8528. key: "mergeWith",
  8529. value: function (previous
  8530. /*: Op*/
  8531. )
  8532. /*: Op*/
  8533. {
  8534. if (!previous) {
  8535. return this;
  8536. }
  8537. if (previous instanceof SetOp) {
  8538. return new SetOp(this.applyTo(previous._value));
  8539. }
  8540. if (previous instanceof UnsetOp) {
  8541. return new SetOp(this._amount);
  8542. }
  8543. if (previous instanceof IncrementOp) {
  8544. return new IncrementOp(this.applyTo(previous._amount));
  8545. }
  8546. throw new Error('Cannot merge Increment Op with the previous Op');
  8547. }
  8548. }, {
  8549. key: "toJSON",
  8550. value: function ()
  8551. /*: { __op: string; amount: number }*/
  8552. {
  8553. return {
  8554. __op: 'Increment',
  8555. amount: this._amount
  8556. };
  8557. }
  8558. }]);
  8559. return IncrementOp;
  8560. }(Op);
  8561. exports.IncrementOp = IncrementOp;
  8562. var AddOp =
  8563. /*#__PURE__*/
  8564. function (_Op4) {
  8565. (0, _inherits2.default)(AddOp, _Op4);
  8566. function AddOp(value
  8567. /*: mixed | Array<mixed>*/
  8568. ) {
  8569. var _this3;
  8570. (0, _classCallCheck2.default)(this, AddOp);
  8571. _this3 = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(AddOp).call(this));
  8572. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this3), "_value", void 0);
  8573. _this3._value = Array.isArray(value) ? value : [value];
  8574. return _this3;
  8575. }
  8576. (0, _createClass2.default)(AddOp, [{
  8577. key: "applyTo",
  8578. value: function (value
  8579. /*: mixed*/
  8580. )
  8581. /*: Array<mixed>*/
  8582. {
  8583. if (value == null) {
  8584. return this._value;
  8585. }
  8586. if (Array.isArray(value)) {
  8587. return value.concat(this._value);
  8588. }
  8589. throw new Error('Cannot add elements to a non-array value');
  8590. }
  8591. }, {
  8592. key: "mergeWith",
  8593. value: function (previous
  8594. /*: Op*/
  8595. )
  8596. /*: Op*/
  8597. {
  8598. if (!previous) {
  8599. return this;
  8600. }
  8601. if (previous instanceof SetOp) {
  8602. return new SetOp(this.applyTo(previous._value));
  8603. }
  8604. if (previous instanceof UnsetOp) {
  8605. return new SetOp(this._value);
  8606. }
  8607. if (previous instanceof AddOp) {
  8608. return new AddOp(this.applyTo(previous._value));
  8609. }
  8610. throw new Error('Cannot merge Add Op with the previous Op');
  8611. }
  8612. }, {
  8613. key: "toJSON",
  8614. value: function ()
  8615. /*: { __op: string; objects: mixed }*/
  8616. {
  8617. return {
  8618. __op: 'Add',
  8619. objects: (0, _encode.default)(this._value, false, true)
  8620. };
  8621. }
  8622. }]);
  8623. return AddOp;
  8624. }(Op);
  8625. exports.AddOp = AddOp;
  8626. var AddUniqueOp =
  8627. /*#__PURE__*/
  8628. function (_Op5) {
  8629. (0, _inherits2.default)(AddUniqueOp, _Op5);
  8630. function AddUniqueOp(value
  8631. /*: mixed | Array<mixed>*/
  8632. ) {
  8633. var _this4;
  8634. (0, _classCallCheck2.default)(this, AddUniqueOp);
  8635. _this4 = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(AddUniqueOp).call(this));
  8636. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this4), "_value", void 0);
  8637. _this4._value = (0, _unique.default)(Array.isArray(value) ? value : [value]);
  8638. return _this4;
  8639. }
  8640. (0, _createClass2.default)(AddUniqueOp, [{
  8641. key: "applyTo",
  8642. value: function (value
  8643. /*: mixed | Array<mixed>*/
  8644. )
  8645. /*: Array<mixed>*/
  8646. {
  8647. if (value == null) {
  8648. return this._value || [];
  8649. }
  8650. if (Array.isArray(value)) {
  8651. // copying value lets Flow guarantee the pointer isn't modified elsewhere
  8652. var valueCopy = value;
  8653. var toAdd = [];
  8654. this._value.forEach(function (v) {
  8655. if (v instanceof _ParseObject.default) {
  8656. if (!(0, _arrayContainsObject.default)(valueCopy, v)) {
  8657. toAdd.push(v);
  8658. }
  8659. } else {
  8660. if (valueCopy.indexOf(v) < 0) {
  8661. toAdd.push(v);
  8662. }
  8663. }
  8664. });
  8665. return value.concat(toAdd);
  8666. }
  8667. throw new Error('Cannot add elements to a non-array value');
  8668. }
  8669. }, {
  8670. key: "mergeWith",
  8671. value: function (previous
  8672. /*: Op*/
  8673. )
  8674. /*: Op*/
  8675. {
  8676. if (!previous) {
  8677. return this;
  8678. }
  8679. if (previous instanceof SetOp) {
  8680. return new SetOp(this.applyTo(previous._value));
  8681. }
  8682. if (previous instanceof UnsetOp) {
  8683. return new SetOp(this._value);
  8684. }
  8685. if (previous instanceof AddUniqueOp) {
  8686. return new AddUniqueOp(this.applyTo(previous._value));
  8687. }
  8688. throw new Error('Cannot merge AddUnique Op with the previous Op');
  8689. }
  8690. }, {
  8691. key: "toJSON",
  8692. value: function ()
  8693. /*: { __op: string; objects: mixed }*/
  8694. {
  8695. return {
  8696. __op: 'AddUnique',
  8697. objects: (0, _encode.default)(this._value, false, true)
  8698. };
  8699. }
  8700. }]);
  8701. return AddUniqueOp;
  8702. }(Op);
  8703. exports.AddUniqueOp = AddUniqueOp;
  8704. var RemoveOp =
  8705. /*#__PURE__*/
  8706. function (_Op6) {
  8707. (0, _inherits2.default)(RemoveOp, _Op6);
  8708. function RemoveOp(value
  8709. /*: mixed | Array<mixed>*/
  8710. ) {
  8711. var _this5;
  8712. (0, _classCallCheck2.default)(this, RemoveOp);
  8713. _this5 = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(RemoveOp).call(this));
  8714. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this5), "_value", void 0);
  8715. _this5._value = (0, _unique.default)(Array.isArray(value) ? value : [value]);
  8716. return _this5;
  8717. }
  8718. (0, _createClass2.default)(RemoveOp, [{
  8719. key: "applyTo",
  8720. value: function (value
  8721. /*: mixed | Array<mixed>*/
  8722. )
  8723. /*: Array<mixed>*/
  8724. {
  8725. if (value == null) {
  8726. return [];
  8727. }
  8728. if (Array.isArray(value)) {
  8729. // var i = value.indexOf(this._value);
  8730. var removed = value.concat([]);
  8731. for (var i = 0; i < this._value.length; i++) {
  8732. var index = removed.indexOf(this._value[i]);
  8733. while (index > -1) {
  8734. removed.splice(index, 1);
  8735. index = removed.indexOf(this._value[i]);
  8736. }
  8737. if (this._value[i] instanceof _ParseObject.default && this._value[i].id) {
  8738. for (var j = 0; j < removed.length; j++) {
  8739. if (removed[j] instanceof _ParseObject.default && this._value[i].id === removed[j].id) {
  8740. removed.splice(j, 1);
  8741. j--;
  8742. }
  8743. }
  8744. }
  8745. }
  8746. return removed;
  8747. }
  8748. throw new Error('Cannot remove elements from a non-array value');
  8749. }
  8750. }, {
  8751. key: "mergeWith",
  8752. value: function (previous
  8753. /*: Op*/
  8754. )
  8755. /*: Op*/
  8756. {
  8757. if (!previous) {
  8758. return this;
  8759. }
  8760. if (previous instanceof SetOp) {
  8761. return new SetOp(this.applyTo(previous._value));
  8762. }
  8763. if (previous instanceof UnsetOp) {
  8764. return new UnsetOp();
  8765. }
  8766. if (previous instanceof RemoveOp) {
  8767. var uniques = previous._value.concat([]);
  8768. for (var i = 0; i < this._value.length; i++) {
  8769. if (this._value[i] instanceof _ParseObject.default) {
  8770. if (!(0, _arrayContainsObject.default)(uniques, this._value[i])) {
  8771. uniques.push(this._value[i]);
  8772. }
  8773. } else {
  8774. if (uniques.indexOf(this._value[i]) < 0) {
  8775. uniques.push(this._value[i]);
  8776. }
  8777. }
  8778. }
  8779. return new RemoveOp(uniques);
  8780. }
  8781. throw new Error('Cannot merge Remove Op with the previous Op');
  8782. }
  8783. }, {
  8784. key: "toJSON",
  8785. value: function ()
  8786. /*: { __op: string; objects: mixed }*/
  8787. {
  8788. return {
  8789. __op: 'Remove',
  8790. objects: (0, _encode.default)(this._value, false, true)
  8791. };
  8792. }
  8793. }]);
  8794. return RemoveOp;
  8795. }(Op);
  8796. exports.RemoveOp = RemoveOp;
  8797. var RelationOp =
  8798. /*#__PURE__*/
  8799. function (_Op7) {
  8800. (0, _inherits2.default)(RelationOp, _Op7);
  8801. function RelationOp(adds
  8802. /*: Array<ParseObject | string>*/
  8803. , removes
  8804. /*: Array<ParseObject | string>*/
  8805. ) {
  8806. var _this6;
  8807. (0, _classCallCheck2.default)(this, RelationOp);
  8808. _this6 = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(RelationOp).call(this));
  8809. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this6), "_targetClassName", void 0);
  8810. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this6), "relationsToAdd", void 0);
  8811. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this6), "relationsToRemove", void 0);
  8812. _this6._targetClassName = null;
  8813. if (Array.isArray(adds)) {
  8814. _this6.relationsToAdd = (0, _unique.default)(adds.map(_this6._extractId, (0, _assertThisInitialized2.default)(_this6)));
  8815. }
  8816. if (Array.isArray(removes)) {
  8817. _this6.relationsToRemove = (0, _unique.default)(removes.map(_this6._extractId, (0, _assertThisInitialized2.default)(_this6)));
  8818. }
  8819. return _this6;
  8820. }
  8821. (0, _createClass2.default)(RelationOp, [{
  8822. key: "_extractId",
  8823. value: function (obj
  8824. /*: string | ParseObject*/
  8825. )
  8826. /*: string*/
  8827. {
  8828. if (typeof obj === 'string') {
  8829. return obj;
  8830. }
  8831. if (!obj.id) {
  8832. throw new Error('You cannot add or remove an unsaved Parse Object from a relation');
  8833. }
  8834. if (!this._targetClassName) {
  8835. this._targetClassName = obj.className;
  8836. }
  8837. if (this._targetClassName !== obj.className) {
  8838. throw new Error('Tried to create a Relation with 2 different object types: ' + this._targetClassName + ' and ' + obj.className + '.');
  8839. }
  8840. return obj.id;
  8841. }
  8842. }, {
  8843. key: "applyTo",
  8844. value: function (value
  8845. /*: mixed*/
  8846. , object
  8847. /*:: ?: { className: string, id: ?string }*/
  8848. , key
  8849. /*:: ?: string*/
  8850. )
  8851. /*: ?ParseRelation*/
  8852. {
  8853. if (!value) {
  8854. if (!object || !key) {
  8855. throw new Error('Cannot apply a RelationOp without either a previous value, or an object and a key');
  8856. }
  8857. var parent = new _ParseObject.default(object.className);
  8858. if (object.id && object.id.indexOf('local') === 0) {
  8859. parent._localId = object.id;
  8860. } else if (object.id) {
  8861. parent.id = object.id;
  8862. }
  8863. var relation = new _ParseRelation.default(parent, key);
  8864. relation.targetClassName = this._targetClassName;
  8865. return relation;
  8866. }
  8867. if (value instanceof _ParseRelation.default) {
  8868. if (this._targetClassName) {
  8869. if (value.targetClassName) {
  8870. if (this._targetClassName !== value.targetClassName) {
  8871. throw new Error('Related object must be a ' + value.targetClassName + ', but a ' + this._targetClassName + ' was passed in.');
  8872. }
  8873. } else {
  8874. value.targetClassName = this._targetClassName;
  8875. }
  8876. }
  8877. return value;
  8878. } else {
  8879. throw new Error('Relation cannot be applied to a non-relation field');
  8880. }
  8881. }
  8882. }, {
  8883. key: "mergeWith",
  8884. value: function (previous
  8885. /*: Op*/
  8886. )
  8887. /*: Op*/
  8888. {
  8889. if (!previous) {
  8890. return this;
  8891. } else if (previous instanceof UnsetOp) {
  8892. throw new Error('You cannot modify a relation after deleting it.');
  8893. } else if (previous instanceof SetOp && previous._value instanceof _ParseRelation.default) {
  8894. return this;
  8895. } else if (previous instanceof RelationOp) {
  8896. if (previous._targetClassName && previous._targetClassName !== this._targetClassName) {
  8897. throw new Error('Related object must be of class ' + previous._targetClassName + ', but ' + (this._targetClassName || 'null') + ' was passed in.');
  8898. }
  8899. var newAdd = previous.relationsToAdd.concat([]);
  8900. this.relationsToRemove.forEach(function (r) {
  8901. var index = newAdd.indexOf(r);
  8902. if (index > -1) {
  8903. newAdd.splice(index, 1);
  8904. }
  8905. });
  8906. this.relationsToAdd.forEach(function (r) {
  8907. var index = newAdd.indexOf(r);
  8908. if (index < 0) {
  8909. newAdd.push(r);
  8910. }
  8911. });
  8912. var newRemove = previous.relationsToRemove.concat([]);
  8913. this.relationsToAdd.forEach(function (r) {
  8914. var index = newRemove.indexOf(r);
  8915. if (index > -1) {
  8916. newRemove.splice(index, 1);
  8917. }
  8918. });
  8919. this.relationsToRemove.forEach(function (r) {
  8920. var index = newRemove.indexOf(r);
  8921. if (index < 0) {
  8922. newRemove.push(r);
  8923. }
  8924. });
  8925. var newRelation = new RelationOp(newAdd, newRemove);
  8926. newRelation._targetClassName = this._targetClassName;
  8927. return newRelation;
  8928. }
  8929. throw new Error('Cannot merge Relation Op with the previous Op');
  8930. }
  8931. }, {
  8932. key: "toJSON",
  8933. value: function ()
  8934. /*: { __op?: string; objects?: mixed; ops?: mixed }*/
  8935. {
  8936. var _this7 = this;
  8937. var idToPointer = function (id) {
  8938. return {
  8939. __type: 'Pointer',
  8940. className: _this7._targetClassName,
  8941. objectId: id
  8942. };
  8943. };
  8944. var adds = null;
  8945. var removes = null;
  8946. var pointers = null;
  8947. if (this.relationsToAdd.length > 0) {
  8948. pointers = this.relationsToAdd.map(idToPointer);
  8949. adds = {
  8950. __op: 'AddRelation',
  8951. objects: pointers
  8952. };
  8953. }
  8954. if (this.relationsToRemove.length > 0) {
  8955. pointers = this.relationsToRemove.map(idToPointer);
  8956. removes = {
  8957. __op: 'RemoveRelation',
  8958. objects: pointers
  8959. };
  8960. }
  8961. if (adds && removes) {
  8962. return {
  8963. __op: 'Batch',
  8964. ops: [adds, removes]
  8965. };
  8966. }
  8967. return adds || removes || {};
  8968. }
  8969. }]);
  8970. return RelationOp;
  8971. }(Op);
  8972. exports.RelationOp = RelationOp;
  8973. },{"./ParseObject":23,"./ParseRelation":27,"./arrayContainsObject":39,"./decode":41,"./encode":42,"./unique":48,"@babel/runtime/helpers/assertThisInitialized":52,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/getPrototypeOf":59,"@babel/runtime/helpers/inherits":60,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/possibleConstructorReturn":68}],25:[function(_dereq_,module,exports){
  8974. "use strict";
  8975. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  8976. Object.defineProperty(exports, "__esModule", {
  8977. value: true
  8978. });
  8979. exports.default = void 0;
  8980. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  8981. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  8982. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  8983. var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
  8984. /**
  8985. * Copyright (c) 2015-present, Parse, LLC.
  8986. * All rights reserved.
  8987. *
  8988. * This source code is licensed under the BSD-style license found in the
  8989. * LICENSE file in the root directory of this source tree. An additional grant
  8990. * of patent rights can be found in the PATENTS file in the same directory.
  8991. *
  8992. * @flow
  8993. */
  8994. /**
  8995. * Creates a new Polygon with any of the following forms:<br>
  8996. * <pre>
  8997. * new Polygon([[0,0],[0,1],[1,1],[1,0]])
  8998. * new Polygon([GeoPoint, GeoPoint, GeoPoint])
  8999. * </pre>
  9000. *
  9001. * <p>Represents a coordinates that may be associated
  9002. * with a key in a ParseObject or used as a reference point for geo queries.
  9003. * This allows proximity-based queries on the key.</p>
  9004. *
  9005. * <p>Example:<pre>
  9006. * var polygon = new Parse.Polygon([[0,0],[0,1],[1,1],[1,0]]);
  9007. * var object = new Parse.Object("PlaceObject");
  9008. * object.set("area", polygon);
  9009. * object.save();</pre></p>
  9010. * @alias Parse.Polygon
  9011. */
  9012. var ParsePolygon =
  9013. /*#__PURE__*/
  9014. function () {
  9015. /**
  9016. * @param {(Number[][]|Parse.GeoPoint[])} coordinates An Array of coordinate pairs
  9017. */
  9018. function ParsePolygon(arg1
  9019. /*: Array<Array<number>> | Array<ParseGeoPoint>*/
  9020. ) {
  9021. (0, _classCallCheck2.default)(this, ParsePolygon);
  9022. (0, _defineProperty2.default)(this, "_coordinates", void 0);
  9023. this._coordinates = ParsePolygon._validate(arg1);
  9024. }
  9025. /**
  9026. * Coordinates value for this Polygon.
  9027. * Throws an exception if not valid type.
  9028. * @property coordinates
  9029. * @type Array
  9030. */
  9031. (0, _createClass2.default)(ParsePolygon, [{
  9032. key: "toJSON",
  9033. /**
  9034. * Returns a JSON representation of the Polygon, suitable for Parse.
  9035. * @return {Object}
  9036. */
  9037. value: function ()
  9038. /*: { __type: string; coordinates: Array<Array<number>>;}*/
  9039. {
  9040. ParsePolygon._validate(this._coordinates);
  9041. return {
  9042. __type: 'Polygon',
  9043. coordinates: this._coordinates
  9044. };
  9045. }
  9046. /**
  9047. * Checks if two polygons are equal
  9048. * @param {(Parse.Polygon|Object)} other
  9049. * @returns {Boolean}
  9050. */
  9051. }, {
  9052. key: "equals",
  9053. value: function (other
  9054. /*: mixed*/
  9055. )
  9056. /*: boolean*/
  9057. {
  9058. if (!(other instanceof ParsePolygon) || this.coordinates.length !== other.coordinates.length) {
  9059. return false;
  9060. }
  9061. var isEqual = true;
  9062. for (var i = 1; i < this._coordinates.length; i += 1) {
  9063. if (this._coordinates[i][0] != other.coordinates[i][0] || this._coordinates[i][1] != other.coordinates[i][1]) {
  9064. isEqual = false;
  9065. break;
  9066. }
  9067. }
  9068. return isEqual;
  9069. }
  9070. /**
  9071. *
  9072. * @param {Parse.GeoPoint} point
  9073. * @returns {Boolean} Returns if the point is contained in the polygon
  9074. */
  9075. }, {
  9076. key: "containsPoint",
  9077. value: function (point
  9078. /*: ParseGeoPoint*/
  9079. )
  9080. /*: boolean*/
  9081. {
  9082. var minX = this._coordinates[0][0];
  9083. var maxX = this._coordinates[0][0];
  9084. var minY = this._coordinates[0][1];
  9085. var maxY = this._coordinates[0][1];
  9086. for (var i = 1; i < this._coordinates.length; i += 1) {
  9087. var p = this._coordinates[i];
  9088. minX = Math.min(p[0], minX);
  9089. maxX = Math.max(p[0], maxX);
  9090. minY = Math.min(p[1], minY);
  9091. maxY = Math.max(p[1], maxY);
  9092. }
  9093. var outside = point.latitude < minX || point.latitude > maxX || point.longitude < minY || point.longitude > maxY;
  9094. if (outside) {
  9095. return false;
  9096. }
  9097. var inside = false;
  9098. for (var _i = 0, j = this._coordinates.length - 1; _i < this._coordinates.length; j = _i++) {
  9099. var startX = this._coordinates[_i][0];
  9100. var startY = this._coordinates[_i][1];
  9101. var endX = this._coordinates[j][0];
  9102. var endY = this._coordinates[j][1];
  9103. var intersect = startY > point.longitude != endY > point.longitude && point.latitude < (endX - startX) * (point.longitude - startY) / (endY - startY) + startX;
  9104. if (intersect) {
  9105. inside = !inside;
  9106. }
  9107. }
  9108. return inside;
  9109. }
  9110. /**
  9111. * Validates that the list of coordinates can form a valid polygon
  9112. * @param {Array} coords the list of coordinated to validate as a polygon
  9113. * @throws {TypeError}
  9114. */
  9115. }, {
  9116. key: "coordinates",
  9117. get: function ()
  9118. /*: Array<Array<number>>*/
  9119. {
  9120. return this._coordinates;
  9121. },
  9122. set: function (coords
  9123. /*: Array<Array<number>> | Array<ParseGeoPoint>*/
  9124. ) {
  9125. this._coordinates = ParsePolygon._validate(coords);
  9126. }
  9127. }], [{
  9128. key: "_validate",
  9129. value: function (coords
  9130. /*: Array<Array<number>> | Array<ParseGeoPoint>*/
  9131. )
  9132. /*: Array<Array<number>>*/
  9133. {
  9134. if (!Array.isArray(coords)) {
  9135. throw new TypeError('Coordinates must be an Array');
  9136. }
  9137. if (coords.length < 3) {
  9138. throw new TypeError('Polygon must have at least 3 GeoPoints or Points');
  9139. }
  9140. var points = [];
  9141. for (var i = 0; i < coords.length; i += 1) {
  9142. var coord = coords[i];
  9143. var geoPoint = void 0;
  9144. if (coord instanceof _ParseGeoPoint.default) {
  9145. geoPoint = coord;
  9146. } else if (Array.isArray(coord) && coord.length === 2) {
  9147. geoPoint = new _ParseGeoPoint.default(coord[0], coord[1]);
  9148. } else {
  9149. throw new TypeError('Coordinates must be an Array of GeoPoints or Points');
  9150. }
  9151. points.push([geoPoint.latitude, geoPoint.longitude]);
  9152. }
  9153. return points;
  9154. }
  9155. }]);
  9156. return ParsePolygon;
  9157. }();
  9158. var _default = ParsePolygon;
  9159. exports.default = _default;
  9160. },{"./ParseGeoPoint":20,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/interopRequireDefault":61}],26:[function(_dereq_,module,exports){
  9161. "use strict";
  9162. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  9163. Object.defineProperty(exports, "__esModule", {
  9164. value: true
  9165. });
  9166. exports.default = void 0;
  9167. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  9168. var _regenerator = _interopRequireDefault(_dereq_("@babel/runtime/regenerator"));
  9169. var _asyncToGenerator2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/asyncToGenerator"));
  9170. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  9171. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  9172. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  9173. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  9174. var _encode = _interopRequireDefault(_dereq_("./encode"));
  9175. var _promiseUtils = _dereq_("./promiseUtils");
  9176. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  9177. var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
  9178. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  9179. var _OfflineQuery = _interopRequireDefault(_dereq_("./OfflineQuery"));
  9180. var _LocalDatastoreUtils = _dereq_("./LocalDatastoreUtils");
  9181. /*
  9182. * Copyright (c) 2015-present, Parse, LLC.
  9183. * All rights reserved.
  9184. *
  9185. * This source code is licensed under the BSD-style license found in the
  9186. * LICENSE file in the root directory of this source tree. An additional grant
  9187. * of patent rights can be found in the PATENTS file in the same directory.
  9188. *
  9189. * @flow
  9190. */
  9191. /**
  9192. * Converts a string into a regex that matches it.
  9193. * Surrounding with \Q .. \E does this, we just need to escape any \E's in
  9194. * the text separately.
  9195. * @private
  9196. */
  9197. function quote(s
  9198. /*: string*/
  9199. ) {
  9200. return '\\Q' + s.replace('\\E', '\\E\\\\E\\Q') + '\\E';
  9201. }
  9202. /**
  9203. * Extracts the class name from queries. If not all queries have the same
  9204. * class name an error will be thrown.
  9205. */
  9206. function _getClassNameFromQueries(queries
  9207. /*: Array<ParseQuery>*/
  9208. )
  9209. /*: ?string*/
  9210. {
  9211. var className = null;
  9212. queries.forEach(function (q) {
  9213. if (!className) {
  9214. className = q.className;
  9215. }
  9216. if (className !== q.className) {
  9217. throw new Error('All queries must be for the same class.');
  9218. }
  9219. });
  9220. return className;
  9221. }
  9222. /*
  9223. * Handles pre-populating the result data of a query with select fields,
  9224. * making sure that the data object contains keys for all objects that have
  9225. * been requested with a select, so that our cached state updates correctly.
  9226. */
  9227. function handleSelectResult(data
  9228. /*: any*/
  9229. , select
  9230. /*: Array<string>*/
  9231. ) {
  9232. var serverDataMask = {};
  9233. select.forEach(function (field) {
  9234. var hasSubObjectSelect = field.indexOf(".") !== -1;
  9235. if (!hasSubObjectSelect && !data.hasOwnProperty(field)) {
  9236. // this field was selected, but is missing from the retrieved data
  9237. data[field] = undefined;
  9238. } else if (hasSubObjectSelect) {
  9239. // this field references a sub-object,
  9240. // so we need to walk down the path components
  9241. var pathComponents = field.split(".");
  9242. var _obj = data;
  9243. var serverMask = serverDataMask;
  9244. pathComponents.forEach(function (component, index, arr) {
  9245. // add keys if the expected data is missing
  9246. if (_obj && !_obj.hasOwnProperty(component)) {
  9247. _obj[component] = undefined;
  9248. }
  9249. if (_obj !== undefined) {
  9250. _obj = _obj[component];
  9251. } //add this path component to the server mask so we can fill it in later if needed
  9252. if (index < arr.length - 1) {
  9253. if (!serverMask[component]) {
  9254. serverMask[component] = {};
  9255. }
  9256. serverMask = serverMask[component];
  9257. }
  9258. });
  9259. }
  9260. });
  9261. if (Object.keys(serverDataMask).length > 0) {
  9262. // When selecting from sub-objects, we don't want to blow away the missing
  9263. // information that we may have retrieved before. We've already added any
  9264. // missing selected keys to sub-objects, but we still need to add in the
  9265. // data for any previously retrieved sub-objects that were not selected.
  9266. var serverData = _CoreManager.default.getObjectStateController().getServerData({
  9267. id: data.objectId,
  9268. className: data.className
  9269. });
  9270. copyMissingDataWithMask(serverData, data, serverDataMask, false);
  9271. }
  9272. }
  9273. function copyMissingDataWithMask(src, dest, mask, copyThisLevel) {
  9274. //copy missing elements at this level
  9275. if (copyThisLevel) {
  9276. for (var _key in src) {
  9277. if (src.hasOwnProperty(_key) && !dest.hasOwnProperty(_key)) {
  9278. dest[_key] = src[_key];
  9279. }
  9280. }
  9281. }
  9282. for (var _key2 in mask) {
  9283. if (dest[_key2] !== undefined && dest[_key2] !== null && src !== undefined && src !== null) {
  9284. //traverse into objects as needed
  9285. copyMissingDataWithMask(src[_key2], dest[_key2], mask[_key2], true);
  9286. }
  9287. }
  9288. }
  9289. function handleOfflineSort(a, b, sorts) {
  9290. var order = sorts[0];
  9291. var operator = order.slice(0, 1);
  9292. var isDescending = operator === '-';
  9293. if (isDescending) {
  9294. order = order.substring(1);
  9295. }
  9296. if (order === '_created_at') {
  9297. order = 'createdAt';
  9298. }
  9299. if (order === '_updated_at') {
  9300. order = 'updatedAt';
  9301. }
  9302. if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(order) || order === 'password') {
  9303. throw new _ParseError.default(_ParseError.default.INVALID_KEY_NAME, "Invalid Key: ".concat(order));
  9304. }
  9305. var field1 = a.get(order);
  9306. var field2 = b.get(order);
  9307. if (field1 < field2) {
  9308. return isDescending ? 1 : -1;
  9309. }
  9310. if (field1 > field2) {
  9311. return isDescending ? -1 : 1;
  9312. }
  9313. if (sorts.length > 1) {
  9314. var remainingSorts = sorts.slice(1);
  9315. return handleOfflineSort(a, b, remainingSorts);
  9316. }
  9317. return 0;
  9318. }
  9319. /**
  9320. * Creates a new parse Parse.Query for the given Parse.Object subclass.
  9321. *
  9322. * <p>Parse.Query defines a query that is used to fetch Parse.Objects. The
  9323. * most common use case is finding all objects that match a query through the
  9324. * <code>find</code> method. for example, this sample code fetches all objects
  9325. * of class <code>myclass</code>. it calls a different function depending on
  9326. * whether the fetch succeeded or not.
  9327. *
  9328. * <pre>
  9329. * var query = new Parse.Query(myclass);
  9330. * query.find().then((results) => {
  9331. * // results is an array of parse.object.
  9332. * }).catch((error) => {
  9333. * // error is an instance of parse.error.
  9334. * });</pre></p>
  9335. *
  9336. * <p>a Parse.Query can also be used to retrieve a single object whose id is
  9337. * known, through the get method. for example, this sample code fetches an
  9338. * object of class <code>myclass</code> and id <code>myid</code>. it calls a
  9339. * different function depending on whether the fetch succeeded or not.
  9340. *
  9341. * <pre>
  9342. * var query = new Parse.Query(myclass);
  9343. * query.get(myid).then((object) => {
  9344. * // object is an instance of parse.object.
  9345. * }).catch((error) => {
  9346. * // error is an instance of parse.error.
  9347. * });</pre></p>
  9348. *
  9349. * <p>a Parse.Query can also be used to count the number of objects that match
  9350. * the query without retrieving all of those objects. for example, this
  9351. * sample code counts the number of objects of the class <code>myclass</code>
  9352. * <pre>
  9353. * var query = new Parse.Query(myclass);
  9354. * query.count().then((number) => {
  9355. * // there are number instances of myclass.
  9356. * }).catch((error) => {
  9357. * // error is an instance of Parse.Error.
  9358. * });</pre></p>
  9359. * @alias Parse.Query
  9360. */
  9361. var ParseQuery =
  9362. /*#__PURE__*/
  9363. function () {
  9364. /**
  9365. * @property className
  9366. * @type String
  9367. */
  9368. /**
  9369. * @param {(String|Parse.Object)} objectClass An instance of a subclass of Parse.Object, or a Parse className string.
  9370. */
  9371. function ParseQuery(objectClass
  9372. /*: string | ParseObject*/
  9373. ) {
  9374. (0, _classCallCheck2.default)(this, ParseQuery);
  9375. (0, _defineProperty2.default)(this, "className", void 0);
  9376. (0, _defineProperty2.default)(this, "_where", void 0);
  9377. (0, _defineProperty2.default)(this, "_include", void 0);
  9378. (0, _defineProperty2.default)(this, "_exclude", void 0);
  9379. (0, _defineProperty2.default)(this, "_select", void 0);
  9380. (0, _defineProperty2.default)(this, "_limit", void 0);
  9381. (0, _defineProperty2.default)(this, "_skip", void 0);
  9382. (0, _defineProperty2.default)(this, "_count", void 0);
  9383. (0, _defineProperty2.default)(this, "_order", void 0);
  9384. (0, _defineProperty2.default)(this, "_readPreference", void 0);
  9385. (0, _defineProperty2.default)(this, "_includeReadPreference", void 0);
  9386. (0, _defineProperty2.default)(this, "_subqueryReadPreference", void 0);
  9387. (0, _defineProperty2.default)(this, "_queriesLocalDatastore", void 0);
  9388. (0, _defineProperty2.default)(this, "_localDatastorePinName", void 0);
  9389. (0, _defineProperty2.default)(this, "_extraOptions", void 0);
  9390. if (typeof objectClass === 'string') {
  9391. if (objectClass === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
  9392. this.className = '_User';
  9393. } else {
  9394. this.className = objectClass;
  9395. }
  9396. } else if (objectClass instanceof _ParseObject.default) {
  9397. this.className = objectClass.className;
  9398. } else if (typeof objectClass === 'function') {
  9399. if (typeof objectClass.className === 'string') {
  9400. this.className = objectClass.className;
  9401. } else {
  9402. var _obj2 = new objectClass();
  9403. this.className = _obj2.className;
  9404. }
  9405. } else {
  9406. throw new TypeError('A ParseQuery must be constructed with a ParseObject or class name.');
  9407. }
  9408. this._where = {};
  9409. this._include = [];
  9410. this._exclude = [];
  9411. this._count = false;
  9412. this._limit = -1; // negative limit is not sent in the server request
  9413. this._skip = 0;
  9414. this._readPreference = null;
  9415. this._includeReadPreference = null;
  9416. this._subqueryReadPreference = null;
  9417. this._queriesLocalDatastore = false;
  9418. this._localDatastorePinName = null;
  9419. this._extraOptions = {};
  9420. }
  9421. /**
  9422. * Adds constraint that at least one of the passed in queries matches.
  9423. * @param {Array} queries
  9424. * @return {Parse.Query} Returns the query, so you can chain this call.
  9425. */
  9426. (0, _createClass2.default)(ParseQuery, [{
  9427. key: "_orQuery",
  9428. value: function (queries
  9429. /*: Array<ParseQuery>*/
  9430. )
  9431. /*: ParseQuery*/
  9432. {
  9433. var queryJSON = queries.map(function (q) {
  9434. return q.toJSON().where;
  9435. });
  9436. this._where.$or = queryJSON;
  9437. return this;
  9438. }
  9439. /**
  9440. * Adds constraint that all of the passed in queries match.
  9441. * @param {Array} queries
  9442. * @return {Parse.Query} Returns the query, so you can chain this call.
  9443. */
  9444. }, {
  9445. key: "_andQuery",
  9446. value: function (queries
  9447. /*: Array<ParseQuery>*/
  9448. )
  9449. /*: ParseQuery*/
  9450. {
  9451. var queryJSON = queries.map(function (q) {
  9452. return q.toJSON().where;
  9453. });
  9454. this._where.$and = queryJSON;
  9455. return this;
  9456. }
  9457. /**
  9458. * Adds constraint that none of the passed in queries match.
  9459. * @param {Array} queries
  9460. * @return {Parse.Query} Returns the query, so you can chain this call.
  9461. */
  9462. }, {
  9463. key: "_norQuery",
  9464. value: function (queries
  9465. /*: Array<ParseQuery>*/
  9466. )
  9467. /*: ParseQuery*/
  9468. {
  9469. var queryJSON = queries.map(function (q) {
  9470. return q.toJSON().where;
  9471. });
  9472. this._where.$nor = queryJSON;
  9473. return this;
  9474. }
  9475. /**
  9476. * Helper for condition queries
  9477. */
  9478. }, {
  9479. key: "_addCondition",
  9480. value: function (key
  9481. /*: string*/
  9482. , condition
  9483. /*: string*/
  9484. , value
  9485. /*: mixed*/
  9486. )
  9487. /*: ParseQuery*/
  9488. {
  9489. if (!this._where[key] || typeof this._where[key] === 'string') {
  9490. this._where[key] = {};
  9491. }
  9492. this._where[key][condition] = (0, _encode.default)(value, false, true);
  9493. return this;
  9494. }
  9495. /**
  9496. * Converts string for regular expression at the beginning
  9497. */
  9498. }, {
  9499. key: "_regexStartWith",
  9500. value: function (string
  9501. /*: string*/
  9502. )
  9503. /*: string*/
  9504. {
  9505. return '^' + quote(string);
  9506. }
  9507. }, {
  9508. key: "_handleOfflineQuery",
  9509. value: function () {
  9510. var _handleOfflineQuery2 = (0, _asyncToGenerator2.default)(
  9511. /*#__PURE__*/
  9512. _regenerator.default.mark(function _callee(params
  9513. /*: any*/
  9514. ) {
  9515. var _this2 = this;
  9516. var localDatastore, objects, results, keys, alwaysSelectedKeys, sorts, count, limit;
  9517. return _regenerator.default.wrap(function (_context) {
  9518. while (1) {
  9519. switch (_context.prev = _context.next) {
  9520. case 0:
  9521. _OfflineQuery.default.validateQuery(this);
  9522. localDatastore = _CoreManager.default.getLocalDatastore();
  9523. _context.next = 4;
  9524. return localDatastore._serializeObjectsFromPinName(this._localDatastorePinName);
  9525. case 4:
  9526. objects = _context.sent;
  9527. results = objects.map(function (json, index, arr) {
  9528. var object = _ParseObject.default.fromJSON(json, false);
  9529. if (json._localId && !json.objectId) {
  9530. object._localId = json._localId;
  9531. }
  9532. if (!_OfflineQuery.default.matchesQuery(_this2.className, object, arr, _this2)) {
  9533. return null;
  9534. }
  9535. return object;
  9536. }).filter(function (object) {
  9537. return object !== null;
  9538. });
  9539. if (params.keys) {
  9540. keys = params.keys.split(',');
  9541. alwaysSelectedKeys = ['className', 'objectId', 'createdAt', 'updatedAt', 'ACL'];
  9542. keys = keys.concat(alwaysSelectedKeys);
  9543. results = results.map(function (object) {
  9544. var json = object._toFullJSON();
  9545. Object.keys(json).forEach(function (key) {
  9546. if (!keys.includes(key)) {
  9547. delete json[key];
  9548. }
  9549. });
  9550. return _ParseObject.default.fromJSON(json, false);
  9551. });
  9552. }
  9553. if (params.order) {
  9554. sorts = params.order.split(',');
  9555. results.sort(function (a, b) {
  9556. return handleOfflineSort(a, b, sorts);
  9557. });
  9558. } // count total before applying limit/skip
  9559. if (params.count) {
  9560. count = results.length; // total count from response
  9561. }
  9562. if (params.skip) {
  9563. if (params.skip >= results.length) {
  9564. results = [];
  9565. } else {
  9566. results = results.splice(params.skip, results.length);
  9567. }
  9568. }
  9569. limit = results.length;
  9570. if (params.limit !== 0 && params.limit < results.length) {
  9571. limit = params.limit;
  9572. }
  9573. results = results.splice(0, limit);
  9574. if (!(typeof count === 'number')) {
  9575. _context.next = 15;
  9576. break;
  9577. }
  9578. return _context.abrupt("return", {
  9579. results: results,
  9580. count: count
  9581. });
  9582. case 15:
  9583. return _context.abrupt("return", results);
  9584. case 16:
  9585. case "end":
  9586. return _context.stop();
  9587. }
  9588. }
  9589. }, _callee, this);
  9590. }));
  9591. return function () {
  9592. return _handleOfflineQuery2.apply(this, arguments);
  9593. };
  9594. }()
  9595. /**
  9596. * Returns a JSON representation of this query.
  9597. * @return {Object} The JSON representation of the query.
  9598. */
  9599. }, {
  9600. key: "toJSON",
  9601. value: function ()
  9602. /*: QueryJSON*/
  9603. {
  9604. var params
  9605. /*: QueryJSON*/
  9606. = {
  9607. where: this._where
  9608. };
  9609. if (this._include.length) {
  9610. params.include = this._include.join(',');
  9611. }
  9612. if (this._exclude.length) {
  9613. params.excludeKeys = this._exclude.join(',');
  9614. }
  9615. if (this._select) {
  9616. params.keys = this._select.join(',');
  9617. }
  9618. if (this._count) {
  9619. params.count = 1;
  9620. }
  9621. if (this._limit >= 0) {
  9622. params.limit = this._limit;
  9623. }
  9624. if (this._skip > 0) {
  9625. params.skip = this._skip;
  9626. }
  9627. if (this._order) {
  9628. params.order = this._order.join(',');
  9629. }
  9630. if (this._readPreference) {
  9631. params.readPreference = this._readPreference;
  9632. }
  9633. if (this._includeReadPreference) {
  9634. params.includeReadPreference = this._includeReadPreference;
  9635. }
  9636. if (this._subqueryReadPreference) {
  9637. params.subqueryReadPreference = this._subqueryReadPreference;
  9638. }
  9639. for (var _key3 in this._extraOptions) {
  9640. params[_key3] = this._extraOptions[_key3];
  9641. }
  9642. return params;
  9643. }
  9644. /**
  9645. * Return a query with conditions from json, can be useful to send query from server side to client
  9646. * Not static, all query conditions was set before calling this method will be deleted.
  9647. * For example on the server side we have
  9648. * var query = new Parse.Query("className");
  9649. * query.equalTo(key: value);
  9650. * query.limit(100);
  9651. * ... (others queries)
  9652. * Create JSON representation of Query Object
  9653. * var jsonFromServer = query.fromJSON();
  9654. *
  9655. * On client side getting query:
  9656. * var query = new Parse.Query("className");
  9657. * query.fromJSON(jsonFromServer);
  9658. *
  9659. * and continue to query...
  9660. * query.skip(100).find().then(...);
  9661. * @param {QueryJSON} json from Parse.Query.toJSON() method
  9662. * @return {Parse.Query} Returns the query, so you can chain this call.
  9663. */
  9664. }, {
  9665. key: "withJSON",
  9666. value: function (json
  9667. /*: QueryJSON*/
  9668. )
  9669. /*: ParseQuery*/
  9670. {
  9671. if (json.where) {
  9672. this._where = json.where;
  9673. }
  9674. if (json.include) {
  9675. this._include = json.include.split(",");
  9676. }
  9677. if (json.keys) {
  9678. this._select = json.keys.split(",");
  9679. }
  9680. if (json.excludeKeys) {
  9681. this._exclude = json.excludeKeys.split(",");
  9682. }
  9683. if (json.count) {
  9684. this._count = json.count === 1;
  9685. }
  9686. if (json.limit) {
  9687. this._limit = json.limit;
  9688. }
  9689. if (json.skip) {
  9690. this._skip = json.skip;
  9691. }
  9692. if (json.order) {
  9693. this._order = json.order.split(",");
  9694. }
  9695. if (json.readPreference) {
  9696. this._readPreference = json.readPreference;
  9697. }
  9698. if (json.includeReadPreference) {
  9699. this._includeReadPreference = json.includeReadPreference;
  9700. }
  9701. if (json.subqueryReadPreference) {
  9702. this._subqueryReadPreference = json.subqueryReadPreference;
  9703. }
  9704. for (var _key4 in json) {
  9705. if (json.hasOwnProperty(_key4)) {
  9706. if (["where", "include", "keys", "count", "limit", "skip", "order", "readPreference", "includeReadPreference", "subqueryReadPreference"].indexOf(_key4) === -1) {
  9707. this._extraOptions[_key4] = json[_key4];
  9708. }
  9709. }
  9710. }
  9711. return this;
  9712. }
  9713. /**
  9714. * Static method to restore Parse.Query by json representation
  9715. * Internally calling Parse.Query.withJSON
  9716. * @param {String} className
  9717. * @param {QueryJSON} json from Parse.Query.toJSON() method
  9718. * @returns {Parse.Query} new created query
  9719. */
  9720. }, {
  9721. key: "get",
  9722. /**
  9723. * Constructs a Parse.Object whose id is already known by fetching data from
  9724. * the server. Either options.success or options.error is called when the
  9725. * find completes. Unlike the <code>first</code> method, it never returns undefined.
  9726. *
  9727. * @param {String} objectId The id of the object to be fetched.
  9728. * @param {Object} options
  9729. * Valid options are:<ul>
  9730. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  9731. * be used for this request.
  9732. * <li>sessionToken: A valid session token, used for making a request on
  9733. * behalf of a specific user.
  9734. * </ul>
  9735. *
  9736. * @return {Promise} A promise that is resolved with the result when
  9737. * the query completes.
  9738. */
  9739. value: function (objectId
  9740. /*: string*/
  9741. , options
  9742. /*:: ?: FullOptions*/
  9743. )
  9744. /*: Promise<ParseObject>*/
  9745. {
  9746. this.equalTo('objectId', objectId);
  9747. var firstOptions = {};
  9748. if (options && options.hasOwnProperty('useMasterKey')) {
  9749. firstOptions.useMasterKey = options.useMasterKey;
  9750. }
  9751. if (options && options.hasOwnProperty('sessionToken')) {
  9752. firstOptions.sessionToken = options.sessionToken;
  9753. }
  9754. return this.first(firstOptions).then(function (response) {
  9755. if (response) {
  9756. return response;
  9757. }
  9758. var errorObject = new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'Object not found.');
  9759. return Promise.reject(errorObject);
  9760. });
  9761. }
  9762. /**
  9763. * Retrieves a list of ParseObjects that satisfy this query.
  9764. * Either options.success or options.error is called when the find
  9765. * completes.
  9766. *
  9767. * @param {Object} options Valid options
  9768. * are:<ul>
  9769. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  9770. * be used for this request.
  9771. * <li>sessionToken: A valid session token, used for making a request on
  9772. * behalf of a specific user.
  9773. * </ul>
  9774. *
  9775. * @return {Promise} A promise that is resolved with the results when
  9776. * the query completes.
  9777. */
  9778. }, {
  9779. key: "find",
  9780. value: function (options
  9781. /*:: ?: FullOptions*/
  9782. )
  9783. /*: Promise<Array<ParseObject>>*/
  9784. {
  9785. var _this3 = this;
  9786. options = options || {};
  9787. var findOptions = {};
  9788. if (options.hasOwnProperty('useMasterKey')) {
  9789. findOptions.useMasterKey = options.useMasterKey;
  9790. }
  9791. if (options.hasOwnProperty('sessionToken')) {
  9792. findOptions.sessionToken = options.sessionToken;
  9793. }
  9794. var controller = _CoreManager.default.getQueryController();
  9795. var select = this._select;
  9796. if (this._queriesLocalDatastore) {
  9797. return this._handleOfflineQuery(this.toJSON());
  9798. }
  9799. return controller.find(this.className, this.toJSON(), findOptions).then(function (response) {
  9800. var results = response.results.map(function (data) {
  9801. // In cases of relations, the server may send back a className
  9802. // on the top level of the payload
  9803. var override = response.className || _this3.className;
  9804. if (!data.className) {
  9805. data.className = override;
  9806. } // Make sure the data object contains keys for all objects that
  9807. // have been requested with a select, so that our cached state
  9808. // updates correctly.
  9809. if (select) {
  9810. handleSelectResult(data, select);
  9811. }
  9812. return _ParseObject.default.fromJSON(data, !select);
  9813. });
  9814. var count = response.count;
  9815. if (typeof count === "number") {
  9816. return {
  9817. results: results,
  9818. count: count
  9819. };
  9820. } else {
  9821. return results;
  9822. }
  9823. });
  9824. }
  9825. /**
  9826. * Counts the number of objects that match this query.
  9827. * Either options.success or options.error is called when the count
  9828. * completes.
  9829. *
  9830. * @param {Object} options
  9831. * Valid options are:<ul>
  9832. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  9833. * be used for this request.
  9834. * <li>sessionToken: A valid session token, used for making a request on
  9835. * behalf of a specific user.
  9836. * </ul>
  9837. *
  9838. * @return {Promise} A promise that is resolved with the count when
  9839. * the query completes.
  9840. */
  9841. }, {
  9842. key: "count",
  9843. value: function (options
  9844. /*:: ?: FullOptions*/
  9845. )
  9846. /*: Promise<number>*/
  9847. {
  9848. options = options || {};
  9849. var findOptions = {};
  9850. if (options.hasOwnProperty('useMasterKey')) {
  9851. findOptions.useMasterKey = options.useMasterKey;
  9852. }
  9853. if (options.hasOwnProperty('sessionToken')) {
  9854. findOptions.sessionToken = options.sessionToken;
  9855. }
  9856. var controller = _CoreManager.default.getQueryController();
  9857. var params = this.toJSON();
  9858. params.limit = 0;
  9859. params.count = 1;
  9860. return controller.find(this.className, params, findOptions).then(function (result) {
  9861. return result.count;
  9862. });
  9863. }
  9864. /**
  9865. * Executes a distinct query and returns unique values
  9866. *
  9867. * @param {String} key A field to find distinct values
  9868. * @param {Object} options
  9869. * Valid options are:<ul>
  9870. * <li>sessionToken: A valid session token, used for making a request on
  9871. * behalf of a specific user.
  9872. * </ul>
  9873. *
  9874. * @return {Promise} A promise that is resolved with the query completes.
  9875. */
  9876. }, {
  9877. key: "distinct",
  9878. value: function (key
  9879. /*: string*/
  9880. , options
  9881. /*:: ?: FullOptions*/
  9882. )
  9883. /*: Promise<Array<mixed>>*/
  9884. {
  9885. options = options || {};
  9886. var distinctOptions = {};
  9887. distinctOptions.useMasterKey = true;
  9888. if (options.hasOwnProperty('sessionToken')) {
  9889. distinctOptions.sessionToken = options.sessionToken;
  9890. }
  9891. var controller = _CoreManager.default.getQueryController();
  9892. var params = {
  9893. distinct: key,
  9894. where: this._where
  9895. };
  9896. return controller.aggregate(this.className, params, distinctOptions).then(function (results) {
  9897. return results.results;
  9898. });
  9899. }
  9900. /**
  9901. * Executes an aggregate query and returns aggregate results
  9902. *
  9903. * @param {Mixed} pipeline Array or Object of stages to process query
  9904. * @param {Object} options Valid options are:<ul>
  9905. * <li>sessionToken: A valid session token, used for making a request on
  9906. * behalf of a specific user.
  9907. * </ul>
  9908. *
  9909. * @return {Promise} A promise that is resolved with the query completes.
  9910. */
  9911. }, {
  9912. key: "aggregate",
  9913. value: function (pipeline
  9914. /*: mixed*/
  9915. , options
  9916. /*:: ?: FullOptions*/
  9917. )
  9918. /*: Promise<Array<mixed>>*/
  9919. {
  9920. options = options || {};
  9921. var aggregateOptions = {};
  9922. aggregateOptions.useMasterKey = true;
  9923. if (options.hasOwnProperty('sessionToken')) {
  9924. aggregateOptions.sessionToken = options.sessionToken;
  9925. }
  9926. var controller = _CoreManager.default.getQueryController();
  9927. if (!Array.isArray(pipeline) && (0, _typeof2.default)(pipeline) !== 'object') {
  9928. throw new Error('Invalid pipeline must be Array or Object');
  9929. }
  9930. return controller.aggregate(this.className, {
  9931. pipeline: pipeline
  9932. }, aggregateOptions).then(function (results) {
  9933. return results.results;
  9934. });
  9935. }
  9936. /**
  9937. * Retrieves at most one Parse.Object that satisfies this query.
  9938. *
  9939. * Either options.success or options.error is called when it completes.
  9940. * success is passed the object if there is one. otherwise, undefined.
  9941. *
  9942. * @param {Object} options Valid options are:<ul>
  9943. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  9944. * be used for this request.
  9945. * <li>sessionToken: A valid session token, used for making a request on
  9946. * behalf of a specific user.
  9947. * </ul>
  9948. *
  9949. * @return {Promise} A promise that is resolved with the object when
  9950. * the query completes.
  9951. */
  9952. }, {
  9953. key: "first",
  9954. value: function (options
  9955. /*:: ?: FullOptions*/
  9956. )
  9957. /*: Promise<ParseObject | void>*/
  9958. {
  9959. var _this4 = this;
  9960. options = options || {};
  9961. var findOptions = {};
  9962. if (options.hasOwnProperty('useMasterKey')) {
  9963. findOptions.useMasterKey = options.useMasterKey;
  9964. }
  9965. if (options.hasOwnProperty('sessionToken')) {
  9966. findOptions.sessionToken = options.sessionToken;
  9967. }
  9968. var controller = _CoreManager.default.getQueryController();
  9969. var params = this.toJSON();
  9970. params.limit = 1;
  9971. var select = this._select;
  9972. if (this._queriesLocalDatastore) {
  9973. return this._handleOfflineQuery(params).then(function (objects) {
  9974. if (!objects[0]) {
  9975. return undefined;
  9976. }
  9977. return objects[0];
  9978. });
  9979. }
  9980. return controller.find(this.className, params, findOptions).then(function (response) {
  9981. var objects = response.results;
  9982. if (!objects[0]) {
  9983. return undefined;
  9984. }
  9985. if (!objects[0].className) {
  9986. objects[0].className = _this4.className;
  9987. } // Make sure the data object contains keys for all objects that
  9988. // have been requested with a select, so that our cached state
  9989. // updates correctly.
  9990. if (select) {
  9991. handleSelectResult(objects[0], select);
  9992. }
  9993. return _ParseObject.default.fromJSON(objects[0], !select);
  9994. });
  9995. }
  9996. /**
  9997. * Iterates over each result of a query, calling a callback for each one. If
  9998. * the callback returns a promise, the iteration will not continue until
  9999. * that promise has been fulfilled. If the callback returns a rejected
  10000. * promise, then iteration will stop with that error. The items are
  10001. * processed in an unspecified order. The query may not have any sort order,
  10002. * and may not use limit or skip.
  10003. * @param {Function} callback Callback that will be called with each result
  10004. * of the query.
  10005. * @param {Object} options Valid options are:<ul>
  10006. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  10007. * be used for this request.
  10008. * <li>sessionToken: A valid session token, used for making a request on
  10009. * behalf of a specific user.
  10010. * </ul>
  10011. * @return {Promise} A promise that will be fulfilled once the
  10012. * iteration has completed.
  10013. */
  10014. }, {
  10015. key: "each",
  10016. value: function (callback
  10017. /*: (obj: ParseObject) => any*/
  10018. , options
  10019. /*:: ?: BatchOptions*/
  10020. )
  10021. /*: Promise<Array<ParseObject>>*/
  10022. {
  10023. options = options || {};
  10024. if (this._order || this._skip || this._limit >= 0) {
  10025. return Promise.reject('Cannot iterate on a query with sort, skip, or limit.');
  10026. }
  10027. var query = new ParseQuery(this.className); // We can override the batch size from the options.
  10028. // This is undocumented, but useful for testing.
  10029. query._limit = options.batchSize || 100;
  10030. query._include = this._include.map(function (i) {
  10031. return i;
  10032. });
  10033. if (this._select) {
  10034. query._select = this._select.map(function (s) {
  10035. return s;
  10036. });
  10037. }
  10038. query._where = {};
  10039. for (var _attr in this._where) {
  10040. var val = this._where[_attr];
  10041. if (Array.isArray(val)) {
  10042. query._where[_attr] = val.map(function (v) {
  10043. return v;
  10044. });
  10045. } else if (val && (0, _typeof2.default)(val) === 'object') {
  10046. var conditionMap = {};
  10047. query._where[_attr] = conditionMap;
  10048. for (var cond in val) {
  10049. conditionMap[cond] = val[cond];
  10050. }
  10051. } else {
  10052. query._where[_attr] = val;
  10053. }
  10054. }
  10055. query.ascending('objectId');
  10056. var findOptions = {};
  10057. if (options.hasOwnProperty('useMasterKey')) {
  10058. findOptions.useMasterKey = options.useMasterKey;
  10059. }
  10060. if (options.hasOwnProperty('sessionToken')) {
  10061. findOptions.sessionToken = options.sessionToken;
  10062. }
  10063. var finished = false;
  10064. return (0, _promiseUtils.continueWhile)(function () {
  10065. return !finished;
  10066. }, function () {
  10067. return query.find(findOptions).then(function (results) {
  10068. var callbacksDone = Promise.resolve();
  10069. results.forEach(function (result) {
  10070. callbacksDone = callbacksDone.then(function () {
  10071. return callback(result);
  10072. });
  10073. });
  10074. return callbacksDone.then(function () {
  10075. if (results.length >= query._limit) {
  10076. query.greaterThan('objectId', results[results.length - 1].id);
  10077. } else {
  10078. finished = true;
  10079. }
  10080. });
  10081. });
  10082. });
  10083. }
  10084. /** Query Conditions **/
  10085. /**
  10086. * Adds a constraint to the query that requires a particular key's value to
  10087. * be equal to the provided value.
  10088. * @param {String} key The key to check.
  10089. * @param value The value that the Parse.Object must contain.
  10090. * @return {Parse.Query} Returns the query, so you can chain this call.
  10091. */
  10092. }, {
  10093. key: "equalTo",
  10094. value: function (key
  10095. /*: string*/
  10096. , value
  10097. /*: mixed*/
  10098. )
  10099. /*: ParseQuery*/
  10100. {
  10101. if (typeof value === 'undefined') {
  10102. return this.doesNotExist(key);
  10103. }
  10104. this._where[key] = (0, _encode.default)(value, false, true);
  10105. return this;
  10106. }
  10107. /**
  10108. * Adds a constraint to the query that requires a particular key's value to
  10109. * be not equal to the provided value.
  10110. * @param {String} key The key to check.
  10111. * @param value The value that must not be equalled.
  10112. * @return {Parse.Query} Returns the query, so you can chain this call.
  10113. */
  10114. }, {
  10115. key: "notEqualTo",
  10116. value: function (key
  10117. /*: string*/
  10118. , value
  10119. /*: mixed*/
  10120. )
  10121. /*: ParseQuery*/
  10122. {
  10123. return this._addCondition(key, '$ne', value);
  10124. }
  10125. /**
  10126. * Adds a constraint to the query that requires a particular key's value to
  10127. * be less than the provided value.
  10128. * @param {String} key The key to check.
  10129. * @param value The value that provides an upper bound.
  10130. * @return {Parse.Query} Returns the query, so you can chain this call.
  10131. */
  10132. }, {
  10133. key: "lessThan",
  10134. value: function (key
  10135. /*: string*/
  10136. , value
  10137. /*: mixed*/
  10138. )
  10139. /*: ParseQuery*/
  10140. {
  10141. return this._addCondition(key, '$lt', value);
  10142. }
  10143. /**
  10144. * Adds a constraint to the query that requires a particular key's value to
  10145. * be greater than the provided value.
  10146. * @param {String} key The key to check.
  10147. * @param value The value that provides an lower bound.
  10148. * @return {Parse.Query} Returns the query, so you can chain this call.
  10149. */
  10150. }, {
  10151. key: "greaterThan",
  10152. value: function (key
  10153. /*: string*/
  10154. , value
  10155. /*: mixed*/
  10156. )
  10157. /*: ParseQuery*/
  10158. {
  10159. return this._addCondition(key, '$gt', value);
  10160. }
  10161. /**
  10162. * Adds a constraint to the query that requires a particular key's value to
  10163. * be less than or equal to the provided value.
  10164. * @param {String} key The key to check.
  10165. * @param value The value that provides an upper bound.
  10166. * @return {Parse.Query} Returns the query, so you can chain this call.
  10167. */
  10168. }, {
  10169. key: "lessThanOrEqualTo",
  10170. value: function (key
  10171. /*: string*/
  10172. , value
  10173. /*: mixed*/
  10174. )
  10175. /*: ParseQuery*/
  10176. {
  10177. return this._addCondition(key, '$lte', value);
  10178. }
  10179. /**
  10180. * Adds a constraint to the query that requires a particular key's value to
  10181. * be greater than or equal to the provided value.
  10182. * @param {String} key The key to check.
  10183. * @param value The value that provides an lower bound.
  10184. * @return {Parse.Query} Returns the query, so you can chain this call.
  10185. */
  10186. }, {
  10187. key: "greaterThanOrEqualTo",
  10188. value: function (key
  10189. /*: string*/
  10190. , value
  10191. /*: mixed*/
  10192. )
  10193. /*: ParseQuery*/
  10194. {
  10195. return this._addCondition(key, '$gte', value);
  10196. }
  10197. /**
  10198. * Adds a constraint to the query that requires a particular key's value to
  10199. * be contained in the provided list of values.
  10200. * @param {String} key The key to check.
  10201. * @param {Array} values The values that will match.
  10202. * @return {Parse.Query} Returns the query, so you can chain this call.
  10203. */
  10204. }, {
  10205. key: "containedIn",
  10206. value: function (key
  10207. /*: string*/
  10208. , value
  10209. /*: mixed*/
  10210. )
  10211. /*: ParseQuery*/
  10212. {
  10213. return this._addCondition(key, '$in', value);
  10214. }
  10215. /**
  10216. * Adds a constraint to the query that requires a particular key's value to
  10217. * not be contained in the provided list of values.
  10218. * @param {String} key The key to check.
  10219. * @param {Array} values The values that will not match.
  10220. * @return {Parse.Query} Returns the query, so you can chain this call.
  10221. */
  10222. }, {
  10223. key: "notContainedIn",
  10224. value: function (key
  10225. /*: string*/
  10226. , value
  10227. /*: mixed*/
  10228. )
  10229. /*: ParseQuery*/
  10230. {
  10231. return this._addCondition(key, '$nin', value);
  10232. }
  10233. /**
  10234. * Adds a constraint to the query that requires a particular key's value to
  10235. * be contained by the provided list of values. Get objects where all array elements match.
  10236. * @param {String} key The key to check.
  10237. * @param {Array} values The values that will match.
  10238. * @return {Parse.Query} Returns the query, so you can chain this call.
  10239. */
  10240. }, {
  10241. key: "containedBy",
  10242. value: function (key
  10243. /*: string*/
  10244. , value
  10245. /*: Array<mixed>*/
  10246. )
  10247. /*: ParseQuery*/
  10248. {
  10249. return this._addCondition(key, '$containedBy', value);
  10250. }
  10251. /**
  10252. * Adds a constraint to the query that requires a particular key's value to
  10253. * contain each one of the provided list of values.
  10254. * @param {String} key The key to check. This key's value must be an array.
  10255. * @param {Array} values The values that will match.
  10256. * @return {Parse.Query} Returns the query, so you can chain this call.
  10257. */
  10258. }, {
  10259. key: "containsAll",
  10260. value: function (key
  10261. /*: string*/
  10262. , values
  10263. /*: Array<mixed>*/
  10264. )
  10265. /*: ParseQuery*/
  10266. {
  10267. return this._addCondition(key, '$all', values);
  10268. }
  10269. /**
  10270. * Adds a constraint to the query that requires a particular key's value to
  10271. * contain each one of the provided list of values starting with given strings.
  10272. * @param {String} key The key to check. This key's value must be an array.
  10273. * @param {Array<String>} values The string values that will match as starting string.
  10274. * @return {Parse.Query} Returns the query, so you can chain this call.
  10275. */
  10276. }, {
  10277. key: "containsAllStartingWith",
  10278. value: function (key
  10279. /*: string*/
  10280. , values
  10281. /*: Array<string>*/
  10282. )
  10283. /*: ParseQuery*/
  10284. {
  10285. var _this = this;
  10286. if (!Array.isArray(values)) {
  10287. values = [values];
  10288. }
  10289. var regexObject = values.map(function (value) {
  10290. return {
  10291. '$regex': _this._regexStartWith(value)
  10292. };
  10293. });
  10294. return this.containsAll(key, regexObject);
  10295. }
  10296. /**
  10297. * Adds a constraint for finding objects that contain the given key.
  10298. * @param {String} key The key that should exist.
  10299. * @return {Parse.Query} Returns the query, so you can chain this call.
  10300. */
  10301. }, {
  10302. key: "exists",
  10303. value: function (key
  10304. /*: string*/
  10305. )
  10306. /*: ParseQuery*/
  10307. {
  10308. return this._addCondition(key, '$exists', true);
  10309. }
  10310. /**
  10311. * Adds a constraint for finding objects that do not contain a given key.
  10312. * @param {String} key The key that should not exist
  10313. * @return {Parse.Query} Returns the query, so you can chain this call.
  10314. */
  10315. }, {
  10316. key: "doesNotExist",
  10317. value: function (key
  10318. /*: string*/
  10319. )
  10320. /*: ParseQuery*/
  10321. {
  10322. return this._addCondition(key, '$exists', false);
  10323. }
  10324. /**
  10325. * Adds a regular expression constraint for finding string values that match
  10326. * the provided regular expression.
  10327. * This may be slow for large datasets.
  10328. * @param {String} key The key that the string to match is stored in.
  10329. * @param {RegExp} regex The regular expression pattern to match.
  10330. * @return {Parse.Query} Returns the query, so you can chain this call.
  10331. */
  10332. }, {
  10333. key: "matches",
  10334. value: function (key
  10335. /*: string*/
  10336. , regex
  10337. /*: RegExp*/
  10338. , modifiers
  10339. /*: string*/
  10340. )
  10341. /*: ParseQuery*/
  10342. {
  10343. this._addCondition(key, '$regex', regex);
  10344. if (!modifiers) {
  10345. modifiers = '';
  10346. }
  10347. if (regex.ignoreCase) {
  10348. modifiers += 'i';
  10349. }
  10350. if (regex.multiline) {
  10351. modifiers += 'm';
  10352. }
  10353. if (modifiers.length) {
  10354. this._addCondition(key, '$options', modifiers);
  10355. }
  10356. return this;
  10357. }
  10358. /**
  10359. * Adds a constraint that requires that a key's value matches a Parse.Query
  10360. * constraint.
  10361. * @param {String} key The key that the contains the object to match the
  10362. * query.
  10363. * @param {Parse.Query} query The query that should match.
  10364. * @return {Parse.Query} Returns the query, so you can chain this call.
  10365. */
  10366. }, {
  10367. key: "matchesQuery",
  10368. value: function (key
  10369. /*: string*/
  10370. , query
  10371. /*: ParseQuery*/
  10372. )
  10373. /*: ParseQuery*/
  10374. {
  10375. var queryJSON = query.toJSON();
  10376. queryJSON.className = query.className;
  10377. return this._addCondition(key, '$inQuery', queryJSON);
  10378. }
  10379. /**
  10380. * Adds a constraint that requires that a key's value not matches a
  10381. * Parse.Query constraint.
  10382. * @param {String} key The key that the contains the object to match the
  10383. * query.
  10384. * @param {Parse.Query} query The query that should not match.
  10385. * @return {Parse.Query} Returns the query, so you can chain this call.
  10386. */
  10387. }, {
  10388. key: "doesNotMatchQuery",
  10389. value: function (key
  10390. /*: string*/
  10391. , query
  10392. /*: ParseQuery*/
  10393. )
  10394. /*: ParseQuery*/
  10395. {
  10396. var queryJSON = query.toJSON();
  10397. queryJSON.className = query.className;
  10398. return this._addCondition(key, '$notInQuery', queryJSON);
  10399. }
  10400. /**
  10401. * Adds a constraint that requires that a key's value matches a value in
  10402. * an object returned by a different Parse.Query.
  10403. * @param {String} key The key that contains the value that is being
  10404. * matched.
  10405. * @param {String} queryKey The key in the objects returned by the query to
  10406. * match against.
  10407. * @param {Parse.Query} query The query to run.
  10408. * @return {Parse.Query} Returns the query, so you can chain this call.
  10409. */
  10410. }, {
  10411. key: "matchesKeyInQuery",
  10412. value: function (key
  10413. /*: string*/
  10414. , queryKey
  10415. /*: string*/
  10416. , query
  10417. /*: ParseQuery*/
  10418. )
  10419. /*: ParseQuery*/
  10420. {
  10421. var queryJSON = query.toJSON();
  10422. queryJSON.className = query.className;
  10423. return this._addCondition(key, '$select', {
  10424. key: queryKey,
  10425. query: queryJSON
  10426. });
  10427. }
  10428. /**
  10429. * Adds a constraint that requires that a key's value not match a value in
  10430. * an object returned by a different Parse.Query.
  10431. * @param {String} key The key that contains the value that is being
  10432. * excluded.
  10433. * @param {String} queryKey The key in the objects returned by the query to
  10434. * match against.
  10435. * @param {Parse.Query} query The query to run.
  10436. * @return {Parse.Query} Returns the query, so you can chain this call.
  10437. */
  10438. }, {
  10439. key: "doesNotMatchKeyInQuery",
  10440. value: function (key
  10441. /*: string*/
  10442. , queryKey
  10443. /*: string*/
  10444. , query
  10445. /*: ParseQuery*/
  10446. )
  10447. /*: ParseQuery*/
  10448. {
  10449. var queryJSON = query.toJSON();
  10450. queryJSON.className = query.className;
  10451. return this._addCondition(key, '$dontSelect', {
  10452. key: queryKey,
  10453. query: queryJSON
  10454. });
  10455. }
  10456. /**
  10457. * Adds a constraint for finding string values that contain a provided
  10458. * string. This may be slow for large datasets.
  10459. * @param {String} key The key that the string to match is stored in.
  10460. * @param {String} substring The substring that the value must contain.
  10461. * @return {Parse.Query} Returns the query, so you can chain this call.
  10462. */
  10463. }, {
  10464. key: "contains",
  10465. value: function (key
  10466. /*: string*/
  10467. , value
  10468. /*: string*/
  10469. )
  10470. /*: ParseQuery*/
  10471. {
  10472. if (typeof value !== 'string') {
  10473. throw new Error('The value being searched for must be a string.');
  10474. }
  10475. return this._addCondition(key, '$regex', quote(value));
  10476. }
  10477. /**
  10478. * Adds a constraint for finding string values that contain a provided
  10479. * string. This may be slow for large datasets. Requires Parse-Server > 2.5.0
  10480. *
  10481. * In order to sort you must use select and ascending ($score is required)
  10482. * <pre>
  10483. * query.fullText('field', 'term');
  10484. * query.ascending('$score');
  10485. * query.select('$score');
  10486. * </pre>
  10487. *
  10488. * To retrieve the weight / rank
  10489. * <pre>
  10490. * object->get('score');
  10491. * </pre>
  10492. *
  10493. * You can define optionals by providing an object as a third parameter
  10494. * <pre>
  10495. * query.fullText('field', 'term', { language: 'es', diacriticSensitive: true });
  10496. * </pre>
  10497. *
  10498. * @param {String} key The key that the string to match is stored in.
  10499. * @param {String} value The string to search
  10500. * @param {Object} options (Optional)
  10501. * @param {String} options.language The language that determines the list of stop words for the search and the rules for the stemmer and tokenizer.
  10502. * @param {Boolean} options.caseSensitive A boolean flag to enable or disable case sensitive search.
  10503. * @param {Boolean} options.diacriticSensitive A boolean flag to enable or disable diacritic sensitive search.
  10504. * @return {Parse.Query} Returns the query, so you can chain this call.
  10505. */
  10506. }, {
  10507. key: "fullText",
  10508. value: function (key
  10509. /*: string*/
  10510. , value
  10511. /*: string*/
  10512. , options
  10513. /*: ?Object*/
  10514. )
  10515. /*: ParseQuery*/
  10516. {
  10517. options = options || {};
  10518. if (!key) {
  10519. throw new Error('A key is required.');
  10520. }
  10521. if (!value) {
  10522. throw new Error('A search term is required');
  10523. }
  10524. if (typeof value !== 'string') {
  10525. throw new Error('The value being searched for must be a string.');
  10526. }
  10527. var fullOptions = {};
  10528. fullOptions.$term = value;
  10529. for (var option in options) {
  10530. switch (option) {
  10531. case 'language':
  10532. fullOptions.$language = options[option];
  10533. break;
  10534. case 'caseSensitive':
  10535. fullOptions.$caseSensitive = options[option];
  10536. break;
  10537. case 'diacriticSensitive':
  10538. fullOptions.$diacriticSensitive = options[option];
  10539. break;
  10540. default:
  10541. throw new Error("Unknown option: ".concat(option));
  10542. }
  10543. }
  10544. return this._addCondition(key, '$text', {
  10545. $search: fullOptions
  10546. });
  10547. }
  10548. /**
  10549. * Method to sort the full text search by text score
  10550. *
  10551. * @return {Parse.Query} Returns the query, so you can chain this call.
  10552. */
  10553. }, {
  10554. key: "sortByTextScore",
  10555. value: function () {
  10556. this.ascending('$score');
  10557. this.select(['$score']);
  10558. return this;
  10559. }
  10560. /**
  10561. * Adds a constraint for finding string values that start with a provided
  10562. * string. This query will use the backend index, so it will be fast even
  10563. * for large datasets.
  10564. * @param {String} key The key that the string to match is stored in.
  10565. * @param {String} prefix The substring that the value must start with.
  10566. * @return {Parse.Query} Returns the query, so you can chain this call.
  10567. */
  10568. }, {
  10569. key: "startsWith",
  10570. value: function (key
  10571. /*: string*/
  10572. , value
  10573. /*: string*/
  10574. )
  10575. /*: ParseQuery*/
  10576. {
  10577. if (typeof value !== 'string') {
  10578. throw new Error('The value being searched for must be a string.');
  10579. }
  10580. return this._addCondition(key, '$regex', this._regexStartWith(value));
  10581. }
  10582. /**
  10583. * Adds a constraint for finding string values that end with a provided
  10584. * string. This will be slow for large datasets.
  10585. * @param {String} key The key that the string to match is stored in.
  10586. * @param {String} suffix The substring that the value must end with.
  10587. * @return {Parse.Query} Returns the query, so you can chain this call.
  10588. */
  10589. }, {
  10590. key: "endsWith",
  10591. value: function (key
  10592. /*: string*/
  10593. , value
  10594. /*: string*/
  10595. )
  10596. /*: ParseQuery*/
  10597. {
  10598. if (typeof value !== 'string') {
  10599. throw new Error('The value being searched for must be a string.');
  10600. }
  10601. return this._addCondition(key, '$regex', quote(value) + '$');
  10602. }
  10603. /**
  10604. * Adds a proximity based constraint for finding objects with key point
  10605. * values near the point given.
  10606. * @param {String} key The key that the Parse.GeoPoint is stored in.
  10607. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  10608. * @return {Parse.Query} Returns the query, so you can chain this call.
  10609. */
  10610. }, {
  10611. key: "near",
  10612. value: function (key
  10613. /*: string*/
  10614. , point
  10615. /*: ParseGeoPoint*/
  10616. )
  10617. /*: ParseQuery*/
  10618. {
  10619. if (!(point instanceof _ParseGeoPoint.default)) {
  10620. // Try to cast it as a GeoPoint
  10621. point = new _ParseGeoPoint.default(point);
  10622. }
  10623. return this._addCondition(key, '$nearSphere', point);
  10624. }
  10625. /**
  10626. * Adds a proximity based constraint for finding objects with key point
  10627. * values near the point given and within the maximum distance given.
  10628. * @param {String} key The key that the Parse.GeoPoint is stored in.
  10629. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  10630. * @param {Number} maxDistance Maximum distance (in radians) of results to
  10631. * return.
  10632. * @param {Boolean} sorted A Bool value that is true if results should be
  10633. * sorted by distance ascending, false is no sorting is required,
  10634. * defaults to true.
  10635. * @return {Parse.Query} Returns the query, so you can chain this call.
  10636. */
  10637. }, {
  10638. key: "withinRadians",
  10639. value: function (key
  10640. /*: string*/
  10641. , point
  10642. /*: ParseGeoPoint*/
  10643. , distance
  10644. /*: number*/
  10645. , sorted
  10646. /*: boolean*/
  10647. )
  10648. /*: ParseQuery*/
  10649. {
  10650. if (sorted || sorted === undefined) {
  10651. this.near(key, point);
  10652. return this._addCondition(key, '$maxDistance', distance);
  10653. } else {
  10654. return this._addCondition(key, '$geoWithin', {
  10655. '$centerSphere': [[point.longitude, point.latitude], distance]
  10656. });
  10657. }
  10658. }
  10659. /**
  10660. * Adds a proximity based constraint for finding objects with key point
  10661. * values near the point given and within the maximum distance given.
  10662. * Radius of earth used is 3958.8 miles.
  10663. * @param {String} key The key that the Parse.GeoPoint is stored in.
  10664. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  10665. * @param {Number} maxDistance Maximum distance (in miles) of results to
  10666. * return.
  10667. * @param {Boolean} sorted A Bool value that is true if results should be
  10668. * sorted by distance ascending, false is no sorting is required,
  10669. * defaults to true.
  10670. * @return {Parse.Query} Returns the query, so you can chain this call.
  10671. */
  10672. }, {
  10673. key: "withinMiles",
  10674. value: function (key
  10675. /*: string*/
  10676. , point
  10677. /*: ParseGeoPoint*/
  10678. , distance
  10679. /*: number*/
  10680. , sorted
  10681. /*: boolean*/
  10682. )
  10683. /*: ParseQuery*/
  10684. {
  10685. return this.withinRadians(key, point, distance / 3958.8, sorted);
  10686. }
  10687. /**
  10688. * Adds a proximity based constraint for finding objects with key point
  10689. * values near the point given and within the maximum distance given.
  10690. * Radius of earth used is 6371.0 kilometers.
  10691. * @param {String} key The key that the Parse.GeoPoint is stored in.
  10692. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  10693. * @param {Number} maxDistance Maximum distance (in kilometers) of results
  10694. * to return.
  10695. * @param {Boolean} sorted A Bool value that is true if results should be
  10696. * sorted by distance ascending, false is no sorting is required,
  10697. * defaults to true.
  10698. * @return {Parse.Query} Returns the query, so you can chain this call.
  10699. */
  10700. }, {
  10701. key: "withinKilometers",
  10702. value: function (key
  10703. /*: string*/
  10704. , point
  10705. /*: ParseGeoPoint*/
  10706. , distance
  10707. /*: number*/
  10708. , sorted
  10709. /*: boolean*/
  10710. )
  10711. /*: ParseQuery*/
  10712. {
  10713. return this.withinRadians(key, point, distance / 6371.0, sorted);
  10714. }
  10715. /**
  10716. * Adds a constraint to the query that requires a particular key's
  10717. * coordinates be contained within a given rectangular geographic bounding
  10718. * box.
  10719. * @param {String} key The key to be constrained.
  10720. * @param {Parse.GeoPoint} southwest
  10721. * The lower-left inclusive corner of the box.
  10722. * @param {Parse.GeoPoint} northeast
  10723. * The upper-right inclusive corner of the box.
  10724. * @return {Parse.Query} Returns the query, so you can chain this call.
  10725. */
  10726. }, {
  10727. key: "withinGeoBox",
  10728. value: function (key
  10729. /*: string*/
  10730. , southwest
  10731. /*: ParseGeoPoint*/
  10732. , northeast
  10733. /*: ParseGeoPoint*/
  10734. )
  10735. /*: ParseQuery*/
  10736. {
  10737. if (!(southwest instanceof _ParseGeoPoint.default)) {
  10738. southwest = new _ParseGeoPoint.default(southwest);
  10739. }
  10740. if (!(northeast instanceof _ParseGeoPoint.default)) {
  10741. northeast = new _ParseGeoPoint.default(northeast);
  10742. }
  10743. this._addCondition(key, '$within', {
  10744. '$box': [southwest, northeast]
  10745. });
  10746. return this;
  10747. }
  10748. /**
  10749. * Adds a constraint to the query that requires a particular key's
  10750. * coordinates be contained within and on the bounds of a given polygon.
  10751. * Supports closed and open (last point is connected to first) paths
  10752. *
  10753. * Polygon must have at least 3 points
  10754. *
  10755. * @param {String} key The key to be constrained.
  10756. * @param {Array} array of geopoints
  10757. * @return {Parse.Query} Returns the query, so you can chain this call.
  10758. */
  10759. }, {
  10760. key: "withinPolygon",
  10761. value: function (key
  10762. /*: string*/
  10763. , points
  10764. /*: Array<Array<number>>*/
  10765. )
  10766. /*: ParseQuery*/
  10767. {
  10768. return this._addCondition(key, '$geoWithin', {
  10769. '$polygon': points
  10770. });
  10771. }
  10772. /**
  10773. * Add a constraint to the query that requires a particular key's
  10774. * coordinates that contains a ParseGeoPoint
  10775. *
  10776. * @param {String} key The key to be constrained.
  10777. * @param {Parse.GeoPoint} GeoPoint
  10778. * @return {Parse.Query} Returns the query, so you can chain this call.
  10779. */
  10780. }, {
  10781. key: "polygonContains",
  10782. value: function (key
  10783. /*: string*/
  10784. , point
  10785. /*: ParseGeoPoint*/
  10786. )
  10787. /*: ParseQuery*/
  10788. {
  10789. return this._addCondition(key, '$geoIntersects', {
  10790. '$point': point
  10791. });
  10792. }
  10793. /** Query Orderings **/
  10794. /**
  10795. * Sorts the results in ascending order by the given key.
  10796. *
  10797. * @param {(String|String[]|...String)} key The key to order by, which is a
  10798. * string of comma separated values, or an Array of keys, or multiple keys.
  10799. * @return {Parse.Query} Returns the query, so you can chain this call.
  10800. */
  10801. }, {
  10802. key: "ascending",
  10803. value: function ()
  10804. /*: ParseQuery*/
  10805. {
  10806. this._order = [];
  10807. for (var _len = arguments.length, keys = new Array(_len), _key5 = 0; _key5 < _len; _key5++) {
  10808. keys[_key5] = arguments[_key5];
  10809. }
  10810. return this.addAscending.apply(this, keys);
  10811. }
  10812. /**
  10813. * Sorts the results in ascending order by the given key,
  10814. * but can also add secondary sort descriptors without overwriting _order.
  10815. *
  10816. * @param {(String|String[]|...String)} key The key to order by, which is a
  10817. * string of comma separated values, or an Array of keys, or multiple keys.
  10818. * @return {Parse.Query} Returns the query, so you can chain this call.
  10819. */
  10820. }, {
  10821. key: "addAscending",
  10822. value: function ()
  10823. /*: ParseQuery*/
  10824. {
  10825. var _this5 = this;
  10826. if (!this._order) {
  10827. this._order = [];
  10828. }
  10829. for (var _len2 = arguments.length, keys = new Array(_len2), _key6 = 0; _key6 < _len2; _key6++) {
  10830. keys[_key6] = arguments[_key6];
  10831. }
  10832. keys.forEach(function (key) {
  10833. if (Array.isArray(key)) {
  10834. key = key.join();
  10835. }
  10836. _this5._order = _this5._order.concat(key.replace(/\s/g, '').split(','));
  10837. });
  10838. return this;
  10839. }
  10840. /**
  10841. * Sorts the results in descending order by the given key.
  10842. *
  10843. * @param {(String|String[]|...String)} key The key to order by, which is a
  10844. * string of comma separated values, or an Array of keys, or multiple keys.
  10845. * @return {Parse.Query} Returns the query, so you can chain this call.
  10846. */
  10847. }, {
  10848. key: "descending",
  10849. value: function ()
  10850. /*: ParseQuery*/
  10851. {
  10852. this._order = [];
  10853. for (var _len3 = arguments.length, keys = new Array(_len3), _key7 = 0; _key7 < _len3; _key7++) {
  10854. keys[_key7] = arguments[_key7];
  10855. }
  10856. return this.addDescending.apply(this, keys);
  10857. }
  10858. /**
  10859. * Sorts the results in descending order by the given key,
  10860. * but can also add secondary sort descriptors without overwriting _order.
  10861. *
  10862. * @param {(String|String[]|...String)} key The key to order by, which is a
  10863. * string of comma separated values, or an Array of keys, or multiple keys.
  10864. * @return {Parse.Query} Returns the query, so you can chain this call.
  10865. */
  10866. }, {
  10867. key: "addDescending",
  10868. value: function ()
  10869. /*: ParseQuery*/
  10870. {
  10871. var _this6 = this;
  10872. if (!this._order) {
  10873. this._order = [];
  10874. }
  10875. for (var _len4 = arguments.length, keys = new Array(_len4), _key8 = 0; _key8 < _len4; _key8++) {
  10876. keys[_key8] = arguments[_key8];
  10877. }
  10878. keys.forEach(function (key) {
  10879. if (Array.isArray(key)) {
  10880. key = key.join();
  10881. }
  10882. _this6._order = _this6._order.concat(key.replace(/\s/g, '').split(',').map(function (k) {
  10883. return '-' + k;
  10884. }));
  10885. });
  10886. return this;
  10887. }
  10888. /** Query Options **/
  10889. /**
  10890. * Sets the number of results to skip before returning any results.
  10891. * This is useful for pagination.
  10892. * Default is to skip zero results.
  10893. * @param {Number} n the number of results to skip.
  10894. * @return {Parse.Query} Returns the query, so you can chain this call.
  10895. */
  10896. }, {
  10897. key: "skip",
  10898. value: function (n
  10899. /*: number*/
  10900. )
  10901. /*: ParseQuery*/
  10902. {
  10903. if (typeof n !== 'number' || n < 0) {
  10904. throw new Error('You can only skip by a positive number');
  10905. }
  10906. this._skip = n;
  10907. return this;
  10908. }
  10909. /**
  10910. * Sets the limit of the number of results to return. The default limit is
  10911. * 100, with a maximum of 1000 results being returned at a time.
  10912. * @param {Number} n the number of results to limit to.
  10913. * @return {Parse.Query} Returns the query, so you can chain this call.
  10914. */
  10915. }, {
  10916. key: "limit",
  10917. value: function (n
  10918. /*: number*/
  10919. )
  10920. /*: ParseQuery*/
  10921. {
  10922. if (typeof n !== 'number') {
  10923. throw new Error('You can only set the limit to a numeric value');
  10924. }
  10925. this._limit = n;
  10926. return this;
  10927. }
  10928. /**
  10929. * Sets the flag to include with response the total number of objects satisfying this query,
  10930. * despite limits/skip. Might be useful for pagination.
  10931. * Note that result of this query will be wrapped as an object with
  10932. *`results`: holding {ParseObject} array and `count`: integer holding total number
  10933. * @param {boolean} b false - disable, true - enable.
  10934. * @return {Parse.Query} Returns the query, so you can chain this call.
  10935. */
  10936. }, {
  10937. key: "withCount",
  10938. value: function ()
  10939. /*: ParseQuery*/
  10940. {
  10941. var includeCount
  10942. /*: boolean*/
  10943. = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  10944. if (typeof includeCount !== 'boolean') {
  10945. throw new Error('You can only set withCount to a boolean value');
  10946. }
  10947. this._count = includeCount;
  10948. return this;
  10949. }
  10950. /**
  10951. * Includes nested Parse.Objects for the provided key. You can use dot
  10952. * notation to specify which fields in the included object are also fetched.
  10953. *
  10954. * You can include all nested Parse.Objects by passing in '*'.
  10955. * Requires Parse Server 3.0.0+
  10956. * <pre>query.include('*');</pre>
  10957. *
  10958. * @param {...String|Array<String>} key The name(s) of the key(s) to include.
  10959. * @return {Parse.Query} Returns the query, so you can chain this call.
  10960. */
  10961. }, {
  10962. key: "include",
  10963. value: function ()
  10964. /*: ParseQuery*/
  10965. {
  10966. var _this7 = this;
  10967. for (var _len5 = arguments.length, keys = new Array(_len5), _key9 = 0; _key9 < _len5; _key9++) {
  10968. keys[_key9] = arguments[_key9];
  10969. }
  10970. keys.forEach(function (key) {
  10971. if (Array.isArray(key)) {
  10972. _this7._include = _this7._include.concat(key);
  10973. } else {
  10974. _this7._include.push(key);
  10975. }
  10976. });
  10977. return this;
  10978. }
  10979. /**
  10980. * Includes all nested Parse.Objects.
  10981. *
  10982. * Requires Parse Server 3.0.0+
  10983. *
  10984. * @return {Parse.Query} Returns the query, so you can chain this call.
  10985. */
  10986. }, {
  10987. key: "includeAll",
  10988. value: function ()
  10989. /*: ParseQuery*/
  10990. {
  10991. return this.include('*');
  10992. }
  10993. /**
  10994. * Restricts the fields of the returned Parse.Objects to include only the
  10995. * provided keys. If this is called multiple times, then all of the keys
  10996. * specified in each of the calls will be included.
  10997. * @param {...String|Array<String>} keys The name(s) of the key(s) to include.
  10998. * @return {Parse.Query} Returns the query, so you can chain this call.
  10999. */
  11000. }, {
  11001. key: "select",
  11002. value: function ()
  11003. /*: ParseQuery*/
  11004. {
  11005. var _this8 = this;
  11006. if (!this._select) {
  11007. this._select = [];
  11008. }
  11009. for (var _len6 = arguments.length, keys = new Array(_len6), _key10 = 0; _key10 < _len6; _key10++) {
  11010. keys[_key10] = arguments[_key10];
  11011. }
  11012. keys.forEach(function (key) {
  11013. if (Array.isArray(key)) {
  11014. _this8._select = _this8._select.concat(key);
  11015. } else {
  11016. _this8._select.push(key);
  11017. }
  11018. });
  11019. return this;
  11020. }
  11021. /**
  11022. * Restricts the fields of the returned Parse.Objects to all keys except the
  11023. * provided keys. Exclude takes precedence over select and include.
  11024. *
  11025. * Requires Parse Server 3.6.0+
  11026. *
  11027. * @param {...String|Array<String>} keys The name(s) of the key(s) to exclude.
  11028. * @return {Parse.Query} Returns the query, so you can chain this call.
  11029. */
  11030. }, {
  11031. key: "exclude",
  11032. value: function ()
  11033. /*: ParseQuery*/
  11034. {
  11035. var _this9 = this;
  11036. for (var _len7 = arguments.length, keys = new Array(_len7), _key11 = 0; _key11 < _len7; _key11++) {
  11037. keys[_key11] = arguments[_key11];
  11038. }
  11039. keys.forEach(function (key) {
  11040. if (Array.isArray(key)) {
  11041. _this9._exclude = _this9._exclude.concat(key);
  11042. } else {
  11043. _this9._exclude.push(key);
  11044. }
  11045. });
  11046. return this;
  11047. }
  11048. /**
  11049. * Changes the read preference that the backend will use when performing the query to the database.
  11050. * @param {String} readPreference The read preference for the main query.
  11051. * @param {String} includeReadPreference The read preference for the queries to include pointers.
  11052. * @param {String} subqueryReadPreference The read preference for the sub queries.
  11053. * @return {Parse.Query} Returns the query, so you can chain this call.
  11054. */
  11055. }, {
  11056. key: "readPreference",
  11057. value: function (_readPreference
  11058. /*: string*/
  11059. , includeReadPreference
  11060. /*:: ?: string*/
  11061. , subqueryReadPreference
  11062. /*:: ?: string*/
  11063. )
  11064. /*: ParseQuery*/
  11065. {
  11066. this._readPreference = _readPreference;
  11067. this._includeReadPreference = includeReadPreference;
  11068. this._subqueryReadPreference = subqueryReadPreference;
  11069. return this;
  11070. }
  11071. /**
  11072. * Subscribe this query to get liveQuery updates
  11073. *
  11074. * @param {String} sessionToken (optional) Defaults to the currentUser
  11075. * @return {Promise<LiveQuerySubscription>} Returns the liveQuerySubscription, it's an event emitter
  11076. * which can be used to get liveQuery updates.
  11077. */
  11078. }, {
  11079. key: "subscribe",
  11080. value: function () {
  11081. var _subscribe = (0, _asyncToGenerator2.default)(
  11082. /*#__PURE__*/
  11083. _regenerator.default.mark(function _callee2(sessionToken
  11084. /*:: ?: string*/
  11085. ) {
  11086. var currentUser, liveQueryClient, subscription;
  11087. return _regenerator.default.wrap(function (_context2) {
  11088. while (1) {
  11089. switch (_context2.prev = _context2.next) {
  11090. case 0:
  11091. _context2.next = 2;
  11092. return _CoreManager.default.getUserController().currentUserAsync();
  11093. case 2:
  11094. currentUser = _context2.sent;
  11095. if (!sessionToken) {
  11096. sessionToken = currentUser ? currentUser.getSessionToken() : undefined;
  11097. }
  11098. _context2.next = 6;
  11099. return _CoreManager.default.getLiveQueryController().getDefaultLiveQueryClient();
  11100. case 6:
  11101. liveQueryClient = _context2.sent;
  11102. if (liveQueryClient.shouldOpen()) {
  11103. liveQueryClient.open();
  11104. }
  11105. subscription = liveQueryClient.subscribe(this, sessionToken);
  11106. return _context2.abrupt("return", subscription);
  11107. case 10:
  11108. case "end":
  11109. return _context2.stop();
  11110. }
  11111. }
  11112. }, _callee2, this);
  11113. }));
  11114. return function () {
  11115. return _subscribe.apply(this, arguments);
  11116. };
  11117. }()
  11118. /**
  11119. * Constructs a Parse.Query that is the OR of the passed in queries. For
  11120. * example:
  11121. * <pre>var compoundQuery = Parse.Query.or(query1, query2, query3);</pre>
  11122. *
  11123. * will create a compoundQuery that is an or of the query1, query2, and
  11124. * query3.
  11125. * @param {...Parse.Query} var_args The list of queries to OR.
  11126. * @static
  11127. * @return {Parse.Query} The query that is the OR of the passed in queries.
  11128. */
  11129. }, {
  11130. key: "fromLocalDatastore",
  11131. /**
  11132. * Changes the source of this query to all pinned objects.
  11133. *
  11134. * @return {Parse.Query} Returns the query, so you can chain this call.
  11135. */
  11136. value: function ()
  11137. /*: ParseQuery*/
  11138. {
  11139. return this.fromPinWithName(null);
  11140. }
  11141. /**
  11142. * Changes the source of this query to the default group of pinned objects.
  11143. *
  11144. * @return {Parse.Query} Returns the query, so you can chain this call.
  11145. */
  11146. }, {
  11147. key: "fromPin",
  11148. value: function ()
  11149. /*: ParseQuery*/
  11150. {
  11151. return this.fromPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
  11152. }
  11153. /**
  11154. * Changes the source of this query to a specific group of pinned objects.
  11155. *
  11156. * @param {String} name The name of query source.
  11157. * @return {Parse.Query} Returns the query, so you can chain this call.
  11158. */
  11159. }, {
  11160. key: "fromPinWithName",
  11161. value: function (name
  11162. /*:: ?: string*/
  11163. )
  11164. /*: ParseQuery*/
  11165. {
  11166. var localDatastore = _CoreManager.default.getLocalDatastore();
  11167. if (localDatastore.checkIfEnabled()) {
  11168. this._queriesLocalDatastore = true;
  11169. this._localDatastorePinName = name;
  11170. }
  11171. return this;
  11172. }
  11173. }], [{
  11174. key: "fromJSON",
  11175. value: function (className
  11176. /*: string*/
  11177. , json
  11178. /*: QueryJSON*/
  11179. )
  11180. /*: ParseQuery*/
  11181. {
  11182. var query = new ParseQuery(className);
  11183. return query.withJSON(json);
  11184. }
  11185. }, {
  11186. key: "or",
  11187. value: function ()
  11188. /*: ParseQuery*/
  11189. {
  11190. for (var _len8 = arguments.length, queries = new Array(_len8), _key12 = 0; _key12 < _len8; _key12++) {
  11191. queries[_key12] = arguments[_key12];
  11192. }
  11193. var className = _getClassNameFromQueries(queries);
  11194. var query = new ParseQuery(className);
  11195. query._orQuery(queries);
  11196. return query;
  11197. }
  11198. /**
  11199. * Constructs a Parse.Query that is the AND of the passed in queries. For
  11200. * example:
  11201. * <pre>var compoundQuery = Parse.Query.and(query1, query2, query3);</pre>
  11202. *
  11203. * will create a compoundQuery that is an and of the query1, query2, and
  11204. * query3.
  11205. * @param {...Parse.Query} var_args The list of queries to AND.
  11206. * @static
  11207. * @return {Parse.Query} The query that is the AND of the passed in queries.
  11208. */
  11209. }, {
  11210. key: "and",
  11211. value: function ()
  11212. /*: ParseQuery*/
  11213. {
  11214. for (var _len9 = arguments.length, queries = new Array(_len9), _key13 = 0; _key13 < _len9; _key13++) {
  11215. queries[_key13] = arguments[_key13];
  11216. }
  11217. var className = _getClassNameFromQueries(queries);
  11218. var query = new ParseQuery(className);
  11219. query._andQuery(queries);
  11220. return query;
  11221. }
  11222. /**
  11223. * Constructs a Parse.Query that is the NOR of the passed in queries. For
  11224. * example:
  11225. * <pre>const compoundQuery = Parse.Query.nor(query1, query2, query3);</pre>
  11226. *
  11227. * will create a compoundQuery that is a nor of the query1, query2, and
  11228. * query3.
  11229. * @param {...Parse.Query} var_args The list of queries to NOR.
  11230. * @static
  11231. * @return {Parse.Query} The query that is the NOR of the passed in queries.
  11232. */
  11233. }, {
  11234. key: "nor",
  11235. value: function ()
  11236. /*: ParseQuery*/
  11237. {
  11238. for (var _len10 = arguments.length, queries = new Array(_len10), _key14 = 0; _key14 < _len10; _key14++) {
  11239. queries[_key14] = arguments[_key14];
  11240. }
  11241. var className = _getClassNameFromQueries(queries);
  11242. var query = new ParseQuery(className);
  11243. query._norQuery(queries);
  11244. return query;
  11245. }
  11246. }]);
  11247. return ParseQuery;
  11248. }();
  11249. var DefaultController = {
  11250. find: function (className
  11251. /*: string*/
  11252. , params
  11253. /*: QueryJSON*/
  11254. , options
  11255. /*: RequestOptions*/
  11256. )
  11257. /*: Promise<Array<ParseObject>>*/
  11258. {
  11259. var RESTController = _CoreManager.default.getRESTController();
  11260. return RESTController.request('GET', 'classes/' + className, params, options);
  11261. },
  11262. aggregate: function (className
  11263. /*: string*/
  11264. , params
  11265. /*: any*/
  11266. , options
  11267. /*: RequestOptions*/
  11268. )
  11269. /*: Promise<Array<mixed>>*/
  11270. {
  11271. var RESTController = _CoreManager.default.getRESTController();
  11272. return RESTController.request('GET', 'aggregate/' + className, params, options);
  11273. }
  11274. };
  11275. _CoreManager.default.setQueryController(DefaultController);
  11276. var _default = ParseQuery;
  11277. exports.default = _default;
  11278. },{"./CoreManager":4,"./LocalDatastoreUtils":12,"./OfflineQuery":14,"./ParseError":18,"./ParseGeoPoint":20,"./ParseObject":23,"./encode":42,"./promiseUtils":47,"@babel/runtime/helpers/asyncToGenerator":53,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73,"@babel/runtime/regenerator":76}],27:[function(_dereq_,module,exports){
  11279. "use strict";
  11280. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  11281. Object.defineProperty(exports, "__esModule", {
  11282. value: true
  11283. });
  11284. exports.default = void 0;
  11285. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  11286. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  11287. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  11288. var _ParseOp = _dereq_("./ParseOp");
  11289. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  11290. var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
  11291. /**
  11292. * Copyright (c) 2015-present, Parse, LLC.
  11293. * All rights reserved.
  11294. *
  11295. * This source code is licensed under the BSD-style license found in the
  11296. * LICENSE file in the root directory of this source tree. An additional grant
  11297. * of patent rights can be found in the PATENTS file in the same directory.
  11298. *
  11299. * @flow
  11300. */
  11301. /**
  11302. * Creates a new Relation for the given parent object and key. This
  11303. * constructor should rarely be used directly, but rather created by
  11304. * Parse.Object.relation.
  11305. *
  11306. * <p>
  11307. * A class that is used to access all of the children of a many-to-many
  11308. * relationship. Each instance of Parse.Relation is associated with a
  11309. * particular parent object and key.
  11310. * </p>
  11311. * @alias Parse.Relation
  11312. */
  11313. var ParseRelation =
  11314. /*#__PURE__*/
  11315. function () {
  11316. /**
  11317. * @param {Parse.Object} parent The parent of this relation.
  11318. * @param {String} key The key for this relation on the parent.
  11319. */
  11320. function ParseRelation(parent
  11321. /*: ?ParseObject*/
  11322. , key
  11323. /*: ?string*/
  11324. ) {
  11325. (0, _classCallCheck2.default)(this, ParseRelation);
  11326. (0, _defineProperty2.default)(this, "parent", void 0);
  11327. (0, _defineProperty2.default)(this, "key", void 0);
  11328. (0, _defineProperty2.default)(this, "targetClassName", void 0);
  11329. this.parent = parent;
  11330. this.key = key;
  11331. this.targetClassName = null;
  11332. }
  11333. /*
  11334. * Makes sure that this relation has the right parent and key.
  11335. */
  11336. (0, _createClass2.default)(ParseRelation, [{
  11337. key: "_ensureParentAndKey",
  11338. value: function (parent
  11339. /*: ParseObject*/
  11340. , key
  11341. /*: string*/
  11342. ) {
  11343. this.key = this.key || key;
  11344. if (this.key !== key) {
  11345. throw new Error('Internal Error. Relation retrieved from two different keys.');
  11346. }
  11347. if (this.parent) {
  11348. if (this.parent.className !== parent.className) {
  11349. throw new Error('Internal Error. Relation retrieved from two different Objects.');
  11350. }
  11351. if (this.parent.id) {
  11352. if (this.parent.id !== parent.id) {
  11353. throw new Error('Internal Error. Relation retrieved from two different Objects.');
  11354. }
  11355. } else if (parent.id) {
  11356. this.parent = parent;
  11357. }
  11358. } else {
  11359. this.parent = parent;
  11360. }
  11361. }
  11362. /**
  11363. * Adds a Parse.Object or an array of Parse.Objects to the relation.
  11364. * @param {} objects The item or items to add.
  11365. */
  11366. }, {
  11367. key: "add",
  11368. value: function (objects
  11369. /*: ParseObject | Array<ParseObject | string>*/
  11370. )
  11371. /*: ParseObject*/
  11372. {
  11373. if (!Array.isArray(objects)) {
  11374. objects = [objects];
  11375. }
  11376. var change = new _ParseOp.RelationOp(objects, []);
  11377. var parent = this.parent;
  11378. if (!parent) {
  11379. throw new Error('Cannot add to a Relation without a parent');
  11380. }
  11381. parent.set(this.key, change);
  11382. this.targetClassName = change._targetClassName;
  11383. return parent;
  11384. }
  11385. /**
  11386. * Removes a Parse.Object or an array of Parse.Objects from this relation.
  11387. * @param {} objects The item or items to remove.
  11388. */
  11389. }, {
  11390. key: "remove",
  11391. value: function (objects
  11392. /*: ParseObject | Array<ParseObject | string>*/
  11393. ) {
  11394. if (!Array.isArray(objects)) {
  11395. objects = [objects];
  11396. }
  11397. var change = new _ParseOp.RelationOp([], objects);
  11398. if (!this.parent) {
  11399. throw new Error('Cannot remove from a Relation without a parent');
  11400. }
  11401. this.parent.set(this.key, change);
  11402. this.targetClassName = change._targetClassName;
  11403. }
  11404. /**
  11405. * Returns a JSON version of the object suitable for saving to disk.
  11406. * @return {Object}
  11407. */
  11408. }, {
  11409. key: "toJSON",
  11410. value: function ()
  11411. /*: { __type: 'Relation', className: ?string }*/
  11412. {
  11413. return {
  11414. __type: 'Relation',
  11415. className: this.targetClassName
  11416. };
  11417. }
  11418. /**
  11419. * Returns a Parse.Query that is limited to objects in this
  11420. * relation.
  11421. * @return {Parse.Query}
  11422. */
  11423. }, {
  11424. key: "query",
  11425. value: function query()
  11426. /*: ParseQuery*/
  11427. {
  11428. var query;
  11429. var parent = this.parent;
  11430. if (!parent) {
  11431. throw new Error('Cannot construct a query for a Relation without a parent');
  11432. }
  11433. if (!this.targetClassName) {
  11434. query = new _ParseQuery.default(parent.className);
  11435. query._extraOptions.redirectClassNameForKey = this.key;
  11436. } else {
  11437. query = new _ParseQuery.default(this.targetClassName);
  11438. }
  11439. query._addCondition('$relatedTo', 'object', {
  11440. __type: 'Pointer',
  11441. className: parent.className,
  11442. objectId: parent.id
  11443. });
  11444. query._addCondition('$relatedTo', 'key', this.key);
  11445. return query;
  11446. }
  11447. }]);
  11448. return ParseRelation;
  11449. }();
  11450. var _default = ParseRelation;
  11451. exports.default = _default;
  11452. },{"./ParseObject":23,"./ParseOp":24,"./ParseQuery":26,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/interopRequireDefault":61}],28:[function(_dereq_,module,exports){
  11453. "use strict";
  11454. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  11455. Object.defineProperty(exports, "__esModule", {
  11456. value: true
  11457. });
  11458. exports.default = void 0;
  11459. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  11460. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  11461. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  11462. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  11463. var _get2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/get"));
  11464. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  11465. var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
  11466. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  11467. var _ParseObject2 = _interopRequireDefault(_dereq_("./ParseObject"));
  11468. /**
  11469. * Copyright (c) 2015-present, Parse, LLC.
  11470. * All rights reserved.
  11471. *
  11472. * This source code is licensed under the BSD-style license found in the
  11473. * LICENSE file in the root directory of this source tree. An additional grant
  11474. * of patent rights can be found in the PATENTS file in the same directory.
  11475. *
  11476. * @flow
  11477. */
  11478. /**
  11479. * Represents a Role on the Parse server. Roles represent groupings of
  11480. * Users for the purposes of granting permissions (e.g. specifying an ACL
  11481. * for an Object). Roles are specified by their sets of child users and
  11482. * child roles, all of which are granted any permissions that the parent
  11483. * role has.
  11484. *
  11485. * <p>Roles must have a name (which cannot be changed after creation of the
  11486. * role), and must specify an ACL.</p>
  11487. * @alias Parse.Role
  11488. * @extends Parse.Object
  11489. */
  11490. var ParseRole =
  11491. /*#__PURE__*/
  11492. function (_ParseObject) {
  11493. (0, _inherits2.default)(ParseRole, _ParseObject);
  11494. /**
  11495. * @param {String} name The name of the Role to create.
  11496. * @param {Parse.ACL} acl The ACL for this role. Roles must have an ACL.
  11497. * A Parse.Role is a local representation of a role persisted to the Parse
  11498. * cloud.
  11499. */
  11500. function ParseRole(name
  11501. /*: string*/
  11502. , acl
  11503. /*: ParseACL*/
  11504. ) {
  11505. var _this;
  11506. (0, _classCallCheck2.default)(this, ParseRole);
  11507. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(ParseRole).call(this, '_Role'));
  11508. if (typeof name === 'string' && acl instanceof _ParseACL.default) {
  11509. _this.setName(name);
  11510. _this.setACL(acl);
  11511. }
  11512. return _this;
  11513. }
  11514. /**
  11515. * Gets the name of the role. You can alternatively call role.get("name")
  11516. *
  11517. * @return {String} the name of the role.
  11518. */
  11519. (0, _createClass2.default)(ParseRole, [{
  11520. key: "getName",
  11521. value: function ()
  11522. /*: ?string*/
  11523. {
  11524. var name = this.get('name');
  11525. if (name == null || typeof name === 'string') {
  11526. return name;
  11527. }
  11528. return '';
  11529. }
  11530. /**
  11531. * Sets the name for a role. This value must be set before the role has
  11532. * been saved to the server, and cannot be set once the role has been
  11533. * saved.
  11534. *
  11535. * <p>
  11536. * A role's name can only contain alphanumeric characters, _, -, and
  11537. * spaces.
  11538. * </p>
  11539. *
  11540. * <p>This is equivalent to calling role.set("name", name)</p>
  11541. *
  11542. * @param {String} name The name of the role.
  11543. * @param {Object} options Standard options object with success and error
  11544. * callbacks.
  11545. */
  11546. }, {
  11547. key: "setName",
  11548. value: function (name
  11549. /*: string*/
  11550. , options
  11551. /*:: ?: mixed*/
  11552. )
  11553. /*: ParseObject | boolean*/
  11554. {
  11555. return this.set('name', name, options);
  11556. }
  11557. /**
  11558. * Gets the Parse.Relation for the Parse.Users that are direct
  11559. * children of this role. These users are granted any privileges that this
  11560. * role has been granted (e.g. read or write access through ACLs). You can
  11561. * add or remove users from the role through this relation.
  11562. *
  11563. * <p>This is equivalent to calling role.relation("users")</p>
  11564. *
  11565. * @return {Parse.Relation} the relation for the users belonging to this
  11566. * role.
  11567. */
  11568. }, {
  11569. key: "getUsers",
  11570. value: function ()
  11571. /*: ParseRelation*/
  11572. {
  11573. return this.relation('users');
  11574. }
  11575. /**
  11576. * Gets the Parse.Relation for the Parse.Roles that are direct
  11577. * children of this role. These roles' users are granted any privileges that
  11578. * this role has been granted (e.g. read or write access through ACLs). You
  11579. * can add or remove child roles from this role through this relation.
  11580. *
  11581. * <p>This is equivalent to calling role.relation("roles")</p>
  11582. *
  11583. * @return {Parse.Relation} the relation for the roles belonging to this
  11584. * role.
  11585. */
  11586. }, {
  11587. key: "getRoles",
  11588. value: function ()
  11589. /*: ParseRelation*/
  11590. {
  11591. return this.relation('roles');
  11592. }
  11593. }, {
  11594. key: "validate",
  11595. value: function (attrs
  11596. /*: AttributeMap*/
  11597. , options
  11598. /*:: ?: mixed*/
  11599. )
  11600. /*: ParseError | boolean*/
  11601. {
  11602. var isInvalid = (0, _get2.default)((0, _getPrototypeOf2.default)(ParseRole.prototype), "validate", this).call(this, attrs, options);
  11603. if (isInvalid) {
  11604. return isInvalid;
  11605. }
  11606. if ('name' in attrs && attrs.name !== this.getName()) {
  11607. var newName = attrs.name;
  11608. if (this.id && this.id !== attrs.objectId) {
  11609. // Check to see if the objectId being set matches this.id
  11610. // This happens during a fetch -- the id is set before calling fetch
  11611. // Let the name be set in this case
  11612. return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'A role\'s name can only be set before it has been saved.');
  11613. }
  11614. if (typeof newName !== 'string') {
  11615. return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'A role\'s name must be a String.');
  11616. }
  11617. if (!/^[0-9a-zA-Z\-_ ]+$/.test(newName)) {
  11618. return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'A role\'s name can be only contain alphanumeric characters, _, ' + '-, and spaces.');
  11619. }
  11620. }
  11621. return false;
  11622. }
  11623. }]);
  11624. return ParseRole;
  11625. }(_ParseObject2.default);
  11626. _ParseObject2.default.registerSubclass('_Role', ParseRole);
  11627. var _default = ParseRole;
  11628. exports.default = _default;
  11629. },{"./ParseACL":16,"./ParseError":18,"./ParseObject":23,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/get":58,"@babel/runtime/helpers/getPrototypeOf":59,"@babel/runtime/helpers/inherits":60,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/possibleConstructorReturn":68}],29:[function(_dereq_,module,exports){
  11630. "use strict";
  11631. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  11632. Object.defineProperty(exports, "__esModule", {
  11633. value: true
  11634. });
  11635. exports.default = void 0;
  11636. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  11637. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  11638. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  11639. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  11640. /**
  11641. * Copyright (c) 2015-present, Parse, LLC.
  11642. * All rights reserved.
  11643. *
  11644. * This source code is licensed under the BSD-style license found in the
  11645. * LICENSE file in the root directory of this source tree. An additional grant
  11646. * of patent rights can be found in the PATENTS file in the same directory.
  11647. *
  11648. * @flow
  11649. */
  11650. var FIELD_TYPES = ['String', 'Number', 'Boolean', 'Date', 'File', 'GeoPoint', 'Polygon', 'Array', 'Object', 'Pointer', 'Relation'];
  11651. /**
  11652. * A Parse.Schema object is for handling schema data from Parse.
  11653. * <p>All the schemas methods require MasterKey.
  11654. *
  11655. * <pre>
  11656. * const schema = new Parse.Schema('MyClass');
  11657. * schema.addString('field');
  11658. * schema.addIndex('index_name', {'field', 1});
  11659. * schema.save();
  11660. * </pre>
  11661. * </p>
  11662. * @alias Parse.Schema
  11663. */
  11664. var ParseSchema =
  11665. /*#__PURE__*/
  11666. function () {
  11667. /**
  11668. * @param {String} className Parse Class string.
  11669. */
  11670. function ParseSchema(className
  11671. /*: string*/
  11672. ) {
  11673. (0, _classCallCheck2.default)(this, ParseSchema);
  11674. (0, _defineProperty2.default)(this, "className", void 0);
  11675. (0, _defineProperty2.default)(this, "_fields", void 0);
  11676. (0, _defineProperty2.default)(this, "_indexes", void 0);
  11677. if (typeof className === 'string') {
  11678. if (className === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
  11679. this.className = '_User';
  11680. } else {
  11681. this.className = className;
  11682. }
  11683. }
  11684. this._fields = {};
  11685. this._indexes = {};
  11686. }
  11687. /**
  11688. * Static method to get all schemas
  11689. *
  11690. * @param {Object} options
  11691. * Valid options are:<ul>
  11692. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  11693. * be used for this request.
  11694. * <li>sessionToken: A valid session token, used for making a request on
  11695. * behalf of a specific user.
  11696. * </ul>
  11697. *
  11698. * @return {Promise} A promise that is resolved with the result when
  11699. * the query completes.
  11700. */
  11701. (0, _createClass2.default)(ParseSchema, [{
  11702. key: "get",
  11703. /**
  11704. * Get the Schema from Parse
  11705. *
  11706. * @param {Object} options
  11707. * Valid options are:<ul>
  11708. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  11709. * be used for this request.
  11710. * <li>sessionToken: A valid session token, used for making a request on
  11711. * behalf of a specific user.
  11712. * </ul>
  11713. *
  11714. * @return {Promise} A promise that is resolved with the result when
  11715. * the query completes.
  11716. */
  11717. value: function (options
  11718. /*: FullOptions*/
  11719. ) {
  11720. this.assertClassName();
  11721. options = options || {};
  11722. var controller = _CoreManager.default.getSchemaController();
  11723. return controller.get(this.className, options).then(function (response) {
  11724. if (!response) {
  11725. throw new Error('Schema not found.');
  11726. }
  11727. return response;
  11728. });
  11729. }
  11730. /**
  11731. * Create a new Schema on Parse
  11732. *
  11733. * @param {Object} options
  11734. * Valid options are:<ul>
  11735. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  11736. * be used for this request.
  11737. * <li>sessionToken: A valid session token, used for making a request on
  11738. * behalf of a specific user.
  11739. * </ul>
  11740. *
  11741. * @return {Promise} A promise that is resolved with the result when
  11742. * the query completes.
  11743. */
  11744. }, {
  11745. key: "save",
  11746. value: function (options
  11747. /*: FullOptions*/
  11748. ) {
  11749. this.assertClassName();
  11750. options = options || {};
  11751. var controller = _CoreManager.default.getSchemaController();
  11752. var params = {
  11753. className: this.className,
  11754. fields: this._fields,
  11755. indexes: this._indexes
  11756. };
  11757. return controller.create(this.className, params, options).then(function (response) {
  11758. return response;
  11759. });
  11760. }
  11761. /**
  11762. * Update a Schema on Parse
  11763. *
  11764. * @param {Object} options
  11765. * Valid options are:<ul>
  11766. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  11767. * be used for this request.
  11768. * <li>sessionToken: A valid session token, used for making a request on
  11769. * behalf of a specific user.
  11770. * </ul>
  11771. *
  11772. * @return {Promise} A promise that is resolved with the result when
  11773. * the query completes.
  11774. */
  11775. }, {
  11776. key: "update",
  11777. value: function (options
  11778. /*: FullOptions*/
  11779. ) {
  11780. this.assertClassName();
  11781. options = options || {};
  11782. var controller = _CoreManager.default.getSchemaController();
  11783. var params = {
  11784. className: this.className,
  11785. fields: this._fields,
  11786. indexes: this._indexes
  11787. };
  11788. this._fields = {};
  11789. this._indexes = {};
  11790. return controller.update(this.className, params, options).then(function (response) {
  11791. return response;
  11792. });
  11793. }
  11794. /**
  11795. * Removing a Schema from Parse
  11796. * Can only be used on Schema without objects
  11797. *
  11798. * @param {Object} options
  11799. * Valid options are:<ul>
  11800. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  11801. * be used for this request.
  11802. * <li>sessionToken: A valid session token, used for making a request on
  11803. * behalf of a specific user.
  11804. * </ul>
  11805. *
  11806. * @return {Promise} A promise that is resolved with the result when
  11807. * the query completes.
  11808. */
  11809. }, {
  11810. key: "delete",
  11811. value: function (options
  11812. /*: FullOptions*/
  11813. ) {
  11814. this.assertClassName();
  11815. options = options || {};
  11816. var controller = _CoreManager.default.getSchemaController();
  11817. return controller.delete(this.className, options).then(function (response) {
  11818. return response;
  11819. });
  11820. }
  11821. /**
  11822. * Removes all objects from a Schema (class) in Parse.
  11823. * EXERCISE CAUTION, running this will delete all objects for this schema and cannot be reversed
  11824. * @return {Promise} A promise that is resolved with the result when
  11825. * the query completes.
  11826. */
  11827. }, {
  11828. key: "purge",
  11829. value: function () {
  11830. this.assertClassName();
  11831. var controller = _CoreManager.default.getSchemaController();
  11832. return controller.purge(this.className).then(function (response) {
  11833. return response;
  11834. });
  11835. }
  11836. /**
  11837. * Assert if ClassName has been filled
  11838. * @private
  11839. */
  11840. }, {
  11841. key: "assertClassName",
  11842. value: function () {
  11843. if (!this.className) {
  11844. throw new Error('You must set a Class Name before making any request.');
  11845. }
  11846. }
  11847. /**
  11848. * Adding a Field to Create / Update a Schema
  11849. *
  11850. * @param {String} name Name of the field that will be created on Parse
  11851. * @param {String} type TheCan be a (String|Number|Boolean|Date|Parse.File|Parse.GeoPoint|Array|Object|Pointer|Parse.Relation)
  11852. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11853. */
  11854. }, {
  11855. key: "addField",
  11856. value: function (name
  11857. /*: string*/
  11858. , type
  11859. /*: string*/
  11860. ) {
  11861. type = type || 'String';
  11862. if (!name) {
  11863. throw new Error('field name may not be null.');
  11864. }
  11865. if (FIELD_TYPES.indexOf(type) === -1) {
  11866. throw new Error("".concat(type, " is not a valid type."));
  11867. }
  11868. this._fields[name] = {
  11869. type: type
  11870. };
  11871. return this;
  11872. }
  11873. /**
  11874. * Adding an Index to Create / Update a Schema
  11875. *
  11876. * @param {String} name Name of the field that will be created on Parse
  11877. * @param {String} type Can be a (String|Number|Boolean|Date|Parse.File|Parse.GeoPoint|Array|Object|Pointer|Parse.Relation)
  11878. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11879. */
  11880. }, {
  11881. key: "addIndex",
  11882. value: function (name
  11883. /*: string*/
  11884. , index
  11885. /*: any*/
  11886. ) {
  11887. if (!name) {
  11888. throw new Error('index name may not be null.');
  11889. }
  11890. if (!index) {
  11891. throw new Error('index may not be null.');
  11892. }
  11893. this._indexes[name] = index;
  11894. return this;
  11895. }
  11896. /**
  11897. * Adding String Field
  11898. *
  11899. * @param {String} name Name of the field that will be created on Parse
  11900. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11901. */
  11902. }, {
  11903. key: "addString",
  11904. value: function (name
  11905. /*: string*/
  11906. ) {
  11907. return this.addField(name, 'String');
  11908. }
  11909. /**
  11910. * Adding Number Field
  11911. *
  11912. * @param {String} name Name of the field that will be created on Parse
  11913. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11914. */
  11915. }, {
  11916. key: "addNumber",
  11917. value: function (name
  11918. /*: string*/
  11919. ) {
  11920. return this.addField(name, 'Number');
  11921. }
  11922. /**
  11923. * Adding Boolean Field
  11924. *
  11925. * @param {String} name Name of the field that will be created on Parse
  11926. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11927. */
  11928. }, {
  11929. key: "addBoolean",
  11930. value: function (name
  11931. /*: string*/
  11932. ) {
  11933. return this.addField(name, 'Boolean');
  11934. }
  11935. /**
  11936. * Adding Date Field
  11937. *
  11938. * @param {String} name Name of the field that will be created on Parse
  11939. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11940. */
  11941. }, {
  11942. key: "addDate",
  11943. value: function (name
  11944. /*: string*/
  11945. ) {
  11946. return this.addField(name, 'Date');
  11947. }
  11948. /**
  11949. * Adding File Field
  11950. *
  11951. * @param {String} name Name of the field that will be created on Parse
  11952. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11953. */
  11954. }, {
  11955. key: "addFile",
  11956. value: function (name
  11957. /*: string*/
  11958. ) {
  11959. return this.addField(name, 'File');
  11960. }
  11961. /**
  11962. * Adding GeoPoint Field
  11963. *
  11964. * @param {String} name Name of the field that will be created on Parse
  11965. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11966. */
  11967. }, {
  11968. key: "addGeoPoint",
  11969. value: function (name
  11970. /*: string*/
  11971. ) {
  11972. return this.addField(name, 'GeoPoint');
  11973. }
  11974. /**
  11975. * Adding Polygon Field
  11976. *
  11977. * @param {String} name Name of the field that will be created on Parse
  11978. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11979. */
  11980. }, {
  11981. key: "addPolygon",
  11982. value: function (name
  11983. /*: string*/
  11984. ) {
  11985. return this.addField(name, 'Polygon');
  11986. }
  11987. /**
  11988. * Adding Array Field
  11989. *
  11990. * @param {String} name Name of the field that will be created on Parse
  11991. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11992. */
  11993. }, {
  11994. key: "addArray",
  11995. value: function (name
  11996. /*: string*/
  11997. ) {
  11998. return this.addField(name, 'Array');
  11999. }
  12000. /**
  12001. * Adding Object Field
  12002. *
  12003. * @param {String} name Name of the field that will be created on Parse
  12004. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12005. */
  12006. }, {
  12007. key: "addObject",
  12008. value: function (name
  12009. /*: string*/
  12010. ) {
  12011. return this.addField(name, 'Object');
  12012. }
  12013. /**
  12014. * Adding Pointer Field
  12015. *
  12016. * @param {String} name Name of the field that will be created on Parse
  12017. * @param {String} targetClass Name of the target Pointer Class
  12018. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12019. */
  12020. }, {
  12021. key: "addPointer",
  12022. value: function (name
  12023. /*: string*/
  12024. , targetClass
  12025. /*: string*/
  12026. ) {
  12027. if (!name) {
  12028. throw new Error('field name may not be null.');
  12029. }
  12030. if (!targetClass) {
  12031. throw new Error('You need to set the targetClass of the Pointer.');
  12032. }
  12033. this._fields[name] = {
  12034. type: 'Pointer',
  12035. targetClass: targetClass
  12036. };
  12037. return this;
  12038. }
  12039. /**
  12040. * Adding Relation Field
  12041. *
  12042. * @param {String} name Name of the field that will be created on Parse
  12043. * @param {String} targetClass Name of the target Pointer Class
  12044. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12045. */
  12046. }, {
  12047. key: "addRelation",
  12048. value: function (name
  12049. /*: string*/
  12050. , targetClass
  12051. /*: string*/
  12052. ) {
  12053. if (!name) {
  12054. throw new Error('field name may not be null.');
  12055. }
  12056. if (!targetClass) {
  12057. throw new Error('You need to set the targetClass of the Relation.');
  12058. }
  12059. this._fields[name] = {
  12060. type: 'Relation',
  12061. targetClass: targetClass
  12062. };
  12063. return this;
  12064. }
  12065. /**
  12066. * Deleting a Field to Update on a Schema
  12067. *
  12068. * @param {String} name Name of the field that will be created on Parse
  12069. * @param {String} targetClass Name of the target Pointer Class
  12070. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12071. */
  12072. }, {
  12073. key: "deleteField",
  12074. value: function (name
  12075. /*: string*/
  12076. ) {
  12077. this._fields[name] = {
  12078. __op: 'Delete'
  12079. };
  12080. }
  12081. /**
  12082. * Deleting an Index to Update on a Schema
  12083. *
  12084. * @param {String} name Name of the field that will be created on Parse
  12085. * @param {String} targetClass Name of the target Pointer Class
  12086. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12087. */
  12088. }, {
  12089. key: "deleteIndex",
  12090. value: function (name
  12091. /*: string*/
  12092. ) {
  12093. this._indexes[name] = {
  12094. __op: 'Delete'
  12095. };
  12096. }
  12097. }], [{
  12098. key: "all",
  12099. value: function (options
  12100. /*: FullOptions*/
  12101. ) {
  12102. options = options || {};
  12103. var controller = _CoreManager.default.getSchemaController();
  12104. return controller.get('', options).then(function (response) {
  12105. if (response.results.length === 0) {
  12106. throw new Error('Schema not found.');
  12107. }
  12108. return response.results;
  12109. });
  12110. }
  12111. }]);
  12112. return ParseSchema;
  12113. }();
  12114. var DefaultController = {
  12115. send: function (className
  12116. /*: string*/
  12117. , method
  12118. /*: string*/
  12119. , params
  12120. /*: any*/
  12121. , options
  12122. /*: RequestOptions*/
  12123. )
  12124. /*: Promise*/
  12125. {
  12126. var RESTController = _CoreManager.default.getRESTController();
  12127. var requestOptions = {
  12128. useMasterKey: true
  12129. };
  12130. if (options.hasOwnProperty('sessionToken')) {
  12131. requestOptions.sessionToken = options.sessionToken;
  12132. }
  12133. return RESTController.request(method, "schemas/".concat(className), params, requestOptions);
  12134. },
  12135. get: function (className
  12136. /*: string*/
  12137. , options
  12138. /*: RequestOptions*/
  12139. )
  12140. /*: Promise*/
  12141. {
  12142. return this.send(className, 'GET', {}, options);
  12143. },
  12144. create: function (className
  12145. /*: string*/
  12146. , params
  12147. /*: any*/
  12148. , options
  12149. /*: RequestOptions*/
  12150. )
  12151. /*: Promise*/
  12152. {
  12153. return this.send(className, 'POST', params, options);
  12154. },
  12155. update: function (className
  12156. /*: string*/
  12157. , params
  12158. /*: any*/
  12159. , options
  12160. /*: RequestOptions*/
  12161. )
  12162. /*: Promise*/
  12163. {
  12164. return this.send(className, 'PUT', params, options);
  12165. },
  12166. delete: function (className
  12167. /*: string*/
  12168. , options
  12169. /*: RequestOptions*/
  12170. )
  12171. /*: Promise*/
  12172. {
  12173. return this.send(className, 'DELETE', {}, options);
  12174. },
  12175. purge: function (className
  12176. /*: string*/
  12177. )
  12178. /*: Promise*/
  12179. {
  12180. var RESTController = _CoreManager.default.getRESTController();
  12181. return RESTController.request('DELETE', "purge/".concat(className), {}, {
  12182. useMasterKey: true
  12183. });
  12184. }
  12185. };
  12186. _CoreManager.default.setSchemaController(DefaultController);
  12187. var _default = ParseSchema;
  12188. exports.default = _default;
  12189. },{"./CoreManager":4,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/interopRequireDefault":61}],30:[function(_dereq_,module,exports){
  12190. "use strict";
  12191. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  12192. Object.defineProperty(exports, "__esModule", {
  12193. value: true
  12194. });
  12195. exports.default = void 0;
  12196. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  12197. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  12198. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  12199. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  12200. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  12201. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  12202. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  12203. var _isRevocableSession = _interopRequireDefault(_dereq_("./isRevocableSession"));
  12204. var _ParseObject2 = _interopRequireDefault(_dereq_("./ParseObject"));
  12205. var _ParseUser = _interopRequireDefault(_dereq_("./ParseUser"));
  12206. /**
  12207. * Copyright (c) 2015-present, Parse, LLC.
  12208. * All rights reserved.
  12209. *
  12210. * This source code is licensed under the BSD-style license found in the
  12211. * LICENSE file in the root directory of this source tree. An additional grant
  12212. * of patent rights can be found in the PATENTS file in the same directory.
  12213. *
  12214. * @flow
  12215. */
  12216. /**
  12217. * <p>A Parse.Session object is a local representation of a revocable session.
  12218. * This class is a subclass of a Parse.Object, and retains the same
  12219. * functionality of a Parse.Object.</p>
  12220. * @alias Parse.Session
  12221. * @extends Parse.Object
  12222. */
  12223. var ParseSession =
  12224. /*#__PURE__*/
  12225. function (_ParseObject) {
  12226. (0, _inherits2.default)(ParseSession, _ParseObject);
  12227. /**
  12228. *
  12229. * @param {Object} attributes The initial set of data to store in the user.
  12230. */
  12231. function ParseSession(attributes
  12232. /*: ?AttributeMap*/
  12233. ) {
  12234. var _this;
  12235. (0, _classCallCheck2.default)(this, ParseSession);
  12236. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(ParseSession).call(this, '_Session'));
  12237. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  12238. if (!_this.set(attributes || {})) {
  12239. throw new Error('Can\'t create an invalid Session');
  12240. }
  12241. }
  12242. return _this;
  12243. }
  12244. /**
  12245. * Returns the session token string.
  12246. * @return {String}
  12247. */
  12248. (0, _createClass2.default)(ParseSession, [{
  12249. key: "getSessionToken",
  12250. value: function ()
  12251. /*: string*/
  12252. {
  12253. var token = this.get('sessionToken');
  12254. if (typeof token === 'string') {
  12255. return token;
  12256. }
  12257. return '';
  12258. }
  12259. }], [{
  12260. key: "readOnlyAttributes",
  12261. value: function () {
  12262. return ['createdWith', 'expiresAt', 'installationId', 'restricted', 'sessionToken', 'user'];
  12263. }
  12264. /**
  12265. * Retrieves the Session object for the currently logged in session.
  12266. * @static
  12267. * @return {Promise} A promise that is resolved with the Parse.Session
  12268. * object after it has been fetched. If there is no current user, the
  12269. * promise will be rejected.
  12270. */
  12271. }, {
  12272. key: "current",
  12273. value: function (options
  12274. /*: FullOptions*/
  12275. ) {
  12276. options = options || {};
  12277. var controller = _CoreManager.default.getSessionController();
  12278. var sessionOptions = {};
  12279. if (options.hasOwnProperty('useMasterKey')) {
  12280. sessionOptions.useMasterKey = options.useMasterKey;
  12281. }
  12282. return _ParseUser.default.currentAsync().then(function (user) {
  12283. if (!user) {
  12284. return Promise.reject('There is no current user.');
  12285. }
  12286. sessionOptions.sessionToken = user.getSessionToken();
  12287. return controller.getSession(sessionOptions);
  12288. });
  12289. }
  12290. /**
  12291. * Determines whether the current session token is revocable.
  12292. * This method is useful for migrating Express.js or Node.js web apps to
  12293. * use revocable sessions. If you are migrating an app that uses the Parse
  12294. * SDK in the browser only, please use Parse.User.enableRevocableSession()
  12295. * instead, so that sessions can be automatically upgraded.
  12296. * @static
  12297. * @return {Boolean}
  12298. */
  12299. }, {
  12300. key: "isCurrentSessionRevocable",
  12301. value: function ()
  12302. /*: boolean*/
  12303. {
  12304. var currentUser = _ParseUser.default.current();
  12305. if (currentUser) {
  12306. return (0, _isRevocableSession.default)(currentUser.getSessionToken() || '');
  12307. }
  12308. return false;
  12309. }
  12310. }]);
  12311. return ParseSession;
  12312. }(_ParseObject2.default);
  12313. _ParseObject2.default.registerSubclass('_Session', ParseSession);
  12314. var DefaultController = {
  12315. getSession: function (options
  12316. /*: RequestOptions*/
  12317. )
  12318. /*: Promise<ParseSession>*/
  12319. {
  12320. var RESTController = _CoreManager.default.getRESTController();
  12321. var session = new ParseSession();
  12322. return RESTController.request('GET', 'sessions/me', {}, options).then(function (sessionData) {
  12323. session._finishFetch(sessionData);
  12324. session._setExisted(true);
  12325. return session;
  12326. });
  12327. }
  12328. };
  12329. _CoreManager.default.setSessionController(DefaultController);
  12330. var _default = ParseSession;
  12331. exports.default = _default;
  12332. },{"./CoreManager":4,"./ParseObject":23,"./ParseUser":31,"./isRevocableSession":45,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/getPrototypeOf":59,"@babel/runtime/helpers/inherits":60,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/possibleConstructorReturn":68,"@babel/runtime/helpers/typeof":73}],31:[function(_dereq_,module,exports){
  12333. "use strict";
  12334. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  12335. Object.defineProperty(exports, "__esModule", {
  12336. value: true
  12337. });
  12338. exports.default = void 0;
  12339. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  12340. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  12341. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  12342. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  12343. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  12344. var _get2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/get"));
  12345. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  12346. var _AnonymousUtils = _interopRequireDefault(_dereq_("./AnonymousUtils"));
  12347. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  12348. var _isRevocableSession = _interopRequireDefault(_dereq_("./isRevocableSession"));
  12349. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  12350. var _ParseObject2 = _interopRequireDefault(_dereq_("./ParseObject"));
  12351. var _ParseSession = _interopRequireDefault(_dereq_("./ParseSession"));
  12352. var _Storage = _interopRequireDefault(_dereq_("./Storage"));
  12353. /**
  12354. * Copyright (c) 2015-present, Parse, LLC.
  12355. * All rights reserved.
  12356. *
  12357. * This source code is licensed under the BSD-style license found in the
  12358. * LICENSE file in the root directory of this source tree. An additional grant
  12359. * of patent rights can be found in the PATENTS file in the same directory.
  12360. *
  12361. * @flow
  12362. */
  12363. var CURRENT_USER_KEY = 'currentUser';
  12364. var canUseCurrentUser = !_CoreManager.default.get('IS_NODE');
  12365. var currentUserCacheMatchesDisk = false;
  12366. var currentUserCache = null;
  12367. var authProviders = {};
  12368. /**
  12369. * <p>A Parse.User object is a local representation of a user persisted to the
  12370. * Parse cloud. This class is a subclass of a Parse.Object, and retains the
  12371. * same functionality of a Parse.Object, but also extends it with various
  12372. * user specific methods, like authentication, signing up, and validation of
  12373. * uniqueness.</p>
  12374. * @alias Parse.User
  12375. * @extends Parse.Object
  12376. */
  12377. var ParseUser =
  12378. /*#__PURE__*/
  12379. function (_ParseObject) {
  12380. (0, _inherits2.default)(ParseUser, _ParseObject);
  12381. /**
  12382. * @param {Object} attributes The initial set of data to store in the user.
  12383. */
  12384. function ParseUser(attributes
  12385. /*: ?AttributeMap*/
  12386. ) {
  12387. var _this;
  12388. (0, _classCallCheck2.default)(this, ParseUser);
  12389. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(ParseUser).call(this, '_User'));
  12390. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  12391. if (!_this.set(attributes || {})) {
  12392. throw new Error('Can\'t create an invalid Parse User');
  12393. }
  12394. }
  12395. return _this;
  12396. }
  12397. /**
  12398. * Request a revocable session token to replace the older style of token.
  12399. * @param {Object} options
  12400. * @return {Promise} A promise that is resolved when the replacement
  12401. * token has been fetched.
  12402. */
  12403. (0, _createClass2.default)(ParseUser, [{
  12404. key: "_upgradeToRevocableSession",
  12405. value: function (options
  12406. /*: RequestOptions*/
  12407. )
  12408. /*: Promise<void>*/
  12409. {
  12410. options = options || {};
  12411. var upgradeOptions = {};
  12412. if (options.hasOwnProperty('useMasterKey')) {
  12413. upgradeOptions.useMasterKey = options.useMasterKey;
  12414. }
  12415. var controller = _CoreManager.default.getUserController();
  12416. return controller.upgradeToRevocableSession(this, upgradeOptions);
  12417. }
  12418. /**
  12419. * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can
  12420. * call linkWith on the user (even if it doesn't exist yet on the server).
  12421. */
  12422. }, {
  12423. key: "_linkWith",
  12424. value: function (provider
  12425. /*: any*/
  12426. , options
  12427. /*: { authData?: AuthData }*/
  12428. )
  12429. /*: Promise<ParseUser>*/
  12430. {
  12431. var _this2 = this;
  12432. var saveOpts
  12433. /*:: ?: FullOptions*/
  12434. = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  12435. saveOpts.sessionToken = saveOpts.sessionToken || this.getSessionToken() || '';
  12436. var authType;
  12437. if (typeof provider === 'string') {
  12438. authType = provider;
  12439. if (authProviders[provider]) {
  12440. provider = authProviders[provider];
  12441. } else {
  12442. var authProvider = {
  12443. restoreAuthentication: function () {
  12444. return true;
  12445. },
  12446. getAuthType: function () {
  12447. return authType;
  12448. }
  12449. };
  12450. authProviders[authType] = authProvider;
  12451. provider = authProvider;
  12452. }
  12453. } else {
  12454. authType = provider.getAuthType();
  12455. }
  12456. if (options && options.hasOwnProperty('authData')) {
  12457. var authData = this.get('authData') || {};
  12458. if ((0, _typeof2.default)(authData) !== 'object') {
  12459. throw new Error('Invalid type: authData field should be an object');
  12460. }
  12461. authData[authType] = options.authData;
  12462. var controller = _CoreManager.default.getUserController();
  12463. return controller.linkWith(this, authData, saveOpts);
  12464. } else {
  12465. return new Promise(function (resolve, reject) {
  12466. provider.authenticate({
  12467. success: function (provider, result) {
  12468. var opts = {};
  12469. opts.authData = result;
  12470. _this2._linkWith(provider, opts, saveOpts).then(function () {
  12471. resolve(_this2);
  12472. }, function (error) {
  12473. reject(error);
  12474. });
  12475. },
  12476. error: function (provider, _error) {
  12477. reject(_error);
  12478. }
  12479. });
  12480. });
  12481. }
  12482. }
  12483. /**
  12484. * Synchronizes auth data for a provider (e.g. puts the access token in the
  12485. * right place to be used by the Facebook SDK).
  12486. */
  12487. }, {
  12488. key: "_synchronizeAuthData",
  12489. value: function (provider
  12490. /*: string*/
  12491. ) {
  12492. if (!this.isCurrent() || !provider) {
  12493. return;
  12494. }
  12495. var authType;
  12496. if (typeof provider === 'string') {
  12497. authType = provider;
  12498. provider = authProviders[authType];
  12499. } else {
  12500. authType = provider.getAuthType();
  12501. }
  12502. var authData = this.get('authData');
  12503. if (!provider || !authData || (0, _typeof2.default)(authData) !== 'object') {
  12504. return;
  12505. }
  12506. var success = provider.restoreAuthentication(authData[authType]);
  12507. if (!success) {
  12508. this._unlinkFrom(provider);
  12509. }
  12510. }
  12511. /**
  12512. * Synchronizes authData for all providers.
  12513. */
  12514. }, {
  12515. key: "_synchronizeAllAuthData",
  12516. value: function () {
  12517. var authData = this.get('authData');
  12518. if ((0, _typeof2.default)(authData) !== 'object') {
  12519. return;
  12520. }
  12521. for (var _key in authData) {
  12522. this._synchronizeAuthData(_key);
  12523. }
  12524. }
  12525. /**
  12526. * Removes null values from authData (which exist temporarily for
  12527. * unlinking)
  12528. */
  12529. }, {
  12530. key: "_cleanupAuthData",
  12531. value: function () {
  12532. if (!this.isCurrent()) {
  12533. return;
  12534. }
  12535. var authData = this.get('authData');
  12536. if ((0, _typeof2.default)(authData) !== 'object') {
  12537. return;
  12538. }
  12539. for (var _key2 in authData) {
  12540. if (!authData[_key2]) {
  12541. delete authData[_key2];
  12542. }
  12543. }
  12544. }
  12545. /**
  12546. * Unlinks a user from a service.
  12547. */
  12548. }, {
  12549. key: "_unlinkFrom",
  12550. value: function (provider
  12551. /*: any*/
  12552. , options
  12553. /*:: ?: FullOptions*/
  12554. ) {
  12555. var _this3 = this;
  12556. if (typeof provider === 'string') {
  12557. provider = authProviders[provider];
  12558. }
  12559. return this._linkWith(provider, {
  12560. authData: null
  12561. }, options).then(function () {
  12562. _this3._synchronizeAuthData(provider);
  12563. return Promise.resolve(_this3);
  12564. });
  12565. }
  12566. /**
  12567. * Checks whether a user is linked to a service.
  12568. */
  12569. }, {
  12570. key: "_isLinked",
  12571. value: function (provider
  12572. /*: any*/
  12573. )
  12574. /*: boolean*/
  12575. {
  12576. var authType;
  12577. if (typeof provider === 'string') {
  12578. authType = provider;
  12579. } else {
  12580. authType = provider.getAuthType();
  12581. }
  12582. var authData = this.get('authData') || {};
  12583. if ((0, _typeof2.default)(authData) !== 'object') {
  12584. return false;
  12585. }
  12586. return !!authData[authType];
  12587. }
  12588. /**
  12589. * Deauthenticates all providers.
  12590. */
  12591. }, {
  12592. key: "_logOutWithAll",
  12593. value: function () {
  12594. var authData = this.get('authData');
  12595. if ((0, _typeof2.default)(authData) !== 'object') {
  12596. return;
  12597. }
  12598. for (var _key3 in authData) {
  12599. this._logOutWith(_key3);
  12600. }
  12601. }
  12602. /**
  12603. * Deauthenticates a single provider (e.g. removing access tokens from the
  12604. * Facebook SDK).
  12605. */
  12606. }, {
  12607. key: "_logOutWith",
  12608. value: function (provider
  12609. /*: any*/
  12610. ) {
  12611. if (!this.isCurrent()) {
  12612. return;
  12613. }
  12614. if (typeof provider === 'string') {
  12615. provider = authProviders[provider];
  12616. }
  12617. if (provider && provider.deauthenticate) {
  12618. provider.deauthenticate();
  12619. }
  12620. }
  12621. /**
  12622. * Class instance method used to maintain specific keys when a fetch occurs.
  12623. * Used to ensure that the session token is not lost.
  12624. */
  12625. }, {
  12626. key: "_preserveFieldsOnFetch",
  12627. value: function ()
  12628. /*: AttributeMap*/
  12629. {
  12630. return {
  12631. sessionToken: this.get('sessionToken')
  12632. };
  12633. }
  12634. /**
  12635. * Returns true if <code>current</code> would return this user.
  12636. * @return {Boolean}
  12637. */
  12638. }, {
  12639. key: "isCurrent",
  12640. value: function ()
  12641. /*: boolean*/
  12642. {
  12643. var current = ParseUser.current();
  12644. return !!current && current.id === this.id;
  12645. }
  12646. /**
  12647. * Returns get("username").
  12648. * @return {String}
  12649. */
  12650. }, {
  12651. key: "getUsername",
  12652. value: function ()
  12653. /*: ?string*/
  12654. {
  12655. var username = this.get('username');
  12656. if (username == null || typeof username === 'string') {
  12657. return username;
  12658. }
  12659. return '';
  12660. }
  12661. /**
  12662. * Calls set("username", username, options) and returns the result.
  12663. * @param {String} username
  12664. * @param {Object} options
  12665. * @return {Boolean}
  12666. */
  12667. }, {
  12668. key: "setUsername",
  12669. value: function (username
  12670. /*: string*/
  12671. ) {
  12672. // Strip anonymity, even we do not support anonymous user in js SDK, we may
  12673. // encounter anonymous user created by android/iOS in cloud code.
  12674. var authData = this.get('authData');
  12675. if (authData && (0, _typeof2.default)(authData) === 'object' && authData.hasOwnProperty('anonymous')) {
  12676. // We need to set anonymous to null instead of deleting it in order to remove it from Parse.
  12677. authData.anonymous = null;
  12678. }
  12679. this.set('username', username);
  12680. }
  12681. /**
  12682. * Calls set("password", password, options) and returns the result.
  12683. * @param {String} password
  12684. * @param {Object} options
  12685. * @return {Boolean}
  12686. */
  12687. }, {
  12688. key: "setPassword",
  12689. value: function (password
  12690. /*: string*/
  12691. ) {
  12692. this.set('password', password);
  12693. }
  12694. /**
  12695. * Returns get("email").
  12696. * @return {String}
  12697. */
  12698. }, {
  12699. key: "getEmail",
  12700. value: function ()
  12701. /*: ?string*/
  12702. {
  12703. var email = this.get('email');
  12704. if (email == null || typeof email === 'string') {
  12705. return email;
  12706. }
  12707. return '';
  12708. }
  12709. /**
  12710. * Calls set("email", email) and returns the result.
  12711. * @param {String} email
  12712. * @return {Boolean}
  12713. */
  12714. }, {
  12715. key: "setEmail",
  12716. value: function (email
  12717. /*: string*/
  12718. ) {
  12719. return this.set('email', email);
  12720. }
  12721. /**
  12722. * Returns the session token for this user, if the user has been logged in,
  12723. * or if it is the result of a query with the master key. Otherwise, returns
  12724. * undefined.
  12725. * @return {String} the session token, or undefined
  12726. */
  12727. }, {
  12728. key: "getSessionToken",
  12729. value: function ()
  12730. /*: ?string*/
  12731. {
  12732. var token = this.get('sessionToken');
  12733. if (token == null || typeof token === 'string') {
  12734. return token;
  12735. }
  12736. return '';
  12737. }
  12738. /**
  12739. * Checks whether this user is the current user and has been authenticated.
  12740. * @return (Boolean) whether this user is the current user and is logged in.
  12741. */
  12742. }, {
  12743. key: "authenticated",
  12744. value: function ()
  12745. /*: boolean*/
  12746. {
  12747. var current = ParseUser.current();
  12748. return !!this.get('sessionToken') && !!current && current.id === this.id;
  12749. }
  12750. /**
  12751. * Signs up a new user. You should call this instead of save for
  12752. * new Parse.Users. This will create a new Parse.User on the server, and
  12753. * also persist the session on disk so that you can access the user using
  12754. * <code>current</code>.
  12755. *
  12756. * <p>A username and password must be set before calling signUp.</p>
  12757. *
  12758. * <p>Calls options.success or options.error on completion.</p>
  12759. *
  12760. * @param {Object} attrs Extra fields to set on the new user, or null.
  12761. * @param {Object} options
  12762. * @return {Promise} A promise that is fulfilled when the signup
  12763. * finishes.
  12764. */
  12765. }, {
  12766. key: "signUp",
  12767. value: function (attrs
  12768. /*: AttributeMap*/
  12769. , options
  12770. /*:: ?: FullOptions*/
  12771. )
  12772. /*: Promise<ParseUser>*/
  12773. {
  12774. options = options || {};
  12775. var signupOptions = {};
  12776. if (options.hasOwnProperty('useMasterKey')) {
  12777. signupOptions.useMasterKey = options.useMasterKey;
  12778. }
  12779. if (options.hasOwnProperty('installationId')) {
  12780. signupOptions.installationId = options.installationId;
  12781. }
  12782. var controller = _CoreManager.default.getUserController();
  12783. return controller.signUp(this, attrs, signupOptions);
  12784. }
  12785. /**
  12786. * Logs in a Parse.User. On success, this saves the session to disk,
  12787. * so you can retrieve the currently logged in user using
  12788. * <code>current</code>.
  12789. *
  12790. * <p>A username and password must be set before calling logIn.</p>
  12791. *
  12792. * <p>Calls options.success or options.error on completion.</p>
  12793. *
  12794. * @param {Object} options
  12795. * @return {Promise} A promise that is fulfilled with the user when
  12796. * the login is complete.
  12797. */
  12798. }, {
  12799. key: "logIn",
  12800. value: function (options
  12801. /*:: ?: FullOptions*/
  12802. )
  12803. /*: Promise<ParseUser>*/
  12804. {
  12805. options = options || {};
  12806. var loginOptions = {};
  12807. if (options.hasOwnProperty('useMasterKey')) {
  12808. loginOptions.useMasterKey = options.useMasterKey;
  12809. }
  12810. if (options.hasOwnProperty('installationId')) {
  12811. loginOptions.installationId = options.installationId;
  12812. }
  12813. var controller = _CoreManager.default.getUserController();
  12814. return controller.logIn(this, loginOptions);
  12815. }
  12816. /**
  12817. * Wrap the default save behavior with functionality to save to local
  12818. * storage if this is current user.
  12819. */
  12820. }, {
  12821. key: "save",
  12822. value: function ()
  12823. /*: Promise<ParseUser>*/
  12824. {
  12825. var _this4 = this;
  12826. for (var _len = arguments.length, args = new Array(_len), _key4 = 0; _key4 < _len; _key4++) {
  12827. args[_key4] = arguments[_key4];
  12828. }
  12829. return (0, _get2.default)((0, _getPrototypeOf2.default)(ParseUser.prototype), "save", this).apply(this, args).then(function () {
  12830. if (_this4.isCurrent()) {
  12831. return _CoreManager.default.getUserController().updateUserOnDisk(_this4);
  12832. }
  12833. return _this4;
  12834. });
  12835. }
  12836. /**
  12837. * Wrap the default destroy behavior with functionality that logs out
  12838. * the current user when it is destroyed
  12839. */
  12840. }, {
  12841. key: "destroy",
  12842. value: function ()
  12843. /*: Promise<ParseUser>*/
  12844. {
  12845. var _this5 = this;
  12846. for (var _len2 = arguments.length, args = new Array(_len2), _key5 = 0; _key5 < _len2; _key5++) {
  12847. args[_key5] = arguments[_key5];
  12848. }
  12849. return (0, _get2.default)((0, _getPrototypeOf2.default)(ParseUser.prototype), "destroy", this).apply(this, args).then(function () {
  12850. if (_this5.isCurrent()) {
  12851. return _CoreManager.default.getUserController().removeUserFromDisk();
  12852. }
  12853. return _this5;
  12854. });
  12855. }
  12856. /**
  12857. * Wrap the default fetch behavior with functionality to save to local
  12858. * storage if this is current user.
  12859. */
  12860. }, {
  12861. key: "fetch",
  12862. value: function ()
  12863. /*: Promise<ParseUser>*/
  12864. {
  12865. var _this6 = this;
  12866. for (var _len3 = arguments.length, args = new Array(_len3), _key6 = 0; _key6 < _len3; _key6++) {
  12867. args[_key6] = arguments[_key6];
  12868. }
  12869. return (0, _get2.default)((0, _getPrototypeOf2.default)(ParseUser.prototype), "fetch", this).apply(this, args).then(function () {
  12870. if (_this6.isCurrent()) {
  12871. return _CoreManager.default.getUserController().updateUserOnDisk(_this6);
  12872. }
  12873. return _this6;
  12874. });
  12875. }
  12876. /**
  12877. * Wrap the default fetchWithInclude behavior with functionality to save to local
  12878. * storage if this is current user.
  12879. */
  12880. }, {
  12881. key: "fetchWithInclude",
  12882. value: function ()
  12883. /*: Promise<ParseUser>*/
  12884. {
  12885. var _this7 = this;
  12886. for (var _len4 = arguments.length, args = new Array(_len4), _key7 = 0; _key7 < _len4; _key7++) {
  12887. args[_key7] = arguments[_key7];
  12888. }
  12889. return (0, _get2.default)((0, _getPrototypeOf2.default)(ParseUser.prototype), "fetchWithInclude", this).apply(this, args).then(function () {
  12890. if (_this7.isCurrent()) {
  12891. return _CoreManager.default.getUserController().updateUserOnDisk(_this7);
  12892. }
  12893. return _this7;
  12894. });
  12895. }
  12896. }], [{
  12897. key: "readOnlyAttributes",
  12898. value: function () {
  12899. return ['sessionToken'];
  12900. }
  12901. /**
  12902. * Adds functionality to the existing Parse.User class
  12903. * @param {Object} protoProps A set of properties to add to the prototype
  12904. * @param {Object} classProps A set of static properties to add to the class
  12905. * @static
  12906. * @return {Class} The newly extended Parse.User class
  12907. */
  12908. }, {
  12909. key: "extend",
  12910. value: function (protoProps
  12911. /*: {[prop: string]: any}*/
  12912. , classProps
  12913. /*: {[prop: string]: any}*/
  12914. ) {
  12915. if (protoProps) {
  12916. for (var _prop in protoProps) {
  12917. if (_prop !== 'className') {
  12918. Object.defineProperty(ParseUser.prototype, _prop, {
  12919. value: protoProps[_prop],
  12920. enumerable: false,
  12921. writable: true,
  12922. configurable: true
  12923. });
  12924. }
  12925. }
  12926. }
  12927. if (classProps) {
  12928. for (var _prop2 in classProps) {
  12929. if (_prop2 !== 'className') {
  12930. Object.defineProperty(ParseUser, _prop2, {
  12931. value: classProps[_prop2],
  12932. enumerable: false,
  12933. writable: true,
  12934. configurable: true
  12935. });
  12936. }
  12937. }
  12938. }
  12939. return ParseUser;
  12940. }
  12941. /**
  12942. * Retrieves the currently logged in ParseUser with a valid session,
  12943. * either from memory or localStorage, if necessary.
  12944. * @static
  12945. * @return {Parse.Object} The currently logged in Parse.User.
  12946. */
  12947. }, {
  12948. key: "current",
  12949. value: function ()
  12950. /*: ?ParseUser*/
  12951. {
  12952. if (!canUseCurrentUser) {
  12953. return null;
  12954. }
  12955. var controller = _CoreManager.default.getUserController();
  12956. return controller.currentUser();
  12957. }
  12958. /**
  12959. * Retrieves the currently logged in ParseUser from asynchronous Storage.
  12960. * @static
  12961. * @return {Promise} A Promise that is resolved with the currently
  12962. * logged in Parse User
  12963. */
  12964. }, {
  12965. key: "currentAsync",
  12966. value: function ()
  12967. /*: Promise<?ParseUser>*/
  12968. {
  12969. if (!canUseCurrentUser) {
  12970. return Promise.resolve(null);
  12971. }
  12972. var controller = _CoreManager.default.getUserController();
  12973. return controller.currentUserAsync();
  12974. }
  12975. /**
  12976. * Signs up a new user with a username (or email) and password.
  12977. * This will create a new Parse.User on the server, and also persist the
  12978. * session in localStorage so that you can access the user using
  12979. * {@link #current}.
  12980. *
  12981. * <p>Calls options.success or options.error on completion.</p>
  12982. *
  12983. * @param {String} username The username (or email) to sign up with.
  12984. * @param {String} password The password to sign up with.
  12985. * @param {Object} attrs Extra fields to set on the new user.
  12986. * @param {Object} options
  12987. * @static
  12988. * @return {Promise} A promise that is fulfilled with the user when
  12989. * the signup completes.
  12990. */
  12991. }, {
  12992. key: "signUp",
  12993. value: function (username
  12994. /*: string*/
  12995. , password
  12996. /*: string*/
  12997. , attrs
  12998. /*: AttributeMap*/
  12999. , options
  13000. /*:: ?: FullOptions*/
  13001. ) {
  13002. attrs = attrs || {};
  13003. attrs.username = username;
  13004. attrs.password = password;
  13005. var user = new this(attrs);
  13006. return user.signUp({}, options);
  13007. }
  13008. /**
  13009. * Logs in a user with a username (or email) and password. On success, this
  13010. * saves the session to disk, so you can retrieve the currently logged in
  13011. * user using <code>current</code>.
  13012. *
  13013. * <p>Calls options.success or options.error on completion.</p>
  13014. *
  13015. * @param {String} username The username (or email) to log in with.
  13016. * @param {String} password The password to log in with.
  13017. * @param {Object} options
  13018. * @static
  13019. * @return {Promise} A promise that is fulfilled with the user when
  13020. * the login completes.
  13021. */
  13022. }, {
  13023. key: "logIn",
  13024. value: function (username
  13025. /*: string*/
  13026. , password
  13027. /*: string*/
  13028. , options
  13029. /*:: ?: FullOptions*/
  13030. ) {
  13031. if (typeof username !== 'string') {
  13032. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Username must be a string.'));
  13033. } else if (typeof password !== 'string') {
  13034. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Password must be a string.'));
  13035. }
  13036. var user = new this();
  13037. user._finishFetch({
  13038. username: username,
  13039. password: password
  13040. });
  13041. return user.logIn(options);
  13042. }
  13043. /**
  13044. * Logs in a user with a session token. On success, this saves the session
  13045. * to disk, so you can retrieve the currently logged in user using
  13046. * <code>current</code>.
  13047. *
  13048. * <p>Calls options.success or options.error on completion.</p>
  13049. *
  13050. * @param {String} sessionToken The sessionToken to log in with.
  13051. * @param {Object} options
  13052. * @static
  13053. * @return {Promise} A promise that is fulfilled with the user when
  13054. * the login completes.
  13055. */
  13056. }, {
  13057. key: "become",
  13058. value: function (sessionToken
  13059. /*: string*/
  13060. , options
  13061. /*:: ?: RequestOptions*/
  13062. ) {
  13063. if (!canUseCurrentUser) {
  13064. throw new Error('It is not memory-safe to become a user in a server environment');
  13065. }
  13066. options = options || {};
  13067. var becomeOptions
  13068. /*: RequestOptions*/
  13069. = {
  13070. sessionToken: sessionToken
  13071. };
  13072. if (options.hasOwnProperty('useMasterKey')) {
  13073. becomeOptions.useMasterKey = options.useMasterKey;
  13074. }
  13075. var controller = _CoreManager.default.getUserController();
  13076. return controller.become(becomeOptions);
  13077. }
  13078. /**
  13079. * Retrieves a user with a session token.
  13080. *
  13081. * @param {String} sessionToken The sessionToken to get user with.
  13082. * @param {Object} options
  13083. * @static
  13084. * @return {Promise} A promise that is fulfilled with the user is fetched.
  13085. */
  13086. }, {
  13087. key: "me",
  13088. value: function (sessionToken
  13089. /*: string*/
  13090. ) {
  13091. var options
  13092. /*:: ?: RequestOptions*/
  13093. = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  13094. var controller = _CoreManager.default.getUserController();
  13095. var meOptions
  13096. /*: RequestOptions*/
  13097. = {
  13098. sessionToken: sessionToken
  13099. };
  13100. if (options.useMasterKey) {
  13101. meOptions.useMasterKey = options.useMasterKey;
  13102. }
  13103. return controller.me(meOptions);
  13104. }
  13105. /**
  13106. * Logs in a user with a session token. On success, this saves the session
  13107. * to disk, so you can retrieve the currently logged in user using
  13108. * <code>current</code>. If there is no session token the user will not logged in.
  13109. *
  13110. * @param {Object} userJSON The JSON map of the User's data
  13111. * @static
  13112. * @return {Promise} A promise that is fulfilled with the user when
  13113. * the login completes.
  13114. */
  13115. }, {
  13116. key: "hydrate",
  13117. value: function (userJSON
  13118. /*: AttributeMap*/
  13119. ) {
  13120. var controller = _CoreManager.default.getUserController();
  13121. return controller.hydrate(userJSON);
  13122. }
  13123. }, {
  13124. key: "logInWith",
  13125. value: function (provider
  13126. /*: any*/
  13127. , options
  13128. /*: { authData?: AuthData }*/
  13129. , saveOpts
  13130. /*:: ?: FullOptions*/
  13131. ) {
  13132. return ParseUser._logInWith(provider, options, saveOpts);
  13133. }
  13134. /**
  13135. * Logs out the currently logged in user session. This will remove the
  13136. * session from disk, log out of linked services, and future calls to
  13137. * <code>current</code> will return <code>null</code>.
  13138. *
  13139. * @param {Object} options
  13140. * @static
  13141. * @return {Promise} A promise that is resolved when the session is
  13142. * destroyed on the server.
  13143. */
  13144. }, {
  13145. key: "logOut",
  13146. value: function () {
  13147. var options
  13148. /*: RequestOptions*/
  13149. = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  13150. var controller = _CoreManager.default.getUserController();
  13151. return controller.logOut(options);
  13152. }
  13153. /**
  13154. * Requests a password reset email to be sent to the specified email address
  13155. * associated with the user account. This email allows the user to securely
  13156. * reset their password on the Parse site.
  13157. *
  13158. * <p>Calls options.success or options.error on completion.</p>
  13159. *
  13160. * @param {String} email The email address associated with the user that
  13161. * forgot their password.
  13162. * @param {Object} options
  13163. * @static
  13164. * @returns {Promise}
  13165. */
  13166. }, {
  13167. key: "requestPasswordReset",
  13168. value: function (email
  13169. /*: string*/
  13170. , options
  13171. /*:: ?: RequestOptions*/
  13172. ) {
  13173. options = options || {};
  13174. var requestOptions = {};
  13175. if (options.hasOwnProperty('useMasterKey')) {
  13176. requestOptions.useMasterKey = options.useMasterKey;
  13177. }
  13178. var controller = _CoreManager.default.getUserController();
  13179. return controller.requestPasswordReset(email, requestOptions);
  13180. }
  13181. /**
  13182. * Allow someone to define a custom User class without className
  13183. * being rewritten to _User. The default behavior is to rewrite
  13184. * User to _User for legacy reasons. This allows developers to
  13185. * override that behavior.
  13186. *
  13187. * @param {Boolean} isAllowed Whether or not to allow custom User class
  13188. * @static
  13189. */
  13190. }, {
  13191. key: "allowCustomUserClass",
  13192. value: function (isAllowed
  13193. /*: boolean*/
  13194. ) {
  13195. _CoreManager.default.set('PERFORM_USER_REWRITE', !isAllowed);
  13196. }
  13197. /**
  13198. * Allows a legacy application to start using revocable sessions. If the
  13199. * current session token is not revocable, a request will be made for a new,
  13200. * revocable session.
  13201. * It is not necessary to call this method from cloud code unless you are
  13202. * handling user signup or login from the server side. In a cloud code call,
  13203. * this function will not attempt to upgrade the current token.
  13204. * @param {Object} options
  13205. * @static
  13206. * @return {Promise} A promise that is resolved when the process has
  13207. * completed. If a replacement session token is requested, the promise
  13208. * will be resolved after a new token has been fetched.
  13209. */
  13210. }, {
  13211. key: "enableRevocableSession",
  13212. value: function (options
  13213. /*:: ?: RequestOptions*/
  13214. ) {
  13215. options = options || {};
  13216. _CoreManager.default.set('FORCE_REVOCABLE_SESSION', true);
  13217. if (canUseCurrentUser) {
  13218. var current = ParseUser.current();
  13219. if (current) {
  13220. return current._upgradeToRevocableSession(options);
  13221. }
  13222. }
  13223. return Promise.resolve();
  13224. }
  13225. /**
  13226. * Enables the use of become or the current user in a server
  13227. * environment. These features are disabled by default, since they depend on
  13228. * global objects that are not memory-safe for most servers.
  13229. * @static
  13230. */
  13231. }, {
  13232. key: "enableUnsafeCurrentUser",
  13233. value: function () {
  13234. canUseCurrentUser = true;
  13235. }
  13236. /**
  13237. * Disables the use of become or the current user in any environment.
  13238. * These features are disabled on servers by default, since they depend on
  13239. * global objects that are not memory-safe for most servers.
  13240. * @static
  13241. */
  13242. }, {
  13243. key: "disableUnsafeCurrentUser",
  13244. value: function () {
  13245. canUseCurrentUser = false;
  13246. }
  13247. }, {
  13248. key: "_registerAuthenticationProvider",
  13249. value: function (provider
  13250. /*: any*/
  13251. ) {
  13252. authProviders[provider.getAuthType()] = provider; // Synchronize the current user with the auth provider.
  13253. ParseUser.currentAsync().then(function (current) {
  13254. if (current) {
  13255. current._synchronizeAuthData(provider.getAuthType());
  13256. }
  13257. });
  13258. }
  13259. }, {
  13260. key: "_logInWith",
  13261. value: function (provider
  13262. /*: any*/
  13263. , options
  13264. /*: { authData?: AuthData }*/
  13265. , saveOpts
  13266. /*:: ?: FullOptions*/
  13267. ) {
  13268. var user = new ParseUser();
  13269. return user._linkWith(provider, options, saveOpts);
  13270. }
  13271. }, {
  13272. key: "_clearCache",
  13273. value: function () {
  13274. currentUserCache = null;
  13275. currentUserCacheMatchesDisk = false;
  13276. }
  13277. }, {
  13278. key: "_setCurrentUserCache",
  13279. value: function (user
  13280. /*: ParseUser*/
  13281. ) {
  13282. currentUserCache = user;
  13283. }
  13284. }]);
  13285. return ParseUser;
  13286. }(_ParseObject2.default);
  13287. _ParseObject2.default.registerSubclass('_User', ParseUser);
  13288. var DefaultController = {
  13289. updateUserOnDisk: function (user) {
  13290. var path = _Storage.default.generatePath(CURRENT_USER_KEY);
  13291. var json = user.toJSON();
  13292. json.className = '_User';
  13293. return _Storage.default.setItemAsync(path, JSON.stringify(json)).then(function () {
  13294. return user;
  13295. });
  13296. },
  13297. removeUserFromDisk: function () {
  13298. var path = _Storage.default.generatePath(CURRENT_USER_KEY);
  13299. currentUserCacheMatchesDisk = true;
  13300. currentUserCache = null;
  13301. return _Storage.default.removeItemAsync(path);
  13302. },
  13303. setCurrentUser: function (user) {
  13304. var currentUser = this.currentUser();
  13305. var promise = Promise.resolve();
  13306. if (currentUser && !user.equals(currentUser) && _AnonymousUtils.default.isLinked(currentUser)) {
  13307. promise = currentUser.destroy({
  13308. sessionToken: currentUser.getSessionToken()
  13309. });
  13310. }
  13311. currentUserCache = user;
  13312. user._cleanupAuthData();
  13313. user._synchronizeAllAuthData();
  13314. return promise.then(function () {
  13315. return DefaultController.updateUserOnDisk(user);
  13316. });
  13317. },
  13318. currentUser: function ()
  13319. /*: ?ParseUser*/
  13320. {
  13321. if (currentUserCache) {
  13322. return currentUserCache;
  13323. }
  13324. if (currentUserCacheMatchesDisk) {
  13325. return null;
  13326. }
  13327. if (_Storage.default.async()) {
  13328. throw new Error('Cannot call currentUser() when using a platform with an async ' + 'storage system. Call currentUserAsync() instead.');
  13329. }
  13330. var path = _Storage.default.generatePath(CURRENT_USER_KEY);
  13331. var userData = _Storage.default.getItem(path);
  13332. currentUserCacheMatchesDisk = true;
  13333. if (!userData) {
  13334. currentUserCache = null;
  13335. return null;
  13336. }
  13337. userData = JSON.parse(userData);
  13338. if (!userData.className) {
  13339. userData.className = '_User';
  13340. }
  13341. if (userData._id) {
  13342. if (userData.objectId !== userData._id) {
  13343. userData.objectId = userData._id;
  13344. }
  13345. delete userData._id;
  13346. }
  13347. if (userData._sessionToken) {
  13348. userData.sessionToken = userData._sessionToken;
  13349. delete userData._sessionToken;
  13350. }
  13351. var current = _ParseObject2.default.fromJSON(userData);
  13352. currentUserCache = current;
  13353. current._synchronizeAllAuthData();
  13354. return current;
  13355. },
  13356. currentUserAsync: function ()
  13357. /*: Promise<?ParseUser>*/
  13358. {
  13359. if (currentUserCache) {
  13360. return Promise.resolve(currentUserCache);
  13361. }
  13362. if (currentUserCacheMatchesDisk) {
  13363. return Promise.resolve(null);
  13364. }
  13365. var path = _Storage.default.generatePath(CURRENT_USER_KEY);
  13366. return _Storage.default.getItemAsync(path).then(function (userData) {
  13367. currentUserCacheMatchesDisk = true;
  13368. if (!userData) {
  13369. currentUserCache = null;
  13370. return Promise.resolve(null);
  13371. }
  13372. userData = JSON.parse(userData);
  13373. if (!userData.className) {
  13374. userData.className = '_User';
  13375. }
  13376. if (userData._id) {
  13377. if (userData.objectId !== userData._id) {
  13378. userData.objectId = userData._id;
  13379. }
  13380. delete userData._id;
  13381. }
  13382. if (userData._sessionToken) {
  13383. userData.sessionToken = userData._sessionToken;
  13384. delete userData._sessionToken;
  13385. }
  13386. var current = _ParseObject2.default.fromJSON(userData);
  13387. currentUserCache = current;
  13388. current._synchronizeAllAuthData();
  13389. return Promise.resolve(current);
  13390. });
  13391. },
  13392. signUp: function (user
  13393. /*: ParseUser*/
  13394. , attrs
  13395. /*: AttributeMap*/
  13396. , options
  13397. /*: RequestOptions*/
  13398. )
  13399. /*: Promise<ParseUser>*/
  13400. {
  13401. var username = attrs && attrs.username || user.get('username');
  13402. var password = attrs && attrs.password || user.get('password');
  13403. if (!username || !username.length) {
  13404. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Cannot sign up user with an empty name.'));
  13405. }
  13406. if (!password || !password.length) {
  13407. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Cannot sign up user with an empty password.'));
  13408. }
  13409. return user.save(attrs, options).then(function () {
  13410. // Clear the password field
  13411. user._finishFetch({
  13412. password: undefined
  13413. });
  13414. if (canUseCurrentUser) {
  13415. return DefaultController.setCurrentUser(user);
  13416. }
  13417. return user;
  13418. });
  13419. },
  13420. logIn: function (user
  13421. /*: ParseUser*/
  13422. , options
  13423. /*: RequestOptions*/
  13424. )
  13425. /*: Promise<ParseUser>*/
  13426. {
  13427. var RESTController = _CoreManager.default.getRESTController();
  13428. var stateController = _CoreManager.default.getObjectStateController();
  13429. var auth = {
  13430. username: user.get('username'),
  13431. password: user.get('password')
  13432. };
  13433. return RESTController.request('GET', 'login', auth, options).then(function (response) {
  13434. user._migrateId(response.objectId);
  13435. user._setExisted(true);
  13436. stateController.setPendingOp(user._getStateIdentifier(), 'username', undefined);
  13437. stateController.setPendingOp(user._getStateIdentifier(), 'password', undefined);
  13438. response.password = undefined;
  13439. user._finishFetch(response);
  13440. if (!canUseCurrentUser) {
  13441. // We can't set the current user, so just return the one we logged in
  13442. return Promise.resolve(user);
  13443. }
  13444. return DefaultController.setCurrentUser(user);
  13445. });
  13446. },
  13447. become: function (options
  13448. /*: RequestOptions*/
  13449. )
  13450. /*: Promise<ParseUser>*/
  13451. {
  13452. var user = new ParseUser();
  13453. var RESTController = _CoreManager.default.getRESTController();
  13454. return RESTController.request('GET', 'users/me', {}, options).then(function (response) {
  13455. user._finishFetch(response);
  13456. user._setExisted(true);
  13457. return DefaultController.setCurrentUser(user);
  13458. });
  13459. },
  13460. hydrate: function (userJSON
  13461. /*: AttributeMap*/
  13462. )
  13463. /*: Promise<ParseUser>*/
  13464. {
  13465. var user = new ParseUser();
  13466. user._finishFetch(userJSON);
  13467. user._setExisted(true);
  13468. if (userJSON.sessionToken && canUseCurrentUser) {
  13469. return DefaultController.setCurrentUser(user);
  13470. } else {
  13471. return Promise.resolve(user);
  13472. }
  13473. },
  13474. me: function (options
  13475. /*: RequestOptions*/
  13476. )
  13477. /*: Promise<ParseUser>*/
  13478. {
  13479. var RESTController = _CoreManager.default.getRESTController();
  13480. return RESTController.request('GET', 'users/me', {}, options).then(function (response) {
  13481. var user = new ParseUser();
  13482. user._finishFetch(response);
  13483. user._setExisted(true);
  13484. return user;
  13485. });
  13486. },
  13487. logOut: function (options
  13488. /*: RequestOptions*/
  13489. )
  13490. /*: Promise<ParseUser>*/
  13491. {
  13492. var RESTController = _CoreManager.default.getRESTController();
  13493. if (options.sessionToken) {
  13494. return RESTController.request('POST', 'logout', {}, options);
  13495. }
  13496. return DefaultController.currentUserAsync().then(function (currentUser) {
  13497. var path = _Storage.default.generatePath(CURRENT_USER_KEY);
  13498. var promise = _Storage.default.removeItemAsync(path);
  13499. if (currentUser !== null) {
  13500. var isAnonymous = _AnonymousUtils.default.isLinked(currentUser);
  13501. var currentSession = currentUser.getSessionToken();
  13502. if (currentSession && (0, _isRevocableSession.default)(currentSession)) {
  13503. promise = promise.then(function () {
  13504. if (isAnonymous) {
  13505. return currentUser.destroy({
  13506. sessionToken: currentSession
  13507. });
  13508. }
  13509. }).then(function () {
  13510. return RESTController.request('POST', 'logout', {}, {
  13511. sessionToken: currentSession
  13512. });
  13513. });
  13514. }
  13515. currentUser._logOutWithAll();
  13516. currentUser._finishFetch({
  13517. sessionToken: undefined
  13518. });
  13519. }
  13520. currentUserCacheMatchesDisk = true;
  13521. currentUserCache = null;
  13522. return promise;
  13523. });
  13524. },
  13525. requestPasswordReset: function (email
  13526. /*: string*/
  13527. , options
  13528. /*: RequestOptions*/
  13529. ) {
  13530. var RESTController = _CoreManager.default.getRESTController();
  13531. return RESTController.request('POST', 'requestPasswordReset', {
  13532. email: email
  13533. }, options);
  13534. },
  13535. upgradeToRevocableSession: function (user
  13536. /*: ParseUser*/
  13537. , options
  13538. /*: RequestOptions*/
  13539. ) {
  13540. var token = user.getSessionToken();
  13541. if (!token) {
  13542. return Promise.reject(new _ParseError.default(_ParseError.default.SESSION_MISSING, 'Cannot upgrade a user with no session token'));
  13543. }
  13544. options.sessionToken = token;
  13545. var RESTController = _CoreManager.default.getRESTController();
  13546. return RESTController.request('POST', 'upgradeToRevocableSession', {}, options).then(function (result) {
  13547. var session = new _ParseSession.default();
  13548. session._finishFetch(result);
  13549. user._finishFetch({
  13550. sessionToken: session.getSessionToken()
  13551. });
  13552. if (user.isCurrent()) {
  13553. return DefaultController.setCurrentUser(user);
  13554. }
  13555. return Promise.resolve(user);
  13556. });
  13557. },
  13558. linkWith: function (user
  13559. /*: ParseUser*/
  13560. , authData
  13561. /*: AuthData*/
  13562. , options
  13563. /*: FullOptions*/
  13564. ) {
  13565. return user.save({
  13566. authData: authData
  13567. }, options).then(function () {
  13568. if (canUseCurrentUser) {
  13569. return DefaultController.setCurrentUser(user);
  13570. }
  13571. return user;
  13572. });
  13573. }
  13574. };
  13575. _CoreManager.default.setUserController(DefaultController);
  13576. var _default = ParseUser;
  13577. exports.default = _default;
  13578. },{"./AnonymousUtils":2,"./CoreManager":4,"./ParseError":18,"./ParseObject":23,"./ParseSession":30,"./Storage":35,"./isRevocableSession":45,"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/get":58,"@babel/runtime/helpers/getPrototypeOf":59,"@babel/runtime/helpers/inherits":60,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/possibleConstructorReturn":68,"@babel/runtime/helpers/typeof":73}],32:[function(_dereq_,module,exports){
  13579. "use strict";
  13580. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  13581. Object.defineProperty(exports, "__esModule", {
  13582. value: true
  13583. });
  13584. exports.send = send;
  13585. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  13586. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  13587. var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
  13588. /**
  13589. * Copyright (c) 2015-present, Parse, LLC.
  13590. * All rights reserved.
  13591. *
  13592. * This source code is licensed under the BSD-style license found in the
  13593. * LICENSE file in the root directory of this source tree. An additional grant
  13594. * of patent rights can be found in the PATENTS file in the same directory.
  13595. *
  13596. * @flow
  13597. */
  13598. /**
  13599. * Contains functions to deal with Push in Parse.
  13600. * @class Parse.Push
  13601. * @static
  13602. * @hideconstructor
  13603. */
  13604. /**
  13605. * Sends a push notification.
  13606. * @method send
  13607. * @name Parse.Push.send
  13608. * @param {Object} data - The data of the push notification. Valid fields
  13609. * are:
  13610. * <ol>
  13611. * <li>channels - An Array of channels to push to.</li>
  13612. * <li>push_time - A Date object for when to send the push.</li>
  13613. * <li>expiration_time - A Date object for when to expire
  13614. * the push.</li>
  13615. * <li>expiration_interval - The seconds from now to expire the push.</li>
  13616. * <li>where - A Parse.Query over Parse.Installation that is used to match
  13617. * a set of installations to push to.</li>
  13618. * <li>data - The data to send as part of the push</li>
  13619. * <ol>
  13620. * @param {Object} options An object that has an optional success function,
  13621. * that takes no arguments and will be called on a successful push, and
  13622. * an error function that takes a Parse.Error and will be called if the push
  13623. * failed.
  13624. * @return {Promise} A promise that is fulfilled when the push request
  13625. * completes.
  13626. */
  13627. function send(data
  13628. /*: PushData*/
  13629. , options
  13630. /*:: ?: { useMasterKey?: boolean, success?: any, error?: any }*/
  13631. )
  13632. /*: Promise*/
  13633. {
  13634. options = options || {};
  13635. if (data.where && data.where instanceof _ParseQuery.default) {
  13636. data.where = data.where.toJSON().where;
  13637. }
  13638. if (data.push_time && (0, _typeof2.default)(data.push_time) === 'object') {
  13639. data.push_time = data.push_time.toJSON();
  13640. }
  13641. if (data.expiration_time && (0, _typeof2.default)(data.expiration_time) === 'object') {
  13642. data.expiration_time = data.expiration_time.toJSON();
  13643. }
  13644. if (data.expiration_time && data.expiration_interval) {
  13645. throw new Error('expiration_time and expiration_interval cannot both be set.');
  13646. }
  13647. return _CoreManager.default.getPushController().send(data, {
  13648. useMasterKey: options.useMasterKey
  13649. });
  13650. }
  13651. var DefaultController = {
  13652. send: function (data
  13653. /*: PushData*/
  13654. , options
  13655. /*: RequestOptions*/
  13656. ) {
  13657. var RESTController = _CoreManager.default.getRESTController();
  13658. var request = RESTController.request('POST', 'push', data, {
  13659. useMasterKey: !!options.useMasterKey
  13660. });
  13661. return request;
  13662. }
  13663. };
  13664. _CoreManager.default.setPushController(DefaultController);
  13665. },{"./CoreManager":4,"./ParseQuery":26,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],33:[function(_dereq_,module,exports){
  13666. (function (process){
  13667. "use strict";
  13668. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  13669. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  13670. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  13671. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  13672. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  13673. function ownKeys(object, enumerableOnly) {
  13674. var keys = Object.keys(object);
  13675. if (Object.getOwnPropertySymbols) {
  13676. var symbols = Object.getOwnPropertySymbols(object);
  13677. if (enumerableOnly) symbols = symbols.filter(function (sym) {
  13678. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  13679. });
  13680. keys.push.apply(keys, symbols);
  13681. }
  13682. return keys;
  13683. }
  13684. function _objectSpread(target) {
  13685. for (var i = 1; i < arguments.length; i++) {
  13686. var source = arguments[i] != null ? arguments[i] : {};
  13687. if (i % 2) {
  13688. ownKeys(source, true).forEach(function (key) {
  13689. (0, _defineProperty2.default)(target, key, source[key]);
  13690. });
  13691. } else if (Object.getOwnPropertyDescriptors) {
  13692. Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  13693. } else {
  13694. ownKeys(source).forEach(function (key) {
  13695. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  13696. });
  13697. }
  13698. }
  13699. return target;
  13700. }
  13701. var XHR = null;
  13702. if (typeof XMLHttpRequest !== 'undefined') {
  13703. XHR = XMLHttpRequest;
  13704. }
  13705. var useXDomainRequest = false;
  13706. if (typeof XDomainRequest !== 'undefined' && !('withCredentials' in new XMLHttpRequest())) {
  13707. useXDomainRequest = true;
  13708. }
  13709. function ajaxIE9(method
  13710. /*: string*/
  13711. , url
  13712. /*: string*/
  13713. , data
  13714. /*: any*/
  13715. , options
  13716. /*:: ?: FullOptions*/
  13717. ) {
  13718. return new Promise(function (resolve, reject) {
  13719. var xdr = new XDomainRequest();
  13720. xdr.onload = function () {
  13721. var response;
  13722. try {
  13723. response = JSON.parse(xdr.responseText);
  13724. } catch (e) {
  13725. reject(e);
  13726. }
  13727. if (response) {
  13728. resolve({
  13729. response: response
  13730. });
  13731. }
  13732. };
  13733. xdr.onerror = xdr.ontimeout = function () {
  13734. // Let's fake a real error message.
  13735. var fakeResponse = {
  13736. responseText: JSON.stringify({
  13737. code: _ParseError.default.X_DOMAIN_REQUEST,
  13738. error: 'IE\'s XDomainRequest does not supply error info.'
  13739. })
  13740. };
  13741. reject(fakeResponse);
  13742. };
  13743. xdr.onprogress = function () {
  13744. if (options && typeof options.progress === 'function') {
  13745. options.progress(xdr.responseText);
  13746. }
  13747. };
  13748. xdr.open(method, url);
  13749. xdr.send(data);
  13750. });
  13751. }
  13752. var RESTController = {
  13753. ajax: function (method
  13754. /*: string*/
  13755. , url
  13756. /*: string*/
  13757. , data
  13758. /*: any*/
  13759. , headers
  13760. /*:: ?: any*/
  13761. , options
  13762. /*:: ?: FullOptions*/
  13763. ) {
  13764. if (useXDomainRequest) {
  13765. return ajaxIE9(method, url, data, headers, options);
  13766. }
  13767. var res, rej;
  13768. var promise = new Promise(function (resolve, reject) {
  13769. res = resolve;
  13770. rej = reject;
  13771. });
  13772. promise.resolve = res;
  13773. promise.reject = rej;
  13774. var attempts = 0;
  13775. var dispatch = function dispatch() {
  13776. if (XHR == null) {
  13777. throw new Error('Cannot make a request: No definition of XMLHttpRequest was found.');
  13778. }
  13779. var handled = false;
  13780. var xhr = new XHR();
  13781. xhr.onreadystatechange = function () {
  13782. if (xhr.readyState !== 4 || handled) {
  13783. return;
  13784. }
  13785. handled = true;
  13786. if (xhr.status >= 200 && xhr.status < 300) {
  13787. var response;
  13788. try {
  13789. response = JSON.parse(xhr.responseText);
  13790. if (typeof xhr.getResponseHeader === 'function') {
  13791. if ((xhr.getAllResponseHeaders() || '').includes('x-parse-job-status-id: ')) {
  13792. response = xhr.getResponseHeader('x-parse-job-status-id');
  13793. }
  13794. }
  13795. } catch (e) {
  13796. promise.reject(e.toString());
  13797. }
  13798. if (response) {
  13799. promise.resolve({
  13800. response: response,
  13801. status: xhr.status,
  13802. xhr: xhr
  13803. });
  13804. }
  13805. } else if (xhr.status >= 500 || xhr.status === 0) {
  13806. // retry on 5XX or node-xmlhttprequest error
  13807. if (++attempts < _CoreManager.default.get('REQUEST_ATTEMPT_LIMIT')) {
  13808. // Exponentially-growing random delay
  13809. var delay = Math.round(Math.random() * 125 * Math.pow(2, attempts));
  13810. setTimeout(dispatch, delay);
  13811. } else if (xhr.status === 0) {
  13812. promise.reject('Unable to connect to the Parse API');
  13813. } else {
  13814. // After the retry limit is reached, fail
  13815. promise.reject(xhr);
  13816. }
  13817. } else {
  13818. promise.reject(xhr);
  13819. }
  13820. };
  13821. headers = headers || {};
  13822. if (typeof headers['Content-Type'] !== 'string') {
  13823. headers['Content-Type'] = 'text/plain'; // Avoid pre-flight
  13824. }
  13825. if (_CoreManager.default.get('IS_NODE')) {
  13826. headers['User-Agent'] = 'Parse/' + _CoreManager.default.get('VERSION') + ' (NodeJS ' + process.versions.node + ')';
  13827. }
  13828. if (_CoreManager.default.get('SERVER_AUTH_TYPE') && _CoreManager.default.get('SERVER_AUTH_TOKEN')) {
  13829. headers['Authorization'] = _CoreManager.default.get('SERVER_AUTH_TYPE') + ' ' + _CoreManager.default.get('SERVER_AUTH_TOKEN');
  13830. }
  13831. if (options && typeof options.progress === 'function') {
  13832. if (xhr.upload) {
  13833. xhr.upload.addEventListener('progress', function (oEvent) {
  13834. if (oEvent.lengthComputable) {
  13835. options.progress(oEvent.loaded / oEvent.total);
  13836. } else {
  13837. options.progress(null);
  13838. }
  13839. });
  13840. } else if (xhr.addEventListener) {
  13841. xhr.addEventListener('progress', function (oEvent) {
  13842. if (oEvent.lengthComputable) {
  13843. options.progress(oEvent.loaded / oEvent.total);
  13844. } else {
  13845. options.progress(null);
  13846. }
  13847. });
  13848. }
  13849. }
  13850. xhr.open(method, url, true);
  13851. for (var h in headers) {
  13852. xhr.setRequestHeader(h, headers[h]);
  13853. }
  13854. xhr.send(data);
  13855. };
  13856. dispatch();
  13857. return promise;
  13858. },
  13859. request: function (method
  13860. /*: string*/
  13861. , path
  13862. /*: string*/
  13863. , data
  13864. /*: mixed*/
  13865. , options
  13866. /*:: ?: RequestOptions*/
  13867. ) {
  13868. options = options || {};
  13869. var url = _CoreManager.default.get('SERVER_URL');
  13870. if (url[url.length - 1] !== '/') {
  13871. url += '/';
  13872. }
  13873. url += path;
  13874. var payload = {};
  13875. if (data && (0, _typeof2.default)(data) === 'object') {
  13876. for (var k in data) {
  13877. payload[k] = data[k];
  13878. }
  13879. }
  13880. if (method !== 'POST') {
  13881. payload._method = method;
  13882. method = 'POST';
  13883. }
  13884. payload._ApplicationId = _CoreManager.default.get('APPLICATION_ID');
  13885. var jsKey = _CoreManager.default.get('JAVASCRIPT_KEY');
  13886. if (jsKey) {
  13887. payload._JavaScriptKey = jsKey;
  13888. }
  13889. payload._ClientVersion = _CoreManager.default.get('VERSION');
  13890. var useMasterKey = options.useMasterKey;
  13891. if (typeof useMasterKey === 'undefined') {
  13892. useMasterKey = _CoreManager.default.get('USE_MASTER_KEY');
  13893. }
  13894. if (useMasterKey) {
  13895. if (_CoreManager.default.get('MASTER_KEY')) {
  13896. delete payload._JavaScriptKey;
  13897. payload._MasterKey = _CoreManager.default.get('MASTER_KEY');
  13898. } else {
  13899. throw new Error('Cannot use the Master Key, it has not been provided.');
  13900. }
  13901. }
  13902. if (_CoreManager.default.get('FORCE_REVOCABLE_SESSION')) {
  13903. payload._RevocableSession = '1';
  13904. }
  13905. var installationId = options.installationId;
  13906. var installationIdPromise;
  13907. if (installationId && typeof installationId === 'string') {
  13908. installationIdPromise = Promise.resolve(installationId);
  13909. } else {
  13910. var installationController = _CoreManager.default.getInstallationController();
  13911. installationIdPromise = installationController.currentInstallationId();
  13912. }
  13913. return installationIdPromise.then(function (iid) {
  13914. payload._InstallationId = iid;
  13915. var userController = _CoreManager.default.getUserController();
  13916. if (options && typeof options.sessionToken === 'string') {
  13917. return Promise.resolve(options.sessionToken);
  13918. } else if (userController) {
  13919. return userController.currentUserAsync().then(function (user) {
  13920. if (user) {
  13921. return Promise.resolve(user.getSessionToken());
  13922. }
  13923. return Promise.resolve(null);
  13924. });
  13925. }
  13926. return Promise.resolve(null);
  13927. }).then(function (token) {
  13928. if (token) {
  13929. payload._SessionToken = token;
  13930. }
  13931. var payloadString = JSON.stringify(payload);
  13932. return RESTController.ajax(method, url, payloadString, {}, options).then(function (_ref) {
  13933. var response = _ref.response,
  13934. status = _ref.status;
  13935. if (options.returnStatus) {
  13936. return _objectSpread({}, response, {
  13937. _status: status
  13938. });
  13939. } else {
  13940. return response;
  13941. }
  13942. });
  13943. }).catch(function (response
  13944. /*: { responseText: string }*/
  13945. ) {
  13946. // Transform the error into an instance of ParseError by trying to parse
  13947. // the error string as JSON
  13948. var error;
  13949. if (response && response.responseText) {
  13950. try {
  13951. var errorJSON = JSON.parse(response.responseText);
  13952. error = new _ParseError.default(errorJSON.code, errorJSON.error);
  13953. } catch (e) {
  13954. // If we fail to parse the error text, that's okay.
  13955. error = new _ParseError.default(_ParseError.default.INVALID_JSON, 'Received an error with invalid JSON from Parse: ' + response.responseText);
  13956. }
  13957. } else {
  13958. error = new _ParseError.default(_ParseError.default.CONNECTION_FAILED, 'XMLHttpRequest failed: ' + JSON.stringify(response));
  13959. }
  13960. return Promise.reject(error);
  13961. });
  13962. },
  13963. _setXHR: function (xhr
  13964. /*: any*/
  13965. ) {
  13966. XHR = xhr;
  13967. }
  13968. };
  13969. module.exports = RESTController;
  13970. }).call(this,_dereq_('_process'))
  13971. },{"./CoreManager":4,"./ParseError":18,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73,"_process":77}],34:[function(_dereq_,module,exports){
  13972. "use strict";
  13973. var _interopRequireWildcard = _dereq_("@babel/runtime/helpers/interopRequireWildcard");
  13974. Object.defineProperty(exports, "__esModule", {
  13975. value: true
  13976. });
  13977. exports.getState = getState;
  13978. exports.initializeState = initializeState;
  13979. exports.removeState = removeState;
  13980. exports.getServerData = getServerData;
  13981. exports.setServerData = setServerData;
  13982. exports.getPendingOps = getPendingOps;
  13983. exports.setPendingOp = setPendingOp;
  13984. exports.pushPendingState = pushPendingState;
  13985. exports.popPendingState = popPendingState;
  13986. exports.mergeFirstPendingState = mergeFirstPendingState;
  13987. exports.getObjectCache = getObjectCache;
  13988. exports.estimateAttribute = estimateAttribute;
  13989. exports.estimateAttributes = estimateAttributes;
  13990. exports.commitServerChanges = commitServerChanges;
  13991. exports.enqueueTask = enqueueTask;
  13992. exports.clearAllState = clearAllState;
  13993. exports.duplicateState = duplicateState;
  13994. var ObjectStateMutations = _interopRequireWildcard(_dereq_("./ObjectStateMutations"));
  13995. /**
  13996. * Copyright (c) 2015-present, Parse, LLC.
  13997. * All rights reserved.
  13998. *
  13999. * This source code is licensed under the BSD-style license found in the
  14000. * LICENSE file in the root directory of this source tree. An additional grant
  14001. * of patent rights can be found in the PATENTS file in the same directory.
  14002. *
  14003. * @flow
  14004. */
  14005. var objectState
  14006. /*: {
  14007. [className: string]: {
  14008. [id: string]: State
  14009. }
  14010. }*/
  14011. = {};
  14012. function getState(obj
  14013. /*: ObjectIdentifier*/
  14014. )
  14015. /*: ?State*/
  14016. {
  14017. var classData = objectState[obj.className];
  14018. if (classData) {
  14019. return classData[obj.id] || null;
  14020. }
  14021. return null;
  14022. }
  14023. function initializeState(obj
  14024. /*: ObjectIdentifier*/
  14025. , initial
  14026. /*:: ?: State*/
  14027. )
  14028. /*: State*/
  14029. {
  14030. var state = getState(obj);
  14031. if (state) {
  14032. return state;
  14033. }
  14034. if (!objectState[obj.className]) {
  14035. objectState[obj.className] = {};
  14036. }
  14037. if (!initial) {
  14038. initial = ObjectStateMutations.defaultState();
  14039. }
  14040. state = objectState[obj.className][obj.id] = initial;
  14041. return state;
  14042. }
  14043. function removeState(obj
  14044. /*: ObjectIdentifier*/
  14045. )
  14046. /*: ?State*/
  14047. {
  14048. var state = getState(obj);
  14049. if (state === null) {
  14050. return null;
  14051. }
  14052. delete objectState[obj.className][obj.id];
  14053. return state;
  14054. }
  14055. function getServerData(obj
  14056. /*: ObjectIdentifier*/
  14057. )
  14058. /*: AttributeMap*/
  14059. {
  14060. var state = getState(obj);
  14061. if (state) {
  14062. return state.serverData;
  14063. }
  14064. return {};
  14065. }
  14066. function setServerData(obj
  14067. /*: ObjectIdentifier*/
  14068. , attributes
  14069. /*: AttributeMap*/
  14070. ) {
  14071. var serverData = initializeState(obj).serverData;
  14072. ObjectStateMutations.setServerData(serverData, attributes);
  14073. }
  14074. function getPendingOps(obj
  14075. /*: ObjectIdentifier*/
  14076. )
  14077. /*: Array<OpsMap>*/
  14078. {
  14079. var state = getState(obj);
  14080. if (state) {
  14081. return state.pendingOps;
  14082. }
  14083. return [{}];
  14084. }
  14085. function setPendingOp(obj
  14086. /*: ObjectIdentifier*/
  14087. , attr
  14088. /*: string*/
  14089. , op
  14090. /*: ?Op*/
  14091. ) {
  14092. var pendingOps = initializeState(obj).pendingOps;
  14093. ObjectStateMutations.setPendingOp(pendingOps, attr, op);
  14094. }
  14095. function pushPendingState(obj
  14096. /*: ObjectIdentifier*/
  14097. ) {
  14098. var pendingOps = initializeState(obj).pendingOps;
  14099. ObjectStateMutations.pushPendingState(pendingOps);
  14100. }
  14101. function popPendingState(obj
  14102. /*: ObjectIdentifier*/
  14103. )
  14104. /*: OpsMap*/
  14105. {
  14106. var pendingOps = initializeState(obj).pendingOps;
  14107. return ObjectStateMutations.popPendingState(pendingOps);
  14108. }
  14109. function mergeFirstPendingState(obj
  14110. /*: ObjectIdentifier*/
  14111. ) {
  14112. var pendingOps = getPendingOps(obj);
  14113. ObjectStateMutations.mergeFirstPendingState(pendingOps);
  14114. }
  14115. function getObjectCache(obj
  14116. /*: ObjectIdentifier*/
  14117. )
  14118. /*: ObjectCache*/
  14119. {
  14120. var state = getState(obj);
  14121. if (state) {
  14122. return state.objectCache;
  14123. }
  14124. return {};
  14125. }
  14126. function estimateAttribute(obj
  14127. /*: ObjectIdentifier*/
  14128. , attr
  14129. /*: string*/
  14130. )
  14131. /*: mixed*/
  14132. {
  14133. var serverData = getServerData(obj);
  14134. var pendingOps = getPendingOps(obj);
  14135. return ObjectStateMutations.estimateAttribute(serverData, pendingOps, obj.className, obj.id, attr);
  14136. }
  14137. function estimateAttributes(obj
  14138. /*: ObjectIdentifier*/
  14139. )
  14140. /*: AttributeMap*/
  14141. {
  14142. var serverData = getServerData(obj);
  14143. var pendingOps = getPendingOps(obj);
  14144. return ObjectStateMutations.estimateAttributes(serverData, pendingOps, obj.className, obj.id);
  14145. }
  14146. function commitServerChanges(obj
  14147. /*: ObjectIdentifier*/
  14148. , changes
  14149. /*: AttributeMap*/
  14150. ) {
  14151. var state = initializeState(obj);
  14152. ObjectStateMutations.commitServerChanges(state.serverData, state.objectCache, changes);
  14153. }
  14154. function enqueueTask(obj
  14155. /*: ObjectIdentifier*/
  14156. , task
  14157. /*: () => Promise*/
  14158. )
  14159. /*: Promise*/
  14160. {
  14161. var state = initializeState(obj);
  14162. return state.tasks.enqueue(task);
  14163. }
  14164. function clearAllState() {
  14165. objectState = {};
  14166. }
  14167. function duplicateState(source
  14168. /*: {id: string}*/
  14169. , dest
  14170. /*: {id: string}*/
  14171. ) {
  14172. dest.id = source.id;
  14173. }
  14174. },{"./ObjectStateMutations":13,"@babel/runtime/helpers/interopRequireWildcard":62}],35:[function(_dereq_,module,exports){
  14175. "use strict";
  14176. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14177. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  14178. /**
  14179. * Copyright (c) 2015-present, Parse, LLC.
  14180. * All rights reserved.
  14181. *
  14182. * This source code is licensed under the BSD-style license found in the
  14183. * LICENSE file in the root directory of this source tree. An additional grant
  14184. * of patent rights can be found in the PATENTS file in the same directory.
  14185. *
  14186. * @flow
  14187. */
  14188. var Storage = {
  14189. async: function ()
  14190. /*: boolean*/
  14191. {
  14192. var controller = _CoreManager.default.getStorageController();
  14193. return !!controller.async;
  14194. },
  14195. getItem: function (path
  14196. /*: string*/
  14197. )
  14198. /*: ?string*/
  14199. {
  14200. var controller = _CoreManager.default.getStorageController();
  14201. if (controller.async === 1) {
  14202. throw new Error('Synchronous storage is not supported by the current storage controller');
  14203. }
  14204. return controller.getItem(path);
  14205. },
  14206. getItemAsync: function (path
  14207. /*: string*/
  14208. )
  14209. /*: Promise<string>*/
  14210. {
  14211. var controller = _CoreManager.default.getStorageController();
  14212. if (controller.async === 1) {
  14213. return controller.getItemAsync(path);
  14214. }
  14215. return Promise.resolve(controller.getItem(path));
  14216. },
  14217. setItem: function (path
  14218. /*: string*/
  14219. , value
  14220. /*: string*/
  14221. )
  14222. /*: void*/
  14223. {
  14224. var controller = _CoreManager.default.getStorageController();
  14225. if (controller.async === 1) {
  14226. throw new Error('Synchronous storage is not supported by the current storage controller');
  14227. }
  14228. return controller.setItem(path, value);
  14229. },
  14230. setItemAsync: function (path
  14231. /*: string*/
  14232. , value
  14233. /*: string*/
  14234. )
  14235. /*: Promise<void>*/
  14236. {
  14237. var controller = _CoreManager.default.getStorageController();
  14238. if (controller.async === 1) {
  14239. return controller.setItemAsync(path, value);
  14240. }
  14241. return Promise.resolve(controller.setItem(path, value));
  14242. },
  14243. removeItem: function (path
  14244. /*: string*/
  14245. )
  14246. /*: void*/
  14247. {
  14248. var controller = _CoreManager.default.getStorageController();
  14249. if (controller.async === 1) {
  14250. throw new Error('Synchronous storage is not supported by the current storage controller');
  14251. }
  14252. return controller.removeItem(path);
  14253. },
  14254. removeItemAsync: function (path
  14255. /*: string*/
  14256. )
  14257. /*: Promise<void>*/
  14258. {
  14259. var controller = _CoreManager.default.getStorageController();
  14260. if (controller.async === 1) {
  14261. return controller.removeItemAsync(path);
  14262. }
  14263. return Promise.resolve(controller.removeItem(path));
  14264. },
  14265. generatePath: function (path
  14266. /*: string*/
  14267. )
  14268. /*: string*/
  14269. {
  14270. if (!_CoreManager.default.get('APPLICATION_ID')) {
  14271. throw new Error('You need to call Parse.initialize before using Parse.');
  14272. }
  14273. if (typeof path !== 'string') {
  14274. throw new Error('Tried to get a Storage path that was not a String.');
  14275. }
  14276. if (path[0] === '/') {
  14277. path = path.substr(1);
  14278. }
  14279. return 'Parse/' + _CoreManager.default.get('APPLICATION_ID') + '/' + path;
  14280. },
  14281. _clear: function () {
  14282. var controller = _CoreManager.default.getStorageController();
  14283. if (controller.hasOwnProperty('clear')) {
  14284. controller.clear();
  14285. }
  14286. }
  14287. };
  14288. module.exports = Storage;
  14289. _CoreManager.default.setStorageController(_dereq_('./StorageController.browser'));
  14290. },{"./CoreManager":4,"./StorageController.browser":36,"@babel/runtime/helpers/interopRequireDefault":61}],36:[function(_dereq_,module,exports){
  14291. "use strict";
  14292. /**
  14293. * Copyright (c) 2015-present, Parse, LLC.
  14294. * All rights reserved.
  14295. *
  14296. * This source code is licensed under the BSD-style license found in the
  14297. * LICENSE file in the root directory of this source tree. An additional grant
  14298. * of patent rights can be found in the PATENTS file in the same directory.
  14299. *
  14300. * @flow
  14301. */
  14302. /* global localStorage */
  14303. var StorageController = {
  14304. async: 0,
  14305. getItem: function (path
  14306. /*: string*/
  14307. )
  14308. /*: ?string*/
  14309. {
  14310. return localStorage.getItem(path);
  14311. },
  14312. setItem: function (path
  14313. /*: string*/
  14314. , value
  14315. /*: string*/
  14316. ) {
  14317. try {
  14318. localStorage.setItem(path, value);
  14319. } catch (e) {// Quota exceeded, possibly due to Safari Private Browsing mode
  14320. }
  14321. },
  14322. removeItem: function (path
  14323. /*: string*/
  14324. ) {
  14325. localStorage.removeItem(path);
  14326. },
  14327. clear: function () {
  14328. localStorage.clear();
  14329. }
  14330. };
  14331. module.exports = StorageController;
  14332. },{}],37:[function(_dereq_,module,exports){
  14333. /*:: type Task = {
  14334. task: () => Promise;
  14335. _completion: Promise
  14336. };*/
  14337. "use strict";
  14338. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14339. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  14340. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  14341. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  14342. /**
  14343. * Copyright (c) 2015-present, Parse, LLC.
  14344. * All rights reserved.
  14345. *
  14346. * This source code is licensed under the BSD-style license found in the
  14347. * LICENSE file in the root directory of this source tree. An additional grant
  14348. * of patent rights can be found in the PATENTS file in the same directory.
  14349. *
  14350. * @flow
  14351. */
  14352. var TaskQueue =
  14353. /*#__PURE__*/
  14354. function () {
  14355. function TaskQueue() {
  14356. (0, _classCallCheck2.default)(this, TaskQueue);
  14357. (0, _defineProperty2.default)(this, "queue", void 0);
  14358. this.queue = [];
  14359. }
  14360. (0, _createClass2.default)(TaskQueue, [{
  14361. key: "enqueue",
  14362. value: function (task
  14363. /*: () => Promise*/
  14364. )
  14365. /*: Promise*/
  14366. {
  14367. var _this = this;
  14368. var res;
  14369. var rej;
  14370. var taskComplete = new Promise(function (resolve, reject) {
  14371. res = resolve;
  14372. rej = reject;
  14373. });
  14374. taskComplete.resolve = res;
  14375. taskComplete.reject = rej;
  14376. this.queue.push({
  14377. task: task,
  14378. _completion: taskComplete
  14379. });
  14380. if (this.queue.length === 1) {
  14381. task().then(function () {
  14382. _this._dequeue();
  14383. taskComplete.resolve();
  14384. }, function (error) {
  14385. _this._dequeue();
  14386. taskComplete.reject(error);
  14387. });
  14388. }
  14389. return taskComplete;
  14390. }
  14391. }, {
  14392. key: "_dequeue",
  14393. value: function () {
  14394. var _this2 = this;
  14395. this.queue.shift();
  14396. if (this.queue.length) {
  14397. var next = this.queue[0];
  14398. next.task().then(function () {
  14399. _this2._dequeue();
  14400. next._completion.resolve();
  14401. }, function (error) {
  14402. _this2._dequeue();
  14403. next._completion.reject(error);
  14404. });
  14405. }
  14406. }
  14407. }]);
  14408. return TaskQueue;
  14409. }();
  14410. module.exports = TaskQueue;
  14411. },{"@babel/runtime/helpers/classCallCheck":54,"@babel/runtime/helpers/createClass":56,"@babel/runtime/helpers/defineProperty":57,"@babel/runtime/helpers/interopRequireDefault":61}],38:[function(_dereq_,module,exports){
  14412. "use strict";
  14413. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14414. var _interopRequireWildcard = _dereq_("@babel/runtime/helpers/interopRequireWildcard");
  14415. Object.defineProperty(exports, "__esModule", {
  14416. value: true
  14417. });
  14418. exports.getState = getState;
  14419. exports.initializeState = initializeState;
  14420. exports.removeState = removeState;
  14421. exports.getServerData = getServerData;
  14422. exports.setServerData = setServerData;
  14423. exports.getPendingOps = getPendingOps;
  14424. exports.setPendingOp = setPendingOp;
  14425. exports.pushPendingState = pushPendingState;
  14426. exports.popPendingState = popPendingState;
  14427. exports.mergeFirstPendingState = mergeFirstPendingState;
  14428. exports.getObjectCache = getObjectCache;
  14429. exports.estimateAttribute = estimateAttribute;
  14430. exports.estimateAttributes = estimateAttributes;
  14431. exports.commitServerChanges = commitServerChanges;
  14432. exports.enqueueTask = enqueueTask;
  14433. exports.duplicateState = duplicateState;
  14434. exports.clearAllState = clearAllState;
  14435. var ObjectStateMutations = _interopRequireWildcard(_dereq_("./ObjectStateMutations"));
  14436. var _TaskQueue = _interopRequireDefault(_dereq_("./TaskQueue"));
  14437. /**
  14438. * Copyright (c) 2015-present, Parse, LLC.
  14439. * All rights reserved.
  14440. *
  14441. * This source code is licensed under the BSD-style license found in the
  14442. * LICENSE file in the root directory of this source tree. An additional grant
  14443. * of patent rights can be found in the PATENTS file in the same directory.
  14444. *
  14445. * @flow
  14446. */
  14447. var objectState = new WeakMap();
  14448. function getState(obj
  14449. /*: ParseObject*/
  14450. )
  14451. /*: ?State*/
  14452. {
  14453. var classData = objectState.get(obj);
  14454. return classData || null;
  14455. }
  14456. function initializeState(obj
  14457. /*: ParseObject*/
  14458. , initial
  14459. /*:: ?: State*/
  14460. )
  14461. /*: State*/
  14462. {
  14463. var state = getState(obj);
  14464. if (state) {
  14465. return state;
  14466. }
  14467. if (!initial) {
  14468. initial = {
  14469. serverData: {},
  14470. pendingOps: [{}],
  14471. objectCache: {},
  14472. tasks: new _TaskQueue.default(),
  14473. existed: false
  14474. };
  14475. }
  14476. state = initial;
  14477. objectState.set(obj, state);
  14478. return state;
  14479. }
  14480. function removeState(obj
  14481. /*: ParseObject*/
  14482. )
  14483. /*: ?State*/
  14484. {
  14485. var state = getState(obj);
  14486. if (state === null) {
  14487. return null;
  14488. }
  14489. objectState.delete(obj);
  14490. return state;
  14491. }
  14492. function getServerData(obj
  14493. /*: ParseObject*/
  14494. )
  14495. /*: AttributeMap*/
  14496. {
  14497. var state = getState(obj);
  14498. if (state) {
  14499. return state.serverData;
  14500. }
  14501. return {};
  14502. }
  14503. function setServerData(obj
  14504. /*: ParseObject*/
  14505. , attributes
  14506. /*: AttributeMap*/
  14507. ) {
  14508. var serverData = initializeState(obj).serverData;
  14509. ObjectStateMutations.setServerData(serverData, attributes);
  14510. }
  14511. function getPendingOps(obj
  14512. /*: ParseObject*/
  14513. )
  14514. /*: Array<OpsMap>*/
  14515. {
  14516. var state = getState(obj);
  14517. if (state) {
  14518. return state.pendingOps;
  14519. }
  14520. return [{}];
  14521. }
  14522. function setPendingOp(obj
  14523. /*: ParseObject*/
  14524. , attr
  14525. /*: string*/
  14526. , op
  14527. /*: ?Op*/
  14528. ) {
  14529. var pendingOps = initializeState(obj).pendingOps;
  14530. ObjectStateMutations.setPendingOp(pendingOps, attr, op);
  14531. }
  14532. function pushPendingState(obj
  14533. /*: ParseObject*/
  14534. ) {
  14535. var pendingOps = initializeState(obj).pendingOps;
  14536. ObjectStateMutations.pushPendingState(pendingOps);
  14537. }
  14538. function popPendingState(obj
  14539. /*: ParseObject*/
  14540. )
  14541. /*: OpsMap*/
  14542. {
  14543. var pendingOps = initializeState(obj).pendingOps;
  14544. return ObjectStateMutations.popPendingState(pendingOps);
  14545. }
  14546. function mergeFirstPendingState(obj
  14547. /*: ParseObject*/
  14548. ) {
  14549. var pendingOps = getPendingOps(obj);
  14550. ObjectStateMutations.mergeFirstPendingState(pendingOps);
  14551. }
  14552. function getObjectCache(obj
  14553. /*: ParseObject*/
  14554. )
  14555. /*: ObjectCache*/
  14556. {
  14557. var state = getState(obj);
  14558. if (state) {
  14559. return state.objectCache;
  14560. }
  14561. return {};
  14562. }
  14563. function estimateAttribute(obj
  14564. /*: ParseObject*/
  14565. , attr
  14566. /*: string*/
  14567. )
  14568. /*: mixed*/
  14569. {
  14570. var serverData = getServerData(obj);
  14571. var pendingOps = getPendingOps(obj);
  14572. return ObjectStateMutations.estimateAttribute(serverData, pendingOps, obj.className, obj.id, attr);
  14573. }
  14574. function estimateAttributes(obj
  14575. /*: ParseObject*/
  14576. )
  14577. /*: AttributeMap*/
  14578. {
  14579. var serverData = getServerData(obj);
  14580. var pendingOps = getPendingOps(obj);
  14581. return ObjectStateMutations.estimateAttributes(serverData, pendingOps, obj.className, obj.id);
  14582. }
  14583. function commitServerChanges(obj
  14584. /*: ParseObject*/
  14585. , changes
  14586. /*: AttributeMap*/
  14587. ) {
  14588. var state = initializeState(obj);
  14589. ObjectStateMutations.commitServerChanges(state.serverData, state.objectCache, changes);
  14590. }
  14591. function enqueueTask(obj
  14592. /*: ParseObject*/
  14593. , task
  14594. /*: () => Promise*/
  14595. )
  14596. /*: Promise*/
  14597. {
  14598. var state = initializeState(obj);
  14599. return state.tasks.enqueue(task);
  14600. }
  14601. function duplicateState(source
  14602. /*: ParseObject*/
  14603. , dest
  14604. /*: ParseObject*/
  14605. )
  14606. /*: void*/
  14607. {
  14608. var oldState = initializeState(source);
  14609. var newState = initializeState(dest);
  14610. for (var key in oldState.serverData) {
  14611. newState.serverData[key] = oldState.serverData[key];
  14612. }
  14613. for (var index = 0; index < oldState.pendingOps.length; index++) {
  14614. for (var _key in oldState.pendingOps[index]) {
  14615. newState.pendingOps[index][_key] = oldState.pendingOps[index][_key];
  14616. }
  14617. }
  14618. for (var _key2 in oldState.objectCache) {
  14619. newState.objectCache[_key2] = oldState.objectCache[_key2];
  14620. }
  14621. newState.existed = oldState.existed;
  14622. }
  14623. function clearAllState() {
  14624. objectState = new WeakMap();
  14625. }
  14626. },{"./ObjectStateMutations":13,"./TaskQueue":37,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/interopRequireWildcard":62}],39:[function(_dereq_,module,exports){
  14627. "use strict";
  14628. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14629. Object.defineProperty(exports, "__esModule", {
  14630. value: true
  14631. });
  14632. exports.default = arrayContainsObject;
  14633. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  14634. /**
  14635. * Copyright (c) 2015-present, Parse, LLC.
  14636. * All rights reserved.
  14637. *
  14638. * This source code is licensed under the BSD-style license found in the
  14639. * LICENSE file in the root directory of this source tree. An additional grant
  14640. * of patent rights can be found in the PATENTS file in the same directory.
  14641. *
  14642. * @flow
  14643. */
  14644. function arrayContainsObject(array
  14645. /*: Array<any>*/
  14646. , object
  14647. /*: ParseObject*/
  14648. )
  14649. /*: boolean*/
  14650. {
  14651. if (array.indexOf(object) > -1) {
  14652. return true;
  14653. }
  14654. for (var i = 0; i < array.length; i++) {
  14655. if (array[i] instanceof _ParseObject.default && array[i].className === object.className && array[i]._getId() === object._getId()) {
  14656. return true;
  14657. }
  14658. }
  14659. return false;
  14660. }
  14661. },{"./ParseObject":23,"@babel/runtime/helpers/interopRequireDefault":61}],40:[function(_dereq_,module,exports){
  14662. "use strict";
  14663. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14664. Object.defineProperty(exports, "__esModule", {
  14665. value: true
  14666. });
  14667. exports.default = canBeSerialized;
  14668. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  14669. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  14670. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  14671. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  14672. /**
  14673. * Copyright (c) 2015-present, Parse, LLC.
  14674. * All rights reserved.
  14675. *
  14676. * This source code is licensed under the BSD-style license found in the
  14677. * LICENSE file in the root directory of this source tree. An additional grant
  14678. * of patent rights can be found in the PATENTS file in the same directory.
  14679. *
  14680. * @flow
  14681. */
  14682. function canBeSerialized(obj
  14683. /*: ParseObject*/
  14684. )
  14685. /*: boolean*/
  14686. {
  14687. if (!(obj instanceof _ParseObject.default)) {
  14688. return true;
  14689. }
  14690. var attributes = obj.attributes;
  14691. for (var attr in attributes) {
  14692. var val = attributes[attr];
  14693. if (!canBeSerializedHelper(val)) {
  14694. return false;
  14695. }
  14696. }
  14697. return true;
  14698. }
  14699. function canBeSerializedHelper(value
  14700. /*: any*/
  14701. )
  14702. /*: boolean*/
  14703. {
  14704. if ((0, _typeof2.default)(value) !== 'object') {
  14705. return true;
  14706. }
  14707. if (value instanceof _ParseRelation.default) {
  14708. return true;
  14709. }
  14710. if (value instanceof _ParseObject.default) {
  14711. return !!value.id;
  14712. }
  14713. if (value instanceof _ParseFile.default) {
  14714. if (value.url()) {
  14715. return true;
  14716. }
  14717. return false;
  14718. }
  14719. if (Array.isArray(value)) {
  14720. for (var i = 0; i < value.length; i++) {
  14721. if (!canBeSerializedHelper(value[i])) {
  14722. return false;
  14723. }
  14724. }
  14725. return true;
  14726. }
  14727. for (var k in value) {
  14728. if (!canBeSerializedHelper(value[k])) {
  14729. return false;
  14730. }
  14731. }
  14732. return true;
  14733. }
  14734. },{"./ParseFile":19,"./ParseObject":23,"./ParseRelation":27,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],41:[function(_dereq_,module,exports){
  14735. "use strict";
  14736. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14737. Object.defineProperty(exports, "__esModule", {
  14738. value: true
  14739. });
  14740. exports.default = decode;
  14741. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  14742. var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
  14743. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  14744. var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
  14745. var _ParsePolygon = _interopRequireDefault(_dereq_("./ParsePolygon"));
  14746. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  14747. var _ParseOp = _dereq_("./ParseOp");
  14748. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  14749. /**
  14750. * Copyright (c) 2015-present, Parse, LLC.
  14751. * All rights reserved.
  14752. *
  14753. * This source code is licensed under the BSD-style license found in the
  14754. * LICENSE file in the root directory of this source tree. An additional grant
  14755. * of patent rights can be found in the PATENTS file in the same directory.
  14756. *
  14757. * @flow
  14758. */
  14759. // eslint-disable-line no-unused-vars
  14760. function decode(value
  14761. /*: any*/
  14762. )
  14763. /*: any*/
  14764. {
  14765. if (value === null || (0, _typeof2.default)(value) !== 'object') {
  14766. return value;
  14767. }
  14768. if (Array.isArray(value)) {
  14769. var dup = [];
  14770. value.forEach(function (v, i) {
  14771. dup[i] = decode(v);
  14772. });
  14773. return dup;
  14774. }
  14775. if (typeof value.__op === 'string') {
  14776. return (0, _ParseOp.opFromJSON)(value);
  14777. }
  14778. if (value.__type === 'Pointer' && value.className) {
  14779. return _ParseObject.default.fromJSON(value);
  14780. }
  14781. if (value.__type === 'Object' && value.className) {
  14782. return _ParseObject.default.fromJSON(value);
  14783. }
  14784. if (value.__type === 'Relation') {
  14785. // The parent and key fields will be populated by the parent
  14786. var relation = new _ParseRelation.default(null, null);
  14787. relation.targetClassName = value.className;
  14788. return relation;
  14789. }
  14790. if (value.__type === 'Date') {
  14791. return new Date(value.iso);
  14792. }
  14793. if (value.__type === 'File') {
  14794. return _ParseFile.default.fromJSON(value);
  14795. }
  14796. if (value.__type === 'GeoPoint') {
  14797. return new _ParseGeoPoint.default({
  14798. latitude: value.latitude,
  14799. longitude: value.longitude
  14800. });
  14801. }
  14802. if (value.__type === 'Polygon') {
  14803. return new _ParsePolygon.default(value.coordinates);
  14804. }
  14805. var copy = {};
  14806. for (var k in value) {
  14807. copy[k] = decode(value[k]);
  14808. }
  14809. return copy;
  14810. }
  14811. },{"./ParseACL":16,"./ParseFile":19,"./ParseGeoPoint":20,"./ParseObject":23,"./ParseOp":24,"./ParsePolygon":25,"./ParseRelation":27,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],42:[function(_dereq_,module,exports){
  14812. "use strict";
  14813. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14814. Object.defineProperty(exports, "__esModule", {
  14815. value: true
  14816. });
  14817. exports.default = _default;
  14818. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  14819. var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
  14820. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  14821. var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
  14822. var _ParsePolygon = _interopRequireDefault(_dereq_("./ParsePolygon"));
  14823. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  14824. var _ParseOp = _dereq_("./ParseOp");
  14825. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  14826. /**
  14827. * Copyright (c) 2015-present, Parse, LLC.
  14828. * All rights reserved.
  14829. *
  14830. * This source code is licensed under the BSD-style license found in the
  14831. * LICENSE file in the root directory of this source tree. An additional grant
  14832. * of patent rights can be found in the PATENTS file in the same directory.
  14833. *
  14834. * @flow
  14835. */
  14836. var toString = Object.prototype.toString;
  14837. function encode(value
  14838. /*: mixed*/
  14839. , disallowObjects
  14840. /*: boolean*/
  14841. , forcePointers
  14842. /*: boolean*/
  14843. , seen
  14844. /*: Array<mixed>*/
  14845. )
  14846. /*: any*/
  14847. {
  14848. if (value instanceof _ParseObject.default) {
  14849. if (disallowObjects) {
  14850. throw new Error('Parse Objects not allowed here');
  14851. }
  14852. var seenEntry = value.id ? value.className + ':' + value.id : value;
  14853. if (forcePointers || !seen || seen.indexOf(seenEntry) > -1 || value.dirty() || Object.keys(value._getServerData()).length < 1) {
  14854. return value.toPointer();
  14855. }
  14856. seen = seen.concat(seenEntry);
  14857. return value._toFullJSON(seen);
  14858. }
  14859. if (value instanceof _ParseOp.Op || value instanceof _ParseACL.default || value instanceof _ParseGeoPoint.default || value instanceof _ParsePolygon.default || value instanceof _ParseRelation.default) {
  14860. return value.toJSON();
  14861. }
  14862. if (value instanceof _ParseFile.default) {
  14863. if (!value.url()) {
  14864. throw new Error('Tried to encode an unsaved file.');
  14865. }
  14866. return value.toJSON();
  14867. }
  14868. if (toString.call(value) === '[object Date]') {
  14869. if (isNaN(value)) {
  14870. throw new Error('Tried to encode an invalid date.');
  14871. }
  14872. return {
  14873. __type: 'Date',
  14874. iso: value
  14875. /*: any*/
  14876. .toJSON()
  14877. };
  14878. }
  14879. if (toString.call(value) === '[object RegExp]' && typeof value.source === 'string') {
  14880. return value.source;
  14881. }
  14882. if (Array.isArray(value)) {
  14883. return value.map(function (v) {
  14884. return encode(v, disallowObjects, forcePointers, seen);
  14885. });
  14886. }
  14887. if (value && (0, _typeof2.default)(value) === 'object') {
  14888. var output = {};
  14889. for (var k in value) {
  14890. output[k] = encode(value[k], disallowObjects, forcePointers, seen);
  14891. }
  14892. return output;
  14893. }
  14894. return value;
  14895. }
  14896. function _default(value
  14897. /*: mixed*/
  14898. , disallowObjects
  14899. /*:: ?: boolean*/
  14900. , forcePointers
  14901. /*:: ?: boolean*/
  14902. , seen
  14903. /*:: ?: Array<mixed>*/
  14904. )
  14905. /*: any*/
  14906. {
  14907. return encode(value, !!disallowObjects, !!forcePointers, seen || []);
  14908. }
  14909. },{"./ParseACL":16,"./ParseFile":19,"./ParseGeoPoint":20,"./ParseObject":23,"./ParseOp":24,"./ParsePolygon":25,"./ParseRelation":27,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],43:[function(_dereq_,module,exports){
  14910. "use strict";
  14911. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14912. Object.defineProperty(exports, "__esModule", {
  14913. value: true
  14914. });
  14915. exports.default = equals;
  14916. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  14917. var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
  14918. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  14919. var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
  14920. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  14921. /**
  14922. * Copyright (c) 2015-present, Parse, LLC.
  14923. * All rights reserved.
  14924. *
  14925. * This source code is licensed under the BSD-style license found in the
  14926. * LICENSE file in the root directory of this source tree. An additional grant
  14927. * of patent rights can be found in the PATENTS file in the same directory.
  14928. */
  14929. var toString = Object.prototype.toString;
  14930. function equals(a, b) {
  14931. if (toString.call(a) === '[object Date]' || toString.call(b) === '[object Date]') {
  14932. var dateA = new Date(a);
  14933. var dateB = new Date(b);
  14934. return +dateA === +dateB;
  14935. }
  14936. if ((0, _typeof2.default)(a) !== (0, _typeof2.default)(b)) {
  14937. return false;
  14938. }
  14939. if (!a || (0, _typeof2.default)(a) !== 'object') {
  14940. // a is a primitive
  14941. return a === b;
  14942. }
  14943. if (Array.isArray(a) || Array.isArray(b)) {
  14944. if (!Array.isArray(a) || !Array.isArray(b)) {
  14945. return false;
  14946. }
  14947. if (a.length !== b.length) {
  14948. return false;
  14949. }
  14950. for (var i = a.length; i--;) {
  14951. if (!equals(a[i], b[i])) {
  14952. return false;
  14953. }
  14954. }
  14955. return true;
  14956. }
  14957. if (a instanceof _ParseACL.default || a instanceof _ParseFile.default || a instanceof _ParseGeoPoint.default || a instanceof _ParseObject.default) {
  14958. return a.equals(b);
  14959. }
  14960. if (b instanceof _ParseObject.default) {
  14961. if (a.__type === 'Object' || a.__type === 'Pointer') {
  14962. return a.objectId === b.id && a.className === b.className;
  14963. }
  14964. }
  14965. if (Object.keys(a).length !== Object.keys(b).length) {
  14966. return false;
  14967. }
  14968. for (var k in a) {
  14969. if (!equals(a[k], b[k])) {
  14970. return false;
  14971. }
  14972. }
  14973. return true;
  14974. }
  14975. },{"./ParseACL":16,"./ParseFile":19,"./ParseGeoPoint":20,"./ParseObject":23,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],44:[function(_dereq_,module,exports){
  14976. "use strict";
  14977. Object.defineProperty(exports, "__esModule", {
  14978. value: true
  14979. });
  14980. exports.default = escape;
  14981. /*
  14982. * Copyright (c) 2015-present, Parse, LLC.
  14983. * All rights reserved.
  14984. *
  14985. * This source code is licensed under the BSD-style license found in the
  14986. * LICENSE file in the root directory of this source tree. An additional grant
  14987. * of patent rights can be found in the PATENTS file in the same directory.
  14988. *
  14989. * @flow
  14990. */
  14991. var encoded = {
  14992. '&': '&amp;',
  14993. '<': '&lt;',
  14994. '>': '&gt;',
  14995. '/': '&#x2F;',
  14996. '\'': '&#x27;',
  14997. '"': '&quot;'
  14998. };
  14999. function escape(str
  15000. /*: string*/
  15001. )
  15002. /*: string*/
  15003. {
  15004. return str.replace(/[&<>\/'"]/g, function (char) {
  15005. return encoded[char];
  15006. });
  15007. }
  15008. },{}],45:[function(_dereq_,module,exports){
  15009. "use strict";
  15010. Object.defineProperty(exports, "__esModule", {
  15011. value: true
  15012. });
  15013. exports.default = isRevocableSession;
  15014. /**
  15015. * Copyright (c) 2015-present, Parse, LLC.
  15016. * All rights reserved.
  15017. *
  15018. * This source code is licensed under the BSD-style license found in the
  15019. * LICENSE file in the root directory of this source tree. An additional grant
  15020. * of patent rights can be found in the PATENTS file in the same directory.
  15021. *
  15022. * @flow
  15023. */
  15024. function isRevocableSession(token
  15025. /*: string*/
  15026. )
  15027. /*: boolean*/
  15028. {
  15029. return token.indexOf('r:') > -1;
  15030. }
  15031. },{}],46:[function(_dereq_,module,exports){
  15032. "use strict";
  15033. Object.defineProperty(exports, "__esModule", {
  15034. value: true
  15035. });
  15036. exports.default = parseDate;
  15037. /**
  15038. * Copyright (c) 2015-present, Parse, LLC.
  15039. * All rights reserved.
  15040. *
  15041. * This source code is licensed under the BSD-style license found in the
  15042. * LICENSE file in the root directory of this source tree. An additional grant
  15043. * of patent rights can be found in the PATENTS file in the same directory.
  15044. *
  15045. * @flow
  15046. */
  15047. function parseDate(iso8601
  15048. /*: string*/
  15049. )
  15050. /*: ?Date*/
  15051. {
  15052. var regexp = new RegExp('^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})' + 'T' + '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})' + '(.([0-9]+))?' + 'Z$');
  15053. var match = regexp.exec(iso8601);
  15054. if (!match) {
  15055. return null;
  15056. }
  15057. var year = parseInt(match[1]) || 0;
  15058. var month = (parseInt(match[2]) || 1) - 1;
  15059. var day = parseInt(match[3]) || 0;
  15060. var hour = parseInt(match[4]) || 0;
  15061. var minute = parseInt(match[5]) || 0;
  15062. var second = parseInt(match[6]) || 0;
  15063. var milli = parseInt(match[8]) || 0;
  15064. return new Date(Date.UTC(year, month, day, hour, minute, second, milli));
  15065. }
  15066. },{}],47:[function(_dereq_,module,exports){
  15067. "use strict";
  15068. Object.defineProperty(exports, "__esModule", {
  15069. value: true
  15070. });
  15071. exports.resolvingPromise = resolvingPromise;
  15072. exports.when = when;
  15073. exports.continueWhile = continueWhile;
  15074. function resolvingPromise() {
  15075. var res;
  15076. var rej;
  15077. var promise = new Promise(function (resolve, reject) {
  15078. res = resolve;
  15079. rej = reject;
  15080. });
  15081. promise.resolve = res;
  15082. promise.reject = rej;
  15083. return promise;
  15084. }
  15085. function when(promises) {
  15086. var objects;
  15087. var arrayArgument = Array.isArray(promises);
  15088. if (arrayArgument) {
  15089. objects = promises;
  15090. } else {
  15091. objects = arguments;
  15092. }
  15093. var total = objects.length;
  15094. var hadError = false;
  15095. var results = [];
  15096. var returnValue = arrayArgument ? [results] : results;
  15097. var errors = [];
  15098. results.length = objects.length;
  15099. errors.length = objects.length;
  15100. if (total === 0) {
  15101. return Promise.resolve(returnValue);
  15102. }
  15103. var promise = new resolvingPromise();
  15104. var resolveOne = function () {
  15105. total--;
  15106. if (total <= 0) {
  15107. if (hadError) {
  15108. promise.reject(errors);
  15109. } else {
  15110. promise.resolve(returnValue);
  15111. }
  15112. }
  15113. };
  15114. var chain = function (object, index) {
  15115. if (object && typeof object.then === 'function') {
  15116. object.then(function (result) {
  15117. results[index] = result;
  15118. resolveOne();
  15119. }, function (error) {
  15120. errors[index] = error;
  15121. hadError = true;
  15122. resolveOne();
  15123. });
  15124. } else {
  15125. results[index] = object;
  15126. resolveOne();
  15127. }
  15128. };
  15129. for (var i = 0; i < objects.length; i++) {
  15130. chain(objects[i], i);
  15131. }
  15132. return promise;
  15133. }
  15134. function continueWhile(test, emitter) {
  15135. if (test()) {
  15136. return emitter().then(function () {
  15137. return continueWhile(test, emitter);
  15138. });
  15139. }
  15140. return Promise.resolve();
  15141. }
  15142. },{}],48:[function(_dereq_,module,exports){
  15143. "use strict";
  15144. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  15145. Object.defineProperty(exports, "__esModule", {
  15146. value: true
  15147. });
  15148. exports.default = unique;
  15149. var _arrayContainsObject = _interopRequireDefault(_dereq_("./arrayContainsObject"));
  15150. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  15151. /**
  15152. * Copyright (c) 2015-present, Parse, LLC.
  15153. * All rights reserved.
  15154. *
  15155. * This source code is licensed under the BSD-style license found in the
  15156. * LICENSE file in the root directory of this source tree. An additional grant
  15157. * of patent rights can be found in the PATENTS file in the same directory.
  15158. *
  15159. * @flow
  15160. */
  15161. function unique
  15162. /*:: <T>*/
  15163. (arr
  15164. /*: Array<T>*/
  15165. )
  15166. /*: Array<T>*/
  15167. {
  15168. var uniques = [];
  15169. arr.forEach(function (value) {
  15170. if (value instanceof _ParseObject.default) {
  15171. if (!(0, _arrayContainsObject.default)(uniques, value)) {
  15172. uniques.push(value);
  15173. }
  15174. } else {
  15175. if (uniques.indexOf(value) < 0) {
  15176. uniques.push(value);
  15177. }
  15178. }
  15179. });
  15180. return uniques;
  15181. }
  15182. },{"./ParseObject":23,"./arrayContainsObject":39,"@babel/runtime/helpers/interopRequireDefault":61}],49:[function(_dereq_,module,exports){
  15183. "use strict";
  15184. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  15185. Object.defineProperty(exports, "__esModule", {
  15186. value: true
  15187. });
  15188. exports.default = unsavedChildren;
  15189. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  15190. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  15191. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  15192. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  15193. /**
  15194. * Copyright (c) 2015-present, Parse, LLC.
  15195. * All rights reserved.
  15196. *
  15197. * This source code is licensed under the BSD-style license found in the
  15198. * LICENSE file in the root directory of this source tree. An additional grant
  15199. * of patent rights can be found in the PATENTS file in the same directory.
  15200. *
  15201. * @flow
  15202. */
  15203. /**
  15204. * Return an array of unsaved children, which are either Parse Objects or Files.
  15205. * If it encounters any dirty Objects without Ids, it will throw an exception.
  15206. */
  15207. function unsavedChildren(obj
  15208. /*: ParseObject*/
  15209. , allowDeepUnsaved
  15210. /*:: ?: boolean*/
  15211. )
  15212. /*: Array<ParseFile | ParseObject>*/
  15213. {
  15214. var encountered = {
  15215. objects: {},
  15216. files: []
  15217. };
  15218. var identifier = obj.className + ':' + obj._getId();
  15219. encountered.objects[identifier] = obj.dirty() ? obj : true;
  15220. var attributes = obj.attributes;
  15221. for (var attr in attributes) {
  15222. if ((0, _typeof2.default)(attributes[attr]) === 'object') {
  15223. traverse(attributes[attr], encountered, false, !!allowDeepUnsaved);
  15224. }
  15225. }
  15226. var unsaved = [];
  15227. for (var id in encountered.objects) {
  15228. if (id !== identifier && encountered.objects[id] !== true) {
  15229. unsaved.push(encountered.objects[id]);
  15230. }
  15231. }
  15232. return unsaved.concat(encountered.files);
  15233. }
  15234. function traverse(obj
  15235. /*: ParseObject*/
  15236. , encountered
  15237. /*: EncounterMap*/
  15238. , shouldThrow
  15239. /*: boolean*/
  15240. , allowDeepUnsaved
  15241. /*: boolean*/
  15242. ) {
  15243. if (obj instanceof _ParseObject.default) {
  15244. if (!obj.id && shouldThrow) {
  15245. throw new Error('Cannot create a pointer to an unsaved Object.');
  15246. }
  15247. var _identifier = obj.className + ':' + obj._getId();
  15248. if (!encountered.objects[_identifier]) {
  15249. encountered.objects[_identifier] = obj.dirty() ? obj : true;
  15250. var attributes = obj.attributes;
  15251. for (var attr in attributes) {
  15252. if ((0, _typeof2.default)(attributes[attr]) === 'object') {
  15253. traverse(attributes[attr], encountered, !allowDeepUnsaved, allowDeepUnsaved);
  15254. }
  15255. }
  15256. }
  15257. return;
  15258. }
  15259. if (obj instanceof _ParseFile.default) {
  15260. if (!obj.url() && encountered.files.indexOf(obj) < 0) {
  15261. encountered.files.push(obj);
  15262. }
  15263. return;
  15264. }
  15265. if (obj instanceof _ParseRelation.default) {
  15266. return;
  15267. }
  15268. if (Array.isArray(obj)) {
  15269. obj.forEach(function (el) {
  15270. if ((0, _typeof2.default)(el) === 'object') {
  15271. traverse(el, encountered, shouldThrow, allowDeepUnsaved);
  15272. }
  15273. });
  15274. }
  15275. for (var k in obj) {
  15276. if ((0, _typeof2.default)(obj[k]) === 'object') {
  15277. traverse(obj[k], encountered, shouldThrow, allowDeepUnsaved);
  15278. }
  15279. }
  15280. }
  15281. },{"./ParseFile":19,"./ParseObject":23,"./ParseRelation":27,"@babel/runtime/helpers/interopRequireDefault":61,"@babel/runtime/helpers/typeof":73}],50:[function(_dereq_,module,exports){
  15282. function _arrayWithHoles(arr) {
  15283. if (Array.isArray(arr)) return arr;
  15284. }
  15285. module.exports = _arrayWithHoles;
  15286. },{}],51:[function(_dereq_,module,exports){
  15287. function _arrayWithoutHoles(arr) {
  15288. if (Array.isArray(arr)) {
  15289. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
  15290. arr2[i] = arr[i];
  15291. }
  15292. return arr2;
  15293. }
  15294. }
  15295. module.exports = _arrayWithoutHoles;
  15296. },{}],52:[function(_dereq_,module,exports){
  15297. function _assertThisInitialized(self) {
  15298. if (self === void 0) {
  15299. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  15300. }
  15301. return self;
  15302. }
  15303. module.exports = _assertThisInitialized;
  15304. },{}],53:[function(_dereq_,module,exports){
  15305. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  15306. try {
  15307. var info = gen[key](arg);
  15308. var value = info.value;
  15309. } catch (error) {
  15310. reject(error);
  15311. return;
  15312. }
  15313. if (info.done) {
  15314. resolve(value);
  15315. } else {
  15316. Promise.resolve(value).then(_next, _throw);
  15317. }
  15318. }
  15319. function _asyncToGenerator(fn) {
  15320. return function () {
  15321. var self = this,
  15322. args = arguments;
  15323. return new Promise(function (resolve, reject) {
  15324. var gen = fn.apply(self, args);
  15325. function _next(value) {
  15326. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
  15327. }
  15328. function _throw(err) {
  15329. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
  15330. }
  15331. _next(undefined);
  15332. });
  15333. };
  15334. }
  15335. module.exports = _asyncToGenerator;
  15336. },{}],54:[function(_dereq_,module,exports){
  15337. function _classCallCheck(instance, Constructor) {
  15338. if (!(instance instanceof Constructor)) {
  15339. throw new TypeError("Cannot call a class as a function");
  15340. }
  15341. }
  15342. module.exports = _classCallCheck;
  15343. },{}],55:[function(_dereq_,module,exports){
  15344. var setPrototypeOf = _dereq_("./setPrototypeOf");
  15345. function isNativeReflectConstruct() {
  15346. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  15347. if (Reflect.construct.sham) return false;
  15348. if (typeof Proxy === "function") return true;
  15349. try {
  15350. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  15351. return true;
  15352. } catch (e) {
  15353. return false;
  15354. }
  15355. }
  15356. function _construct(Parent, args, Class) {
  15357. if (isNativeReflectConstruct()) {
  15358. module.exports = _construct = Reflect.construct;
  15359. } else {
  15360. module.exports = _construct = function _construct(Parent, args, Class) {
  15361. var a = [null];
  15362. a.push.apply(a, args);
  15363. var Constructor = Function.bind.apply(Parent, a);
  15364. var instance = new Constructor();
  15365. if (Class) setPrototypeOf(instance, Class.prototype);
  15366. return instance;
  15367. };
  15368. }
  15369. return _construct.apply(null, arguments);
  15370. }
  15371. module.exports = _construct;
  15372. },{"./setPrototypeOf":69}],56:[function(_dereq_,module,exports){
  15373. function _defineProperties(target, props) {
  15374. for (var i = 0; i < props.length; i++) {
  15375. var descriptor = props[i];
  15376. descriptor.enumerable = descriptor.enumerable || false;
  15377. descriptor.configurable = true;
  15378. if ("value" in descriptor) descriptor.writable = true;
  15379. Object.defineProperty(target, descriptor.key, descriptor);
  15380. }
  15381. }
  15382. function _createClass(Constructor, protoProps, staticProps) {
  15383. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  15384. if (staticProps) _defineProperties(Constructor, staticProps);
  15385. return Constructor;
  15386. }
  15387. module.exports = _createClass;
  15388. },{}],57:[function(_dereq_,module,exports){
  15389. function _defineProperty(obj, key, value) {
  15390. if (key in obj) {
  15391. Object.defineProperty(obj, key, {
  15392. value: value,
  15393. enumerable: true,
  15394. configurable: true,
  15395. writable: true
  15396. });
  15397. } else {
  15398. obj[key] = value;
  15399. }
  15400. return obj;
  15401. }
  15402. module.exports = _defineProperty;
  15403. },{}],58:[function(_dereq_,module,exports){
  15404. var superPropBase = _dereq_("./superPropBase");
  15405. function _get(target, property, receiver) {
  15406. if (typeof Reflect !== "undefined" && Reflect.get) {
  15407. module.exports = _get = Reflect.get;
  15408. } else {
  15409. module.exports = _get = function _get(target, property, receiver) {
  15410. var base = superPropBase(target, property);
  15411. if (!base) return;
  15412. var desc = Object.getOwnPropertyDescriptor(base, property);
  15413. if (desc.get) {
  15414. return desc.get.call(receiver);
  15415. }
  15416. return desc.value;
  15417. };
  15418. }
  15419. return _get(target, property, receiver || target);
  15420. }
  15421. module.exports = _get;
  15422. },{"./superPropBase":71}],59:[function(_dereq_,module,exports){
  15423. function _getPrototypeOf(o) {
  15424. module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  15425. return o.__proto__ || Object.getPrototypeOf(o);
  15426. };
  15427. return _getPrototypeOf(o);
  15428. }
  15429. module.exports = _getPrototypeOf;
  15430. },{}],60:[function(_dereq_,module,exports){
  15431. var setPrototypeOf = _dereq_("./setPrototypeOf");
  15432. function _inherits(subClass, superClass) {
  15433. if (typeof superClass !== "function" && superClass !== null) {
  15434. throw new TypeError("Super expression must either be null or a function");
  15435. }
  15436. subClass.prototype = Object.create(superClass && superClass.prototype, {
  15437. constructor: {
  15438. value: subClass,
  15439. writable: true,
  15440. configurable: true
  15441. }
  15442. });
  15443. if (superClass) setPrototypeOf(subClass, superClass);
  15444. }
  15445. module.exports = _inherits;
  15446. },{"./setPrototypeOf":69}],61:[function(_dereq_,module,exports){
  15447. function _interopRequireDefault(obj) {
  15448. return obj && obj.__esModule ? obj : {
  15449. "default": obj
  15450. };
  15451. }
  15452. module.exports = _interopRequireDefault;
  15453. },{}],62:[function(_dereq_,module,exports){
  15454. function _interopRequireWildcard(obj) {
  15455. if (obj && obj.__esModule) {
  15456. return obj;
  15457. } else {
  15458. var newObj = {};
  15459. if (obj != null) {
  15460. for (var key in obj) {
  15461. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  15462. var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
  15463. if (desc.get || desc.set) {
  15464. Object.defineProperty(newObj, key, desc);
  15465. } else {
  15466. newObj[key] = obj[key];
  15467. }
  15468. }
  15469. }
  15470. }
  15471. newObj["default"] = obj;
  15472. return newObj;
  15473. }
  15474. }
  15475. module.exports = _interopRequireWildcard;
  15476. },{}],63:[function(_dereq_,module,exports){
  15477. function _isNativeFunction(fn) {
  15478. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  15479. }
  15480. module.exports = _isNativeFunction;
  15481. },{}],64:[function(_dereq_,module,exports){
  15482. function _iterableToArray(iter) {
  15483. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  15484. }
  15485. module.exports = _iterableToArray;
  15486. },{}],65:[function(_dereq_,module,exports){
  15487. function _iterableToArrayLimit(arr, i) {
  15488. var _arr = [];
  15489. var _n = true;
  15490. var _d = false;
  15491. var _e = undefined;
  15492. try {
  15493. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  15494. _arr.push(_s.value);
  15495. if (i && _arr.length === i) break;
  15496. }
  15497. } catch (err) {
  15498. _d = true;
  15499. _e = err;
  15500. } finally {
  15501. try {
  15502. if (!_n && _i["return"] != null) _i["return"]();
  15503. } finally {
  15504. if (_d) throw _e;
  15505. }
  15506. }
  15507. return _arr;
  15508. }
  15509. module.exports = _iterableToArrayLimit;
  15510. },{}],66:[function(_dereq_,module,exports){
  15511. function _nonIterableRest() {
  15512. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  15513. }
  15514. module.exports = _nonIterableRest;
  15515. },{}],67:[function(_dereq_,module,exports){
  15516. function _nonIterableSpread() {
  15517. throw new TypeError("Invalid attempt to spread non-iterable instance");
  15518. }
  15519. module.exports = _nonIterableSpread;
  15520. },{}],68:[function(_dereq_,module,exports){
  15521. var _typeof = _dereq_("../helpers/typeof");
  15522. var assertThisInitialized = _dereq_("./assertThisInitialized");
  15523. function _possibleConstructorReturn(self, call) {
  15524. if (call && (_typeof(call) === "object" || typeof call === "function")) {
  15525. return call;
  15526. }
  15527. return assertThisInitialized(self);
  15528. }
  15529. module.exports = _possibleConstructorReturn;
  15530. },{"../helpers/typeof":73,"./assertThisInitialized":52}],69:[function(_dereq_,module,exports){
  15531. function _setPrototypeOf(o, p) {
  15532. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  15533. o.__proto__ = p;
  15534. return o;
  15535. };
  15536. return _setPrototypeOf(o, p);
  15537. }
  15538. module.exports = _setPrototypeOf;
  15539. },{}],70:[function(_dereq_,module,exports){
  15540. var arrayWithHoles = _dereq_("./arrayWithHoles");
  15541. var iterableToArrayLimit = _dereq_("./iterableToArrayLimit");
  15542. var nonIterableRest = _dereq_("./nonIterableRest");
  15543. function _slicedToArray(arr, i) {
  15544. return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();
  15545. }
  15546. module.exports = _slicedToArray;
  15547. },{"./arrayWithHoles":50,"./iterableToArrayLimit":65,"./nonIterableRest":66}],71:[function(_dereq_,module,exports){
  15548. var getPrototypeOf = _dereq_("./getPrototypeOf");
  15549. function _superPropBase(object, property) {
  15550. while (!Object.prototype.hasOwnProperty.call(object, property)) {
  15551. object = getPrototypeOf(object);
  15552. if (object === null) break;
  15553. }
  15554. return object;
  15555. }
  15556. module.exports = _superPropBase;
  15557. },{"./getPrototypeOf":59}],72:[function(_dereq_,module,exports){
  15558. var arrayWithoutHoles = _dereq_("./arrayWithoutHoles");
  15559. var iterableToArray = _dereq_("./iterableToArray");
  15560. var nonIterableSpread = _dereq_("./nonIterableSpread");
  15561. function _toConsumableArray(arr) {
  15562. return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
  15563. }
  15564. module.exports = _toConsumableArray;
  15565. },{"./arrayWithoutHoles":51,"./iterableToArray":64,"./nonIterableSpread":67}],73:[function(_dereq_,module,exports){
  15566. function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
  15567. function _typeof(obj) {
  15568. if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
  15569. module.exports = _typeof = function _typeof(obj) {
  15570. return _typeof2(obj);
  15571. };
  15572. } else {
  15573. module.exports = _typeof = function _typeof(obj) {
  15574. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
  15575. };
  15576. }
  15577. return _typeof(obj);
  15578. }
  15579. module.exports = _typeof;
  15580. },{}],74:[function(_dereq_,module,exports){
  15581. var getPrototypeOf = _dereq_("./getPrototypeOf");
  15582. var setPrototypeOf = _dereq_("./setPrototypeOf");
  15583. var isNativeFunction = _dereq_("./isNativeFunction");
  15584. var construct = _dereq_("./construct");
  15585. function _wrapNativeSuper(Class) {
  15586. var _cache = typeof Map === "function" ? new Map() : undefined;
  15587. module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) {
  15588. if (Class === null || !isNativeFunction(Class)) return Class;
  15589. if (typeof Class !== "function") {
  15590. throw new TypeError("Super expression must either be null or a function");
  15591. }
  15592. if (typeof _cache !== "undefined") {
  15593. if (_cache.has(Class)) return _cache.get(Class);
  15594. _cache.set(Class, Wrapper);
  15595. }
  15596. function Wrapper() {
  15597. return construct(Class, arguments, getPrototypeOf(this).constructor);
  15598. }
  15599. Wrapper.prototype = Object.create(Class.prototype, {
  15600. constructor: {
  15601. value: Wrapper,
  15602. enumerable: false,
  15603. writable: true,
  15604. configurable: true
  15605. }
  15606. });
  15607. return setPrototypeOf(Wrapper, Class);
  15608. };
  15609. return _wrapNativeSuper(Class);
  15610. }
  15611. module.exports = _wrapNativeSuper;
  15612. },{"./construct":55,"./getPrototypeOf":59,"./isNativeFunction":63,"./setPrototypeOf":69}],75:[function(_dereq_,module,exports){
  15613. /**
  15614. * Copyright (c) 2014-present, Facebook, Inc.
  15615. *
  15616. * This source code is licensed under the MIT license found in the
  15617. * LICENSE file in the root directory of this source tree.
  15618. */
  15619. var runtime = (function (exports) {
  15620. "use strict";
  15621. var Op = Object.prototype;
  15622. var hasOwn = Op.hasOwnProperty;
  15623. var undefined; // More compressible than void 0.
  15624. var $Symbol = typeof Symbol === "function" ? Symbol : {};
  15625. var iteratorSymbol = $Symbol.iterator || "@@iterator";
  15626. var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  15627. var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  15628. function wrap(innerFn, outerFn, self, tryLocsList) {
  15629. // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
  15630. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
  15631. var generator = Object.create(protoGenerator.prototype);
  15632. var context = new Context(tryLocsList || []);
  15633. // The ._invoke method unifies the implementations of the .next,
  15634. // .throw, and .return methods.
  15635. generator._invoke = makeInvokeMethod(innerFn, self, context);
  15636. return generator;
  15637. }
  15638. exports.wrap = wrap;
  15639. // Try/catch helper to minimize deoptimizations. Returns a completion
  15640. // record like context.tryEntries[i].completion. This interface could
  15641. // have been (and was previously) designed to take a closure to be
  15642. // invoked without arguments, but in all the cases we care about we
  15643. // already have an existing method we want to call, so there's no need
  15644. // to create a new function object. We can even get away with assuming
  15645. // the method takes exactly one argument, since that happens to be true
  15646. // in every case, so we don't have to touch the arguments object. The
  15647. // only additional allocation required is the completion record, which
  15648. // has a stable shape and so hopefully should be cheap to allocate.
  15649. function tryCatch(fn, obj, arg) {
  15650. try {
  15651. return { type: "normal", arg: fn.call(obj, arg) };
  15652. } catch (err) {
  15653. return { type: "throw", arg: err };
  15654. }
  15655. }
  15656. var GenStateSuspendedStart = "suspendedStart";
  15657. var GenStateSuspendedYield = "suspendedYield";
  15658. var GenStateExecuting = "executing";
  15659. var GenStateCompleted = "completed";
  15660. // Returning this object from the innerFn has the same effect as
  15661. // breaking out of the dispatch switch statement.
  15662. var ContinueSentinel = {};
  15663. // Dummy constructor functions that we use as the .constructor and
  15664. // .constructor.prototype properties for functions that return Generator
  15665. // objects. For full spec compliance, you may wish to configure your
  15666. // minifier not to mangle the names of these two functions.
  15667. function Generator() {}
  15668. function GeneratorFunction() {}
  15669. function GeneratorFunctionPrototype() {}
  15670. // This is a polyfill for %IteratorPrototype% for environments that
  15671. // don't natively support it.
  15672. var IteratorPrototype = {};
  15673. IteratorPrototype[iteratorSymbol] = function () {
  15674. return this;
  15675. };
  15676. var getProto = Object.getPrototypeOf;
  15677. var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  15678. if (NativeIteratorPrototype &&
  15679. NativeIteratorPrototype !== Op &&
  15680. hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
  15681. // This environment has a native %IteratorPrototype%; use it instead
  15682. // of the polyfill.
  15683. IteratorPrototype = NativeIteratorPrototype;
  15684. }
  15685. var Gp = GeneratorFunctionPrototype.prototype =
  15686. Generator.prototype = Object.create(IteratorPrototype);
  15687. GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  15688. GeneratorFunctionPrototype.constructor = GeneratorFunction;
  15689. GeneratorFunctionPrototype[toStringTagSymbol] =
  15690. GeneratorFunction.displayName = "GeneratorFunction";
  15691. // Helper for defining the .next, .throw, and .return methods of the
  15692. // Iterator interface in terms of a single ._invoke method.
  15693. function defineIteratorMethods(prototype) {
  15694. ["next", "throw", "return"].forEach(function(method) {
  15695. prototype[method] = function(arg) {
  15696. return this._invoke(method, arg);
  15697. };
  15698. });
  15699. }
  15700. exports.isGeneratorFunction = function(genFun) {
  15701. var ctor = typeof genFun === "function" && genFun.constructor;
  15702. return ctor
  15703. ? ctor === GeneratorFunction ||
  15704. // For the native GeneratorFunction constructor, the best we can
  15705. // do is to check its .name property.
  15706. (ctor.displayName || ctor.name) === "GeneratorFunction"
  15707. : false;
  15708. };
  15709. exports.mark = function(genFun) {
  15710. if (Object.setPrototypeOf) {
  15711. Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
  15712. } else {
  15713. genFun.__proto__ = GeneratorFunctionPrototype;
  15714. if (!(toStringTagSymbol in genFun)) {
  15715. genFun[toStringTagSymbol] = "GeneratorFunction";
  15716. }
  15717. }
  15718. genFun.prototype = Object.create(Gp);
  15719. return genFun;
  15720. };
  15721. // Within the body of any async function, `await x` is transformed to
  15722. // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  15723. // `hasOwn.call(value, "__await")` to determine if the yielded value is
  15724. // meant to be awaited.
  15725. exports.awrap = function(arg) {
  15726. return { __await: arg };
  15727. };
  15728. function AsyncIterator(generator) {
  15729. function invoke(method, arg, resolve, reject) {
  15730. var record = tryCatch(generator[method], generator, arg);
  15731. if (record.type === "throw") {
  15732. reject(record.arg);
  15733. } else {
  15734. var result = record.arg;
  15735. var value = result.value;
  15736. if (value &&
  15737. typeof value === "object" &&
  15738. hasOwn.call(value, "__await")) {
  15739. return Promise.resolve(value.__await).then(function(value) {
  15740. invoke("next", value, resolve, reject);
  15741. }, function(err) {
  15742. invoke("throw", err, resolve, reject);
  15743. });
  15744. }
  15745. return Promise.resolve(value).then(function(unwrapped) {
  15746. // When a yielded Promise is resolved, its final value becomes
  15747. // the .value of the Promise<{value,done}> result for the
  15748. // current iteration.
  15749. result.value = unwrapped;
  15750. resolve(result);
  15751. }, function(error) {
  15752. // If a rejected Promise was yielded, throw the rejection back
  15753. // into the async generator function so it can be handled there.
  15754. return invoke("throw", error, resolve, reject);
  15755. });
  15756. }
  15757. }
  15758. var previousPromise;
  15759. function enqueue(method, arg) {
  15760. function callInvokeWithMethodAndArg() {
  15761. return new Promise(function(resolve, reject) {
  15762. invoke(method, arg, resolve, reject);
  15763. });
  15764. }
  15765. return previousPromise =
  15766. // If enqueue has been called before, then we want to wait until
  15767. // all previous Promises have been resolved before calling invoke,
  15768. // so that results are always delivered in the correct order. If
  15769. // enqueue has not been called before, then it is important to
  15770. // call invoke immediately, without waiting on a callback to fire,
  15771. // so that the async generator function has the opportunity to do
  15772. // any necessary setup in a predictable way. This predictability
  15773. // is why the Promise constructor synchronously invokes its
  15774. // executor callback, and why async functions synchronously
  15775. // execute code before the first await. Since we implement simple
  15776. // async functions in terms of async generators, it is especially
  15777. // important to get this right, even though it requires care.
  15778. previousPromise ? previousPromise.then(
  15779. callInvokeWithMethodAndArg,
  15780. // Avoid propagating failures to Promises returned by later
  15781. // invocations of the iterator.
  15782. callInvokeWithMethodAndArg
  15783. ) : callInvokeWithMethodAndArg();
  15784. }
  15785. // Define the unified helper method that is used to implement .next,
  15786. // .throw, and .return (see defineIteratorMethods).
  15787. this._invoke = enqueue;
  15788. }
  15789. defineIteratorMethods(AsyncIterator.prototype);
  15790. AsyncIterator.prototype[asyncIteratorSymbol] = function () {
  15791. return this;
  15792. };
  15793. exports.AsyncIterator = AsyncIterator;
  15794. // Note that simple async functions are implemented on top of
  15795. // AsyncIterator objects; they just return a Promise for the value of
  15796. // the final result produced by the iterator.
  15797. exports.async = function(innerFn, outerFn, self, tryLocsList) {
  15798. var iter = new AsyncIterator(
  15799. wrap(innerFn, outerFn, self, tryLocsList)
  15800. );
  15801. return exports.isGeneratorFunction(outerFn)
  15802. ? iter // If outerFn is a generator, return the full iterator.
  15803. : iter.next().then(function(result) {
  15804. return result.done ? result.value : iter.next();
  15805. });
  15806. };
  15807. function makeInvokeMethod(innerFn, self, context) {
  15808. var state = GenStateSuspendedStart;
  15809. return function invoke(method, arg) {
  15810. if (state === GenStateExecuting) {
  15811. throw new Error("Generator is already running");
  15812. }
  15813. if (state === GenStateCompleted) {
  15814. if (method === "throw") {
  15815. throw arg;
  15816. }
  15817. // Be forgiving, per 25.3.3.3.3 of the spec:
  15818. // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
  15819. return doneResult();
  15820. }
  15821. context.method = method;
  15822. context.arg = arg;
  15823. while (true) {
  15824. var delegate = context.delegate;
  15825. if (delegate) {
  15826. var delegateResult = maybeInvokeDelegate(delegate, context);
  15827. if (delegateResult) {
  15828. if (delegateResult === ContinueSentinel) continue;
  15829. return delegateResult;
  15830. }
  15831. }
  15832. if (context.method === "next") {
  15833. // Setting context._sent for legacy support of Babel's
  15834. // function.sent implementation.
  15835. context.sent = context._sent = context.arg;
  15836. } else if (context.method === "throw") {
  15837. if (state === GenStateSuspendedStart) {
  15838. state = GenStateCompleted;
  15839. throw context.arg;
  15840. }
  15841. context.dispatchException(context.arg);
  15842. } else if (context.method === "return") {
  15843. context.abrupt("return", context.arg);
  15844. }
  15845. state = GenStateExecuting;
  15846. var record = tryCatch(innerFn, self, context);
  15847. if (record.type === "normal") {
  15848. // If an exception is thrown from innerFn, we leave state ===
  15849. // GenStateExecuting and loop back for another invocation.
  15850. state = context.done
  15851. ? GenStateCompleted
  15852. : GenStateSuspendedYield;
  15853. if (record.arg === ContinueSentinel) {
  15854. continue;
  15855. }
  15856. return {
  15857. value: record.arg,
  15858. done: context.done
  15859. };
  15860. } else if (record.type === "throw") {
  15861. state = GenStateCompleted;
  15862. // Dispatch the exception by looping back around to the
  15863. // context.dispatchException(context.arg) call above.
  15864. context.method = "throw";
  15865. context.arg = record.arg;
  15866. }
  15867. }
  15868. };
  15869. }
  15870. // Call delegate.iterator[context.method](context.arg) and handle the
  15871. // result, either by returning a { value, done } result from the
  15872. // delegate iterator, or by modifying context.method and context.arg,
  15873. // setting context.delegate to null, and returning the ContinueSentinel.
  15874. function maybeInvokeDelegate(delegate, context) {
  15875. var method = delegate.iterator[context.method];
  15876. if (method === undefined) {
  15877. // A .throw or .return when the delegate iterator has no .throw
  15878. // method always terminates the yield* loop.
  15879. context.delegate = null;
  15880. if (context.method === "throw") {
  15881. // Note: ["return"] must be used for ES3 parsing compatibility.
  15882. if (delegate.iterator["return"]) {
  15883. // If the delegate iterator has a return method, give it a
  15884. // chance to clean up.
  15885. context.method = "return";
  15886. context.arg = undefined;
  15887. maybeInvokeDelegate(delegate, context);
  15888. if (context.method === "throw") {
  15889. // If maybeInvokeDelegate(context) changed context.method from
  15890. // "return" to "throw", let that override the TypeError below.
  15891. return ContinueSentinel;
  15892. }
  15893. }
  15894. context.method = "throw";
  15895. context.arg = new TypeError(
  15896. "The iterator does not provide a 'throw' method");
  15897. }
  15898. return ContinueSentinel;
  15899. }
  15900. var record = tryCatch(method, delegate.iterator, context.arg);
  15901. if (record.type === "throw") {
  15902. context.method = "throw";
  15903. context.arg = record.arg;
  15904. context.delegate = null;
  15905. return ContinueSentinel;
  15906. }
  15907. var info = record.arg;
  15908. if (! info) {
  15909. context.method = "throw";
  15910. context.arg = new TypeError("iterator result is not an object");
  15911. context.delegate = null;
  15912. return ContinueSentinel;
  15913. }
  15914. if (info.done) {
  15915. // Assign the result of the finished delegate to the temporary
  15916. // variable specified by delegate.resultName (see delegateYield).
  15917. context[delegate.resultName] = info.value;
  15918. // Resume execution at the desired location (see delegateYield).
  15919. context.next = delegate.nextLoc;
  15920. // If context.method was "throw" but the delegate handled the
  15921. // exception, let the outer generator proceed normally. If
  15922. // context.method was "next", forget context.arg since it has been
  15923. // "consumed" by the delegate iterator. If context.method was
  15924. // "return", allow the original .return call to continue in the
  15925. // outer generator.
  15926. if (context.method !== "return") {
  15927. context.method = "next";
  15928. context.arg = undefined;
  15929. }
  15930. } else {
  15931. // Re-yield the result returned by the delegate method.
  15932. return info;
  15933. }
  15934. // The delegate iterator is finished, so forget it and continue with
  15935. // the outer generator.
  15936. context.delegate = null;
  15937. return ContinueSentinel;
  15938. }
  15939. // Define Generator.prototype.{next,throw,return} in terms of the
  15940. // unified ._invoke helper method.
  15941. defineIteratorMethods(Gp);
  15942. Gp[toStringTagSymbol] = "Generator";
  15943. // A Generator should always return itself as the iterator object when the
  15944. // @@iterator function is called on it. Some browsers' implementations of the
  15945. // iterator prototype chain incorrectly implement this, causing the Generator
  15946. // object to not be returned from this call. This ensures that doesn't happen.
  15947. // See https://github.com/facebook/regenerator/issues/274 for more details.
  15948. Gp[iteratorSymbol] = function() {
  15949. return this;
  15950. };
  15951. Gp.toString = function() {
  15952. return "[object Generator]";
  15953. };
  15954. function pushTryEntry(locs) {
  15955. var entry = { tryLoc: locs[0] };
  15956. if (1 in locs) {
  15957. entry.catchLoc = locs[1];
  15958. }
  15959. if (2 in locs) {
  15960. entry.finallyLoc = locs[2];
  15961. entry.afterLoc = locs[3];
  15962. }
  15963. this.tryEntries.push(entry);
  15964. }
  15965. function resetTryEntry(entry) {
  15966. var record = entry.completion || {};
  15967. record.type = "normal";
  15968. delete record.arg;
  15969. entry.completion = record;
  15970. }
  15971. function Context(tryLocsList) {
  15972. // The root entry object (effectively a try statement without a catch
  15973. // or a finally block) gives us a place to store values thrown from
  15974. // locations where there is no enclosing try statement.
  15975. this.tryEntries = [{ tryLoc: "root" }];
  15976. tryLocsList.forEach(pushTryEntry, this);
  15977. this.reset(true);
  15978. }
  15979. exports.keys = function(object) {
  15980. var keys = [];
  15981. for (var key in object) {
  15982. keys.push(key);
  15983. }
  15984. keys.reverse();
  15985. // Rather than returning an object with a next method, we keep
  15986. // things simple and return the next function itself.
  15987. return function next() {
  15988. while (keys.length) {
  15989. var key = keys.pop();
  15990. if (key in object) {
  15991. next.value = key;
  15992. next.done = false;
  15993. return next;
  15994. }
  15995. }
  15996. // To avoid creating an additional object, we just hang the .value
  15997. // and .done properties off the next function object itself. This
  15998. // also ensures that the minifier will not anonymize the function.
  15999. next.done = true;
  16000. return next;
  16001. };
  16002. };
  16003. function values(iterable) {
  16004. if (iterable) {
  16005. var iteratorMethod = iterable[iteratorSymbol];
  16006. if (iteratorMethod) {
  16007. return iteratorMethod.call(iterable);
  16008. }
  16009. if (typeof iterable.next === "function") {
  16010. return iterable;
  16011. }
  16012. if (!isNaN(iterable.length)) {
  16013. var i = -1, next = function next() {
  16014. while (++i < iterable.length) {
  16015. if (hasOwn.call(iterable, i)) {
  16016. next.value = iterable[i];
  16017. next.done = false;
  16018. return next;
  16019. }
  16020. }
  16021. next.value = undefined;
  16022. next.done = true;
  16023. return next;
  16024. };
  16025. return next.next = next;
  16026. }
  16027. }
  16028. // Return an iterator with no values.
  16029. return { next: doneResult };
  16030. }
  16031. exports.values = values;
  16032. function doneResult() {
  16033. return { value: undefined, done: true };
  16034. }
  16035. Context.prototype = {
  16036. constructor: Context,
  16037. reset: function(skipTempReset) {
  16038. this.prev = 0;
  16039. this.next = 0;
  16040. // Resetting context._sent for legacy support of Babel's
  16041. // function.sent implementation.
  16042. this.sent = this._sent = undefined;
  16043. this.done = false;
  16044. this.delegate = null;
  16045. this.method = "next";
  16046. this.arg = undefined;
  16047. this.tryEntries.forEach(resetTryEntry);
  16048. if (!skipTempReset) {
  16049. for (var name in this) {
  16050. // Not sure about the optimal order of these conditions:
  16051. if (name.charAt(0) === "t" &&
  16052. hasOwn.call(this, name) &&
  16053. !isNaN(+name.slice(1))) {
  16054. this[name] = undefined;
  16055. }
  16056. }
  16057. }
  16058. },
  16059. stop: function() {
  16060. this.done = true;
  16061. var rootEntry = this.tryEntries[0];
  16062. var rootRecord = rootEntry.completion;
  16063. if (rootRecord.type === "throw") {
  16064. throw rootRecord.arg;
  16065. }
  16066. return this.rval;
  16067. },
  16068. dispatchException: function(exception) {
  16069. if (this.done) {
  16070. throw exception;
  16071. }
  16072. var context = this;
  16073. function handle(loc, caught) {
  16074. record.type = "throw";
  16075. record.arg = exception;
  16076. context.next = loc;
  16077. if (caught) {
  16078. // If the dispatched exception was caught by a catch block,
  16079. // then let that catch block handle the exception normally.
  16080. context.method = "next";
  16081. context.arg = undefined;
  16082. }
  16083. return !! caught;
  16084. }
  16085. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  16086. var entry = this.tryEntries[i];
  16087. var record = entry.completion;
  16088. if (entry.tryLoc === "root") {
  16089. // Exception thrown outside of any try block that could handle
  16090. // it, so set the completion value of the entire function to
  16091. // throw the exception.
  16092. return handle("end");
  16093. }
  16094. if (entry.tryLoc <= this.prev) {
  16095. var hasCatch = hasOwn.call(entry, "catchLoc");
  16096. var hasFinally = hasOwn.call(entry, "finallyLoc");
  16097. if (hasCatch && hasFinally) {
  16098. if (this.prev < entry.catchLoc) {
  16099. return handle(entry.catchLoc, true);
  16100. } else if (this.prev < entry.finallyLoc) {
  16101. return handle(entry.finallyLoc);
  16102. }
  16103. } else if (hasCatch) {
  16104. if (this.prev < entry.catchLoc) {
  16105. return handle(entry.catchLoc, true);
  16106. }
  16107. } else if (hasFinally) {
  16108. if (this.prev < entry.finallyLoc) {
  16109. return handle(entry.finallyLoc);
  16110. }
  16111. } else {
  16112. throw new Error("try statement without catch or finally");
  16113. }
  16114. }
  16115. }
  16116. },
  16117. abrupt: function(type, arg) {
  16118. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  16119. var entry = this.tryEntries[i];
  16120. if (entry.tryLoc <= this.prev &&
  16121. hasOwn.call(entry, "finallyLoc") &&
  16122. this.prev < entry.finallyLoc) {
  16123. var finallyEntry = entry;
  16124. break;
  16125. }
  16126. }
  16127. if (finallyEntry &&
  16128. (type === "break" ||
  16129. type === "continue") &&
  16130. finallyEntry.tryLoc <= arg &&
  16131. arg <= finallyEntry.finallyLoc) {
  16132. // Ignore the finally entry if control is not jumping to a
  16133. // location outside the try/catch block.
  16134. finallyEntry = null;
  16135. }
  16136. var record = finallyEntry ? finallyEntry.completion : {};
  16137. record.type = type;
  16138. record.arg = arg;
  16139. if (finallyEntry) {
  16140. this.method = "next";
  16141. this.next = finallyEntry.finallyLoc;
  16142. return ContinueSentinel;
  16143. }
  16144. return this.complete(record);
  16145. },
  16146. complete: function(record, afterLoc) {
  16147. if (record.type === "throw") {
  16148. throw record.arg;
  16149. }
  16150. if (record.type === "break" ||
  16151. record.type === "continue") {
  16152. this.next = record.arg;
  16153. } else if (record.type === "return") {
  16154. this.rval = this.arg = record.arg;
  16155. this.method = "return";
  16156. this.next = "end";
  16157. } else if (record.type === "normal" && afterLoc) {
  16158. this.next = afterLoc;
  16159. }
  16160. return ContinueSentinel;
  16161. },
  16162. finish: function(finallyLoc) {
  16163. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  16164. var entry = this.tryEntries[i];
  16165. if (entry.finallyLoc === finallyLoc) {
  16166. this.complete(entry.completion, entry.afterLoc);
  16167. resetTryEntry(entry);
  16168. return ContinueSentinel;
  16169. }
  16170. }
  16171. },
  16172. "catch": function(tryLoc) {
  16173. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  16174. var entry = this.tryEntries[i];
  16175. if (entry.tryLoc === tryLoc) {
  16176. var record = entry.completion;
  16177. if (record.type === "throw") {
  16178. var thrown = record.arg;
  16179. resetTryEntry(entry);
  16180. }
  16181. return thrown;
  16182. }
  16183. }
  16184. // The context.catch method must only be called with a location
  16185. // argument that corresponds to a known catch block.
  16186. throw new Error("illegal catch attempt");
  16187. },
  16188. delegateYield: function(iterable, resultName, nextLoc) {
  16189. this.delegate = {
  16190. iterator: values(iterable),
  16191. resultName: resultName,
  16192. nextLoc: nextLoc
  16193. };
  16194. if (this.method === "next") {
  16195. // Deliberately forget the last sent value so that we don't
  16196. // accidentally pass it on to the delegate.
  16197. this.arg = undefined;
  16198. }
  16199. return ContinueSentinel;
  16200. }
  16201. };
  16202. // Regardless of whether this script is executing as a CommonJS module
  16203. // or not, return the runtime object so that we can declare the variable
  16204. // regeneratorRuntime in the outer scope, which allows this module to be
  16205. // injected easily by `bin/regenerator --include-runtime script.js`.
  16206. return exports;
  16207. }(
  16208. // If this script is executing as a CommonJS module, use module.exports
  16209. // as the regeneratorRuntime namespace. Otherwise create a new empty
  16210. // object. Either way, the resulting object will be used to initialize
  16211. // the regeneratorRuntime variable at the top of this file.
  16212. typeof module === "object" ? module.exports : {}
  16213. ));
  16214. try {
  16215. regeneratorRuntime = runtime;
  16216. } catch (accidentalStrictMode) {
  16217. // This module should not be running in strict mode, so the above
  16218. // assignment should always work unless something is misconfigured. Just
  16219. // in case runtime.js accidentally runs in strict mode, we can escape
  16220. // strict mode using a global Function call. This could conceivably fail
  16221. // if a Content Security Policy forbids using Function, but in that case
  16222. // the proper solution is to fix the accidental strict mode problem. If
  16223. // you've misconfigured your bundler to force strict mode and applied a
  16224. // CSP to forbid Function, and you're not willing to fix either of those
  16225. // problems, please detail your unique predicament in a GitHub issue.
  16226. Function("r", "regeneratorRuntime = r")(runtime);
  16227. }
  16228. },{}],76:[function(_dereq_,module,exports){
  16229. module.exports = _dereq_("regenerator-runtime");
  16230. },{"regenerator-runtime":75}],77:[function(_dereq_,module,exports){
  16231. },{}],78:[function(_dereq_,module,exports){
  16232. // Copyright Joyent, Inc. and other Node contributors.
  16233. //
  16234. // Permission is hereby granted, free of charge, to any person obtaining a
  16235. // copy of this software and associated documentation files (the
  16236. // "Software"), to deal in the Software without restriction, including
  16237. // without limitation the rights to use, copy, modify, merge, publish,
  16238. // distribute, sublicense, and/or sell copies of the Software, and to permit
  16239. // persons to whom the Software is furnished to do so, subject to the
  16240. // following conditions:
  16241. //
  16242. // The above copyright notice and this permission notice shall be included
  16243. // in all copies or substantial portions of the Software.
  16244. //
  16245. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16246. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16247. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  16248. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  16249. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  16250. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  16251. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  16252. var objectCreate = Object.create || objectCreatePolyfill
  16253. var objectKeys = Object.keys || objectKeysPolyfill
  16254. var bind = Function.prototype.bind || functionBindPolyfill
  16255. function EventEmitter() {
  16256. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  16257. this._events = objectCreate(null);
  16258. this._eventsCount = 0;
  16259. }
  16260. this._maxListeners = this._maxListeners || undefined;
  16261. }
  16262. module.exports = EventEmitter;
  16263. // Backwards-compat with node 0.10.x
  16264. EventEmitter.EventEmitter = EventEmitter;
  16265. EventEmitter.prototype._events = undefined;
  16266. EventEmitter.prototype._maxListeners = undefined;
  16267. // By default EventEmitters will print a warning if more than 10 listeners are
  16268. // added to it. This is a useful default which helps finding memory leaks.
  16269. var defaultMaxListeners = 10;
  16270. var hasDefineProperty;
  16271. try {
  16272. var o = {};
  16273. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  16274. hasDefineProperty = o.x === 0;
  16275. } catch (err) { hasDefineProperty = false }
  16276. if (hasDefineProperty) {
  16277. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  16278. enumerable: true,
  16279. get: function() {
  16280. return defaultMaxListeners;
  16281. },
  16282. set: function(arg) {
  16283. // check whether the input is a positive number (whose value is zero or
  16284. // greater and not a NaN).
  16285. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  16286. throw new TypeError('"defaultMaxListeners" must be a positive number');
  16287. defaultMaxListeners = arg;
  16288. }
  16289. });
  16290. } else {
  16291. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  16292. }
  16293. // Obviously not all Emitters should be limited to 10. This function allows
  16294. // that to be increased. Set to zero for unlimited.
  16295. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  16296. if (typeof n !== 'number' || n < 0 || isNaN(n))
  16297. throw new TypeError('"n" argument must be a positive number');
  16298. this._maxListeners = n;
  16299. return this;
  16300. };
  16301. function $getMaxListeners(that) {
  16302. if (that._maxListeners === undefined)
  16303. return EventEmitter.defaultMaxListeners;
  16304. return that._maxListeners;
  16305. }
  16306. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  16307. return $getMaxListeners(this);
  16308. };
  16309. // These standalone emit* functions are used to optimize calling of event
  16310. // handlers for fast cases because emit() itself often has a variable number of
  16311. // arguments and can be deoptimized because of that. These functions always have
  16312. // the same number of arguments and thus do not get deoptimized, so the code
  16313. // inside them can execute faster.
  16314. function emitNone(handler, isFn, self) {
  16315. if (isFn)
  16316. handler.call(self);
  16317. else {
  16318. var len = handler.length;
  16319. var listeners = arrayClone(handler, len);
  16320. for (var i = 0; i < len; ++i)
  16321. listeners[i].call(self);
  16322. }
  16323. }
  16324. function emitOne(handler, isFn, self, arg1) {
  16325. if (isFn)
  16326. handler.call(self, arg1);
  16327. else {
  16328. var len = handler.length;
  16329. var listeners = arrayClone(handler, len);
  16330. for (var i = 0; i < len; ++i)
  16331. listeners[i].call(self, arg1);
  16332. }
  16333. }
  16334. function emitTwo(handler, isFn, self, arg1, arg2) {
  16335. if (isFn)
  16336. handler.call(self, arg1, arg2);
  16337. else {
  16338. var len = handler.length;
  16339. var listeners = arrayClone(handler, len);
  16340. for (var i = 0; i < len; ++i)
  16341. listeners[i].call(self, arg1, arg2);
  16342. }
  16343. }
  16344. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  16345. if (isFn)
  16346. handler.call(self, arg1, arg2, arg3);
  16347. else {
  16348. var len = handler.length;
  16349. var listeners = arrayClone(handler, len);
  16350. for (var i = 0; i < len; ++i)
  16351. listeners[i].call(self, arg1, arg2, arg3);
  16352. }
  16353. }
  16354. function emitMany(handler, isFn, self, args) {
  16355. if (isFn)
  16356. handler.apply(self, args);
  16357. else {
  16358. var len = handler.length;
  16359. var listeners = arrayClone(handler, len);
  16360. for (var i = 0; i < len; ++i)
  16361. listeners[i].apply(self, args);
  16362. }
  16363. }
  16364. EventEmitter.prototype.emit = function emit(type) {
  16365. var er, handler, len, args, i, events;
  16366. var doError = (type === 'error');
  16367. events = this._events;
  16368. if (events)
  16369. doError = (doError && events.error == null);
  16370. else if (!doError)
  16371. return false;
  16372. // If there is no 'error' event listener then throw.
  16373. if (doError) {
  16374. if (arguments.length > 1)
  16375. er = arguments[1];
  16376. if (er instanceof Error) {
  16377. throw er; // Unhandled 'error' event
  16378. } else {
  16379. // At least give some kind of context to the user
  16380. var err = new Error('Unhandled "error" event. (' + er + ')');
  16381. err.context = er;
  16382. throw err;
  16383. }
  16384. return false;
  16385. }
  16386. handler = events[type];
  16387. if (!handler)
  16388. return false;
  16389. var isFn = typeof handler === 'function';
  16390. len = arguments.length;
  16391. switch (len) {
  16392. // fast cases
  16393. case 1:
  16394. emitNone(handler, isFn, this);
  16395. break;
  16396. case 2:
  16397. emitOne(handler, isFn, this, arguments[1]);
  16398. break;
  16399. case 3:
  16400. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  16401. break;
  16402. case 4:
  16403. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  16404. break;
  16405. // slower
  16406. default:
  16407. args = new Array(len - 1);
  16408. for (i = 1; i < len; i++)
  16409. args[i - 1] = arguments[i];
  16410. emitMany(handler, isFn, this, args);
  16411. }
  16412. return true;
  16413. };
  16414. function _addListener(target, type, listener, prepend) {
  16415. var m;
  16416. var events;
  16417. var existing;
  16418. if (typeof listener !== 'function')
  16419. throw new TypeError('"listener" argument must be a function');
  16420. events = target._events;
  16421. if (!events) {
  16422. events = target._events = objectCreate(null);
  16423. target._eventsCount = 0;
  16424. } else {
  16425. // To avoid recursion in the case that type === "newListener"! Before
  16426. // adding it to the listeners, first emit "newListener".
  16427. if (events.newListener) {
  16428. target.emit('newListener', type,
  16429. listener.listener ? listener.listener : listener);
  16430. // Re-assign `events` because a newListener handler could have caused the
  16431. // this._events to be assigned to a new object
  16432. events = target._events;
  16433. }
  16434. existing = events[type];
  16435. }
  16436. if (!existing) {
  16437. // Optimize the case of one listener. Don't need the extra array object.
  16438. existing = events[type] = listener;
  16439. ++target._eventsCount;
  16440. } else {
  16441. if (typeof existing === 'function') {
  16442. // Adding the second element, need to change to array.
  16443. existing = events[type] =
  16444. prepend ? [listener, existing] : [existing, listener];
  16445. } else {
  16446. // If we've already got an array, just append.
  16447. if (prepend) {
  16448. existing.unshift(listener);
  16449. } else {
  16450. existing.push(listener);
  16451. }
  16452. }
  16453. // Check for listener leak
  16454. if (!existing.warned) {
  16455. m = $getMaxListeners(target);
  16456. if (m && m > 0 && existing.length > m) {
  16457. existing.warned = true;
  16458. var w = new Error('Possible EventEmitter memory leak detected. ' +
  16459. existing.length + ' "' + String(type) + '" listeners ' +
  16460. 'added. Use emitter.setMaxListeners() to ' +
  16461. 'increase limit.');
  16462. w.name = 'MaxListenersExceededWarning';
  16463. w.emitter = target;
  16464. w.type = type;
  16465. w.count = existing.length;
  16466. if (typeof console === 'object' && console.warn) {
  16467. console.warn('%s: %s', w.name, w.message);
  16468. }
  16469. }
  16470. }
  16471. }
  16472. return target;
  16473. }
  16474. EventEmitter.prototype.addListener = function addListener(type, listener) {
  16475. return _addListener(this, type, listener, false);
  16476. };
  16477. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  16478. EventEmitter.prototype.prependListener =
  16479. function prependListener(type, listener) {
  16480. return _addListener(this, type, listener, true);
  16481. };
  16482. function onceWrapper() {
  16483. if (!this.fired) {
  16484. this.target.removeListener(this.type, this.wrapFn);
  16485. this.fired = true;
  16486. switch (arguments.length) {
  16487. case 0:
  16488. return this.listener.call(this.target);
  16489. case 1:
  16490. return this.listener.call(this.target, arguments[0]);
  16491. case 2:
  16492. return this.listener.call(this.target, arguments[0], arguments[1]);
  16493. case 3:
  16494. return this.listener.call(this.target, arguments[0], arguments[1],
  16495. arguments[2]);
  16496. default:
  16497. var args = new Array(arguments.length);
  16498. for (var i = 0; i < args.length; ++i)
  16499. args[i] = arguments[i];
  16500. this.listener.apply(this.target, args);
  16501. }
  16502. }
  16503. }
  16504. function _onceWrap(target, type, listener) {
  16505. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  16506. var wrapped = bind.call(onceWrapper, state);
  16507. wrapped.listener = listener;
  16508. state.wrapFn = wrapped;
  16509. return wrapped;
  16510. }
  16511. EventEmitter.prototype.once = function once(type, listener) {
  16512. if (typeof listener !== 'function')
  16513. throw new TypeError('"listener" argument must be a function');
  16514. this.on(type, _onceWrap(this, type, listener));
  16515. return this;
  16516. };
  16517. EventEmitter.prototype.prependOnceListener =
  16518. function prependOnceListener(type, listener) {
  16519. if (typeof listener !== 'function')
  16520. throw new TypeError('"listener" argument must be a function');
  16521. this.prependListener(type, _onceWrap(this, type, listener));
  16522. return this;
  16523. };
  16524. // Emits a 'removeListener' event if and only if the listener was removed.
  16525. EventEmitter.prototype.removeListener =
  16526. function removeListener(type, listener) {
  16527. var list, events, position, i, originalListener;
  16528. if (typeof listener !== 'function')
  16529. throw new TypeError('"listener" argument must be a function');
  16530. events = this._events;
  16531. if (!events)
  16532. return this;
  16533. list = events[type];
  16534. if (!list)
  16535. return this;
  16536. if (list === listener || list.listener === listener) {
  16537. if (--this._eventsCount === 0)
  16538. this._events = objectCreate(null);
  16539. else {
  16540. delete events[type];
  16541. if (events.removeListener)
  16542. this.emit('removeListener', type, list.listener || listener);
  16543. }
  16544. } else if (typeof list !== 'function') {
  16545. position = -1;
  16546. for (i = list.length - 1; i >= 0; i--) {
  16547. if (list[i] === listener || list[i].listener === listener) {
  16548. originalListener = list[i].listener;
  16549. position = i;
  16550. break;
  16551. }
  16552. }
  16553. if (position < 0)
  16554. return this;
  16555. if (position === 0)
  16556. list.shift();
  16557. else
  16558. spliceOne(list, position);
  16559. if (list.length === 1)
  16560. events[type] = list[0];
  16561. if (events.removeListener)
  16562. this.emit('removeListener', type, originalListener || listener);
  16563. }
  16564. return this;
  16565. };
  16566. EventEmitter.prototype.removeAllListeners =
  16567. function removeAllListeners(type) {
  16568. var listeners, events, i;
  16569. events = this._events;
  16570. if (!events)
  16571. return this;
  16572. // not listening for removeListener, no need to emit
  16573. if (!events.removeListener) {
  16574. if (arguments.length === 0) {
  16575. this._events = objectCreate(null);
  16576. this._eventsCount = 0;
  16577. } else if (events[type]) {
  16578. if (--this._eventsCount === 0)
  16579. this._events = objectCreate(null);
  16580. else
  16581. delete events[type];
  16582. }
  16583. return this;
  16584. }
  16585. // emit removeListener for all listeners on all events
  16586. if (arguments.length === 0) {
  16587. var keys = objectKeys(events);
  16588. var key;
  16589. for (i = 0; i < keys.length; ++i) {
  16590. key = keys[i];
  16591. if (key === 'removeListener') continue;
  16592. this.removeAllListeners(key);
  16593. }
  16594. this.removeAllListeners('removeListener');
  16595. this._events = objectCreate(null);
  16596. this._eventsCount = 0;
  16597. return this;
  16598. }
  16599. listeners = events[type];
  16600. if (typeof listeners === 'function') {
  16601. this.removeListener(type, listeners);
  16602. } else if (listeners) {
  16603. // LIFO order
  16604. for (i = listeners.length - 1; i >= 0; i--) {
  16605. this.removeListener(type, listeners[i]);
  16606. }
  16607. }
  16608. return this;
  16609. };
  16610. function _listeners(target, type, unwrap) {
  16611. var events = target._events;
  16612. if (!events)
  16613. return [];
  16614. var evlistener = events[type];
  16615. if (!evlistener)
  16616. return [];
  16617. if (typeof evlistener === 'function')
  16618. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  16619. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  16620. }
  16621. EventEmitter.prototype.listeners = function listeners(type) {
  16622. return _listeners(this, type, true);
  16623. };
  16624. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  16625. return _listeners(this, type, false);
  16626. };
  16627. EventEmitter.listenerCount = function(emitter, type) {
  16628. if (typeof emitter.listenerCount === 'function') {
  16629. return emitter.listenerCount(type);
  16630. } else {
  16631. return listenerCount.call(emitter, type);
  16632. }
  16633. };
  16634. EventEmitter.prototype.listenerCount = listenerCount;
  16635. function listenerCount(type) {
  16636. var events = this._events;
  16637. if (events) {
  16638. var evlistener = events[type];
  16639. if (typeof evlistener === 'function') {
  16640. return 1;
  16641. } else if (evlistener) {
  16642. return evlistener.length;
  16643. }
  16644. }
  16645. return 0;
  16646. }
  16647. EventEmitter.prototype.eventNames = function eventNames() {
  16648. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  16649. };
  16650. // About 1.5x faster than the two-arg version of Array#splice().
  16651. function spliceOne(list, index) {
  16652. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  16653. list[i] = list[k];
  16654. list.pop();
  16655. }
  16656. function arrayClone(arr, n) {
  16657. var copy = new Array(n);
  16658. for (var i = 0; i < n; ++i)
  16659. copy[i] = arr[i];
  16660. return copy;
  16661. }
  16662. function unwrapListeners(arr) {
  16663. var ret = new Array(arr.length);
  16664. for (var i = 0; i < ret.length; ++i) {
  16665. ret[i] = arr[i].listener || arr[i];
  16666. }
  16667. return ret;
  16668. }
  16669. function objectCreatePolyfill(proto) {
  16670. var F = function() {};
  16671. F.prototype = proto;
  16672. return new F;
  16673. }
  16674. function objectKeysPolyfill(obj) {
  16675. var keys = [];
  16676. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  16677. keys.push(k);
  16678. }
  16679. return k;
  16680. }
  16681. function functionBindPolyfill(context) {
  16682. var fn = this;
  16683. return function () {
  16684. return fn.apply(context, arguments);
  16685. };
  16686. }
  16687. },{}],79:[function(_dereq_,module,exports){
  16688. /**
  16689. * Convert array of 16 byte values to UUID string format of the form:
  16690. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  16691. */
  16692. var byteToHex = [];
  16693. for (var i = 0; i < 256; ++i) {
  16694. byteToHex[i] = (i + 0x100).toString(16).substr(1);
  16695. }
  16696. function bytesToUuid(buf, offset) {
  16697. var i = offset || 0;
  16698. var bth = byteToHex;
  16699. // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
  16700. return ([bth[buf[i++]], bth[buf[i++]],
  16701. bth[buf[i++]], bth[buf[i++]], '-',
  16702. bth[buf[i++]], bth[buf[i++]], '-',
  16703. bth[buf[i++]], bth[buf[i++]], '-',
  16704. bth[buf[i++]], bth[buf[i++]], '-',
  16705. bth[buf[i++]], bth[buf[i++]],
  16706. bth[buf[i++]], bth[buf[i++]],
  16707. bth[buf[i++]], bth[buf[i++]]]).join('');
  16708. }
  16709. module.exports = bytesToUuid;
  16710. },{}],80:[function(_dereq_,module,exports){
  16711. // Unique ID creation requires a high quality random # generator. In the
  16712. // browser this is a little complicated due to unknown quality of Math.random()
  16713. // and inconsistent support for the `crypto` API. We do the best we can via
  16714. // feature-detection
  16715. // getRandomValues needs to be invoked in a context where "this" is a Crypto
  16716. // implementation. Also, find the complete implementation of crypto on IE11.
  16717. var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
  16718. (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
  16719. if (getRandomValues) {
  16720. // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
  16721. var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
  16722. module.exports = function whatwgRNG() {
  16723. getRandomValues(rnds8);
  16724. return rnds8;
  16725. };
  16726. } else {
  16727. // Math.random()-based (RNG)
  16728. //
  16729. // If all else fails, use Math.random(). It's fast, but is of unspecified
  16730. // quality.
  16731. var rnds = new Array(16);
  16732. module.exports = function mathRNG() {
  16733. for (var i = 0, r; i < 16; i++) {
  16734. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  16735. rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  16736. }
  16737. return rnds;
  16738. };
  16739. }
  16740. },{}],81:[function(_dereq_,module,exports){
  16741. var rng = _dereq_('./lib/rng');
  16742. var bytesToUuid = _dereq_('./lib/bytesToUuid');
  16743. function v4(options, buf, offset) {
  16744. var i = buf && offset || 0;
  16745. if (typeof(options) == 'string') {
  16746. buf = options === 'binary' ? new Array(16) : null;
  16747. options = null;
  16748. }
  16749. options = options || {};
  16750. var rnds = options.random || (options.rng || rng)();
  16751. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  16752. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  16753. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  16754. // Copy bytes to buffer, if provided
  16755. if (buf) {
  16756. for (var ii = 0; ii < 16; ++ii) {
  16757. buf[i + ii] = rnds[ii];
  16758. }
  16759. }
  16760. return buf || bytesToUuid(rnds);
  16761. }
  16762. module.exports = v4;
  16763. },{"./lib/bytesToUuid":79,"./lib/rng":80}]},{},[15])(15)
  16764. });