parse.weapp.js 553 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867
  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":63}],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":63,"uuid/v4":83}],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":43,"./encode":44,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],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":79}],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":80}],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":63}],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":36,"@babel/runtime/helpers/interopRequireDefault":63}],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(_dereq_('./Socket.weapp'));
  1625. var _default = LiveQueryClient;
  1626. exports.default = _default;
  1627. },{"./CoreManager":4,"./EventEmitter":5,"./LiveQuerySubscription":9,"./ParseObject":23,"./Socket.weapp":35,"./promiseUtils":49,"@babel/runtime/helpers/assertThisInitialized":54,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/getPrototypeOf":61,"@babel/runtime/helpers/inherits":62,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/possibleConstructorReturn":70,"@babel/runtime/helpers/typeof":75}],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":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/getPrototypeOf":61,"@babel/runtime/helpers/inherits":62,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/possibleConstructorReturn":70}],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.weapp'));
  2553. _CoreManager.default.setLocalDatastore(LocalDatastore);
  2554. },{"./CoreManager":4,"./LocalDatastoreController.weapp":11,"./LocalDatastoreUtils":12,"./ParseQuery":26,"@babel/runtime/helpers/asyncToGenerator":55,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/slicedToArray":72,"@babel/runtime/helpers/toConsumableArray":74,"@babel/runtime/regenerator":78}],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. var LocalDatastoreController = {
  2568. fromPinWithName: function (name
  2569. /*: string*/
  2570. )
  2571. /*: Array<Object>*/
  2572. {
  2573. var values = wx.getStorageSync(name);
  2574. if (!values) {
  2575. return [];
  2576. }
  2577. return values;
  2578. },
  2579. pinWithName: function (name
  2580. /*: string*/
  2581. , value
  2582. /*: any*/
  2583. ) {
  2584. try {
  2585. wx.setStorageSync(name, value);
  2586. } catch (e) {// Quota exceeded
  2587. }
  2588. },
  2589. unPinWithName: function (name
  2590. /*: string*/
  2591. ) {
  2592. wx.removeStorageSync(name);
  2593. },
  2594. getAllContents: function ()
  2595. /*: Object*/
  2596. {
  2597. var res = wx.getStorageInfoSync();
  2598. var keys = res.keys;
  2599. var LDS = {};
  2600. var _iteratorNormalCompletion = true;
  2601. var _didIteratorError = false;
  2602. var _iteratorError = undefined;
  2603. try {
  2604. for (var _iterator = keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  2605. var key = _step.value;
  2606. if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
  2607. LDS[key] = wx.getStorageSync(key);
  2608. }
  2609. }
  2610. } catch (err) {
  2611. _didIteratorError = true;
  2612. _iteratorError = err;
  2613. } finally {
  2614. try {
  2615. if (!_iteratorNormalCompletion && _iterator.return != null) {
  2616. _iterator.return();
  2617. }
  2618. } finally {
  2619. if (_didIteratorError) {
  2620. throw _iteratorError;
  2621. }
  2622. }
  2623. }
  2624. return LDS;
  2625. },
  2626. getRawStorage: function ()
  2627. /*: Object*/
  2628. {
  2629. var res = wx.getStorageInfoSync();
  2630. var keys = res.keys;
  2631. var storage = {};
  2632. var _iteratorNormalCompletion2 = true;
  2633. var _didIteratorError2 = false;
  2634. var _iteratorError2 = undefined;
  2635. try {
  2636. for (var _iterator2 = keys[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  2637. var key = _step2.value;
  2638. storage[key] = wx.getStorageSync(key);
  2639. }
  2640. } catch (err) {
  2641. _didIteratorError2 = true;
  2642. _iteratorError2 = err;
  2643. } finally {
  2644. try {
  2645. if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
  2646. _iterator2.return();
  2647. }
  2648. } finally {
  2649. if (_didIteratorError2) {
  2650. throw _iteratorError2;
  2651. }
  2652. }
  2653. }
  2654. return storage;
  2655. },
  2656. clear: function ()
  2657. /*: Promise*/
  2658. {
  2659. var res = wx.getStorageInfoSync();
  2660. var keys = res.keys;
  2661. var toRemove = [];
  2662. var _iteratorNormalCompletion3 = true;
  2663. var _didIteratorError3 = false;
  2664. var _iteratorError3 = undefined;
  2665. try {
  2666. for (var _iterator3 = keys[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
  2667. var key = _step3.value;
  2668. if ((0, _LocalDatastoreUtils.isLocalDatastoreKey)(key)) {
  2669. toRemove.push(key);
  2670. }
  2671. }
  2672. } catch (err) {
  2673. _didIteratorError3 = true;
  2674. _iteratorError3 = err;
  2675. } finally {
  2676. try {
  2677. if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
  2678. _iterator3.return();
  2679. }
  2680. } finally {
  2681. if (_didIteratorError3) {
  2682. throw _iteratorError3;
  2683. }
  2684. }
  2685. }
  2686. var promises = toRemove.map(this.unPinWithName);
  2687. return Promise.all(promises);
  2688. }
  2689. };
  2690. module.exports = LocalDatastoreController;
  2691. },{"./LocalDatastoreUtils":12}],12:[function(_dereq_,module,exports){
  2692. "use strict";
  2693. Object.defineProperty(exports, "__esModule", {
  2694. value: true
  2695. });
  2696. exports.isLocalDatastoreKey = isLocalDatastoreKey;
  2697. exports.OBJECT_PREFIX = exports.PIN_PREFIX = exports.DEFAULT_PIN = void 0;
  2698. /**
  2699. * Copyright (c) 2015-present, Parse, LLC.
  2700. * All rights reserved.
  2701. *
  2702. * This source code is licensed under the BSD-style license found in the
  2703. * LICENSE file in the root directory of this source tree. An additional grant
  2704. * of patent rights can be found in the PATENTS file in the same directory.
  2705. *
  2706. * @flow
  2707. */
  2708. var DEFAULT_PIN = '_default';
  2709. exports.DEFAULT_PIN = DEFAULT_PIN;
  2710. var PIN_PREFIX = 'parsePin_';
  2711. exports.PIN_PREFIX = PIN_PREFIX;
  2712. var OBJECT_PREFIX = 'Parse_LDS_';
  2713. exports.OBJECT_PREFIX = OBJECT_PREFIX;
  2714. function isLocalDatastoreKey(key
  2715. /*: string*/
  2716. )
  2717. /*: boolean*/
  2718. {
  2719. return !!(key && (key === DEFAULT_PIN || key.startsWith(PIN_PREFIX) || key.startsWith(OBJECT_PREFIX)));
  2720. }
  2721. },{}],13:[function(_dereq_,module,exports){
  2722. "use strict";
  2723. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  2724. Object.defineProperty(exports, "__esModule", {
  2725. value: true
  2726. });
  2727. exports.defaultState = defaultState;
  2728. exports.setServerData = setServerData;
  2729. exports.setPendingOp = setPendingOp;
  2730. exports.pushPendingState = pushPendingState;
  2731. exports.popPendingState = popPendingState;
  2732. exports.mergeFirstPendingState = mergeFirstPendingState;
  2733. exports.estimateAttribute = estimateAttribute;
  2734. exports.estimateAttributes = estimateAttributes;
  2735. exports.commitServerChanges = commitServerChanges;
  2736. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  2737. var _encode = _interopRequireDefault(_dereq_("./encode"));
  2738. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  2739. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  2740. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  2741. var _TaskQueue = _interopRequireDefault(_dereq_("./TaskQueue"));
  2742. var _ParseOp = _dereq_("./ParseOp");
  2743. /**
  2744. * Copyright (c) 2015-present, Parse, LLC.
  2745. * All rights reserved.
  2746. *
  2747. * This source code is licensed under the BSD-style license found in the
  2748. * LICENSE file in the root directory of this source tree. An additional grant
  2749. * of patent rights can be found in the PATENTS file in the same directory.
  2750. *
  2751. * @flow
  2752. */
  2753. function defaultState()
  2754. /*: State*/
  2755. {
  2756. return {
  2757. serverData: {},
  2758. pendingOps: [{}],
  2759. objectCache: {},
  2760. tasks: new _TaskQueue.default(),
  2761. existed: false
  2762. };
  2763. }
  2764. function setServerData(serverData
  2765. /*: AttributeMap*/
  2766. , attributes
  2767. /*: AttributeMap*/
  2768. ) {
  2769. for (var _attr in attributes) {
  2770. if (typeof attributes[_attr] !== 'undefined') {
  2771. serverData[_attr] = attributes[_attr];
  2772. } else {
  2773. delete serverData[_attr];
  2774. }
  2775. }
  2776. }
  2777. function setPendingOp(pendingOps
  2778. /*: Array<OpsMap>*/
  2779. , attr
  2780. /*: string*/
  2781. , op
  2782. /*: ?Op*/
  2783. ) {
  2784. var last = pendingOps.length - 1;
  2785. if (op) {
  2786. pendingOps[last][attr] = op;
  2787. } else {
  2788. delete pendingOps[last][attr];
  2789. }
  2790. }
  2791. function pushPendingState(pendingOps
  2792. /*: Array<OpsMap>*/
  2793. ) {
  2794. pendingOps.push({});
  2795. }
  2796. function popPendingState(pendingOps
  2797. /*: Array<OpsMap>*/
  2798. )
  2799. /*: OpsMap*/
  2800. {
  2801. var first = pendingOps.shift();
  2802. if (!pendingOps.length) {
  2803. pendingOps[0] = {};
  2804. }
  2805. return first;
  2806. }
  2807. function mergeFirstPendingState(pendingOps
  2808. /*: Array<OpsMap>*/
  2809. ) {
  2810. var first = popPendingState(pendingOps);
  2811. var next = pendingOps[0];
  2812. for (var _attr2 in first) {
  2813. if (next[_attr2] && first[_attr2]) {
  2814. var merged = next[_attr2].mergeWith(first[_attr2]);
  2815. if (merged) {
  2816. next[_attr2] = merged;
  2817. }
  2818. } else {
  2819. next[_attr2] = first[_attr2];
  2820. }
  2821. }
  2822. }
  2823. function estimateAttribute(serverData
  2824. /*: AttributeMap*/
  2825. , pendingOps
  2826. /*: Array<OpsMap>*/
  2827. , className
  2828. /*: string*/
  2829. , id
  2830. /*: ?string*/
  2831. , attr
  2832. /*: string*/
  2833. )
  2834. /*: mixed*/
  2835. {
  2836. var value = serverData[attr];
  2837. for (var i = 0; i < pendingOps.length; i++) {
  2838. if (pendingOps[i][attr]) {
  2839. if (pendingOps[i][attr] instanceof _ParseOp.RelationOp) {
  2840. if (id) {
  2841. value = pendingOps[i][attr].applyTo(value, {
  2842. className: className,
  2843. id: id
  2844. }, attr);
  2845. }
  2846. } else {
  2847. value = pendingOps[i][attr].applyTo(value);
  2848. }
  2849. }
  2850. }
  2851. return value;
  2852. }
  2853. function estimateAttributes(serverData
  2854. /*: AttributeMap*/
  2855. , pendingOps
  2856. /*: Array<OpsMap>*/
  2857. , className
  2858. /*: string*/
  2859. , id
  2860. /*: ?string*/
  2861. )
  2862. /*: AttributeMap*/
  2863. {
  2864. var data = {};
  2865. for (var attr in serverData) {
  2866. data[attr] = serverData[attr];
  2867. }
  2868. for (var i = 0; i < pendingOps.length; i++) {
  2869. for (attr in pendingOps[i]) {
  2870. if (pendingOps[i][attr] instanceof _ParseOp.RelationOp) {
  2871. if (id) {
  2872. data[attr] = pendingOps[i][attr].applyTo(data[attr], {
  2873. className: className,
  2874. id: id
  2875. }, attr);
  2876. }
  2877. } else {
  2878. if (attr.includes('.')) {
  2879. // convert a.b.c into { a: { b: { c: value } } }
  2880. var fields = attr.split('.');
  2881. var last = fields[fields.length - 1];
  2882. var object = Object.assign({}, data);
  2883. for (var _i = 0; _i < fields.length - 1; _i++) {
  2884. object = object[fields[_i]];
  2885. }
  2886. object[last] = pendingOps[i][attr].applyTo(object[last]);
  2887. } else {
  2888. data[attr] = pendingOps[i][attr].applyTo(data[attr]);
  2889. }
  2890. }
  2891. }
  2892. }
  2893. return data;
  2894. }
  2895. function commitServerChanges(serverData
  2896. /*: AttributeMap*/
  2897. , objectCache
  2898. /*: ObjectCache*/
  2899. , changes
  2900. /*: AttributeMap*/
  2901. ) {
  2902. for (var _attr3 in changes) {
  2903. var val = changes[_attr3];
  2904. serverData[_attr3] = val;
  2905. if (val && (0, _typeof2.default)(val) === 'object' && !(val instanceof _ParseObject.default) && !(val instanceof _ParseFile.default) && !(val instanceof _ParseRelation.default)) {
  2906. var json = (0, _encode.default)(val, false, true);
  2907. objectCache[_attr3] = JSON.stringify(json);
  2908. }
  2909. }
  2910. }
  2911. },{"./ParseFile":19,"./ParseObject":23,"./ParseOp":24,"./ParseRelation":27,"./TaskQueue":38,"./encode":44,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],14:[function(_dereq_,module,exports){
  2912. "use strict";
  2913. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  2914. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  2915. var equalObjects = _dereq_('./equals').default;
  2916. var decode = _dereq_('./decode').default;
  2917. var ParseError = _dereq_('./ParseError').default;
  2918. var ParsePolygon = _dereq_('./ParsePolygon').default;
  2919. var ParseGeoPoint = _dereq_('./ParseGeoPoint').default;
  2920. /**
  2921. * contains -- Determines if an object is contained in a list with special handling for Parse pointers.
  2922. */
  2923. function contains(haystack, needle) {
  2924. if (needle && needle.__type && (needle.__type === 'Pointer' || needle.__type === 'Object')) {
  2925. for (var i in haystack) {
  2926. var ptr = haystack[i];
  2927. if (typeof ptr === 'string' && ptr === needle.objectId) {
  2928. return true;
  2929. }
  2930. if (ptr.className === needle.className && ptr.objectId === needle.objectId) {
  2931. return true;
  2932. }
  2933. }
  2934. return false;
  2935. }
  2936. return haystack.indexOf(needle) > -1;
  2937. }
  2938. function transformObject(object) {
  2939. if (object._toFullJSON) {
  2940. return object._toFullJSON();
  2941. }
  2942. return object;
  2943. }
  2944. /**
  2945. * matchesQuery -- Determines if an object would be returned by a Parse Query
  2946. * It's a lightweight, where-clause only implementation of a full query engine.
  2947. * Since we find queries that match objects, rather than objects that match
  2948. * queries, we can avoid building a full-blown query tool.
  2949. */
  2950. function matchesQuery(className, object, objects, query) {
  2951. if (object.className !== className) {
  2952. return false;
  2953. }
  2954. var obj = object;
  2955. var q = query;
  2956. if (object.toJSON) {
  2957. obj = object.toJSON();
  2958. }
  2959. if (query.toJSON) {
  2960. q = query.toJSON().where;
  2961. }
  2962. obj.className = className;
  2963. for (var field in q) {
  2964. if (!matchesKeyConstraints(className, obj, objects, field, q[field])) {
  2965. return false;
  2966. }
  2967. }
  2968. return true;
  2969. }
  2970. function equalObjectsGeneric(obj, compareTo, eqlFn) {
  2971. if (Array.isArray(obj)) {
  2972. for (var i = 0; i < obj.length; i++) {
  2973. if (eqlFn(obj[i], compareTo)) {
  2974. return true;
  2975. }
  2976. }
  2977. return false;
  2978. }
  2979. return eqlFn(obj, compareTo);
  2980. }
  2981. /**
  2982. * Determines whether an object matches a single key's constraints
  2983. */
  2984. function matchesKeyConstraints(className, object, objects, key, constraints) {
  2985. if (constraints === null) {
  2986. return false;
  2987. }
  2988. if (key.indexOf('.') >= 0) {
  2989. // Key references a subobject
  2990. var keyComponents = key.split('.');
  2991. var subObjectKey = keyComponents[0];
  2992. var keyRemainder = keyComponents.slice(1).join('.');
  2993. return matchesKeyConstraints(className, object[subObjectKey] || {}, objects, keyRemainder, constraints);
  2994. }
  2995. var i;
  2996. if (key === '$or') {
  2997. for (i = 0; i < constraints.length; i++) {
  2998. if (matchesQuery(className, object, objects, constraints[i])) {
  2999. return true;
  3000. }
  3001. }
  3002. return false;
  3003. }
  3004. if (key === '$and') {
  3005. for (i = 0; i < constraints.length; i++) {
  3006. if (!matchesQuery(className, object, objects, constraints[i])) {
  3007. return false;
  3008. }
  3009. }
  3010. return true;
  3011. }
  3012. if (key === '$nor') {
  3013. for (i = 0; i < constraints.length; i++) {
  3014. if (matchesQuery(className, object, objects, constraints[i])) {
  3015. return false;
  3016. }
  3017. }
  3018. return true;
  3019. }
  3020. if (key === '$relatedTo') {
  3021. // Bail! We can't handle relational queries locally
  3022. return false;
  3023. }
  3024. if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(key)) {
  3025. throw new ParseError(ParseError.INVALID_KEY_NAME, "Invalid Key: ".concat(key));
  3026. } // Equality (or Array contains) cases
  3027. if ((0, _typeof2.default)(constraints) !== 'object') {
  3028. if (Array.isArray(object[key])) {
  3029. return object[key].indexOf(constraints) > -1;
  3030. }
  3031. return object[key] === constraints;
  3032. }
  3033. var compareTo;
  3034. if (constraints.__type) {
  3035. if (constraints.__type === 'Pointer') {
  3036. return equalObjectsGeneric(object[key], constraints, function (obj, ptr) {
  3037. return typeof obj !== 'undefined' && ptr.className === obj.className && ptr.objectId === obj.objectId;
  3038. });
  3039. }
  3040. return equalObjectsGeneric(decode(object[key]), decode(constraints), equalObjects);
  3041. } // More complex cases
  3042. for (var condition in constraints) {
  3043. compareTo = constraints[condition];
  3044. if (compareTo.__type) {
  3045. compareTo = decode(compareTo);
  3046. } // Compare Date Object or Date String
  3047. if (toString.call(compareTo) === '[object Date]' || typeof compareTo === 'string' && new Date(compareTo) !== 'Invalid Date' && !isNaN(new Date(compareTo))) {
  3048. object[key] = new Date(object[key].iso ? object[key].iso : object[key]);
  3049. }
  3050. switch (condition) {
  3051. case '$lt':
  3052. if (object[key] >= compareTo) {
  3053. return false;
  3054. }
  3055. break;
  3056. case '$lte':
  3057. if (object[key] > compareTo) {
  3058. return false;
  3059. }
  3060. break;
  3061. case '$gt':
  3062. if (object[key] <= compareTo) {
  3063. return false;
  3064. }
  3065. break;
  3066. case '$gte':
  3067. if (object[key] < compareTo) {
  3068. return false;
  3069. }
  3070. break;
  3071. case '$ne':
  3072. if (equalObjects(object[key], compareTo)) {
  3073. return false;
  3074. }
  3075. break;
  3076. case '$in':
  3077. if (!contains(compareTo, object[key])) {
  3078. return false;
  3079. }
  3080. break;
  3081. case '$nin':
  3082. if (contains(compareTo, object[key])) {
  3083. return false;
  3084. }
  3085. break;
  3086. case '$all':
  3087. for (i = 0; i < compareTo.length; i++) {
  3088. if (object[key].indexOf(compareTo[i]) < 0) {
  3089. return false;
  3090. }
  3091. }
  3092. break;
  3093. case '$exists':
  3094. {
  3095. var propertyExists = typeof object[key] !== 'undefined';
  3096. var existenceIsRequired = constraints['$exists'];
  3097. if (typeof constraints['$exists'] !== 'boolean') {
  3098. // The SDK will never submit a non-boolean for $exists, but if someone
  3099. // tries to submit a non-boolean for $exits outside the SDKs, just ignore it.
  3100. break;
  3101. }
  3102. if (!propertyExists && existenceIsRequired || propertyExists && !existenceIsRequired) {
  3103. return false;
  3104. }
  3105. break;
  3106. }
  3107. case '$regex':
  3108. {
  3109. if ((0, _typeof2.default)(compareTo) === 'object') {
  3110. return compareTo.test(object[key]);
  3111. } // JS doesn't support perl-style escaping
  3112. var expString = '';
  3113. var escapeEnd = -2;
  3114. var escapeStart = compareTo.indexOf('\\Q');
  3115. while (escapeStart > -1) {
  3116. // Add the unescaped portion
  3117. expString += compareTo.substring(escapeEnd + 2, escapeStart);
  3118. escapeEnd = compareTo.indexOf('\\E', escapeStart);
  3119. if (escapeEnd > -1) {
  3120. expString += compareTo.substring(escapeStart + 2, escapeEnd).replace(/\\\\\\\\E/g, '\\E').replace(/\W/g, '\\$&');
  3121. }
  3122. escapeStart = compareTo.indexOf('\\Q', escapeEnd);
  3123. }
  3124. expString += compareTo.substring(Math.max(escapeStart, escapeEnd + 2));
  3125. var modifiers = constraints.$options || '';
  3126. modifiers = modifiers.replace('x', '').replace('s', ''); // Parse Server / Mongo support x and s modifiers but JS RegExp doesn't
  3127. var exp = new RegExp(expString, modifiers);
  3128. if (!exp.test(object[key])) {
  3129. return false;
  3130. }
  3131. break;
  3132. }
  3133. case '$nearSphere':
  3134. {
  3135. if (!compareTo || !object[key]) {
  3136. return false;
  3137. }
  3138. var distance = compareTo.radiansTo(object[key]);
  3139. var max = constraints.$maxDistance || Infinity;
  3140. return distance <= max;
  3141. }
  3142. case '$within':
  3143. {
  3144. if (!compareTo || !object[key]) {
  3145. return false;
  3146. }
  3147. var southWest = compareTo.$box[0];
  3148. var northEast = compareTo.$box[1];
  3149. if (southWest.latitude > northEast.latitude || southWest.longitude > northEast.longitude) {
  3150. // Invalid box, crosses the date line
  3151. return false;
  3152. }
  3153. return object[key].latitude > southWest.latitude && object[key].latitude < northEast.latitude && object[key].longitude > southWest.longitude && object[key].longitude < northEast.longitude;
  3154. }
  3155. case '$options':
  3156. // Not a query type, but a way to add options to $regex. Ignore and
  3157. // avoid the default
  3158. break;
  3159. case '$maxDistance':
  3160. // Not a query type, but a way to add a cap to $nearSphere. Ignore and
  3161. // avoid the default
  3162. break;
  3163. case '$select':
  3164. {
  3165. var subQueryObjects = objects.filter(function (obj, index, arr) {
  3166. return matchesQuery(compareTo.query.className, obj, arr, compareTo.query.where);
  3167. });
  3168. for (var _i = 0; _i < subQueryObjects.length; _i += 1) {
  3169. var subObject = transformObject(subQueryObjects[_i]);
  3170. return equalObjects(object[key], subObject[compareTo.key]);
  3171. }
  3172. return false;
  3173. }
  3174. case '$dontSelect':
  3175. {
  3176. var _subQueryObjects = objects.filter(function (obj, index, arr) {
  3177. return matchesQuery(compareTo.query.className, obj, arr, compareTo.query.where);
  3178. });
  3179. for (var _i2 = 0; _i2 < _subQueryObjects.length; _i2 += 1) {
  3180. var _subObject = transformObject(_subQueryObjects[_i2]);
  3181. return !equalObjects(object[key], _subObject[compareTo.key]);
  3182. }
  3183. return false;
  3184. }
  3185. case '$inQuery':
  3186. {
  3187. var _subQueryObjects2 = objects.filter(function (obj, index, arr) {
  3188. return matchesQuery(compareTo.className, obj, arr, compareTo.where);
  3189. });
  3190. for (var _i3 = 0; _i3 < _subQueryObjects2.length; _i3 += 1) {
  3191. var _subObject2 = transformObject(_subQueryObjects2[_i3]);
  3192. if (object[key].className === _subObject2.className && object[key].objectId === _subObject2.objectId) {
  3193. return true;
  3194. }
  3195. }
  3196. return false;
  3197. }
  3198. case '$notInQuery':
  3199. {
  3200. var _subQueryObjects3 = objects.filter(function (obj, index, arr) {
  3201. return matchesQuery(compareTo.className, obj, arr, compareTo.where);
  3202. });
  3203. for (var _i4 = 0; _i4 < _subQueryObjects3.length; _i4 += 1) {
  3204. var _subObject3 = transformObject(_subQueryObjects3[_i4]);
  3205. if (object[key].className === _subObject3.className && object[key].objectId === _subObject3.objectId) {
  3206. return false;
  3207. }
  3208. }
  3209. return true;
  3210. }
  3211. case '$containedBy':
  3212. {
  3213. var _iteratorNormalCompletion = true;
  3214. var _didIteratorError = false;
  3215. var _iteratorError = undefined;
  3216. try {
  3217. for (var _iterator = object[key][Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  3218. var value = _step.value;
  3219. if (!contains(compareTo, value)) {
  3220. return false;
  3221. }
  3222. }
  3223. } catch (err) {
  3224. _didIteratorError = true;
  3225. _iteratorError = err;
  3226. } finally {
  3227. try {
  3228. if (!_iteratorNormalCompletion && _iterator.return != null) {
  3229. _iterator.return();
  3230. }
  3231. } finally {
  3232. if (_didIteratorError) {
  3233. throw _iteratorError;
  3234. }
  3235. }
  3236. }
  3237. return true;
  3238. }
  3239. case '$geoWithin':
  3240. {
  3241. var points = compareTo.$polygon.map(function (geoPoint) {
  3242. return [geoPoint.latitude, geoPoint.longitude];
  3243. });
  3244. var polygon = new ParsePolygon(points);
  3245. return polygon.containsPoint(object[key]);
  3246. }
  3247. case '$geoIntersects':
  3248. {
  3249. var _polygon = new ParsePolygon(object[key].coordinates);
  3250. var point = new ParseGeoPoint(compareTo.$point);
  3251. return _polygon.containsPoint(point);
  3252. }
  3253. default:
  3254. return false;
  3255. }
  3256. }
  3257. return true;
  3258. }
  3259. function validateQuery(query
  3260. /*: any*/
  3261. ) {
  3262. var q = query;
  3263. if (query.toJSON) {
  3264. q = query.toJSON().where;
  3265. }
  3266. var specialQuerykeys = ['$and', '$or', '$nor', '_rperm', '_wperm', '_perishable_token', '_email_verify_token', '_email_verify_token_expires_at', '_account_lockout_expires_at', '_failed_login_count'];
  3267. Object.keys(q).forEach(function (key) {
  3268. if (q && q[key] && q[key].$regex) {
  3269. if (typeof q[key].$options === 'string') {
  3270. if (!q[key].$options.match(/^[imxs]+$/)) {
  3271. throw new ParseError(ParseError.INVALID_QUERY, "Bad $options value for query: ".concat(q[key].$options));
  3272. }
  3273. }
  3274. }
  3275. if (specialQuerykeys.indexOf(key) < 0 && !key.match(/^[a-zA-Z][a-zA-Z0-9_\.]*$/)) {
  3276. throw new ParseError(ParseError.INVALID_KEY_NAME, "Invalid key name: ".concat(key));
  3277. }
  3278. });
  3279. }
  3280. var OfflineQuery = {
  3281. matchesQuery: matchesQuery,
  3282. validateQuery: validateQuery
  3283. };
  3284. module.exports = OfflineQuery;
  3285. },{"./ParseError":18,"./ParseGeoPoint":20,"./ParsePolygon":25,"./decode":43,"./equals":45,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],15:[function(_dereq_,module,exports){
  3286. "use strict";
  3287. var _interopRequireWildcard = _dereq_("@babel/runtime/helpers/interopRequireWildcard");
  3288. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  3289. var _decode = _interopRequireDefault(_dereq_("./decode"));
  3290. var _encode = _interopRequireDefault(_dereq_("./encode"));
  3291. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  3292. var _InstallationController = _interopRequireDefault(_dereq_("./InstallationController"));
  3293. var ParseOp = _interopRequireWildcard(_dereq_("./ParseOp"));
  3294. var _RESTController = _interopRequireDefault(_dereq_("./RESTController"));
  3295. /**
  3296. * Copyright (c) 2015-present, Parse, LLC.
  3297. * All rights reserved.
  3298. *
  3299. * This source code is licensed under the BSD-style license found in the
  3300. * LICENSE file in the root directory of this source tree. An additional grant
  3301. * of patent rights can be found in the PATENTS file in the same directory.
  3302. */
  3303. /**
  3304. * Contains all Parse API classes and functions.
  3305. * @static
  3306. * @global
  3307. * @class
  3308. * @hideconstructor
  3309. */
  3310. var Parse = {
  3311. /**
  3312. * Call this method first to set up your authentication tokens for Parse.
  3313. * You can get your keys from the Data Browser on parse.com.
  3314. * @param {String} applicationId Your Parse Application ID.
  3315. * @param {String} javaScriptKey (optional) Your Parse JavaScript Key (Not needed for parse-server)
  3316. * @param {String} masterKey (optional) Your Parse Master Key. (Node.js only!)
  3317. * @static
  3318. */
  3319. initialize: function (applicationId
  3320. /*: string*/
  3321. , javaScriptKey
  3322. /*: string*/
  3323. ) {
  3324. Parse._initialize(applicationId, javaScriptKey);
  3325. },
  3326. _initialize: function (applicationId
  3327. /*: string*/
  3328. , javaScriptKey
  3329. /*: string*/
  3330. , masterKey
  3331. /*: string*/
  3332. ) {
  3333. _CoreManager.default.set('APPLICATION_ID', applicationId);
  3334. _CoreManager.default.set('JAVASCRIPT_KEY', javaScriptKey);
  3335. _CoreManager.default.set('MASTER_KEY', masterKey);
  3336. _CoreManager.default.set('USE_MASTER_KEY', false);
  3337. },
  3338. /**
  3339. * Call this method to set your AsyncStorage engine
  3340. * Starting Parse@1.11, the ParseSDK do not provide a React AsyncStorage as the ReactNative module
  3341. * is not provided at a stable path and changes over versions.
  3342. * @param {AsyncStorage} storage a react native async storage.
  3343. * @static
  3344. */
  3345. setAsyncStorage: function (storage
  3346. /*: any*/
  3347. ) {
  3348. _CoreManager.default.setAsyncStorage(storage);
  3349. },
  3350. /**
  3351. * Call this method to set your LocalDatastoreStorage engine
  3352. * If using React-Native use {@link Parse.setAsyncStorage Parse.setAsyncStorage()}
  3353. * @param {LocalDatastoreController} controller a data storage.
  3354. * @static
  3355. */
  3356. setLocalDatastoreController: function (controller
  3357. /*: any*/
  3358. ) {
  3359. _CoreManager.default.setLocalDatastoreController(controller);
  3360. }
  3361. };
  3362. /** These legacy setters may eventually be deprecated **/
  3363. /**
  3364. * @member Parse.applicationId
  3365. * @type string
  3366. * @static
  3367. */
  3368. Object.defineProperty(Parse, 'applicationId', {
  3369. get: function () {
  3370. return _CoreManager.default.get('APPLICATION_ID');
  3371. },
  3372. set: function (value) {
  3373. _CoreManager.default.set('APPLICATION_ID', value);
  3374. }
  3375. });
  3376. /**
  3377. * @member Parse.javaScriptKey
  3378. * @type string
  3379. * @static
  3380. */
  3381. Object.defineProperty(Parse, 'javaScriptKey', {
  3382. get: function () {
  3383. return _CoreManager.default.get('JAVASCRIPT_KEY');
  3384. },
  3385. set: function (value) {
  3386. _CoreManager.default.set('JAVASCRIPT_KEY', value);
  3387. }
  3388. });
  3389. /**
  3390. * @member Parse.masterKey
  3391. * @type string
  3392. * @static
  3393. */
  3394. Object.defineProperty(Parse, 'masterKey', {
  3395. get: function () {
  3396. return _CoreManager.default.get('MASTER_KEY');
  3397. },
  3398. set: function (value) {
  3399. _CoreManager.default.set('MASTER_KEY', value);
  3400. }
  3401. });
  3402. /**
  3403. * @member Parse.serverURL
  3404. * @type string
  3405. * @static
  3406. */
  3407. Object.defineProperty(Parse, 'serverURL', {
  3408. get: function () {
  3409. return _CoreManager.default.get('SERVER_URL');
  3410. },
  3411. set: function (value) {
  3412. _CoreManager.default.set('SERVER_URL', value);
  3413. }
  3414. });
  3415. /**
  3416. * @member Parse.serverAuthToken
  3417. * @type string
  3418. * @static
  3419. */
  3420. Object.defineProperty(Parse, 'serverAuthToken', {
  3421. get: function () {
  3422. return _CoreManager.default.get('SERVER_AUTH_TOKEN');
  3423. },
  3424. set: function (value) {
  3425. _CoreManager.default.set('SERVER_AUTH_TOKEN', value);
  3426. }
  3427. });
  3428. /**
  3429. * @member Parse.serverAuthType
  3430. * @type string
  3431. * @static
  3432. */
  3433. Object.defineProperty(Parse, 'serverAuthType', {
  3434. get: function () {
  3435. return _CoreManager.default.get('SERVER_AUTH_TYPE');
  3436. },
  3437. set: function (value) {
  3438. _CoreManager.default.set('SERVER_AUTH_TYPE', value);
  3439. }
  3440. });
  3441. /**
  3442. * @member Parse.liveQueryServerURL
  3443. * @type string
  3444. * @static
  3445. */
  3446. Object.defineProperty(Parse, 'liveQueryServerURL', {
  3447. get: function () {
  3448. return _CoreManager.default.get('LIVEQUERY_SERVER_URL');
  3449. },
  3450. set: function (value) {
  3451. _CoreManager.default.set('LIVEQUERY_SERVER_URL', value);
  3452. }
  3453. });
  3454. /* End setters */
  3455. Parse.ACL = _dereq_('./ParseACL').default;
  3456. Parse.Analytics = _dereq_('./Analytics');
  3457. Parse.AnonymousUtils = _dereq_('./AnonymousUtils').default;
  3458. Parse.Cloud = _dereq_('./Cloud');
  3459. Parse.CoreManager = _dereq_('./CoreManager');
  3460. Parse.Config = _dereq_('./ParseConfig').default;
  3461. Parse.Error = _dereq_('./ParseError').default;
  3462. Parse.FacebookUtils = _dereq_('./FacebookUtils').default;
  3463. Parse.File = _dereq_('./ParseFile').default;
  3464. Parse.GeoPoint = _dereq_('./ParseGeoPoint').default;
  3465. Parse.Polygon = _dereq_('./ParsePolygon').default;
  3466. Parse.Installation = _dereq_('./ParseInstallation').default;
  3467. Parse.LocalDatastore = _dereq_('./LocalDatastore');
  3468. Parse.Object = _dereq_('./ParseObject').default;
  3469. Parse.Op = {
  3470. Set: ParseOp.SetOp,
  3471. Unset: ParseOp.UnsetOp,
  3472. Increment: ParseOp.IncrementOp,
  3473. Add: ParseOp.AddOp,
  3474. Remove: ParseOp.RemoveOp,
  3475. AddUnique: ParseOp.AddUniqueOp,
  3476. Relation: ParseOp.RelationOp
  3477. };
  3478. Parse.Push = _dereq_('./Push');
  3479. Parse.Query = _dereq_('./ParseQuery').default;
  3480. Parse.Relation = _dereq_('./ParseRelation').default;
  3481. Parse.Role = _dereq_('./ParseRole').default;
  3482. Parse.Schema = _dereq_('./ParseSchema').default;
  3483. Parse.Session = _dereq_('./ParseSession').default;
  3484. Parse.Storage = _dereq_('./Storage');
  3485. Parse.User = _dereq_('./ParseUser').default;
  3486. Parse.LiveQuery = _dereq_('./ParseLiveQuery').default;
  3487. Parse.LiveQueryClient = _dereq_('./LiveQueryClient').default;
  3488. Parse._request = function () {
  3489. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3490. args[_key] = arguments[_key];
  3491. }
  3492. return _CoreManager.default.getRESTController().request.apply(null, args);
  3493. };
  3494. Parse._ajax = function () {
  3495. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  3496. args[_key2] = arguments[_key2];
  3497. }
  3498. return _CoreManager.default.getRESTController().ajax.apply(null, args);
  3499. }; // We attempt to match the signatures of the legacy versions of these methods
  3500. Parse._decode = function (_, value) {
  3501. return (0, _decode.default)(value);
  3502. };
  3503. Parse._encode = function (value, _, disallowObjects) {
  3504. return (0, _encode.default)(value, disallowObjects);
  3505. };
  3506. Parse._getInstallationId = function () {
  3507. return _CoreManager.default.getInstallationController().currentInstallationId();
  3508. };
  3509. /**
  3510. * Enable pinning in your application.
  3511. * This must be called before your application can use pinning.
  3512. *
  3513. * @static
  3514. */
  3515. Parse.enableLocalDatastore = function () {
  3516. Parse.LocalDatastore.isEnabled = true;
  3517. };
  3518. /**
  3519. * Flag that indicates whether Local Datastore is enabled.
  3520. *
  3521. * @static
  3522. */
  3523. Parse.isLocalDatastoreEnabled = function () {
  3524. return Parse.LocalDatastore.isEnabled;
  3525. };
  3526. /**
  3527. * Gets all contents from Local Datastore
  3528. *
  3529. * <pre>
  3530. * await Parse.dumpLocalDatastore();
  3531. * </pre>
  3532. *
  3533. * @static
  3534. */
  3535. Parse.dumpLocalDatastore = function () {
  3536. if (!Parse.LocalDatastore.isEnabled) {
  3537. console.log('Parse.enableLocalDatastore() must be called first'); // eslint-disable-line no-console
  3538. return Promise.resolve({});
  3539. } else {
  3540. return Parse.LocalDatastore._getAllContents();
  3541. }
  3542. };
  3543. _CoreManager.default.setInstallationController(_InstallationController.default);
  3544. _CoreManager.default.setRESTController(_RESTController.default);
  3545. // For legacy requires, of the form `var Parse = require('parse').Parse`
  3546. Parse.Parse = Parse;
  3547. module.exports = Parse;
  3548. },{"./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":36,"./decode":43,"./encode":44,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/interopRequireWildcard":64}],16:[function(_dereq_,module,exports){
  3549. "use strict";
  3550. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  3551. Object.defineProperty(exports, "__esModule", {
  3552. value: true
  3553. });
  3554. exports.default = void 0;
  3555. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  3556. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  3557. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  3558. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  3559. var _ParseRole = _interopRequireDefault(_dereq_("./ParseRole"));
  3560. var _ParseUser = _interopRequireDefault(_dereq_("./ParseUser"));
  3561. /**
  3562. * Copyright (c) 2015-present, Parse, LLC.
  3563. * All rights reserved.
  3564. *
  3565. * This source code is licensed under the BSD-style license found in the
  3566. * LICENSE file in the root directory of this source tree. An additional grant
  3567. * of patent rights can be found in the PATENTS file in the same directory.
  3568. *
  3569. * @flow
  3570. */
  3571. var PUBLIC_KEY = '*';
  3572. /**
  3573. * Creates a new ACL.
  3574. * If no argument is given, the ACL has no permissions for anyone.
  3575. * If the argument is a Parse.User, the ACL will have read and write
  3576. * permission for only that user.
  3577. * If the argument is any other JSON object, that object will be interpretted
  3578. * as a serialized ACL created with toJSON().
  3579. *
  3580. * <p>An ACL, or Access Control List can be added to any
  3581. * <code>Parse.Object</code> to restrict access to only a subset of users
  3582. * of your application.</p>
  3583. * @alias Parse.ACL
  3584. */
  3585. var ParseACL =
  3586. /*#__PURE__*/
  3587. function () {
  3588. /**
  3589. * @param {(Parse.User|Object)} user The user to initialize the ACL for
  3590. */
  3591. function ParseACL(arg1
  3592. /*: ParseUser | ByIdMap*/
  3593. ) {
  3594. (0, _classCallCheck2.default)(this, ParseACL);
  3595. (0, _defineProperty2.default)(this, "permissionsById", void 0);
  3596. this.permissionsById = {};
  3597. if (arg1 && (0, _typeof2.default)(arg1) === 'object') {
  3598. if (arg1 instanceof _ParseUser.default) {
  3599. this.setReadAccess(arg1, true);
  3600. this.setWriteAccess(arg1, true);
  3601. } else {
  3602. for (var _userId in arg1) {
  3603. var accessList = arg1[_userId];
  3604. if (typeof _userId !== 'string') {
  3605. throw new TypeError('Tried to create an ACL with an invalid user id.');
  3606. }
  3607. this.permissionsById[_userId] = {};
  3608. for (var _permission in accessList) {
  3609. var allowed = accessList[_permission];
  3610. if (_permission !== 'read' && _permission !== 'write') {
  3611. throw new TypeError('Tried to create an ACL with an invalid permission type.');
  3612. }
  3613. if (typeof allowed !== 'boolean') {
  3614. throw new TypeError('Tried to create an ACL with an invalid permission value.');
  3615. }
  3616. this.permissionsById[_userId][_permission] = allowed;
  3617. }
  3618. }
  3619. }
  3620. } else if (typeof arg1 === 'function') {
  3621. throw new TypeError('ParseACL constructed with a function. Did you forget ()?');
  3622. }
  3623. }
  3624. /**
  3625. * Returns a JSON-encoded version of the ACL.
  3626. * @return {Object}
  3627. */
  3628. (0, _createClass2.default)(ParseACL, [{
  3629. key: "toJSON",
  3630. value: function ()
  3631. /*: ByIdMap*/
  3632. {
  3633. var permissions = {};
  3634. for (var p in this.permissionsById) {
  3635. permissions[p] = this.permissionsById[p];
  3636. }
  3637. return permissions;
  3638. }
  3639. /**
  3640. * Returns whether this ACL is equal to another object
  3641. * @param other The other object to compare to
  3642. * @return {Boolean}
  3643. */
  3644. }, {
  3645. key: "equals",
  3646. value: function (other
  3647. /*: ParseACL*/
  3648. )
  3649. /*: boolean*/
  3650. {
  3651. if (!(other instanceof ParseACL)) {
  3652. return false;
  3653. }
  3654. var users = Object.keys(this.permissionsById);
  3655. var otherUsers = Object.keys(other.permissionsById);
  3656. if (users.length !== otherUsers.length) {
  3657. return false;
  3658. }
  3659. for (var u in this.permissionsById) {
  3660. if (!other.permissionsById[u]) {
  3661. return false;
  3662. }
  3663. if (this.permissionsById[u].read !== other.permissionsById[u].read) {
  3664. return false;
  3665. }
  3666. if (this.permissionsById[u].write !== other.permissionsById[u].write) {
  3667. return false;
  3668. }
  3669. }
  3670. return true;
  3671. }
  3672. }, {
  3673. key: "_setAccess",
  3674. value: function (accessType
  3675. /*: string*/
  3676. , userId
  3677. /*: ParseUser | ParseRole | string*/
  3678. , allowed
  3679. /*: boolean*/
  3680. ) {
  3681. if (userId instanceof _ParseUser.default) {
  3682. userId = userId.id;
  3683. } else if (userId instanceof _ParseRole.default) {
  3684. var name = userId.getName();
  3685. if (!name) {
  3686. throw new TypeError('Role must have a name');
  3687. }
  3688. userId = 'role:' + name;
  3689. }
  3690. if (typeof userId !== 'string') {
  3691. throw new TypeError('userId must be a string.');
  3692. }
  3693. if (typeof allowed !== 'boolean') {
  3694. throw new TypeError('allowed must be either true or false.');
  3695. }
  3696. var permissions = this.permissionsById[userId];
  3697. if (!permissions) {
  3698. if (!allowed) {
  3699. // The user already doesn't have this permission, so no action is needed
  3700. return;
  3701. } else {
  3702. permissions = {};
  3703. this.permissionsById[userId] = permissions;
  3704. }
  3705. }
  3706. if (allowed) {
  3707. this.permissionsById[userId][accessType] = true;
  3708. } else {
  3709. delete permissions[accessType];
  3710. if (Object.keys(permissions).length === 0) {
  3711. delete this.permissionsById[userId];
  3712. }
  3713. }
  3714. }
  3715. }, {
  3716. key: "_getAccess",
  3717. value: function (accessType
  3718. /*: string*/
  3719. , userId
  3720. /*: ParseUser | ParseRole | string*/
  3721. )
  3722. /*: boolean*/
  3723. {
  3724. if (userId instanceof _ParseUser.default) {
  3725. userId = userId.id;
  3726. if (!userId) {
  3727. throw new Error('Cannot get access for a ParseUser without an ID');
  3728. }
  3729. } else if (userId instanceof _ParseRole.default) {
  3730. var name = userId.getName();
  3731. if (!name) {
  3732. throw new TypeError('Role must have a name');
  3733. }
  3734. userId = 'role:' + name;
  3735. }
  3736. var permissions = this.permissionsById[userId];
  3737. if (!permissions) {
  3738. return false;
  3739. }
  3740. return !!permissions[accessType];
  3741. }
  3742. /**
  3743. * Sets whether the given user is allowed to read this object.
  3744. * @param userId An instance of Parse.User or its objectId.
  3745. * @param {Boolean} allowed Whether that user should have read access.
  3746. */
  3747. }, {
  3748. key: "setReadAccess",
  3749. value: function (userId
  3750. /*: ParseUser | ParseRole | string*/
  3751. , allowed
  3752. /*: boolean*/
  3753. ) {
  3754. this._setAccess('read', userId, allowed);
  3755. }
  3756. /**
  3757. * Get whether the given user id is *explicitly* allowed to read this object.
  3758. * Even if this returns false, the user may still be able to access it if
  3759. * getPublicReadAccess returns true or a role that the user belongs to has
  3760. * write access.
  3761. * @param userId An instance of Parse.User or its objectId, or a Parse.Role.
  3762. * @return {Boolean}
  3763. */
  3764. }, {
  3765. key: "getReadAccess",
  3766. value: function (userId
  3767. /*: ParseUser | ParseRole | string*/
  3768. )
  3769. /*: boolean*/
  3770. {
  3771. return this._getAccess('read', userId);
  3772. }
  3773. /**
  3774. * Sets whether the given user id is allowed to write this object.
  3775. * @param userId An instance of Parse.User or its objectId, or a Parse.Role..
  3776. * @param {Boolean} allowed Whether that user should have write access.
  3777. */
  3778. }, {
  3779. key: "setWriteAccess",
  3780. value: function (userId
  3781. /*: ParseUser | ParseRole | string*/
  3782. , allowed
  3783. /*: boolean*/
  3784. ) {
  3785. this._setAccess('write', userId, allowed);
  3786. }
  3787. /**
  3788. * Gets whether the given user id is *explicitly* allowed to write this object.
  3789. * Even if this returns false, the user may still be able to write it if
  3790. * getPublicWriteAccess returns true or a role that the user belongs to has
  3791. * write access.
  3792. * @param userId An instance of Parse.User or its objectId, or a Parse.Role.
  3793. * @return {Boolean}
  3794. */
  3795. }, {
  3796. key: "getWriteAccess",
  3797. value: function (userId
  3798. /*: ParseUser | ParseRole | string*/
  3799. )
  3800. /*: boolean*/
  3801. {
  3802. return this._getAccess('write', userId);
  3803. }
  3804. /**
  3805. * Sets whether the public is allowed to read this object.
  3806. * @param {Boolean} allowed
  3807. */
  3808. }, {
  3809. key: "setPublicReadAccess",
  3810. value: function (allowed
  3811. /*: boolean*/
  3812. ) {
  3813. this.setReadAccess(PUBLIC_KEY, allowed);
  3814. }
  3815. /**
  3816. * Gets whether the public is allowed to read this object.
  3817. * @return {Boolean}
  3818. */
  3819. }, {
  3820. key: "getPublicReadAccess",
  3821. value: function ()
  3822. /*: boolean*/
  3823. {
  3824. return this.getReadAccess(PUBLIC_KEY);
  3825. }
  3826. /**
  3827. * Sets whether the public is allowed to write this object.
  3828. * @param {Boolean} allowed
  3829. */
  3830. }, {
  3831. key: "setPublicWriteAccess",
  3832. value: function (allowed
  3833. /*: boolean*/
  3834. ) {
  3835. this.setWriteAccess(PUBLIC_KEY, allowed);
  3836. }
  3837. /**
  3838. * Gets whether the public is allowed to write this object.
  3839. * @return {Boolean}
  3840. */
  3841. }, {
  3842. key: "getPublicWriteAccess",
  3843. value: function ()
  3844. /*: boolean*/
  3845. {
  3846. return this.getWriteAccess(PUBLIC_KEY);
  3847. }
  3848. /**
  3849. * Gets whether users belonging to the given role are allowed
  3850. * to read this object. Even if this returns false, the role may
  3851. * still be able to write it if a parent role has read access.
  3852. *
  3853. * @param role The name of the role, or a Parse.Role object.
  3854. * @return {Boolean} true if the role has read access. false otherwise.
  3855. * @throws {TypeError} If role is neither a Parse.Role nor a String.
  3856. */
  3857. }, {
  3858. key: "getRoleReadAccess",
  3859. value: function (role
  3860. /*: ParseRole | string*/
  3861. )
  3862. /*: boolean*/
  3863. {
  3864. if (role instanceof _ParseRole.default) {
  3865. // Normalize to the String name
  3866. role = role.getName();
  3867. }
  3868. if (typeof role !== 'string') {
  3869. throw new TypeError('role must be a ParseRole or a String');
  3870. }
  3871. return this.getReadAccess('role:' + role);
  3872. }
  3873. /**
  3874. * Gets whether users belonging to the given role are allowed
  3875. * to write this object. Even if this returns false, the role may
  3876. * still be able to write it if a parent role has write access.
  3877. *
  3878. * @param role The name of the role, or a Parse.Role object.
  3879. * @return {Boolean} true if the role has write access. false otherwise.
  3880. * @throws {TypeError} If role is neither a Parse.Role nor a String.
  3881. */
  3882. }, {
  3883. key: "getRoleWriteAccess",
  3884. value: function (role
  3885. /*: ParseRole | string*/
  3886. )
  3887. /*: boolean*/
  3888. {
  3889. if (role instanceof _ParseRole.default) {
  3890. // Normalize to the String name
  3891. role = role.getName();
  3892. }
  3893. if (typeof role !== 'string') {
  3894. throw new TypeError('role must be a ParseRole or a String');
  3895. }
  3896. return this.getWriteAccess('role:' + role);
  3897. }
  3898. /**
  3899. * Sets whether users belonging to the given role are allowed
  3900. * to read this object.
  3901. *
  3902. * @param role The name of the role, or a Parse.Role object.
  3903. * @param {Boolean} allowed Whether the given role can read this object.
  3904. * @throws {TypeError} If role is neither a Parse.Role nor a String.
  3905. */
  3906. }, {
  3907. key: "setRoleReadAccess",
  3908. value: function (role
  3909. /*: ParseRole | string*/
  3910. , allowed
  3911. /*: boolean*/
  3912. ) {
  3913. if (role instanceof _ParseRole.default) {
  3914. // Normalize to the String name
  3915. role = role.getName();
  3916. }
  3917. if (typeof role !== 'string') {
  3918. throw new TypeError('role must be a ParseRole or a String');
  3919. }
  3920. this.setReadAccess('role:' + role, allowed);
  3921. }
  3922. /**
  3923. * Sets whether users belonging to the given role are allowed
  3924. * to write this object.
  3925. *
  3926. * @param role The name of the role, or a Parse.Role object.
  3927. * @param {Boolean} allowed Whether the given role can write this object.
  3928. * @throws {TypeError} If role is neither a Parse.Role nor a String.
  3929. */
  3930. }, {
  3931. key: "setRoleWriteAccess",
  3932. value: function (role
  3933. /*: ParseRole | string*/
  3934. , allowed
  3935. /*: boolean*/
  3936. ) {
  3937. if (role instanceof _ParseRole.default) {
  3938. // Normalize to the String name
  3939. role = role.getName();
  3940. }
  3941. if (typeof role !== 'string') {
  3942. throw new TypeError('role must be a ParseRole or a String');
  3943. }
  3944. this.setWriteAccess('role:' + role, allowed);
  3945. }
  3946. }]);
  3947. return ParseACL;
  3948. }();
  3949. var _default = ParseACL;
  3950. exports.default = _default;
  3951. },{"./ParseRole":28,"./ParseUser":31,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],17:[function(_dereq_,module,exports){
  3952. "use strict";
  3953. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  3954. Object.defineProperty(exports, "__esModule", {
  3955. value: true
  3956. });
  3957. exports.default = void 0;
  3958. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  3959. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  3960. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  3961. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  3962. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  3963. var _decode = _interopRequireDefault(_dereq_("./decode"));
  3964. var _encode = _interopRequireDefault(_dereq_("./encode"));
  3965. var _escape2 = _interopRequireDefault(_dereq_("./escape"));
  3966. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  3967. var _Storage = _interopRequireDefault(_dereq_("./Storage"));
  3968. /**
  3969. * Copyright (c) 2015-present, Parse, LLC.
  3970. * All rights reserved.
  3971. *
  3972. * This source code is licensed under the BSD-style license found in the
  3973. * LICENSE file in the root directory of this source tree. An additional grant
  3974. * of patent rights can be found in the PATENTS file in the same directory.
  3975. *
  3976. * @flow
  3977. */
  3978. /**
  3979. * Parse.Config is a local representation of configuration data that
  3980. * can be set from the Parse dashboard.
  3981. *
  3982. * @alias Parse.Config
  3983. */
  3984. var ParseConfig =
  3985. /*#__PURE__*/
  3986. function () {
  3987. function ParseConfig() {
  3988. (0, _classCallCheck2.default)(this, ParseConfig);
  3989. (0, _defineProperty2.default)(this, "attributes", void 0);
  3990. (0, _defineProperty2.default)(this, "_escapedAttributes", void 0);
  3991. this.attributes = {};
  3992. this._escapedAttributes = {};
  3993. }
  3994. /**
  3995. * Gets the value of an attribute.
  3996. * @param {String} attr The name of an attribute.
  3997. */
  3998. (0, _createClass2.default)(ParseConfig, [{
  3999. key: "get",
  4000. value: function (attr
  4001. /*: string*/
  4002. )
  4003. /*: any*/
  4004. {
  4005. return this.attributes[attr];
  4006. }
  4007. /**
  4008. * Gets the HTML-escaped value of an attribute.
  4009. * @param {String} attr The name of an attribute.
  4010. */
  4011. }, {
  4012. key: "escape",
  4013. value: function (attr
  4014. /*: string*/
  4015. )
  4016. /*: string*/
  4017. {
  4018. var html = this._escapedAttributes[attr];
  4019. if (html) {
  4020. return html;
  4021. }
  4022. var val = this.attributes[attr];
  4023. var escaped = '';
  4024. if (val != null) {
  4025. escaped = (0, _escape2.default)(val.toString());
  4026. }
  4027. this._escapedAttributes[attr] = escaped;
  4028. return escaped;
  4029. }
  4030. /**
  4031. * Retrieves the most recently-fetched configuration object, either from
  4032. * memory or from local storage if necessary.
  4033. *
  4034. * @static
  4035. * @return {Config} The most recently-fetched Parse.Config if it
  4036. * exists, else an empty Parse.Config.
  4037. */
  4038. }], [{
  4039. key: "current",
  4040. value: function () {
  4041. var controller = _CoreManager.default.getConfigController();
  4042. return controller.current();
  4043. }
  4044. /**
  4045. * Gets a new configuration object from the server.
  4046. * @static
  4047. * @return {Promise} A promise that is resolved with a newly-created
  4048. * configuration object when the get completes.
  4049. */
  4050. }, {
  4051. key: "get",
  4052. value: function () {
  4053. var controller = _CoreManager.default.getConfigController();
  4054. return controller.get();
  4055. }
  4056. /**
  4057. * Save value keys to the server.
  4058. * @static
  4059. * @return {Promise} A promise that is resolved with a newly-created
  4060. * configuration object or with the current with the update.
  4061. */
  4062. }, {
  4063. key: "save",
  4064. value: function (attrs
  4065. /*: { [key: string]: any }*/
  4066. ) {
  4067. var controller = _CoreManager.default.getConfigController(); //To avoid a mismatch with the local and the cloud config we get a new version
  4068. return controller.save(attrs).then(function () {
  4069. return controller.get();
  4070. }, function (error) {
  4071. return Promise.reject(error);
  4072. });
  4073. }
  4074. }]);
  4075. return ParseConfig;
  4076. }();
  4077. var currentConfig = null;
  4078. var CURRENT_CONFIG_KEY = 'currentConfig';
  4079. function decodePayload(data) {
  4080. try {
  4081. var json = JSON.parse(data);
  4082. if (json && (0, _typeof2.default)(json) === 'object') {
  4083. return (0, _decode.default)(json);
  4084. }
  4085. } catch (e) {
  4086. return null;
  4087. }
  4088. }
  4089. var DefaultController = {
  4090. current: function () {
  4091. if (currentConfig) {
  4092. return currentConfig;
  4093. }
  4094. var config = new ParseConfig();
  4095. var storagePath = _Storage.default.generatePath(CURRENT_CONFIG_KEY);
  4096. var configData;
  4097. if (!_Storage.default.async()) {
  4098. configData = _Storage.default.getItem(storagePath);
  4099. if (configData) {
  4100. var attributes = decodePayload(configData);
  4101. if (attributes) {
  4102. config.attributes = attributes;
  4103. currentConfig = config;
  4104. }
  4105. }
  4106. return config;
  4107. } // Return a promise for async storage controllers
  4108. return _Storage.default.getItemAsync(storagePath).then(function (configData) {
  4109. if (configData) {
  4110. var _attributes = decodePayload(configData);
  4111. if (_attributes) {
  4112. config.attributes = _attributes;
  4113. currentConfig = config;
  4114. }
  4115. }
  4116. return config;
  4117. });
  4118. },
  4119. get: function () {
  4120. var RESTController = _CoreManager.default.getRESTController();
  4121. return RESTController.request('GET', 'config', {}, {}).then(function (response) {
  4122. if (!response || !response.params) {
  4123. var error = new _ParseError.default(_ParseError.default.INVALID_JSON, 'Config JSON response invalid.');
  4124. return Promise.reject(error);
  4125. }
  4126. var config = new ParseConfig();
  4127. config.attributes = {};
  4128. for (var attr in response.params) {
  4129. config.attributes[attr] = (0, _decode.default)(response.params[attr]);
  4130. }
  4131. currentConfig = config;
  4132. return _Storage.default.setItemAsync(_Storage.default.generatePath(CURRENT_CONFIG_KEY), JSON.stringify(response.params)).then(function () {
  4133. return config;
  4134. });
  4135. });
  4136. },
  4137. save: function (attrs
  4138. /*: { [key: string]: any }*/
  4139. ) {
  4140. var RESTController = _CoreManager.default.getRESTController();
  4141. var encodedAttrs = {};
  4142. for (var _key in attrs) {
  4143. encodedAttrs[_key] = (0, _encode.default)(attrs[_key]);
  4144. }
  4145. return RESTController.request('PUT', 'config', {
  4146. params: encodedAttrs
  4147. }, {
  4148. useMasterKey: true
  4149. }).then(function (response) {
  4150. if (response && response.result) {
  4151. return Promise.resolve();
  4152. } else {
  4153. var error = new _ParseError.default(_ParseError.default.INTERNAL_SERVER_ERROR, 'Error occured updating Config.');
  4154. return Promise.reject(error);
  4155. }
  4156. });
  4157. }
  4158. };
  4159. _CoreManager.default.setConfigController(DefaultController);
  4160. var _default = ParseConfig;
  4161. exports.default = _default;
  4162. },{"./CoreManager":4,"./ParseError":18,"./Storage":36,"./decode":43,"./encode":44,"./escape":46,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],18:[function(_dereq_,module,exports){
  4163. "use strict";
  4164. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  4165. Object.defineProperty(exports, "__esModule", {
  4166. value: true
  4167. });
  4168. exports.default = void 0;
  4169. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  4170. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  4171. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  4172. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  4173. var _assertThisInitialized2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/assertThisInitialized"));
  4174. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  4175. var _wrapNativeSuper2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/wrapNativeSuper"));
  4176. /**
  4177. * Copyright (c) 2015-present, Parse, LLC.
  4178. * All rights reserved.
  4179. *
  4180. * This source code is licensed under the BSD-style license found in the
  4181. * LICENSE file in the root directory of this source tree. An additional grant
  4182. * of patent rights can be found in the PATENTS file in the same directory.
  4183. */
  4184. /**
  4185. * Constructs a new Parse.Error object with the given code and message.
  4186. * @alias Parse.Error
  4187. */
  4188. var ParseError =
  4189. /*#__PURE__*/
  4190. function (_Error) {
  4191. (0, _inherits2.default)(ParseError, _Error);
  4192. /**
  4193. * @param {Number} code An error code constant from <code>Parse.Error</code>.
  4194. * @param {String} message A detailed description of the error.
  4195. */
  4196. function ParseError(code, message) {
  4197. var _this;
  4198. (0, _classCallCheck2.default)(this, ParseError);
  4199. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(ParseError).call(this, message));
  4200. _this.code = code;
  4201. Object.defineProperty((0, _assertThisInitialized2.default)(_this), 'message', {
  4202. enumerable: true,
  4203. value: message
  4204. });
  4205. return _this;
  4206. }
  4207. (0, _createClass2.default)(ParseError, [{
  4208. key: "toString",
  4209. value: function () {
  4210. return 'ParseError: ' + this.code + ' ' + this.message;
  4211. }
  4212. }]);
  4213. return ParseError;
  4214. }((0, _wrapNativeSuper2.default)(Error));
  4215. /**
  4216. * Error code indicating some error other than those enumerated here.
  4217. * @property OTHER_CAUSE
  4218. * @static
  4219. * @final
  4220. */
  4221. ParseError.OTHER_CAUSE = -1;
  4222. /**
  4223. * Error code indicating that something has gone wrong with the server.
  4224. * If you get this error code, it is Parse's fault. Contact us at
  4225. * https://parse.com/help
  4226. * @property INTERNAL_SERVER_ERROR
  4227. * @static
  4228. * @final
  4229. */
  4230. ParseError.INTERNAL_SERVER_ERROR = 1;
  4231. /**
  4232. * Error code indicating the connection to the Parse servers failed.
  4233. * @property CONNECTION_FAILED
  4234. * @static
  4235. * @final
  4236. */
  4237. ParseError.CONNECTION_FAILED = 100;
  4238. /**
  4239. * Error code indicating the specified object doesn't exist.
  4240. * @property OBJECT_NOT_FOUND
  4241. * @static
  4242. * @final
  4243. */
  4244. ParseError.OBJECT_NOT_FOUND = 101;
  4245. /**
  4246. * Error code indicating you tried to query with a datatype that doesn't
  4247. * support it, like exact matching an array or object.
  4248. * @property INVALID_QUERY
  4249. * @static
  4250. * @final
  4251. */
  4252. ParseError.INVALID_QUERY = 102;
  4253. /**
  4254. * Error code indicating a missing or invalid classname. Classnames are
  4255. * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the
  4256. * only valid characters.
  4257. * @property INVALID_CLASS_NAME
  4258. * @static
  4259. * @final
  4260. */
  4261. ParseError.INVALID_CLASS_NAME = 103;
  4262. /**
  4263. * Error code indicating an unspecified object id.
  4264. * @property MISSING_OBJECT_ID
  4265. * @static
  4266. * @final
  4267. */
  4268. ParseError.MISSING_OBJECT_ID = 104;
  4269. /**
  4270. * Error code indicating an invalid key name. Keys are case-sensitive. They
  4271. * must start with a letter, and a-zA-Z0-9_ are the only valid characters.
  4272. * @property INVALID_KEY_NAME
  4273. * @static
  4274. * @final
  4275. */
  4276. ParseError.INVALID_KEY_NAME = 105;
  4277. /**
  4278. * Error code indicating a malformed pointer. You should not see this unless
  4279. * you have been mucking about changing internal Parse code.
  4280. * @property INVALID_POINTER
  4281. * @static
  4282. * @final
  4283. */
  4284. ParseError.INVALID_POINTER = 106;
  4285. /**
  4286. * Error code indicating that badly formed JSON was received upstream. This
  4287. * either indicates you have done something unusual with modifying how
  4288. * things encode to JSON, or the network is failing badly.
  4289. * @property INVALID_JSON
  4290. * @static
  4291. * @final
  4292. */
  4293. ParseError.INVALID_JSON = 107;
  4294. /**
  4295. * Error code indicating that the feature you tried to access is only
  4296. * available internally for testing purposes.
  4297. * @property COMMAND_UNAVAILABLE
  4298. * @static
  4299. * @final
  4300. */
  4301. ParseError.COMMAND_UNAVAILABLE = 108;
  4302. /**
  4303. * You must call Parse.initialize before using the Parse library.
  4304. * @property NOT_INITIALIZED
  4305. * @static
  4306. * @final
  4307. */
  4308. ParseError.NOT_INITIALIZED = 109;
  4309. /**
  4310. * Error code indicating that a field was set to an inconsistent type.
  4311. * @property INCORRECT_TYPE
  4312. * @static
  4313. * @final
  4314. */
  4315. ParseError.INCORRECT_TYPE = 111;
  4316. /**
  4317. * Error code indicating an invalid channel name. A channel name is either
  4318. * an empty string (the broadcast channel) or contains only a-zA-Z0-9_
  4319. * characters and starts with a letter.
  4320. * @property INVALID_CHANNEL_NAME
  4321. * @static
  4322. * @final
  4323. */
  4324. ParseError.INVALID_CHANNEL_NAME = 112;
  4325. /**
  4326. * Error code indicating that push is misconfigured.
  4327. * @property PUSH_MISCONFIGURED
  4328. * @static
  4329. * @final
  4330. */
  4331. ParseError.PUSH_MISCONFIGURED = 115;
  4332. /**
  4333. * Error code indicating that the object is too large.
  4334. * @property OBJECT_TOO_LARGE
  4335. * @static
  4336. * @final
  4337. */
  4338. ParseError.OBJECT_TOO_LARGE = 116;
  4339. /**
  4340. * Error code indicating that the operation isn't allowed for clients.
  4341. * @property OPERATION_FORBIDDEN
  4342. * @static
  4343. * @final
  4344. */
  4345. ParseError.OPERATION_FORBIDDEN = 119;
  4346. /**
  4347. * Error code indicating the result was not found in the cache.
  4348. * @property CACHE_MISS
  4349. * @static
  4350. * @final
  4351. */
  4352. ParseError.CACHE_MISS = 120;
  4353. /**
  4354. * Error code indicating that an invalid key was used in a nested
  4355. * JSONObject.
  4356. * @property INVALID_NESTED_KEY
  4357. * @static
  4358. * @final
  4359. */
  4360. ParseError.INVALID_NESTED_KEY = 121;
  4361. /**
  4362. * Error code indicating that an invalid filename was used for ParseFile.
  4363. * A valid file name contains only a-zA-Z0-9_. characters and is between 1
  4364. * and 128 characters.
  4365. * @property INVALID_FILE_NAME
  4366. * @static
  4367. * @final
  4368. */
  4369. ParseError.INVALID_FILE_NAME = 122;
  4370. /**
  4371. * Error code indicating an invalid ACL was provided.
  4372. * @property INVALID_ACL
  4373. * @static
  4374. * @final
  4375. */
  4376. ParseError.INVALID_ACL = 123;
  4377. /**
  4378. * Error code indicating that the request timed out on the server. Typically
  4379. * this indicates that the request is too expensive to run.
  4380. * @property TIMEOUT
  4381. * @static
  4382. * @final
  4383. */
  4384. ParseError.TIMEOUT = 124;
  4385. /**
  4386. * Error code indicating that the email address was invalid.
  4387. * @property INVALID_EMAIL_ADDRESS
  4388. * @static
  4389. * @final
  4390. */
  4391. ParseError.INVALID_EMAIL_ADDRESS = 125;
  4392. /**
  4393. * Error code indicating a missing content type.
  4394. * @property MISSING_CONTENT_TYPE
  4395. * @static
  4396. * @final
  4397. */
  4398. ParseError.MISSING_CONTENT_TYPE = 126;
  4399. /**
  4400. * Error code indicating a missing content length.
  4401. * @property MISSING_CONTENT_LENGTH
  4402. * @static
  4403. * @final
  4404. */
  4405. ParseError.MISSING_CONTENT_LENGTH = 127;
  4406. /**
  4407. * Error code indicating an invalid content length.
  4408. * @property INVALID_CONTENT_LENGTH
  4409. * @static
  4410. * @final
  4411. */
  4412. ParseError.INVALID_CONTENT_LENGTH = 128;
  4413. /**
  4414. * Error code indicating a file that was too large.
  4415. * @property FILE_TOO_LARGE
  4416. * @static
  4417. * @final
  4418. */
  4419. ParseError.FILE_TOO_LARGE = 129;
  4420. /**
  4421. * Error code indicating an error saving a file.
  4422. * @property FILE_SAVE_ERROR
  4423. * @static
  4424. * @final
  4425. */
  4426. ParseError.FILE_SAVE_ERROR = 130;
  4427. /**
  4428. * Error code indicating that a unique field was given a value that is
  4429. * already taken.
  4430. * @property DUPLICATE_VALUE
  4431. * @static
  4432. * @final
  4433. */
  4434. ParseError.DUPLICATE_VALUE = 137;
  4435. /**
  4436. * Error code indicating that a role's name is invalid.
  4437. * @property INVALID_ROLE_NAME
  4438. * @static
  4439. * @final
  4440. */
  4441. ParseError.INVALID_ROLE_NAME = 139;
  4442. /**
  4443. * Error code indicating that an application quota was exceeded. Upgrade to
  4444. * resolve.
  4445. * @property EXCEEDED_QUOTA
  4446. * @static
  4447. * @final
  4448. */
  4449. ParseError.EXCEEDED_QUOTA = 140;
  4450. /**
  4451. * Error code indicating that a Cloud Code script failed.
  4452. * @property SCRIPT_FAILED
  4453. * @static
  4454. * @final
  4455. */
  4456. ParseError.SCRIPT_FAILED = 141;
  4457. /**
  4458. * Error code indicating that a Cloud Code validation failed.
  4459. * @property VALIDATION_ERROR
  4460. * @static
  4461. * @final
  4462. */
  4463. ParseError.VALIDATION_ERROR = 142;
  4464. /**
  4465. * Error code indicating that invalid image data was provided.
  4466. * @property INVALID_IMAGE_DATA
  4467. * @static
  4468. * @final
  4469. */
  4470. ParseError.INVALID_IMAGE_DATA = 143;
  4471. /**
  4472. * Error code indicating an unsaved file.
  4473. * @property UNSAVED_FILE_ERROR
  4474. * @static
  4475. * @final
  4476. */
  4477. ParseError.UNSAVED_FILE_ERROR = 151;
  4478. /**
  4479. * Error code indicating an invalid push time.
  4480. * @property INVALID_PUSH_TIME_ERROR
  4481. * @static
  4482. * @final
  4483. */
  4484. ParseError.INVALID_PUSH_TIME_ERROR = 152;
  4485. /**
  4486. * Error code indicating an error deleting a file.
  4487. * @property FILE_DELETE_ERROR
  4488. * @static
  4489. * @final
  4490. */
  4491. ParseError.FILE_DELETE_ERROR = 153;
  4492. /**
  4493. * Error code indicating that the application has exceeded its request
  4494. * limit.
  4495. * @property REQUEST_LIMIT_EXCEEDED
  4496. * @static
  4497. * @final
  4498. */
  4499. ParseError.REQUEST_LIMIT_EXCEEDED = 155;
  4500. /**
  4501. * Error code indicating an invalid event name.
  4502. * @property INVALID_EVENT_NAME
  4503. * @static
  4504. * @final
  4505. */
  4506. ParseError.INVALID_EVENT_NAME = 160;
  4507. /**
  4508. * Error code indicating that the username is missing or empty.
  4509. * @property USERNAME_MISSING
  4510. * @static
  4511. * @final
  4512. */
  4513. ParseError.USERNAME_MISSING = 200;
  4514. /**
  4515. * Error code indicating that the password is missing or empty.
  4516. * @property PASSWORD_MISSING
  4517. * @static
  4518. * @final
  4519. */
  4520. ParseError.PASSWORD_MISSING = 201;
  4521. /**
  4522. * Error code indicating that the username has already been taken.
  4523. * @property USERNAME_TAKEN
  4524. * @static
  4525. * @final
  4526. */
  4527. ParseError.USERNAME_TAKEN = 202;
  4528. /**
  4529. * Error code indicating that the email has already been taken.
  4530. * @property EMAIL_TAKEN
  4531. * @static
  4532. * @final
  4533. */
  4534. ParseError.EMAIL_TAKEN = 203;
  4535. /**
  4536. * Error code indicating that the email is missing, but must be specified.
  4537. * @property EMAIL_MISSING
  4538. * @static
  4539. * @final
  4540. */
  4541. ParseError.EMAIL_MISSING = 204;
  4542. /**
  4543. * Error code indicating that a user with the specified email was not found.
  4544. * @property EMAIL_NOT_FOUND
  4545. * @static
  4546. * @final
  4547. */
  4548. ParseError.EMAIL_NOT_FOUND = 205;
  4549. /**
  4550. * Error code indicating that a user object without a valid session could
  4551. * not be altered.
  4552. * @property SESSION_MISSING
  4553. * @static
  4554. * @final
  4555. */
  4556. ParseError.SESSION_MISSING = 206;
  4557. /**
  4558. * Error code indicating that a user can only be created through signup.
  4559. * @property MUST_CREATE_USER_THROUGH_SIGNUP
  4560. * @static
  4561. * @final
  4562. */
  4563. ParseError.MUST_CREATE_USER_THROUGH_SIGNUP = 207;
  4564. /**
  4565. * Error code indicating that an an account being linked is already linked
  4566. * to another user.
  4567. * @property ACCOUNT_ALREADY_LINKED
  4568. * @static
  4569. * @final
  4570. */
  4571. ParseError.ACCOUNT_ALREADY_LINKED = 208;
  4572. /**
  4573. * Error code indicating that the current session token is invalid.
  4574. * @property INVALID_SESSION_TOKEN
  4575. * @static
  4576. * @final
  4577. */
  4578. ParseError.INVALID_SESSION_TOKEN = 209;
  4579. /**
  4580. * Error code indicating that a user cannot be linked to an account because
  4581. * that account's id could not be found.
  4582. * @property LINKED_ID_MISSING
  4583. * @static
  4584. * @final
  4585. */
  4586. ParseError.LINKED_ID_MISSING = 250;
  4587. /**
  4588. * Error code indicating that a user with a linked (e.g. Facebook) account
  4589. * has an invalid session.
  4590. * @property INVALID_LINKED_SESSION
  4591. * @static
  4592. * @final
  4593. */
  4594. ParseError.INVALID_LINKED_SESSION = 251;
  4595. /**
  4596. * Error code indicating that a service being linked (e.g. Facebook or
  4597. * Twitter) is unsupported.
  4598. * @property UNSUPPORTED_SERVICE
  4599. * @static
  4600. * @final
  4601. */
  4602. ParseError.UNSUPPORTED_SERVICE = 252;
  4603. /**
  4604. * Error code indicating an invalid operation occured on schema
  4605. * @property INVALID_SCHEMA_OPERATION
  4606. * @static
  4607. * @final
  4608. */
  4609. ParseError.INVALID_SCHEMA_OPERATION = 255;
  4610. /**
  4611. * Error code indicating that there were multiple errors. Aggregate errors
  4612. * have an "errors" property, which is an array of error objects with more
  4613. * detail about each error that occurred.
  4614. * @property AGGREGATE_ERROR
  4615. * @static
  4616. * @final
  4617. */
  4618. ParseError.AGGREGATE_ERROR = 600;
  4619. /**
  4620. * Error code indicating the client was unable to read an input file.
  4621. * @property FILE_READ_ERROR
  4622. * @static
  4623. * @final
  4624. */
  4625. ParseError.FILE_READ_ERROR = 601;
  4626. /**
  4627. * Error code indicating a real error code is unavailable because
  4628. * we had to use an XDomainRequest object to allow CORS requests in
  4629. * Internet Explorer, which strips the body from HTTP responses that have
  4630. * a non-2XX status code.
  4631. * @property X_DOMAIN_REQUEST
  4632. * @static
  4633. * @final
  4634. */
  4635. ParseError.X_DOMAIN_REQUEST = 602;
  4636. var _default = ParseError;
  4637. exports.default = _default;
  4638. },{"@babel/runtime/helpers/assertThisInitialized":54,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/getPrototypeOf":61,"@babel/runtime/helpers/inherits":62,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/possibleConstructorReturn":70,"@babel/runtime/helpers/wrapNativeSuper":76}],19:[function(_dereq_,module,exports){
  4639. "use strict";
  4640. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  4641. Object.defineProperty(exports, "__esModule", {
  4642. value: true
  4643. });
  4644. exports.default = void 0;
  4645. var _regenerator = _interopRequireDefault(_dereq_("@babel/runtime/regenerator"));
  4646. var _asyncToGenerator2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/asyncToGenerator"));
  4647. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  4648. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  4649. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  4650. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  4651. /**
  4652. * Copyright (c) 2015-present, Parse, LLC.
  4653. * All rights reserved.
  4654. *
  4655. * This source code is licensed under the BSD-style license found in the
  4656. * LICENSE file in the root directory of this source tree. An additional grant
  4657. * of patent rights can be found in the PATENTS file in the same directory.
  4658. *
  4659. * @flow
  4660. */
  4661. /* global XMLHttpRequest, Blob */
  4662. var XHR = null;
  4663. if (typeof XMLHttpRequest !== 'undefined') {
  4664. XHR = XMLHttpRequest;
  4665. }
  4666. XHR = _dereq_('./Xhr.weapp');
  4667. /*:: type Base64 = { base64: string };*/
  4668. /*:: type Uri = { uri: string };*/
  4669. /*:: type FileData = Array<number> | Base64 | Blob | Uri;*/
  4670. /*:: export type FileSource = {
  4671. format: 'file';
  4672. file: Blob;
  4673. type: string
  4674. } | {
  4675. format: 'base64';
  4676. base64: string;
  4677. type: string
  4678. } | {
  4679. format: 'uri';
  4680. uri: string;
  4681. type: string
  4682. };*/
  4683. var dataUriRegexp = /^data:([a-zA-Z]+\/[-a-zA-Z0-9+.]+)(;charset=[a-zA-Z0-9\-\/]*)?;base64,/;
  4684. function b64Digit(number
  4685. /*: number*/
  4686. )
  4687. /*: string*/
  4688. {
  4689. if (number < 26) {
  4690. return String.fromCharCode(65 + number);
  4691. }
  4692. if (number < 52) {
  4693. return String.fromCharCode(97 + (number - 26));
  4694. }
  4695. if (number < 62) {
  4696. return String.fromCharCode(48 + (number - 52));
  4697. }
  4698. if (number === 62) {
  4699. return '+';
  4700. }
  4701. if (number === 63) {
  4702. return '/';
  4703. }
  4704. throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
  4705. }
  4706. /**
  4707. * A Parse.File is a local representation of a file that is saved to the Parse
  4708. * cloud.
  4709. * @alias Parse.File
  4710. */
  4711. var ParseFile =
  4712. /*#__PURE__*/
  4713. function () {
  4714. /**
  4715. * @param name {String} The file's name. This will be prefixed by a unique
  4716. * value once the file has finished saving. The file name must begin with
  4717. * an alphanumeric character, and consist of alphanumeric characters,
  4718. * periods, spaces, underscores, or dashes.
  4719. * @param data {Array} The data for the file, as either:
  4720. * 1. an Array of byte value Numbers, or
  4721. * 2. an Object like { base64: "..." } with a base64-encoded String.
  4722. * 3. an Object like { uri: "..." } with a uri String.
  4723. * 4. a File object selected with a file upload control. (3) only works
  4724. * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
  4725. * For example:
  4726. * <pre>
  4727. * var fileUploadControl = $("#profilePhotoFileUpload")[0];
  4728. * if (fileUploadControl.files.length > 0) {
  4729. * var file = fileUploadControl.files[0];
  4730. * var name = "photo.jpg";
  4731. * var parseFile = new Parse.File(name, file);
  4732. * parseFile.save().then(function() {
  4733. * // The file has been saved to Parse.
  4734. * }, function(error) {
  4735. * // The file either could not be read, or could not be saved to Parse.
  4736. * });
  4737. * }</pre>
  4738. * @param type {String} Optional Content-Type header to use for the file. If
  4739. * this is omitted, the content type will be inferred from the name's
  4740. * extension.
  4741. */
  4742. function ParseFile(name
  4743. /*: string*/
  4744. , data
  4745. /*:: ?: FileData*/
  4746. , type
  4747. /*:: ?: string*/
  4748. ) {
  4749. (0, _classCallCheck2.default)(this, ParseFile);
  4750. (0, _defineProperty2.default)(this, "_name", void 0);
  4751. (0, _defineProperty2.default)(this, "_url", void 0);
  4752. (0, _defineProperty2.default)(this, "_source", void 0);
  4753. (0, _defineProperty2.default)(this, "_previousSave", void 0);
  4754. (0, _defineProperty2.default)(this, "_data", void 0);
  4755. var specifiedType = type || '';
  4756. this._name = name;
  4757. if (data !== undefined) {
  4758. if (Array.isArray(data)) {
  4759. this._data = ParseFile.encodeBase64(data);
  4760. this._source = {
  4761. format: 'base64',
  4762. base64: this._data,
  4763. type: specifiedType
  4764. };
  4765. } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
  4766. this._source = {
  4767. format: 'file',
  4768. file: data,
  4769. type: specifiedType
  4770. };
  4771. } else if (data && typeof data.uri === 'string' && data.uri !== undefined) {
  4772. this._source = {
  4773. format: 'uri',
  4774. uri: data.uri,
  4775. type: specifiedType
  4776. };
  4777. } else if (data && typeof data.base64 === 'string') {
  4778. var base64 = data.base64;
  4779. var commaIndex = base64.indexOf(',');
  4780. if (commaIndex !== -1) {
  4781. var matches = dataUriRegexp.exec(base64.slice(0, commaIndex + 1)); // if data URI with type and charset, there will be 4 matches.
  4782. this._data = base64.slice(commaIndex + 1);
  4783. this._source = {
  4784. format: 'base64',
  4785. base64: this._data,
  4786. type: matches[1]
  4787. };
  4788. } else {
  4789. this._data = base64;
  4790. this._source = {
  4791. format: 'base64',
  4792. base64: base64,
  4793. type: specifiedType
  4794. };
  4795. }
  4796. } else {
  4797. throw new TypeError('Cannot create a Parse.File with that data.');
  4798. }
  4799. }
  4800. }
  4801. /**
  4802. * Return the data for the file, downloading it if not already present.
  4803. * Data is present if initialized with Byte Array, Base64 or Saved with Uri.
  4804. * Data is cleared if saved with File object selected with a file upload control
  4805. *
  4806. * @return {Promise} Promise that is resolve with base64 data
  4807. */
  4808. (0, _createClass2.default)(ParseFile, [{
  4809. key: "getData",
  4810. value: function () {
  4811. var _getData = (0, _asyncToGenerator2.default)(
  4812. /*#__PURE__*/
  4813. _regenerator.default.mark(function _callee() {
  4814. var controller, result;
  4815. return _regenerator.default.wrap(function (_context) {
  4816. while (1) {
  4817. switch (_context.prev = _context.next) {
  4818. case 0:
  4819. if (!this._data) {
  4820. _context.next = 2;
  4821. break;
  4822. }
  4823. return _context.abrupt("return", this._data);
  4824. case 2:
  4825. if (this._url) {
  4826. _context.next = 4;
  4827. break;
  4828. }
  4829. throw new Error('Cannot retrieve data for unsaved ParseFile.');
  4830. case 4:
  4831. controller = _CoreManager.default.getFileController();
  4832. _context.next = 7;
  4833. return controller.download(this._url);
  4834. case 7:
  4835. result = _context.sent;
  4836. this._data = result.base64;
  4837. return _context.abrupt("return", this._data);
  4838. case 10:
  4839. case "end":
  4840. return _context.stop();
  4841. }
  4842. }
  4843. }, _callee, this);
  4844. }));
  4845. return function () {
  4846. return _getData.apply(this, arguments);
  4847. };
  4848. }()
  4849. /**
  4850. * Gets the name of the file. Before save is called, this is the filename
  4851. * given by the user. After save is called, that name gets prefixed with a
  4852. * unique identifier.
  4853. * @return {String}
  4854. */
  4855. }, {
  4856. key: "name",
  4857. value: function ()
  4858. /*: string*/
  4859. {
  4860. return this._name;
  4861. }
  4862. /**
  4863. * Gets the url of the file. It is only available after you save the file or
  4864. * after you get the file from a Parse.Object.
  4865. * @param {Object} options An object to specify url options
  4866. * @return {String}
  4867. */
  4868. }, {
  4869. key: "url",
  4870. value: function (options
  4871. /*:: ?: { forceSecure?: boolean }*/
  4872. )
  4873. /*: ?string*/
  4874. {
  4875. options = options || {};
  4876. if (!this._url) {
  4877. return;
  4878. }
  4879. if (options.forceSecure) {
  4880. return this._url.replace(/^http:\/\//i, 'https://');
  4881. } else {
  4882. return this._url;
  4883. }
  4884. }
  4885. /**
  4886. * Saves the file to the Parse cloud.
  4887. * @param {Object} options
  4888. * * Valid options are:<ul>
  4889. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  4890. * be used for this request.
  4891. * <li>progress: In Browser only, callback for upload progress
  4892. * </ul>
  4893. * @return {Promise} Promise that is resolved when the save finishes.
  4894. */
  4895. }, {
  4896. key: "save",
  4897. value: function (options
  4898. /*:: ?: FullOptions*/
  4899. ) {
  4900. var _this = this;
  4901. options = options || {};
  4902. var controller = _CoreManager.default.getFileController();
  4903. if (!this._previousSave) {
  4904. if (this._source.format === 'file') {
  4905. this._previousSave = controller.saveFile(this._name, this._source, options).then(function (res) {
  4906. _this._name = res.name;
  4907. _this._url = res.url;
  4908. _this._data = null;
  4909. return _this;
  4910. });
  4911. } else if (this._source.format === 'uri') {
  4912. this._previousSave = controller.download(this._source.uri).then(function (result) {
  4913. var newSource = {
  4914. format: 'base64',
  4915. base64: result.base64,
  4916. type: result.contentType
  4917. };
  4918. _this._data = result.base64;
  4919. return controller.saveBase64(_this._name, newSource, options);
  4920. }).then(function (res) {
  4921. _this._name = res.name;
  4922. _this._url = res.url;
  4923. return _this;
  4924. });
  4925. } else {
  4926. this._previousSave = controller.saveBase64(this._name, this._source, options).then(function (res) {
  4927. _this._name = res.name;
  4928. _this._url = res.url;
  4929. return _this;
  4930. });
  4931. }
  4932. }
  4933. if (this._previousSave) {
  4934. return this._previousSave;
  4935. }
  4936. }
  4937. }, {
  4938. key: "toJSON",
  4939. value: function ()
  4940. /*: { name: ?string, url: ?string }*/
  4941. {
  4942. return {
  4943. __type: 'File',
  4944. name: this._name,
  4945. url: this._url
  4946. };
  4947. }
  4948. }, {
  4949. key: "equals",
  4950. value: function (other
  4951. /*: mixed*/
  4952. )
  4953. /*: boolean*/
  4954. {
  4955. if (this === other) {
  4956. return true;
  4957. } // Unsaved Files are never equal, since they will be saved to different URLs
  4958. return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
  4959. }
  4960. }], [{
  4961. key: "fromJSON",
  4962. value: function (obj)
  4963. /*: ParseFile*/
  4964. {
  4965. if (obj.__type !== 'File') {
  4966. throw new TypeError('JSON object does not represent a ParseFile');
  4967. }
  4968. var file = new ParseFile(obj.name);
  4969. file._url = obj.url;
  4970. return file;
  4971. }
  4972. }, {
  4973. key: "encodeBase64",
  4974. value: function (bytes
  4975. /*: Array<number>*/
  4976. )
  4977. /*: string*/
  4978. {
  4979. var chunks = [];
  4980. chunks.length = Math.ceil(bytes.length / 3);
  4981. for (var i = 0; i < chunks.length; i++) {
  4982. var b1 = bytes[i * 3];
  4983. var b2 = bytes[i * 3 + 1] || 0;
  4984. var b3 = bytes[i * 3 + 2] || 0;
  4985. var has2 = i * 3 + 1 < bytes.length;
  4986. var has3 = i * 3 + 2 < bytes.length;
  4987. 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('');
  4988. }
  4989. return chunks.join('');
  4990. }
  4991. }]);
  4992. return ParseFile;
  4993. }();
  4994. var DefaultController = {
  4995. saveFile: function (name
  4996. /*: string*/
  4997. , source
  4998. /*: FileSource*/
  4999. , options
  5000. /*:: ?: FullOptions*/
  5001. ) {
  5002. if (source.format !== 'file') {
  5003. throw new Error('saveFile can only be used with File-type sources.');
  5004. } // To directly upload a File, we use a REST-style AJAX request
  5005. var headers = {
  5006. 'X-Parse-Application-ID': _CoreManager.default.get('APPLICATION_ID'),
  5007. 'Content-Type': source.type || (source.file ? source.file.type : null)
  5008. };
  5009. var jsKey = _CoreManager.default.get('JAVASCRIPT_KEY');
  5010. if (jsKey) {
  5011. headers['X-Parse-JavaScript-Key'] = jsKey;
  5012. }
  5013. var url = _CoreManager.default.get('SERVER_URL');
  5014. if (url[url.length - 1] !== '/') {
  5015. url += '/';
  5016. }
  5017. url += 'files/' + name;
  5018. return _CoreManager.default.getRESTController().ajax('POST', url, source.file, headers, options).then(function (res) {
  5019. return res.response;
  5020. });
  5021. },
  5022. saveBase64: function (name
  5023. /*: string*/
  5024. , source
  5025. /*: FileSource*/
  5026. , options
  5027. /*:: ?: FullOptions*/
  5028. ) {
  5029. if (source.format !== 'base64') {
  5030. throw new Error('saveBase64 can only be used with Base64-type sources.');
  5031. }
  5032. var data
  5033. /*: { base64: any; _ContentType?: any }*/
  5034. = {
  5035. base64: source.base64
  5036. };
  5037. if (source.type) {
  5038. data._ContentType = source.type;
  5039. }
  5040. return _CoreManager.default.getRESTController().request('POST', 'files/' + name, data, options);
  5041. },
  5042. download: function (uri) {
  5043. if (XHR) {
  5044. return this.downloadAjax(uri);
  5045. } else {
  5046. return Promise.reject('Cannot make a request: No definition of XMLHttpRequest was found.');
  5047. }
  5048. },
  5049. downloadAjax: function (uri) {
  5050. return new Promise(function (resolve, reject) {
  5051. var xhr = new XHR();
  5052. xhr.open('GET', uri, true);
  5053. xhr.responseType = 'arraybuffer';
  5054. xhr.onerror = function (e) {
  5055. reject(e);
  5056. };
  5057. xhr.onreadystatechange = function () {
  5058. if (xhr.readyState !== 4) {
  5059. return;
  5060. }
  5061. var bytes = new Uint8Array(this.response);
  5062. resolve({
  5063. base64: ParseFile.encodeBase64(bytes),
  5064. contentType: xhr.getResponseHeader('content-type')
  5065. });
  5066. };
  5067. xhr.send();
  5068. });
  5069. },
  5070. _setXHR: function (xhr
  5071. /*: any*/
  5072. ) {
  5073. XHR = xhr;
  5074. }
  5075. };
  5076. _CoreManager.default.setFileController(DefaultController);
  5077. var _default = ParseFile;
  5078. exports.default = _default;
  5079. },{"./CoreManager":4,"./Xhr.weapp":40,"@babel/runtime/helpers/asyncToGenerator":55,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/regenerator":78}],20:[function(_dereq_,module,exports){
  5080. "use strict";
  5081. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  5082. Object.defineProperty(exports, "__esModule", {
  5083. value: true
  5084. });
  5085. exports.default = void 0;
  5086. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  5087. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  5088. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  5089. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  5090. /**
  5091. * Copyright (c) 2015-present, Parse, LLC.
  5092. * All rights reserved.
  5093. *
  5094. * This source code is licensed under the BSD-style license found in the
  5095. * LICENSE file in the root directory of this source tree. An additional grant
  5096. * of patent rights can be found in the PATENTS file in the same directory.
  5097. *
  5098. * @flow
  5099. */
  5100. /**
  5101. * Creates a new GeoPoint with any of the following forms:<br>
  5102. * <pre>
  5103. * new GeoPoint(otherGeoPoint)
  5104. * new GeoPoint(30, 30)
  5105. * new GeoPoint([30, 30])
  5106. * new GeoPoint({latitude: 30, longitude: 30})
  5107. * new GeoPoint() // defaults to (0, 0)
  5108. * </pre>
  5109. * <p>Represents a latitude / longitude point that may be associated
  5110. * with a key in a ParseObject or used as a reference point for geo queries.
  5111. * This allows proximity-based queries on the key.</p>
  5112. *
  5113. * <p>Only one key in a class may contain a GeoPoint.</p>
  5114. *
  5115. * <p>Example:<pre>
  5116. * var point = new Parse.GeoPoint(30.0, -20.0);
  5117. * var object = new Parse.Object("PlaceObject");
  5118. * object.set("location", point);
  5119. * object.save();</pre></p>
  5120. * @alias Parse.GeoPoint
  5121. */
  5122. /* global navigator */
  5123. var ParseGeoPoint =
  5124. /*#__PURE__*/
  5125. function () {
  5126. /**
  5127. * @param {(Number[]|Object|Number)} options Either a list of coordinate pairs, an object with `latitude`, `longitude`, or the latitude or the point.
  5128. * @param {Number} longitude The longitude of the GeoPoint
  5129. */
  5130. function ParseGeoPoint(arg1
  5131. /*: Array<number> |
  5132. { latitude: number; longitude: number } |
  5133. number*/
  5134. , arg2
  5135. /*:: ?: number*/
  5136. ) {
  5137. (0, _classCallCheck2.default)(this, ParseGeoPoint);
  5138. (0, _defineProperty2.default)(this, "_latitude", void 0);
  5139. (0, _defineProperty2.default)(this, "_longitude", void 0);
  5140. if (Array.isArray(arg1)) {
  5141. ParseGeoPoint._validate(arg1[0], arg1[1]);
  5142. this._latitude = arg1[0];
  5143. this._longitude = arg1[1];
  5144. } else if ((0, _typeof2.default)(arg1) === 'object') {
  5145. ParseGeoPoint._validate(arg1.latitude, arg1.longitude);
  5146. this._latitude = arg1.latitude;
  5147. this._longitude = arg1.longitude;
  5148. } else if (arg1 !== undefined && arg2 !== undefined) {
  5149. ParseGeoPoint._validate(arg1, arg2);
  5150. this._latitude = arg1;
  5151. this._longitude = arg2;
  5152. } else {
  5153. this._latitude = 0;
  5154. this._longitude = 0;
  5155. }
  5156. }
  5157. /**
  5158. * North-south portion of the coordinate, in range [-90, 90].
  5159. * Throws an exception if set out of range in a modern browser.
  5160. * @property latitude
  5161. * @type Number
  5162. */
  5163. (0, _createClass2.default)(ParseGeoPoint, [{
  5164. key: "toJSON",
  5165. /**
  5166. * Returns a JSON representation of the GeoPoint, suitable for Parse.
  5167. * @return {Object}
  5168. */
  5169. value: function ()
  5170. /*: { __type: string; latitude: number; longitude: number }*/
  5171. {
  5172. ParseGeoPoint._validate(this._latitude, this._longitude);
  5173. return {
  5174. __type: 'GeoPoint',
  5175. latitude: this._latitude,
  5176. longitude: this._longitude
  5177. };
  5178. }
  5179. }, {
  5180. key: "equals",
  5181. value: function (other
  5182. /*: mixed*/
  5183. )
  5184. /*: boolean*/
  5185. {
  5186. return other instanceof ParseGeoPoint && this.latitude === other.latitude && this.longitude === other.longitude;
  5187. }
  5188. /**
  5189. * Returns the distance from this GeoPoint to another in radians.
  5190. * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
  5191. * @return {Number}
  5192. */
  5193. }, {
  5194. key: "radiansTo",
  5195. value: function (point
  5196. /*: ParseGeoPoint*/
  5197. )
  5198. /*: number*/
  5199. {
  5200. var d2r = Math.PI / 180.0;
  5201. var lat1rad = this.latitude * d2r;
  5202. var long1rad = this.longitude * d2r;
  5203. var lat2rad = point.latitude * d2r;
  5204. var long2rad = point.longitude * d2r;
  5205. var sinDeltaLatDiv2 = Math.sin((lat1rad - lat2rad) / 2);
  5206. var sinDeltaLongDiv2 = Math.sin((long1rad - long2rad) / 2); // Square of half the straight line chord distance between both points.
  5207. var a = sinDeltaLatDiv2 * sinDeltaLatDiv2 + Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2;
  5208. a = Math.min(1.0, a);
  5209. return 2 * Math.asin(Math.sqrt(a));
  5210. }
  5211. /**
  5212. * Returns the distance from this GeoPoint to another in kilometers.
  5213. * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
  5214. * @return {Number}
  5215. */
  5216. }, {
  5217. key: "kilometersTo",
  5218. value: function (point
  5219. /*: ParseGeoPoint*/
  5220. )
  5221. /*: number*/
  5222. {
  5223. return this.radiansTo(point) * 6371.0;
  5224. }
  5225. /**
  5226. * Returns the distance from this GeoPoint to another in miles.
  5227. * @param {Parse.GeoPoint} point the other Parse.GeoPoint.
  5228. * @return {Number}
  5229. */
  5230. }, {
  5231. key: "milesTo",
  5232. value: function (point
  5233. /*: ParseGeoPoint*/
  5234. )
  5235. /*: number*/
  5236. {
  5237. return this.radiansTo(point) * 3958.8;
  5238. }
  5239. /*
  5240. * Throws an exception if the given lat-long is out of bounds.
  5241. */
  5242. }, {
  5243. key: "latitude",
  5244. get: function ()
  5245. /*: number*/
  5246. {
  5247. return this._latitude;
  5248. },
  5249. set: function (val
  5250. /*: number*/
  5251. ) {
  5252. ParseGeoPoint._validate(val, this.longitude);
  5253. this._latitude = val;
  5254. }
  5255. /**
  5256. * East-west portion of the coordinate, in range [-180, 180].
  5257. * Throws if set out of range in a modern browser.
  5258. * @property longitude
  5259. * @type Number
  5260. */
  5261. }, {
  5262. key: "longitude",
  5263. get: function ()
  5264. /*: number*/
  5265. {
  5266. return this._longitude;
  5267. },
  5268. set: function (val
  5269. /*: number*/
  5270. ) {
  5271. ParseGeoPoint._validate(this.latitude, val);
  5272. this._longitude = val;
  5273. }
  5274. }], [{
  5275. key: "_validate",
  5276. value: function (latitude
  5277. /*: number*/
  5278. , longitude
  5279. /*: number*/
  5280. ) {
  5281. if (isNaN(latitude) || isNaN(longitude) || typeof latitude !== 'number' || typeof longitude !== 'number') {
  5282. throw new TypeError('GeoPoint latitude and longitude must be valid numbers');
  5283. }
  5284. if (latitude < -90.0) {
  5285. throw new TypeError('GeoPoint latitude out of bounds: ' + latitude + ' < -90.0.');
  5286. }
  5287. if (latitude > 90.0) {
  5288. throw new TypeError('GeoPoint latitude out of bounds: ' + latitude + ' > 90.0.');
  5289. }
  5290. if (longitude < -180.0) {
  5291. throw new TypeError('GeoPoint longitude out of bounds: ' + longitude + ' < -180.0.');
  5292. }
  5293. if (longitude > 180.0) {
  5294. throw new TypeError('GeoPoint longitude out of bounds: ' + longitude + ' > 180.0.');
  5295. }
  5296. }
  5297. /**
  5298. * Creates a GeoPoint with the user's current location, if available.
  5299. * Calls options.success with a new GeoPoint instance or calls options.error.
  5300. * @static
  5301. */
  5302. }, {
  5303. key: "current",
  5304. value: function () {
  5305. return navigator.geolocation.getCurrentPosition(function (location) {
  5306. return new ParseGeoPoint(location.coords.latitude, location.coords.longitude);
  5307. });
  5308. }
  5309. }]);
  5310. return ParseGeoPoint;
  5311. }();
  5312. var _default = ParseGeoPoint;
  5313. exports.default = _default;
  5314. },{"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],21:[function(_dereq_,module,exports){
  5315. "use strict";
  5316. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  5317. Object.defineProperty(exports, "__esModule", {
  5318. value: true
  5319. });
  5320. exports.default = void 0;
  5321. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  5322. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  5323. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  5324. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  5325. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  5326. var _ParseObject2 = _interopRequireDefault(_dereq_("./ParseObject"));
  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. var Installation =
  5338. /*#__PURE__*/
  5339. function (_ParseObject) {
  5340. (0, _inherits2.default)(Installation, _ParseObject);
  5341. function Installation(attributes
  5342. /*: ?AttributeMap*/
  5343. ) {
  5344. var _this;
  5345. (0, _classCallCheck2.default)(this, Installation);
  5346. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(Installation).call(this, '_Installation'));
  5347. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  5348. if (!_this.set(attributes || {})) {
  5349. throw new Error('Can\'t create an invalid Session');
  5350. }
  5351. }
  5352. return _this;
  5353. }
  5354. return Installation;
  5355. }(_ParseObject2.default);
  5356. exports.default = Installation;
  5357. _ParseObject2.default.registerSubclass('_Installation', Installation);
  5358. },{"./ParseObject":23,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/getPrototypeOf":61,"@babel/runtime/helpers/inherits":62,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/possibleConstructorReturn":70,"@babel/runtime/helpers/typeof":75}],22:[function(_dereq_,module,exports){
  5359. "use strict";
  5360. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  5361. Object.defineProperty(exports, "__esModule", {
  5362. value: true
  5363. });
  5364. exports.default = void 0;
  5365. var _regenerator = _interopRequireDefault(_dereq_("@babel/runtime/regenerator"));
  5366. var _asyncToGenerator2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/asyncToGenerator"));
  5367. var _EventEmitter = _interopRequireDefault(_dereq_("./EventEmitter"));
  5368. var _LiveQueryClient = _interopRequireDefault(_dereq_("./LiveQueryClient"));
  5369. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  5370. /**
  5371. * Copyright (c) 2015-present, Parse, LLC.
  5372. * All rights reserved.
  5373. *
  5374. * This source code is licensed under the BSD-style license found in the
  5375. * LICENSE file in the root directory of this source tree. An additional grant
  5376. * of patent rights can be found in the PATENTS file in the same directory.
  5377. *
  5378. * @flow
  5379. */
  5380. function getLiveQueryClient()
  5381. /*: LiveQueryClient*/
  5382. {
  5383. return _CoreManager.default.getLiveQueryController().getDefaultLiveQueryClient();
  5384. }
  5385. /**
  5386. *
  5387. * We expose three events to help you monitor the status of the WebSocket connection:
  5388. *
  5389. * <p>Open - When we establish the WebSocket connection to the LiveQuery server, you'll get this event.
  5390. *
  5391. * <pre>
  5392. * Parse.LiveQuery.on('open', () => {
  5393. *
  5394. * });</pre></p>
  5395. *
  5396. * <p>Close - When we lose the WebSocket connection to the LiveQuery server, you'll get this event.
  5397. *
  5398. * <pre>
  5399. * Parse.LiveQuery.on('close', () => {
  5400. *
  5401. * });</pre></p>
  5402. *
  5403. * <p>Error - When some network error or LiveQuery server error happens, you'll get this event.
  5404. *
  5405. * <pre>
  5406. * Parse.LiveQuery.on('error', (error) => {
  5407. *
  5408. * });</pre></p>
  5409. *
  5410. * @class Parse.LiveQuery
  5411. * @static
  5412. *
  5413. */
  5414. var LiveQuery = new _EventEmitter.default();
  5415. /**
  5416. * After open is called, the LiveQuery will try to send a connect request
  5417. * to the LiveQuery server.
  5418. */
  5419. LiveQuery.open =
  5420. /*#__PURE__*/
  5421. (0, _asyncToGenerator2.default)(
  5422. /*#__PURE__*/
  5423. _regenerator.default.mark(function _callee() {
  5424. var liveQueryClient;
  5425. return _regenerator.default.wrap(function (_context) {
  5426. while (1) {
  5427. switch (_context.prev = _context.next) {
  5428. case 0:
  5429. _context.next = 2;
  5430. return getLiveQueryClient();
  5431. case 2:
  5432. liveQueryClient = _context.sent;
  5433. return _context.abrupt("return", liveQueryClient.open());
  5434. case 4:
  5435. case "end":
  5436. return _context.stop();
  5437. }
  5438. }
  5439. }, _callee);
  5440. }));
  5441. /**
  5442. * When you're done using LiveQuery, you can call Parse.LiveQuery.close().
  5443. * This function will close the WebSocket connection to the LiveQuery server,
  5444. * cancel the auto reconnect, and unsubscribe all subscriptions based on it.
  5445. * If you call query.subscribe() after this, we'll create a new WebSocket
  5446. * connection to the LiveQuery server.
  5447. */
  5448. LiveQuery.close =
  5449. /*#__PURE__*/
  5450. (0, _asyncToGenerator2.default)(
  5451. /*#__PURE__*/
  5452. _regenerator.default.mark(function _callee2() {
  5453. var liveQueryClient;
  5454. return _regenerator.default.wrap(function (_context2) {
  5455. while (1) {
  5456. switch (_context2.prev = _context2.next) {
  5457. case 0:
  5458. _context2.next = 2;
  5459. return getLiveQueryClient();
  5460. case 2:
  5461. liveQueryClient = _context2.sent;
  5462. return _context2.abrupt("return", liveQueryClient.close());
  5463. case 4:
  5464. case "end":
  5465. return _context2.stop();
  5466. }
  5467. }
  5468. }, _callee2);
  5469. })); // Register a default onError callback to make sure we do not crash on error
  5470. LiveQuery.on('error', function () {});
  5471. var _default = LiveQuery;
  5472. exports.default = _default;
  5473. var defaultLiveQueryClient;
  5474. var DefaultLiveQueryController = {
  5475. setDefaultLiveQueryClient: function (liveQueryClient
  5476. /*: LiveQueryClient*/
  5477. ) {
  5478. defaultLiveQueryClient = liveQueryClient;
  5479. },
  5480. getDefaultLiveQueryClient: function () {
  5481. var _getDefaultLiveQueryClient = (0, _asyncToGenerator2.default)(
  5482. /*#__PURE__*/
  5483. _regenerator.default.mark(function _callee3() {
  5484. var currentUser, sessionToken, liveQueryServerURL, serverURL, protocol, host, applicationId, javascriptKey, masterKey;
  5485. return _regenerator.default.wrap(function (_context3) {
  5486. while (1) {
  5487. switch (_context3.prev = _context3.next) {
  5488. case 0:
  5489. if (!defaultLiveQueryClient) {
  5490. _context3.next = 2;
  5491. break;
  5492. }
  5493. return _context3.abrupt("return", defaultLiveQueryClient);
  5494. case 2:
  5495. _context3.next = 4;
  5496. return _CoreManager.default.getUserController().currentUserAsync();
  5497. case 4:
  5498. currentUser = _context3.sent;
  5499. sessionToken = currentUser ? currentUser.getSessionToken() : undefined;
  5500. liveQueryServerURL = _CoreManager.default.get('LIVEQUERY_SERVER_URL');
  5501. if (!(liveQueryServerURL && liveQueryServerURL.indexOf('ws') !== 0)) {
  5502. _context3.next = 9;
  5503. break;
  5504. }
  5505. throw new Error('You need to set a proper Parse LiveQuery server url before using LiveQueryClient');
  5506. case 9:
  5507. // If we can not find Parse.liveQueryServerURL, we try to extract it from Parse.serverURL
  5508. if (!liveQueryServerURL) {
  5509. serverURL = _CoreManager.default.get('SERVER_URL');
  5510. protocol = serverURL.indexOf('https') === 0 ? 'wss://' : 'ws://';
  5511. host = serverURL.replace(/^https?:\/\//, '');
  5512. liveQueryServerURL = protocol + host;
  5513. _CoreManager.default.set('LIVEQUERY_SERVER_URL', liveQueryServerURL);
  5514. }
  5515. applicationId = _CoreManager.default.get('APPLICATION_ID');
  5516. javascriptKey = _CoreManager.default.get('JAVASCRIPT_KEY');
  5517. masterKey = _CoreManager.default.get('MASTER_KEY');
  5518. defaultLiveQueryClient = new _LiveQueryClient.default({
  5519. applicationId: applicationId,
  5520. serverURL: liveQueryServerURL,
  5521. javascriptKey: javascriptKey,
  5522. masterKey: masterKey,
  5523. sessionToken: sessionToken
  5524. });
  5525. defaultLiveQueryClient.on('error', function (error) {
  5526. LiveQuery.emit('error', error);
  5527. });
  5528. defaultLiveQueryClient.on('open', function () {
  5529. LiveQuery.emit('open');
  5530. });
  5531. defaultLiveQueryClient.on('close', function () {
  5532. LiveQuery.emit('close');
  5533. });
  5534. return _context3.abrupt("return", defaultLiveQueryClient);
  5535. case 18:
  5536. case "end":
  5537. return _context3.stop();
  5538. }
  5539. }
  5540. }, _callee3);
  5541. }));
  5542. return function () {
  5543. return _getDefaultLiveQueryClient.apply(this, arguments);
  5544. };
  5545. }(),
  5546. _clearCachedDefaultClient: function () {
  5547. defaultLiveQueryClient = null;
  5548. }
  5549. };
  5550. _CoreManager.default.setLiveQueryController(DefaultLiveQueryController);
  5551. },{"./CoreManager":4,"./EventEmitter":5,"./LiveQueryClient":8,"@babel/runtime/helpers/asyncToGenerator":55,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/regenerator":78}],23:[function(_dereq_,module,exports){
  5552. "use strict";
  5553. var _interopRequireWildcard = _dereq_("@babel/runtime/helpers/interopRequireWildcard");
  5554. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  5555. Object.defineProperty(exports, "__esModule", {
  5556. value: true
  5557. });
  5558. exports.default = void 0;
  5559. var _regenerator = _interopRequireDefault(_dereq_("@babel/runtime/regenerator"));
  5560. var _asyncToGenerator2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/asyncToGenerator"));
  5561. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  5562. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  5563. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  5564. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  5565. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  5566. var _canBeSerialized = _interopRequireDefault(_dereq_("./canBeSerialized"));
  5567. var _decode = _interopRequireDefault(_dereq_("./decode"));
  5568. var _encode = _interopRequireDefault(_dereq_("./encode"));
  5569. var _escape2 = _interopRequireDefault(_dereq_("./escape"));
  5570. var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
  5571. var _parseDate = _interopRequireDefault(_dereq_("./parseDate"));
  5572. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  5573. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  5574. var _promiseUtils = _dereq_("./promiseUtils");
  5575. var _LocalDatastoreUtils = _dereq_("./LocalDatastoreUtils");
  5576. var _ParseOp = _dereq_("./ParseOp");
  5577. var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
  5578. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  5579. var SingleInstanceStateController = _interopRequireWildcard(_dereq_("./SingleInstanceStateController"));
  5580. var _unique = _interopRequireDefault(_dereq_("./unique"));
  5581. var UniqueInstanceStateController = _interopRequireWildcard(_dereq_("./UniqueInstanceStateController"));
  5582. var _unsavedChildren = _interopRequireDefault(_dereq_("./unsavedChildren"));
  5583. /**
  5584. * Copyright (c) 2015-present, Parse, LLC.
  5585. * All rights reserved.
  5586. *
  5587. * This source code is licensed under the BSD-style license found in the
  5588. * LICENSE file in the root directory of this source tree. An additional grant
  5589. * of patent rights can be found in the PATENTS file in the same directory.
  5590. *
  5591. * @flow
  5592. */
  5593. var DEFAULT_BATCH_SIZE = 20; // Mapping of class names to constructors, so we can populate objects from the
  5594. // server with appropriate subclasses of ParseObject
  5595. var classMap = {}; // Global counter for generating unique local Ids
  5596. var localCount = 0; // Global counter for generating unique Ids for non-single-instance objects
  5597. var objectCount = 0; // On web clients, objects are single-instance: any two objects with the same Id
  5598. // will have the same attributes. However, this may be dangerous default
  5599. // behavior in a server scenario
  5600. var singleInstance = !_CoreManager.default.get('IS_NODE');
  5601. if (singleInstance) {
  5602. _CoreManager.default.setObjectStateController(SingleInstanceStateController);
  5603. } else {
  5604. _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
  5605. }
  5606. function getServerUrlPath() {
  5607. var serverUrl = _CoreManager.default.get('SERVER_URL');
  5608. if (serverUrl[serverUrl.length - 1] !== '/') {
  5609. serverUrl += '/';
  5610. }
  5611. var url = serverUrl.replace(/https?:\/\//, '');
  5612. return url.substr(url.indexOf('/'));
  5613. }
  5614. /**
  5615. * Creates a new model with defined attributes.
  5616. *
  5617. * <p>You won't normally call this method directly. It is recommended that
  5618. * you use a subclass of <code>Parse.Object</code> instead, created by calling
  5619. * <code>extend</code>.</p>
  5620. *
  5621. * <p>However, if you don't want to use a subclass, or aren't sure which
  5622. * subclass is appropriate, you can use this form:<pre>
  5623. * var object = new Parse.Object("ClassName");
  5624. * </pre>
  5625. * That is basically equivalent to:<pre>
  5626. * var MyClass = Parse.Object.extend("ClassName");
  5627. * var object = new MyClass();
  5628. * </pre></p>
  5629. *
  5630. * @alias Parse.Object
  5631. */
  5632. var ParseObject =
  5633. /*#__PURE__*/
  5634. function () {
  5635. /**
  5636. * @param {String} className The class name for the object
  5637. * @param {Object} attributes The initial set of data to store in the object.
  5638. * @param {Object} options The options for this object instance.
  5639. */
  5640. function ParseObject(className
  5641. /*: ?string | { className: string, [attr: string]: mixed }*/
  5642. , attributes
  5643. /*:: ?: { [attr: string]: mixed }*/
  5644. , options
  5645. /*:: ?: { ignoreValidation: boolean }*/
  5646. ) {
  5647. (0, _classCallCheck2.default)(this, ParseObject);
  5648. (0, _defineProperty2.default)(this, "id", void 0);
  5649. (0, _defineProperty2.default)(this, "_localId", void 0);
  5650. (0, _defineProperty2.default)(this, "_objCount", void 0);
  5651. (0, _defineProperty2.default)(this, "className", void 0); // Enable legacy initializers
  5652. if (typeof this.initialize === 'function') {
  5653. this.initialize.apply(this, arguments);
  5654. }
  5655. var toSet = null;
  5656. this._objCount = objectCount++;
  5657. if (typeof className === 'string') {
  5658. this.className = className;
  5659. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  5660. toSet = attributes;
  5661. }
  5662. } else if (className && (0, _typeof2.default)(className) === 'object') {
  5663. this.className = className.className;
  5664. toSet = {};
  5665. for (var _attr in className) {
  5666. if (_attr !== 'className') {
  5667. toSet[_attr] = className[_attr];
  5668. }
  5669. }
  5670. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  5671. options = attributes;
  5672. }
  5673. }
  5674. if (toSet && !this.set(toSet, options)) {
  5675. throw new Error('Can\'t create an invalid Parse Object');
  5676. }
  5677. }
  5678. /**
  5679. * The ID of this object, unique within its class.
  5680. * @property id
  5681. * @type String
  5682. */
  5683. (0, _createClass2.default)(ParseObject, [{
  5684. key: "_getId",
  5685. /** Private methods **/
  5686. /**
  5687. * Returns a local or server Id used uniquely identify this object
  5688. */
  5689. value: function ()
  5690. /*: string*/
  5691. {
  5692. if (typeof this.id === 'string') {
  5693. return this.id;
  5694. }
  5695. if (typeof this._localId === 'string') {
  5696. return this._localId;
  5697. }
  5698. var localId = 'local' + String(localCount++);
  5699. this._localId = localId;
  5700. return localId;
  5701. }
  5702. /**
  5703. * Returns a unique identifier used to pull data from the State Controller.
  5704. */
  5705. }, {
  5706. key: "_getStateIdentifier",
  5707. value: function ()
  5708. /*: ParseObject | {id: string, className: string}*/
  5709. {
  5710. if (singleInstance) {
  5711. var id = this.id;
  5712. if (!id) {
  5713. id = this._getId();
  5714. }
  5715. return {
  5716. id: id,
  5717. className: this.className
  5718. };
  5719. } else {
  5720. return this;
  5721. }
  5722. }
  5723. }, {
  5724. key: "_getServerData",
  5725. value: function ()
  5726. /*: AttributeMap*/
  5727. {
  5728. var stateController = _CoreManager.default.getObjectStateController();
  5729. return stateController.getServerData(this._getStateIdentifier());
  5730. }
  5731. }, {
  5732. key: "_clearServerData",
  5733. value: function () {
  5734. var serverData = this._getServerData();
  5735. var unset = {};
  5736. for (var _attr2 in serverData) {
  5737. unset[_attr2] = undefined;
  5738. }
  5739. var stateController = _CoreManager.default.getObjectStateController();
  5740. stateController.setServerData(this._getStateIdentifier(), unset);
  5741. }
  5742. }, {
  5743. key: "_getPendingOps",
  5744. value: function ()
  5745. /*: Array<OpsMap>*/
  5746. {
  5747. var stateController = _CoreManager.default.getObjectStateController();
  5748. return stateController.getPendingOps(this._getStateIdentifier());
  5749. }
  5750. /**
  5751. * @param {Array<string>} [keysToClear] - if specified, only ops matching
  5752. * these fields will be cleared
  5753. */
  5754. }, {
  5755. key: "_clearPendingOps",
  5756. value: function (keysToClear
  5757. /*:: ?: Array<string>*/
  5758. ) {
  5759. var pending = this._getPendingOps();
  5760. var latest = pending[pending.length - 1];
  5761. var keys = keysToClear || Object.keys(latest);
  5762. keys.forEach(function (key) {
  5763. delete latest[key];
  5764. });
  5765. }
  5766. }, {
  5767. key: "_getDirtyObjectAttributes",
  5768. value: function ()
  5769. /*: AttributeMap*/
  5770. {
  5771. var attributes = this.attributes;
  5772. var stateController = _CoreManager.default.getObjectStateController();
  5773. var objectCache = stateController.getObjectCache(this._getStateIdentifier());
  5774. var dirty = {};
  5775. for (var _attr3 in attributes) {
  5776. var val = attributes[_attr3];
  5777. if (val && (0, _typeof2.default)(val) === 'object' && !(val instanceof ParseObject) && !(val instanceof _ParseFile.default) && !(val instanceof _ParseRelation.default)) {
  5778. // Due to the way browsers construct maps, the key order will not change
  5779. // unless the object is changed
  5780. try {
  5781. var json = (0, _encode.default)(val, false, true);
  5782. var stringified = JSON.stringify(json);
  5783. if (objectCache[_attr3] !== stringified) {
  5784. dirty[_attr3] = val;
  5785. }
  5786. } catch (e) {
  5787. // Error occurred, possibly by a nested unsaved pointer in a mutable container
  5788. // No matter how it happened, it indicates a change in the attribute
  5789. dirty[_attr3] = val;
  5790. }
  5791. }
  5792. }
  5793. return dirty;
  5794. }
  5795. }, {
  5796. key: "_toFullJSON",
  5797. value: function (seen
  5798. /*:: ?: Array<any>*/
  5799. )
  5800. /*: AttributeMap*/
  5801. {
  5802. var json
  5803. /*: { [key: string]: mixed }*/
  5804. = this.toJSON(seen);
  5805. json.__type = 'Object';
  5806. json.className = this.className;
  5807. return json;
  5808. }
  5809. }, {
  5810. key: "_getSaveJSON",
  5811. value: function ()
  5812. /*: AttributeMap*/
  5813. {
  5814. var pending = this._getPendingOps();
  5815. var dirtyObjects = this._getDirtyObjectAttributes();
  5816. var json = {};
  5817. for (var attr in dirtyObjects) {
  5818. var isDotNotation = false;
  5819. for (var i = 0; i < pending.length; i += 1) {
  5820. for (var field in pending[i]) {
  5821. // Dot notation operations are handled later
  5822. if (field.includes('.')) {
  5823. var fieldName = field.split('.')[0];
  5824. if (fieldName === attr) {
  5825. isDotNotation = true;
  5826. break;
  5827. }
  5828. }
  5829. }
  5830. }
  5831. if (!isDotNotation) {
  5832. json[attr] = new _ParseOp.SetOp(dirtyObjects[attr]).toJSON();
  5833. }
  5834. }
  5835. for (attr in pending[0]) {
  5836. json[attr] = pending[0][attr].toJSON();
  5837. }
  5838. return json;
  5839. }
  5840. }, {
  5841. key: "_getSaveParams",
  5842. value: function ()
  5843. /*: SaveParams*/
  5844. {
  5845. var method = this.id ? 'PUT' : 'POST';
  5846. var body = this._getSaveJSON();
  5847. var path = 'classes/' + this.className;
  5848. if (this.id) {
  5849. path += '/' + this.id;
  5850. } else if (this.className === '_User') {
  5851. path = 'users';
  5852. }
  5853. return {
  5854. method: method,
  5855. body: body,
  5856. path: path
  5857. };
  5858. }
  5859. }, {
  5860. key: "_finishFetch",
  5861. value: function (serverData
  5862. /*: AttributeMap*/
  5863. ) {
  5864. if (!this.id && serverData.objectId) {
  5865. this.id = serverData.objectId;
  5866. }
  5867. var stateController = _CoreManager.default.getObjectStateController();
  5868. stateController.initializeState(this._getStateIdentifier());
  5869. var decoded = {};
  5870. for (var _attr4 in serverData) {
  5871. if (_attr4 === 'ACL') {
  5872. decoded[_attr4] = new _ParseACL.default(serverData[_attr4]);
  5873. } else if (_attr4 !== 'objectId') {
  5874. decoded[_attr4] = (0, _decode.default)(serverData[_attr4]);
  5875. if (decoded[_attr4] instanceof _ParseRelation.default) {
  5876. decoded[_attr4]._ensureParentAndKey(this, _attr4);
  5877. }
  5878. }
  5879. }
  5880. if (decoded.createdAt && typeof decoded.createdAt === 'string') {
  5881. decoded.createdAt = (0, _parseDate.default)(decoded.createdAt);
  5882. }
  5883. if (decoded.updatedAt && typeof decoded.updatedAt === 'string') {
  5884. decoded.updatedAt = (0, _parseDate.default)(decoded.updatedAt);
  5885. }
  5886. if (!decoded.updatedAt && decoded.createdAt) {
  5887. decoded.updatedAt = decoded.createdAt;
  5888. }
  5889. stateController.commitServerChanges(this._getStateIdentifier(), decoded);
  5890. }
  5891. }, {
  5892. key: "_setExisted",
  5893. value: function (existed
  5894. /*: boolean*/
  5895. ) {
  5896. var stateController = _CoreManager.default.getObjectStateController();
  5897. var state = stateController.getState(this._getStateIdentifier());
  5898. if (state) {
  5899. state.existed = existed;
  5900. }
  5901. }
  5902. }, {
  5903. key: "_migrateId",
  5904. value: function (serverId
  5905. /*: string*/
  5906. ) {
  5907. if (this._localId && serverId) {
  5908. if (singleInstance) {
  5909. var stateController = _CoreManager.default.getObjectStateController();
  5910. var oldState = stateController.removeState(this._getStateIdentifier());
  5911. this.id = serverId;
  5912. delete this._localId;
  5913. if (oldState) {
  5914. stateController.initializeState(this._getStateIdentifier(), oldState);
  5915. }
  5916. } else {
  5917. this.id = serverId;
  5918. delete this._localId;
  5919. }
  5920. }
  5921. }
  5922. }, {
  5923. key: "_handleSaveResponse",
  5924. value: function (response
  5925. /*: AttributeMap*/
  5926. , status
  5927. /*: number*/
  5928. ) {
  5929. var changes = {};
  5930. var stateController = _CoreManager.default.getObjectStateController();
  5931. var pending = stateController.popPendingState(this._getStateIdentifier());
  5932. for (var attr in pending) {
  5933. if (pending[attr] instanceof _ParseOp.RelationOp) {
  5934. changes[attr] = pending[attr].applyTo(undefined, this, attr);
  5935. } else if (!(attr in response)) {
  5936. // Only SetOps and UnsetOps should not come back with results
  5937. changes[attr] = pending[attr].applyTo(undefined);
  5938. }
  5939. }
  5940. for (attr in response) {
  5941. if ((attr === 'createdAt' || attr === 'updatedAt') && typeof response[attr] === 'string') {
  5942. changes[attr] = (0, _parseDate.default)(response[attr]);
  5943. } else if (attr === 'ACL') {
  5944. changes[attr] = new _ParseACL.default(response[attr]);
  5945. } else if (attr !== 'objectId') {
  5946. changes[attr] = (0, _decode.default)(response[attr]);
  5947. if (changes[attr] instanceof _ParseOp.UnsetOp) {
  5948. changes[attr] = undefined;
  5949. }
  5950. }
  5951. }
  5952. if (changes.createdAt && !changes.updatedAt) {
  5953. changes.updatedAt = changes.createdAt;
  5954. }
  5955. this._migrateId(response.objectId);
  5956. if (status !== 201) {
  5957. this._setExisted(true);
  5958. }
  5959. stateController.commitServerChanges(this._getStateIdentifier(), changes);
  5960. }
  5961. }, {
  5962. key: "_handleSaveError",
  5963. value: function () {
  5964. var stateController = _CoreManager.default.getObjectStateController();
  5965. stateController.mergeFirstPendingState(this._getStateIdentifier());
  5966. }
  5967. /** Public methods **/
  5968. }, {
  5969. key: "initialize",
  5970. value: function () {} // NOOP
  5971. /**
  5972. * Returns a JSON version of the object suitable for saving to Parse.
  5973. * @return {Object}
  5974. */
  5975. }, {
  5976. key: "toJSON",
  5977. value: function (seen
  5978. /*: Array<any> | void*/
  5979. )
  5980. /*: AttributeMap*/
  5981. {
  5982. var seenEntry = this.id ? this.className + ':' + this.id : this;
  5983. seen = seen || [seenEntry];
  5984. var json = {};
  5985. var attrs = this.attributes;
  5986. for (var _attr5 in attrs) {
  5987. if ((_attr5 === 'createdAt' || _attr5 === 'updatedAt') && attrs[_attr5].toJSON) {
  5988. json[_attr5] = attrs[_attr5].toJSON();
  5989. } else {
  5990. json[_attr5] = (0, _encode.default)(attrs[_attr5], false, false, seen);
  5991. }
  5992. }
  5993. var pending = this._getPendingOps();
  5994. for (var _attr6 in pending[0]) {
  5995. json[_attr6] = pending[0][_attr6].toJSON();
  5996. }
  5997. if (this.id) {
  5998. json.objectId = this.id;
  5999. }
  6000. return json;
  6001. }
  6002. /**
  6003. * Determines whether this ParseObject is equal to another ParseObject
  6004. * @param {Object} other - An other object ot compare
  6005. * @return {Boolean}
  6006. */
  6007. }, {
  6008. key: "equals",
  6009. value: function (other
  6010. /*: mixed*/
  6011. )
  6012. /*: boolean*/
  6013. {
  6014. if (this === other) {
  6015. return true;
  6016. }
  6017. return other instanceof ParseObject && this.className === other.className && this.id === other.id && typeof this.id !== 'undefined';
  6018. }
  6019. /**
  6020. * Returns true if this object has been modified since its last
  6021. * save/refresh. If an attribute is specified, it returns true only if that
  6022. * particular attribute has been modified since the last save/refresh.
  6023. * @param {String} attr An attribute name (optional).
  6024. * @return {Boolean}
  6025. */
  6026. }, {
  6027. key: "dirty",
  6028. value: function (attr
  6029. /*:: ?: string*/
  6030. )
  6031. /*: boolean*/
  6032. {
  6033. if (!this.id) {
  6034. return true;
  6035. }
  6036. var pendingOps = this._getPendingOps();
  6037. var dirtyObjects = this._getDirtyObjectAttributes();
  6038. if (attr) {
  6039. if (dirtyObjects.hasOwnProperty(attr)) {
  6040. return true;
  6041. }
  6042. for (var i = 0; i < pendingOps.length; i++) {
  6043. if (pendingOps[i].hasOwnProperty(attr)) {
  6044. return true;
  6045. }
  6046. }
  6047. return false;
  6048. }
  6049. if (Object.keys(pendingOps[0]).length !== 0) {
  6050. return true;
  6051. }
  6052. if (Object.keys(dirtyObjects).length !== 0) {
  6053. return true;
  6054. }
  6055. return false;
  6056. }
  6057. /**
  6058. * Returns an array of keys that have been modified since last save/refresh
  6059. * @return {String[]}
  6060. */
  6061. }, {
  6062. key: "dirtyKeys",
  6063. value: function ()
  6064. /*: Array<string>*/
  6065. {
  6066. var pendingOps = this._getPendingOps();
  6067. var keys = {};
  6068. for (var i = 0; i < pendingOps.length; i++) {
  6069. for (var _attr7 in pendingOps[i]) {
  6070. keys[_attr7] = true;
  6071. }
  6072. }
  6073. var dirtyObjects = this._getDirtyObjectAttributes();
  6074. for (var _attr8 in dirtyObjects) {
  6075. keys[_attr8] = true;
  6076. }
  6077. return Object.keys(keys);
  6078. }
  6079. /**
  6080. * Returns true if the object has been fetched.
  6081. * @return {Boolean}
  6082. */
  6083. }, {
  6084. key: "isDataAvailable",
  6085. value: function ()
  6086. /*: boolean*/
  6087. {
  6088. var serverData = this._getServerData();
  6089. return !!Object.keys(serverData).length;
  6090. }
  6091. /**
  6092. * Gets a Pointer referencing this Object.
  6093. * @return {Pointer}
  6094. */
  6095. }, {
  6096. key: "toPointer",
  6097. value: function ()
  6098. /*: Pointer*/
  6099. {
  6100. if (!this.id) {
  6101. throw new Error('Cannot create a pointer to an unsaved ParseObject');
  6102. }
  6103. return {
  6104. __type: 'Pointer',
  6105. className: this.className,
  6106. objectId: this.id
  6107. };
  6108. }
  6109. /**
  6110. * Gets the value of an attribute.
  6111. * @param {String} attr The string name of an attribute.
  6112. */
  6113. }, {
  6114. key: "get",
  6115. value: function (attr
  6116. /*: string*/
  6117. )
  6118. /*: mixed*/
  6119. {
  6120. return this.attributes[attr];
  6121. }
  6122. /**
  6123. * Gets a relation on the given class for the attribute.
  6124. * @param String attr The attribute to get the relation for.
  6125. * @return {Parse.Relation}
  6126. */
  6127. }, {
  6128. key: "relation",
  6129. value: function (attr
  6130. /*: string*/
  6131. )
  6132. /*: ParseRelation*/
  6133. {
  6134. var value = this.get(attr);
  6135. if (value) {
  6136. if (!(value instanceof _ParseRelation.default)) {
  6137. throw new Error('Called relation() on non-relation field ' + attr);
  6138. }
  6139. value._ensureParentAndKey(this, attr);
  6140. return value;
  6141. }
  6142. return new _ParseRelation.default(this, attr);
  6143. }
  6144. /**
  6145. * Gets the HTML-escaped value of an attribute.
  6146. * @param {String} attr The string name of an attribute.
  6147. */
  6148. }, {
  6149. key: "escape",
  6150. value: function (attr
  6151. /*: string*/
  6152. )
  6153. /*: string*/
  6154. {
  6155. var val = this.attributes[attr];
  6156. if (val == null) {
  6157. return '';
  6158. }
  6159. if (typeof val !== 'string') {
  6160. if (typeof val.toString !== 'function') {
  6161. return '';
  6162. }
  6163. val = val.toString();
  6164. }
  6165. return (0, _escape2.default)(val);
  6166. }
  6167. /**
  6168. * Returns <code>true</code> if the attribute contains a value that is not
  6169. * null or undefined.
  6170. * @param {String} attr The string name of the attribute.
  6171. * @return {Boolean}
  6172. */
  6173. }, {
  6174. key: "has",
  6175. value: function (attr
  6176. /*: string*/
  6177. )
  6178. /*: boolean*/
  6179. {
  6180. var attributes = this.attributes;
  6181. if (attributes.hasOwnProperty(attr)) {
  6182. return attributes[attr] != null;
  6183. }
  6184. return false;
  6185. }
  6186. /**
  6187. * Sets a hash of model attributes on the object.
  6188. *
  6189. * <p>You can call it with an object containing keys and values, with one
  6190. * key and value, or dot notation. For example:<pre>
  6191. * gameTurn.set({
  6192. * player: player1,
  6193. * diceRoll: 2
  6194. * }, {
  6195. * error: function(gameTurnAgain, error) {
  6196. * // The set failed validation.
  6197. * }
  6198. * });
  6199. *
  6200. * game.set("currentPlayer", player2, {
  6201. * error: function(gameTurnAgain, error) {
  6202. * // The set failed validation.
  6203. * }
  6204. * });
  6205. *
  6206. * game.set("finished", true);</pre></p>
  6207. *
  6208. * game.set("player.score", 10);</pre></p>
  6209. *
  6210. * @param {String} key The key to set.
  6211. * @param {} value The value to give it.
  6212. * @param {Object} options A set of options for the set.
  6213. * The only supported option is <code>error</code>.
  6214. * @return {(ParseObject|Boolean)} true if the set succeeded.
  6215. */
  6216. }, {
  6217. key: "set",
  6218. value: function (key
  6219. /*: mixed*/
  6220. , value
  6221. /*: mixed*/
  6222. , options
  6223. /*:: ?: mixed*/
  6224. )
  6225. /*: ParseObject | boolean*/
  6226. {
  6227. var changes = {};
  6228. var newOps = {};
  6229. if (key && (0, _typeof2.default)(key) === 'object') {
  6230. changes = key;
  6231. options = value;
  6232. } else if (typeof key === 'string') {
  6233. changes[key] = value;
  6234. } else {
  6235. return this;
  6236. }
  6237. options = options || {};
  6238. var readonly = [];
  6239. if (typeof this.constructor.readOnlyAttributes === 'function') {
  6240. readonly = readonly.concat(this.constructor.readOnlyAttributes());
  6241. }
  6242. for (var k in changes) {
  6243. if (k === 'createdAt' || k === 'updatedAt') {
  6244. // This property is read-only, but for legacy reasons we silently
  6245. // ignore it
  6246. continue;
  6247. }
  6248. if (readonly.indexOf(k) > -1) {
  6249. throw new Error('Cannot modify readonly attribute: ' + k);
  6250. }
  6251. if (options.unset) {
  6252. newOps[k] = new _ParseOp.UnsetOp();
  6253. } else if (changes[k] instanceof _ParseOp.Op) {
  6254. newOps[k] = changes[k];
  6255. } else if (changes[k] && (0, _typeof2.default)(changes[k]) === 'object' && typeof changes[k].__op === 'string') {
  6256. newOps[k] = (0, _ParseOp.opFromJSON)(changes[k]);
  6257. } else if (k === 'objectId' || k === 'id') {
  6258. if (typeof changes[k] === 'string') {
  6259. this.id = changes[k];
  6260. }
  6261. } else if (k === 'ACL' && (0, _typeof2.default)(changes[k]) === 'object' && !(changes[k] instanceof _ParseACL.default)) {
  6262. newOps[k] = new _ParseOp.SetOp(new _ParseACL.default(changes[k]));
  6263. } else if (changes[k] instanceof _ParseRelation.default) {
  6264. var relation = new _ParseRelation.default(this, k);
  6265. relation.targetClassName = changes[k].targetClassName;
  6266. newOps[k] = new _ParseOp.SetOp(relation);
  6267. } else {
  6268. newOps[k] = new _ParseOp.SetOp(changes[k]);
  6269. }
  6270. }
  6271. var currentAttributes = this.attributes; // Only set nested fields if exists
  6272. var serverData = this._getServerData();
  6273. if (typeof key === 'string' && key.includes('.')) {
  6274. var field = key.split('.')[0];
  6275. if (!serverData[field]) {
  6276. return this;
  6277. }
  6278. } // Calculate new values
  6279. var newValues = {};
  6280. for (var _attr9 in newOps) {
  6281. if (newOps[_attr9] instanceof _ParseOp.RelationOp) {
  6282. newValues[_attr9] = newOps[_attr9].applyTo(currentAttributes[_attr9], this, _attr9);
  6283. } else if (!(newOps[_attr9] instanceof _ParseOp.UnsetOp)) {
  6284. newValues[_attr9] = newOps[_attr9].applyTo(currentAttributes[_attr9]);
  6285. }
  6286. } // Validate changes
  6287. if (!options.ignoreValidation) {
  6288. var validation = this.validate(newValues);
  6289. if (validation) {
  6290. if (typeof options.error === 'function') {
  6291. options.error(this, validation);
  6292. }
  6293. return false;
  6294. }
  6295. } // Consolidate Ops
  6296. var pendingOps = this._getPendingOps();
  6297. var last = pendingOps.length - 1;
  6298. var stateController = _CoreManager.default.getObjectStateController();
  6299. for (var _attr10 in newOps) {
  6300. var nextOp = newOps[_attr10].mergeWith(pendingOps[last][_attr10]);
  6301. stateController.setPendingOp(this._getStateIdentifier(), _attr10, nextOp);
  6302. }
  6303. return this;
  6304. }
  6305. /**
  6306. * Remove an attribute from the model. This is a noop if the attribute doesn't
  6307. * exist.
  6308. * @param {String} attr The string name of an attribute.
  6309. * @return {(ParseObject|Boolean)}
  6310. */
  6311. }, {
  6312. key: "unset",
  6313. value: function (attr
  6314. /*: string*/
  6315. , options
  6316. /*:: ?: { [opt: string]: mixed }*/
  6317. )
  6318. /*: ParseObject | boolean*/
  6319. {
  6320. options = options || {};
  6321. options.unset = true;
  6322. return this.set(attr, null, options);
  6323. }
  6324. /**
  6325. * Atomically increments the value of the given attribute the next time the
  6326. * object is saved. If no amount is specified, 1 is used by default.
  6327. *
  6328. * @param attr {String} The key.
  6329. * @param amount {Number} The amount to increment by (optional).
  6330. * @return {(ParseObject|Boolean)}
  6331. */
  6332. }, {
  6333. key: "increment",
  6334. value: function (attr
  6335. /*: string*/
  6336. , amount
  6337. /*:: ?: number*/
  6338. )
  6339. /*: ParseObject | boolean*/
  6340. {
  6341. if (typeof amount === 'undefined') {
  6342. amount = 1;
  6343. }
  6344. if (typeof amount !== 'number') {
  6345. throw new Error('Cannot increment by a non-numeric amount.');
  6346. }
  6347. return this.set(attr, new _ParseOp.IncrementOp(amount));
  6348. }
  6349. /**
  6350. * Atomically add an object to the end of the array associated with a given
  6351. * key.
  6352. * @param attr {String} The key.
  6353. * @param item {} The item to add.
  6354. * @return {(ParseObject|Boolean)}
  6355. */
  6356. }, {
  6357. key: "add",
  6358. value: function (attr
  6359. /*: string*/
  6360. , item
  6361. /*: mixed*/
  6362. )
  6363. /*: ParseObject | boolean*/
  6364. {
  6365. return this.set(attr, new _ParseOp.AddOp([item]));
  6366. }
  6367. /**
  6368. * Atomically add the objects to the end of the array associated with a given
  6369. * key.
  6370. * @param attr {String} The key.
  6371. * @param items {Object[]} The items to add.
  6372. * @return {(ParseObject|Boolean)}
  6373. */
  6374. }, {
  6375. key: "addAll",
  6376. value: function (attr
  6377. /*: string*/
  6378. , items
  6379. /*: Array<mixed>*/
  6380. )
  6381. /*: ParseObject | boolean*/
  6382. {
  6383. return this.set(attr, new _ParseOp.AddOp(items));
  6384. }
  6385. /**
  6386. * Atomically add an object to the array associated with a given key, only
  6387. * if it is not already present in the array. The position of the insert is
  6388. * not guaranteed.
  6389. *
  6390. * @param attr {String} The key.
  6391. * @param item {} The object to add.
  6392. * @return {(ParseObject|Boolean)}
  6393. */
  6394. }, {
  6395. key: "addUnique",
  6396. value: function (attr
  6397. /*: string*/
  6398. , item
  6399. /*: mixed*/
  6400. )
  6401. /*: ParseObject | boolean*/
  6402. {
  6403. return this.set(attr, new _ParseOp.AddUniqueOp([item]));
  6404. }
  6405. /**
  6406. * Atomically add the objects to the array associated with a given key, only
  6407. * if it is not already present in the array. The position of the insert is
  6408. * not guaranteed.
  6409. *
  6410. * @param attr {String} The key.
  6411. * @param items {Object[]} The objects to add.
  6412. * @return {(ParseObject|Boolean)}
  6413. */
  6414. }, {
  6415. key: "addAllUnique",
  6416. value: function (attr
  6417. /*: string*/
  6418. , items
  6419. /*: Array<mixed>*/
  6420. )
  6421. /*: ParseObject | boolean*/
  6422. {
  6423. return this.set(attr, new _ParseOp.AddUniqueOp(items));
  6424. }
  6425. /**
  6426. * Atomically remove all instances of an object from the array associated
  6427. * with a given key.
  6428. *
  6429. * @param attr {String} The key.
  6430. * @param item {} The object to remove.
  6431. * @return {(ParseObject|Boolean)}
  6432. */
  6433. }, {
  6434. key: "remove",
  6435. value: function (attr
  6436. /*: string*/
  6437. , item
  6438. /*: mixed*/
  6439. )
  6440. /*: ParseObject | boolean*/
  6441. {
  6442. return this.set(attr, new _ParseOp.RemoveOp([item]));
  6443. }
  6444. /**
  6445. * Atomically remove all instances of the objects from the array associated
  6446. * with a given key.
  6447. *
  6448. * @param attr {String} The key.
  6449. * @param items {Object[]} The object to remove.
  6450. * @return {(ParseObject|Boolean)}
  6451. */
  6452. }, {
  6453. key: "removeAll",
  6454. value: function (attr
  6455. /*: string*/
  6456. , items
  6457. /*: Array<mixed>*/
  6458. )
  6459. /*: ParseObject | boolean*/
  6460. {
  6461. return this.set(attr, new _ParseOp.RemoveOp(items));
  6462. }
  6463. /**
  6464. * Returns an instance of a subclass of Parse.Op describing what kind of
  6465. * modification has been performed on this field since the last time it was
  6466. * saved. For example, after calling object.increment("x"), calling
  6467. * object.op("x") would return an instance of Parse.Op.Increment.
  6468. *
  6469. * @param attr {String} The key.
  6470. * @returns {Parse.Op} The operation, or undefined if none.
  6471. */
  6472. }, {
  6473. key: "op",
  6474. value: function (attr
  6475. /*: string*/
  6476. )
  6477. /*: ?Op*/
  6478. {
  6479. var pending = this._getPendingOps();
  6480. for (var i = pending.length; i--;) {
  6481. if (pending[i][attr]) {
  6482. return pending[i][attr];
  6483. }
  6484. }
  6485. }
  6486. /**
  6487. * Creates a new model with identical attributes to this one.
  6488. * @return {Parse.Object}
  6489. */
  6490. }, {
  6491. key: "clone",
  6492. value: function clone()
  6493. /*: any*/
  6494. {
  6495. var clone = new this.constructor();
  6496. if (!clone.className) {
  6497. clone.className = this.className;
  6498. }
  6499. var attributes = this.attributes;
  6500. if (typeof this.constructor.readOnlyAttributes === 'function') {
  6501. var readonly = this.constructor.readOnlyAttributes() || []; // Attributes are frozen, so we have to rebuild an object,
  6502. // rather than delete readonly keys
  6503. var copy = {};
  6504. for (var a in attributes) {
  6505. if (readonly.indexOf(a) < 0) {
  6506. copy[a] = attributes[a];
  6507. }
  6508. }
  6509. attributes = copy;
  6510. }
  6511. if (clone.set) {
  6512. clone.set(attributes);
  6513. }
  6514. return clone;
  6515. }
  6516. /**
  6517. * Creates a new instance of this object. Not to be confused with clone()
  6518. * @return {Parse.Object}
  6519. */
  6520. }, {
  6521. key: "newInstance",
  6522. value: function ()
  6523. /*: any*/
  6524. {
  6525. var clone = new this.constructor();
  6526. if (!clone.className) {
  6527. clone.className = this.className;
  6528. }
  6529. clone.id = this.id;
  6530. if (singleInstance) {
  6531. // Just return an object with the right id
  6532. return clone;
  6533. }
  6534. var stateController = _CoreManager.default.getObjectStateController();
  6535. if (stateController) {
  6536. stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier());
  6537. }
  6538. return clone;
  6539. }
  6540. /**
  6541. * Returns true if this object has never been saved to Parse.
  6542. * @return {Boolean}
  6543. */
  6544. }, {
  6545. key: "isNew",
  6546. value: function ()
  6547. /*: boolean*/
  6548. {
  6549. return !this.id;
  6550. }
  6551. /**
  6552. * Returns true if this object was created by the Parse server when the
  6553. * object might have already been there (e.g. in the case of a Facebook
  6554. * login)
  6555. * @return {Boolean}
  6556. */
  6557. }, {
  6558. key: "existed",
  6559. value: function ()
  6560. /*: boolean*/
  6561. {
  6562. if (!this.id) {
  6563. return false;
  6564. }
  6565. var stateController = _CoreManager.default.getObjectStateController();
  6566. var state = stateController.getState(this._getStateIdentifier());
  6567. if (state) {
  6568. return state.existed;
  6569. }
  6570. return false;
  6571. }
  6572. /**
  6573. * Checks if the model is currently in a valid state.
  6574. * @return {Boolean}
  6575. */
  6576. }, {
  6577. key: "isValid",
  6578. value: function ()
  6579. /*: boolean*/
  6580. {
  6581. return !this.validate(this.attributes);
  6582. }
  6583. /**
  6584. * You should not call this function directly unless you subclass
  6585. * <code>Parse.Object</code>, in which case you can override this method
  6586. * to provide additional validation on <code>set</code> and
  6587. * <code>save</code>. Your implementation should return
  6588. *
  6589. * @param {Object} attrs The current data to validate.
  6590. * @return {} False if the data is valid. An error object otherwise.
  6591. * @see Parse.Object#set
  6592. */
  6593. }, {
  6594. key: "validate",
  6595. value: function (attrs
  6596. /*: AttributeMap*/
  6597. )
  6598. /*: ParseError | boolean*/
  6599. {
  6600. if (attrs.hasOwnProperty('ACL') && !(attrs.ACL instanceof _ParseACL.default)) {
  6601. return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'ACL must be a Parse ACL.');
  6602. }
  6603. for (var _key in attrs) {
  6604. if (!/^[A-Za-z][0-9A-Za-z_.]*$/.test(_key)) {
  6605. return new _ParseError.default(_ParseError.default.INVALID_KEY_NAME);
  6606. }
  6607. }
  6608. return false;
  6609. }
  6610. /**
  6611. * Returns the ACL for this object.
  6612. * @returns {Parse.ACL} An instance of Parse.ACL.
  6613. * @see Parse.Object#get
  6614. */
  6615. }, {
  6616. key: "getACL",
  6617. value: function ()
  6618. /*: ?ParseACL*/
  6619. {
  6620. var acl = this.get('ACL');
  6621. if (acl instanceof _ParseACL.default) {
  6622. return acl;
  6623. }
  6624. return null;
  6625. }
  6626. /**
  6627. * Sets the ACL to be used for this object.
  6628. * @param {Parse.ACL} acl An instance of Parse.ACL.
  6629. * @param {Object} options
  6630. * @return {(ParseObject|Boolean)} Whether the set passed validation.
  6631. * @see Parse.Object#set
  6632. */
  6633. }, {
  6634. key: "setACL",
  6635. value: function (acl
  6636. /*: ParseACL*/
  6637. , options
  6638. /*:: ?: mixed*/
  6639. )
  6640. /*: ParseObject | boolean*/
  6641. {
  6642. return this.set('ACL', acl, options);
  6643. }
  6644. /**
  6645. * Clears any (or specific) changes to this object made since the last call to save()
  6646. * @param {string} [keys] - specify which fields to revert
  6647. */
  6648. }, {
  6649. key: "revert",
  6650. value: function ()
  6651. /*: void*/
  6652. {
  6653. var keysToRevert;
  6654. for (var _len = arguments.length, keys = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
  6655. keys[_key2] = arguments[_key2];
  6656. }
  6657. if (keys.length) {
  6658. keysToRevert = [];
  6659. for (var _i = 0, _keys = keys; _i < _keys.length; _i++) {
  6660. var _key3 = _keys[_i];
  6661. if (typeof _key3 === "string") {
  6662. keysToRevert.push(_key3);
  6663. } else {
  6664. throw new Error("Parse.Object#revert expects either no, or a list of string, arguments.");
  6665. }
  6666. }
  6667. }
  6668. this._clearPendingOps(keysToRevert);
  6669. }
  6670. /**
  6671. * Clears all attributes on a model
  6672. * @return {(ParseObject | boolean)}
  6673. */
  6674. }, {
  6675. key: "clear",
  6676. value: function ()
  6677. /*: ParseObject | boolean*/
  6678. {
  6679. var attributes = this.attributes;
  6680. var erasable = {};
  6681. var readonly = ['createdAt', 'updatedAt'];
  6682. if (typeof this.constructor.readOnlyAttributes === 'function') {
  6683. readonly = readonly.concat(this.constructor.readOnlyAttributes());
  6684. }
  6685. for (var _attr11 in attributes) {
  6686. if (readonly.indexOf(_attr11) < 0) {
  6687. erasable[_attr11] = true;
  6688. }
  6689. }
  6690. return this.set(erasable, {
  6691. unset: true
  6692. });
  6693. }
  6694. /**
  6695. * Fetch the model from the server. If the server's representation of the
  6696. * model differs from its current attributes, they will be overriden.
  6697. *
  6698. * @param {Object} options
  6699. * Valid options are:<ul>
  6700. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  6701. * be used for this request.
  6702. * <li>sessionToken: A valid session token, used for making a request on
  6703. * behalf of a specific user.
  6704. * <li>include: The name(s) of the key(s) to include. Can be a string, an array of strings,
  6705. * or an array of array of strings.
  6706. * </ul>
  6707. * @return {Promise} A promise that is fulfilled when the fetch
  6708. * completes.
  6709. */
  6710. }, {
  6711. key: "fetch",
  6712. value: function (options
  6713. /*: RequestOptions*/
  6714. )
  6715. /*: Promise*/
  6716. {
  6717. options = options || {};
  6718. var fetchOptions = {};
  6719. if (options.hasOwnProperty('useMasterKey')) {
  6720. fetchOptions.useMasterKey = options.useMasterKey;
  6721. }
  6722. if (options.hasOwnProperty('sessionToken')) {
  6723. fetchOptions.sessionToken = options.sessionToken;
  6724. }
  6725. if (options.hasOwnProperty('include')) {
  6726. fetchOptions.include = [];
  6727. if (Array.isArray(options.include)) {
  6728. options.include.forEach(function (key) {
  6729. if (Array.isArray(key)) {
  6730. fetchOptions.include = fetchOptions.include.concat(key);
  6731. } else {
  6732. fetchOptions.include.push(key);
  6733. }
  6734. });
  6735. } else {
  6736. fetchOptions.include.push(options.include);
  6737. }
  6738. }
  6739. var controller = _CoreManager.default.getObjectController();
  6740. return controller.fetch(this, true, fetchOptions);
  6741. }
  6742. /**
  6743. * Fetch the model from the server. If the server's representation of the
  6744. * model differs from its current attributes, they will be overriden.
  6745. *
  6746. * Includes nested Parse.Objects for the provided key. You can use dot
  6747. * notation to specify which fields in the included object are also fetched.
  6748. *
  6749. * @param {String|Array<string|Array<string>>} keys The name(s) of the key(s) to include.
  6750. * @param {Object} options
  6751. * Valid options are:<ul>
  6752. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  6753. * be used for this request.
  6754. * <li>sessionToken: A valid session token, used for making a request on
  6755. * behalf of a specific user.
  6756. * </ul>
  6757. * @return {Promise} A promise that is fulfilled when the fetch
  6758. * completes.
  6759. */
  6760. }, {
  6761. key: "fetchWithInclude",
  6762. value: function (keys
  6763. /*: String|Array<string|Array<string>>*/
  6764. , options
  6765. /*: RequestOptions*/
  6766. )
  6767. /*: Promise*/
  6768. {
  6769. options = options || {};
  6770. options.include = keys;
  6771. return this.fetch(options);
  6772. }
  6773. /**
  6774. * Set a hash of model attributes, and save the model to the server.
  6775. * updatedAt will be updated when the request returns.
  6776. * You can either call it as:<pre>
  6777. * object.save();</pre>
  6778. * or<pre>
  6779. * object.save(attrs);</pre>
  6780. * or<pre>
  6781. * object.save(null, options);</pre>
  6782. * or<pre>
  6783. * object.save(attrs, options);</pre>
  6784. * or<pre>
  6785. * object.save(key, value, options);</pre>
  6786. *
  6787. * For example, <pre>
  6788. * gameTurn.save({
  6789. * player: "Jake Cutter",
  6790. * diceRoll: 2
  6791. * }).then(function(gameTurnAgain) {
  6792. * // The save was successful.
  6793. * }, function(error) {
  6794. * // The save failed. Error is an instance of Parse.Error.
  6795. * });</pre>
  6796. *
  6797. * @param {String|Object|null} [attrs]
  6798. * Valid options are:<ul>
  6799. * <li>`Object` - Key/value pairs to update on the object.</li>
  6800. * <li>`String` Key - Key of attribute to update (requires arg2 to also be string)</li>
  6801. * <li>`null` - Passing null for arg1 allows you to save the object with options passed in arg2.</li>
  6802. * </ul>
  6803. *
  6804. * @param {String|Object} [options]
  6805. * <ul>
  6806. * <li>`String` Value - If arg1 was passed as a key, arg2 is the value that should be set on that key.</li>
  6807. * <li>`Object` Options - Valid options are:
  6808. * <ul>
  6809. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  6810. * be used for this request.
  6811. * <li>sessionToken: A valid session token, used for making a request on
  6812. * behalf of a specific user.
  6813. * </ul>
  6814. * </li>
  6815. * </ul>
  6816. *
  6817. * @param {Object} [options]
  6818. * Used to pass option parameters to method if arg1 and arg2 were both passed as strings.
  6819. * Valid options are:
  6820. * <ul>
  6821. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  6822. * be used for this request.
  6823. * <li>sessionToken: A valid session token, used for making a request on
  6824. * behalf of a specific user.
  6825. * </ul>
  6826. *
  6827. * @return {Promise} A promise that is fulfilled when the save
  6828. * completes.
  6829. */
  6830. }, {
  6831. key: "save",
  6832. value: function (arg1
  6833. /*: ?string | { [attr: string]: mixed }*/
  6834. , arg2
  6835. /*: FullOptions | mixed*/
  6836. , arg3
  6837. /*:: ?: FullOptions*/
  6838. )
  6839. /*: Promise*/
  6840. {
  6841. var _this = this;
  6842. var attrs;
  6843. var options;
  6844. if ((0, _typeof2.default)(arg1) === 'object' || typeof arg1 === 'undefined') {
  6845. attrs = arg1;
  6846. if ((0, _typeof2.default)(arg2) === 'object') {
  6847. options = arg2;
  6848. }
  6849. } else {
  6850. attrs = {};
  6851. attrs[arg1] = arg2;
  6852. options = arg3;
  6853. } // TODO: safely remove me
  6854. // Support save({ success: function() {}, error: function() {} })
  6855. if (!options && attrs) {
  6856. options = {};
  6857. if (typeof attrs.success === 'function') {
  6858. options.success = attrs.success;
  6859. delete attrs.success;
  6860. }
  6861. if (typeof attrs.error === 'function') {
  6862. options.error = attrs.error;
  6863. delete attrs.error;
  6864. }
  6865. }
  6866. if (attrs) {
  6867. var validation = this.validate(attrs);
  6868. if (validation) {
  6869. if (options && typeof options.error === 'function') {
  6870. options.error(this, validation);
  6871. }
  6872. return Promise.reject(validation);
  6873. }
  6874. this.set(attrs, options);
  6875. }
  6876. options = options || {};
  6877. var saveOptions = {};
  6878. if (options.hasOwnProperty('useMasterKey')) {
  6879. saveOptions.useMasterKey = !!options.useMasterKey;
  6880. }
  6881. if (options.hasOwnProperty('sessionToken') && typeof options.sessionToken === 'string') {
  6882. saveOptions.sessionToken = options.sessionToken;
  6883. }
  6884. var controller = _CoreManager.default.getObjectController();
  6885. var unsaved = (0, _unsavedChildren.default)(this);
  6886. return controller.save(unsaved, saveOptions).then(function () {
  6887. return controller.save(_this, saveOptions);
  6888. });
  6889. }
  6890. /**
  6891. * Destroy this model on the server if it was already persisted.
  6892. *
  6893. * @param {Object} options
  6894. * Valid options are:<ul>
  6895. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  6896. * be used for this request.
  6897. * <li>sessionToken: A valid session token, used for making a request on
  6898. * behalf of a specific user.
  6899. * </ul>
  6900. * @return {Promise} A promise that is fulfilled when the destroy
  6901. * completes.
  6902. */
  6903. }, {
  6904. key: "destroy",
  6905. value: function (options
  6906. /*: RequestOptions*/
  6907. )
  6908. /*: Promise*/
  6909. {
  6910. options = options || {};
  6911. var destroyOptions = {};
  6912. if (options.hasOwnProperty('useMasterKey')) {
  6913. destroyOptions.useMasterKey = options.useMasterKey;
  6914. }
  6915. if (options.hasOwnProperty('sessionToken')) {
  6916. destroyOptions.sessionToken = options.sessionToken;
  6917. }
  6918. if (!this.id) {
  6919. return Promise.resolve();
  6920. }
  6921. return _CoreManager.default.getObjectController().destroy(this, destroyOptions);
  6922. }
  6923. /**
  6924. * Asynchronously stores the object and every object it points to in the local datastore,
  6925. * recursively, using a default pin name: _default.
  6926. *
  6927. * If those other objects have not been fetched from Parse, they will not be stored.
  6928. * However, if they have changed data, all the changes will be retained.
  6929. *
  6930. * <pre>
  6931. * await object.pin();
  6932. * </pre>
  6933. *
  6934. * To retrieve object:
  6935. * <code>query.fromLocalDatastore()</code> or <code>query.fromPin()</code>
  6936. *
  6937. * @return {Promise} A promise that is fulfilled when the pin completes.
  6938. */
  6939. }, {
  6940. key: "pin",
  6941. value: function ()
  6942. /*: Promise<void>*/
  6943. {
  6944. return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
  6945. }
  6946. /**
  6947. * Asynchronously removes the object and every object it points to in the local datastore,
  6948. * recursively, using a default pin name: _default.
  6949. *
  6950. * <pre>
  6951. * await object.unPin();
  6952. * </pre>
  6953. *
  6954. * @return {Promise} A promise that is fulfilled when the unPin completes.
  6955. */
  6956. }, {
  6957. key: "unPin",
  6958. value: function ()
  6959. /*: Promise<void>*/
  6960. {
  6961. return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
  6962. }
  6963. /**
  6964. * Asynchronously returns if the object is pinned
  6965. *
  6966. * <pre>
  6967. * const isPinned = await object.isPinned();
  6968. * </pre>
  6969. *
  6970. * @return {Promise<boolean>} A boolean promise that is fulfilled if object is pinned.
  6971. */
  6972. }, {
  6973. key: "isPinned",
  6974. value: function () {
  6975. var _isPinned = (0, _asyncToGenerator2.default)(
  6976. /*#__PURE__*/
  6977. _regenerator.default.mark(function _callee() {
  6978. var localDatastore, objectKey, pin;
  6979. return _regenerator.default.wrap(function (_context) {
  6980. while (1) {
  6981. switch (_context.prev = _context.next) {
  6982. case 0:
  6983. localDatastore = _CoreManager.default.getLocalDatastore();
  6984. if (localDatastore.isEnabled) {
  6985. _context.next = 3;
  6986. break;
  6987. }
  6988. return _context.abrupt("return", Promise.reject('Parse.enableLocalDatastore() must be called first'));
  6989. case 3:
  6990. objectKey = localDatastore.getKeyForObject(this);
  6991. _context.next = 6;
  6992. return localDatastore.fromPinWithName(objectKey);
  6993. case 6:
  6994. pin = _context.sent;
  6995. return _context.abrupt("return", pin.length > 0);
  6996. case 8:
  6997. case "end":
  6998. return _context.stop();
  6999. }
  7000. }
  7001. }, _callee, this);
  7002. }));
  7003. return function () {
  7004. return _isPinned.apply(this, arguments);
  7005. };
  7006. }()
  7007. /**
  7008. * Asynchronously stores the objects and every object they point to in the local datastore, recursively.
  7009. *
  7010. * If those other objects have not been fetched from Parse, they will not be stored.
  7011. * However, if they have changed data, all the changes will be retained.
  7012. *
  7013. * <pre>
  7014. * await object.pinWithName(name);
  7015. * </pre>
  7016. *
  7017. * To retrieve object:
  7018. * <code>query.fromLocalDatastore()</code> or <code>query.fromPinWithName(name)</code>
  7019. *
  7020. * @param {String} name Name of Pin.
  7021. * @return {Promise} A promise that is fulfilled when the pin completes.
  7022. */
  7023. }, {
  7024. key: "pinWithName",
  7025. value: function (name
  7026. /*: string*/
  7027. )
  7028. /*: Promise<void>*/
  7029. {
  7030. return ParseObject.pinAllWithName(name, [this]);
  7031. }
  7032. /**
  7033. * Asynchronously removes the object and every object it points to in the local datastore, recursively.
  7034. *
  7035. * <pre>
  7036. * await object.unPinWithName(name);
  7037. * </pre>
  7038. *
  7039. * @param {String} name Name of Pin.
  7040. * @return {Promise} A promise that is fulfilled when the unPin completes.
  7041. */
  7042. }, {
  7043. key: "unPinWithName",
  7044. value: function (name
  7045. /*: string*/
  7046. )
  7047. /*: Promise<void>*/
  7048. {
  7049. return ParseObject.unPinAllWithName(name, [this]);
  7050. }
  7051. /**
  7052. * Asynchronously loads data from the local datastore into this object.
  7053. *
  7054. * <pre>
  7055. * await object.fetchFromLocalDatastore();
  7056. * </pre>
  7057. *
  7058. * You can create an unfetched pointer with <code>Parse.Object.createWithoutData()</code>
  7059. * and then call <code>fetchFromLocalDatastore()</code> on it.
  7060. *
  7061. * @return {Promise} A promise that is fulfilled when the fetch completes.
  7062. */
  7063. }, {
  7064. key: "fetchFromLocalDatastore",
  7065. value: function () {
  7066. var _fetchFromLocalDatastore = (0, _asyncToGenerator2.default)(
  7067. /*#__PURE__*/
  7068. _regenerator.default.mark(function _callee2() {
  7069. var localDatastore, objectKey, pinned, result;
  7070. return _regenerator.default.wrap(function (_context2) {
  7071. while (1) {
  7072. switch (_context2.prev = _context2.next) {
  7073. case 0:
  7074. localDatastore = _CoreManager.default.getLocalDatastore();
  7075. if (localDatastore.isEnabled) {
  7076. _context2.next = 3;
  7077. break;
  7078. }
  7079. throw new Error('Parse.enableLocalDatastore() must be called first');
  7080. case 3:
  7081. objectKey = localDatastore.getKeyForObject(this);
  7082. _context2.next = 6;
  7083. return localDatastore._serializeObject(objectKey);
  7084. case 6:
  7085. pinned = _context2.sent;
  7086. if (pinned) {
  7087. _context2.next = 9;
  7088. break;
  7089. }
  7090. throw new Error('Cannot fetch an unsaved ParseObject');
  7091. case 9:
  7092. result = ParseObject.fromJSON(pinned);
  7093. this._finishFetch(result.toJSON());
  7094. return _context2.abrupt("return", this);
  7095. case 12:
  7096. case "end":
  7097. return _context2.stop();
  7098. }
  7099. }
  7100. }, _callee2, this);
  7101. }));
  7102. return function () {
  7103. return _fetchFromLocalDatastore.apply(this, arguments);
  7104. };
  7105. }()
  7106. /** Static methods **/
  7107. }, {
  7108. key: "attributes",
  7109. /** Prototype getters / setters **/
  7110. get: function ()
  7111. /*: AttributeMap*/
  7112. {
  7113. var stateController = _CoreManager.default.getObjectStateController();
  7114. return Object.freeze(stateController.estimateAttributes(this._getStateIdentifier()));
  7115. }
  7116. /**
  7117. * The first time this object was saved on the server.
  7118. * @property createdAt
  7119. * @type Date
  7120. */
  7121. }, {
  7122. key: "createdAt",
  7123. get: function ()
  7124. /*: ?Date*/
  7125. {
  7126. return this._getServerData().createdAt;
  7127. }
  7128. /**
  7129. * The last time this object was updated on the server.
  7130. * @property updatedAt
  7131. * @type Date
  7132. */
  7133. }, {
  7134. key: "updatedAt",
  7135. get: function ()
  7136. /*: ?Date*/
  7137. {
  7138. return this._getServerData().updatedAt;
  7139. }
  7140. }], [{
  7141. key: "_clearAllState",
  7142. value: function () {
  7143. var stateController = _CoreManager.default.getObjectStateController();
  7144. stateController.clearAllState();
  7145. }
  7146. /**
  7147. * Fetches the given list of Parse.Object.
  7148. * If any error is encountered, stops and calls the error handler.
  7149. *
  7150. * <pre>
  7151. * Parse.Object.fetchAll([object1, object2, ...])
  7152. * .then((list) => {
  7153. * // All the objects were fetched.
  7154. * }, (error) => {
  7155. * // An error occurred while fetching one of the objects.
  7156. * });
  7157. * </pre>
  7158. *
  7159. * @param {Array} list A list of <code>Parse.Object</code>.
  7160. * @param {Object} options
  7161. * Valid options are:<ul>
  7162. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  7163. * be used for this request.
  7164. * <li>sessionToken: A valid session token, used for making a request on
  7165. * behalf of a specific user.
  7166. * <li>include: The name(s) of the key(s) to include. Can be a string, an array of strings,
  7167. * or an array of array of strings.
  7168. * </ul>
  7169. * @static
  7170. */
  7171. }, {
  7172. key: "fetchAll",
  7173. value: function (list
  7174. /*: Array<ParseObject>*/
  7175. ) {
  7176. var options
  7177. /*: RequestOptions*/
  7178. = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  7179. var queryOptions = {};
  7180. if (options.hasOwnProperty('useMasterKey')) {
  7181. queryOptions.useMasterKey = options.useMasterKey;
  7182. }
  7183. if (options.hasOwnProperty('sessionToken')) {
  7184. queryOptions.sessionToken = options.sessionToken;
  7185. }
  7186. if (options.hasOwnProperty('include')) {
  7187. queryOptions.include = [];
  7188. if (Array.isArray(options.include)) {
  7189. options.include.forEach(function (key) {
  7190. if (Array.isArray(key)) {
  7191. queryOptions.include = queryOptions.include.concat(key);
  7192. } else {
  7193. queryOptions.include.push(key);
  7194. }
  7195. });
  7196. } else {
  7197. queryOptions.include.push(options.include);
  7198. }
  7199. }
  7200. return _CoreManager.default.getObjectController().fetch(list, true, queryOptions);
  7201. }
  7202. /**
  7203. * Fetches the given list of Parse.Object.
  7204. *
  7205. * Includes nested Parse.Objects for the provided key. You can use dot
  7206. * notation to specify which fields in the included object are also fetched.
  7207. *
  7208. * If any error is encountered, stops and calls the error handler.
  7209. *
  7210. * <pre>
  7211. * Parse.Object.fetchAllWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
  7212. * .then((list) => {
  7213. * // All the objects were fetched.
  7214. * }, (error) => {
  7215. * // An error occurred while fetching one of the objects.
  7216. * });
  7217. * </pre>
  7218. *
  7219. * @param {Array} list A list of <code>Parse.Object</code>.
  7220. * @param {String|Array<string|Array<string>>} keys The name(s) of the key(s) to include.
  7221. * @param {Object} options
  7222. * Valid options are:<ul>
  7223. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  7224. * be used for this request.
  7225. * <li>sessionToken: A valid session token, used for making a request on
  7226. * behalf of a specific user.
  7227. * </ul>
  7228. * @static
  7229. */
  7230. }, {
  7231. key: "fetchAllWithInclude",
  7232. value: function (list
  7233. /*: Array<ParseObject>*/
  7234. , keys
  7235. /*: String|Array<string|Array<string>>*/
  7236. , options
  7237. /*: RequestOptions*/
  7238. ) {
  7239. options = options || {};
  7240. options.include = keys;
  7241. return ParseObject.fetchAll(list, options);
  7242. }
  7243. /**
  7244. * Fetches the given list of Parse.Object if needed.
  7245. * If any error is encountered, stops and calls the error handler.
  7246. *
  7247. * <pre>
  7248. * Parse.Object.fetchAllIfNeeded([object1, ...])
  7249. * .then((list) => {
  7250. * // Objects were fetched and updated.
  7251. * }, (error) => {
  7252. * // An error occurred while fetching one of the objects.
  7253. * });
  7254. * </pre>
  7255. *
  7256. * @param {Array} list A list of <code>Parse.Object</code>.
  7257. * @param {Object} options
  7258. * @static
  7259. */
  7260. }, {
  7261. key: "fetchAllIfNeeded",
  7262. value: function (list
  7263. /*: Array<ParseObject>*/
  7264. , options) {
  7265. options = options || {};
  7266. var queryOptions = {};
  7267. if (options.hasOwnProperty('useMasterKey')) {
  7268. queryOptions.useMasterKey = options.useMasterKey;
  7269. }
  7270. if (options.hasOwnProperty('sessionToken')) {
  7271. queryOptions.sessionToken = options.sessionToken;
  7272. }
  7273. return _CoreManager.default.getObjectController().fetch(list, false, queryOptions);
  7274. }
  7275. /**
  7276. * Destroy the given list of models on the server if it was already persisted.
  7277. *
  7278. * <p>Unlike saveAll, if an error occurs while deleting an individual model,
  7279. * this method will continue trying to delete the rest of the models if
  7280. * possible, except in the case of a fatal error like a connection error.
  7281. *
  7282. * <p>In particular, the Parse.Error object returned in the case of error may
  7283. * be one of two types:
  7284. *
  7285. * <ul>
  7286. * <li>A Parse.Error.AGGREGATE_ERROR. This object's "errors" property is an
  7287. * array of other Parse.Error objects. Each error object in this array
  7288. * has an "object" property that references the object that could not be
  7289. * deleted (for instance, because that object could not be found).</li>
  7290. * <li>A non-aggregate Parse.Error. This indicates a serious error that
  7291. * caused the delete operation to be aborted partway through (for
  7292. * instance, a connection failure in the middle of the delete).</li>
  7293. * </ul>
  7294. *
  7295. * <pre>
  7296. * Parse.Object.destroyAll([object1, object2, ...])
  7297. * .then((list) => {
  7298. * // All the objects were deleted.
  7299. * }, (error) => {
  7300. * // An error occurred while deleting one or more of the objects.
  7301. * // If this is an aggregate error, then we can inspect each error
  7302. * // object individually to determine the reason why a particular
  7303. * // object was not deleted.
  7304. * if (error.code === Parse.Error.AGGREGATE_ERROR) {
  7305. * for (var i = 0; i < error.errors.length; i++) {
  7306. * console.log("Couldn't delete " + error.errors[i].object.id +
  7307. * "due to " + error.errors[i].message);
  7308. * }
  7309. * } else {
  7310. * console.log("Delete aborted because of " + error.message);
  7311. * }
  7312. * });
  7313. * </pre>
  7314. *
  7315. * @param {Array} list A list of <code>Parse.Object</code>.
  7316. * @param {Object} options
  7317. * @static
  7318. * Valid options are:<ul>
  7319. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  7320. * be used for this request.
  7321. * <li>sessionToken: A valid session token, used for making a request on
  7322. * behalf of a specific user.
  7323. * <li>batchSize: Number of objects to process per request
  7324. * </ul>
  7325. * @return {Promise} A promise that is fulfilled when the destroyAll
  7326. * completes.
  7327. */
  7328. }, {
  7329. key: "destroyAll",
  7330. value: function (list
  7331. /*: Array<ParseObject>*/
  7332. ) {
  7333. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  7334. var destroyOptions = {};
  7335. if (options.hasOwnProperty('useMasterKey')) {
  7336. destroyOptions.useMasterKey = options.useMasterKey;
  7337. }
  7338. if (options.hasOwnProperty('sessionToken')) {
  7339. destroyOptions.sessionToken = options.sessionToken;
  7340. }
  7341. if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
  7342. destroyOptions.batchSize = options.batchSize;
  7343. }
  7344. return _CoreManager.default.getObjectController().destroy(list, destroyOptions);
  7345. }
  7346. /**
  7347. * Saves the given list of Parse.Object.
  7348. * If any error is encountered, stops and calls the error handler.
  7349. *
  7350. * <pre>
  7351. * Parse.Object.saveAll([object1, object2, ...])
  7352. * .then((list) => {
  7353. * // All the objects were saved.
  7354. * }, (error) => {
  7355. * // An error occurred while saving one of the objects.
  7356. * });
  7357. * </pre>
  7358. *
  7359. * @param {Array} list A list of <code>Parse.Object</code>.
  7360. * @param {Object} options
  7361. * @static
  7362. * Valid options are:<ul>
  7363. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  7364. * be used for this request.
  7365. * <li>sessionToken: A valid session token, used for making a request on
  7366. * behalf of a specific user.
  7367. * <li>batchSize: Number of objects to process per request
  7368. * </ul>
  7369. */
  7370. }, {
  7371. key: "saveAll",
  7372. value: function (list
  7373. /*: Array<ParseObject>*/
  7374. ) {
  7375. var options
  7376. /*: RequestOptions*/
  7377. = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  7378. var saveOptions = {};
  7379. if (options.hasOwnProperty('useMasterKey')) {
  7380. saveOptions.useMasterKey = options.useMasterKey;
  7381. }
  7382. if (options.hasOwnProperty('sessionToken')) {
  7383. saveOptions.sessionToken = options.sessionToken;
  7384. }
  7385. if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
  7386. saveOptions.batchSize = options.batchSize;
  7387. }
  7388. return _CoreManager.default.getObjectController().save(list, saveOptions);
  7389. }
  7390. /**
  7391. * Creates a reference to a subclass of Parse.Object with the given id. This
  7392. * does not exist on Parse.Object, only on subclasses.
  7393. *
  7394. * <p>A shortcut for: <pre>
  7395. * var Foo = Parse.Object.extend("Foo");
  7396. * var pointerToFoo = new Foo();
  7397. * pointerToFoo.id = "myObjectId";
  7398. * </pre>
  7399. *
  7400. * @param {String} id The ID of the object to create a reference to.
  7401. * @static
  7402. * @return {Parse.Object} A Parse.Object reference.
  7403. */
  7404. }, {
  7405. key: "createWithoutData",
  7406. value: function (id
  7407. /*: string*/
  7408. ) {
  7409. var obj = new this();
  7410. obj.id = id;
  7411. return obj;
  7412. }
  7413. /**
  7414. * Creates a new instance of a Parse Object from a JSON representation.
  7415. * @param {Object} json The JSON map of the Object's data
  7416. * @param {boolean} override In single instance mode, all old server data
  7417. * is overwritten if this is set to true
  7418. * @static
  7419. * @return {Parse.Object} A Parse.Object reference
  7420. */
  7421. }, {
  7422. key: "fromJSON",
  7423. value: function (json
  7424. /*: any*/
  7425. , override
  7426. /*:: ?: boolean*/
  7427. ) {
  7428. if (!json.className) {
  7429. throw new Error('Cannot create an object without a className');
  7430. }
  7431. var constructor = classMap[json.className];
  7432. var o = constructor ? new constructor() : new ParseObject(json.className);
  7433. var otherAttributes = {};
  7434. for (var _attr12 in json) {
  7435. if (_attr12 !== 'className' && _attr12 !== '__type') {
  7436. otherAttributes[_attr12] = json[_attr12];
  7437. }
  7438. }
  7439. if (override) {
  7440. // id needs to be set before clearServerData can work
  7441. if (otherAttributes.objectId) {
  7442. o.id = otherAttributes.objectId;
  7443. }
  7444. var preserved = null;
  7445. if (typeof o._preserveFieldsOnFetch === 'function') {
  7446. preserved = o._preserveFieldsOnFetch();
  7447. }
  7448. o._clearServerData();
  7449. if (preserved) {
  7450. o._finishFetch(preserved);
  7451. }
  7452. }
  7453. o._finishFetch(otherAttributes);
  7454. if (json.objectId) {
  7455. o._setExisted(true);
  7456. }
  7457. return o;
  7458. }
  7459. /**
  7460. * Registers a subclass of Parse.Object with a specific class name.
  7461. * When objects of that class are retrieved from a query, they will be
  7462. * instantiated with this subclass.
  7463. * This is only necessary when using ES6 subclassing.
  7464. * @param {String} className The class name of the subclass
  7465. * @param {Class} constructor The subclass
  7466. */
  7467. }, {
  7468. key: "registerSubclass",
  7469. value: function (className
  7470. /*: string*/
  7471. , constructor
  7472. /*: any*/
  7473. ) {
  7474. if (typeof className !== 'string') {
  7475. throw new TypeError('The first argument must be a valid class name.');
  7476. }
  7477. if (typeof constructor === 'undefined') {
  7478. throw new TypeError('You must supply a subclass constructor.');
  7479. }
  7480. if (typeof constructor !== 'function') {
  7481. throw new TypeError('You must register the subclass constructor. ' + 'Did you attempt to register an instance of the subclass?');
  7482. }
  7483. classMap[className] = constructor;
  7484. if (!constructor.className) {
  7485. constructor.className = className;
  7486. }
  7487. }
  7488. /**
  7489. * Creates a new subclass of Parse.Object for the given Parse class name.
  7490. *
  7491. * <p>Every extension of a Parse class will inherit from the most recent
  7492. * previous extension of that class. When a Parse.Object is automatically
  7493. * created by parsing JSON, it will use the most recent extension of that
  7494. * class.</p>
  7495. *
  7496. * <p>You should call either:<pre>
  7497. * var MyClass = Parse.Object.extend("MyClass", {
  7498. * <i>Instance methods</i>,
  7499. * initialize: function(attrs, options) {
  7500. * this.someInstanceProperty = [],
  7501. * <i>Other instance properties</i>
  7502. * }
  7503. * }, {
  7504. * <i>Class properties</i>
  7505. * });</pre>
  7506. * or, for Backbone compatibility:<pre>
  7507. * var MyClass = Parse.Object.extend({
  7508. * className: "MyClass",
  7509. * <i>Instance methods</i>,
  7510. * initialize: function(attrs, options) {
  7511. * this.someInstanceProperty = [],
  7512. * <i>Other instance properties</i>
  7513. * }
  7514. * }, {
  7515. * <i>Class properties</i>
  7516. * });</pre></p>
  7517. *
  7518. * @param {String} className The name of the Parse class backing this model.
  7519. * @param {Object} protoProps Instance properties to add to instances of the
  7520. * class returned from this method.
  7521. * @param {Object} classProps Class properties to add the class returned from
  7522. * this method.
  7523. * @return {Class} A new subclass of Parse.Object.
  7524. */
  7525. }, {
  7526. key: "extend",
  7527. value: function (className
  7528. /*: any*/
  7529. , protoProps
  7530. /*: any*/
  7531. , classProps
  7532. /*: any*/
  7533. ) {
  7534. if (typeof className !== 'string') {
  7535. if (className && typeof className.className === 'string') {
  7536. return ParseObject.extend(className.className, className, protoProps);
  7537. } else {
  7538. throw new Error('Parse.Object.extend\'s first argument should be the className.');
  7539. }
  7540. }
  7541. var adjustedClassName = className;
  7542. if (adjustedClassName === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
  7543. adjustedClassName = '_User';
  7544. }
  7545. var parentProto = ParseObject.prototype;
  7546. if (this.hasOwnProperty('__super__') && this.__super__) {
  7547. parentProto = this.prototype;
  7548. } else if (classMap[adjustedClassName]) {
  7549. parentProto = classMap[adjustedClassName].prototype;
  7550. }
  7551. var ParseObjectSubclass = function (attributes, options) {
  7552. this.className = adjustedClassName;
  7553. this._objCount = objectCount++; // Enable legacy initializers
  7554. if (typeof this.initialize === 'function') {
  7555. this.initialize.apply(this, arguments);
  7556. }
  7557. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  7558. if (!this.set(attributes || {}, options)) {
  7559. throw new Error('Can\'t create an invalid Parse Object');
  7560. }
  7561. }
  7562. };
  7563. ParseObjectSubclass.className = adjustedClassName;
  7564. ParseObjectSubclass.__super__ = parentProto;
  7565. ParseObjectSubclass.prototype = Object.create(parentProto, {
  7566. constructor: {
  7567. value: ParseObjectSubclass,
  7568. enumerable: false,
  7569. writable: true,
  7570. configurable: true
  7571. }
  7572. });
  7573. if (protoProps) {
  7574. for (var prop in protoProps) {
  7575. if (prop !== 'className') {
  7576. Object.defineProperty(ParseObjectSubclass.prototype, prop, {
  7577. value: protoProps[prop],
  7578. enumerable: false,
  7579. writable: true,
  7580. configurable: true
  7581. });
  7582. }
  7583. }
  7584. }
  7585. if (classProps) {
  7586. for (var _prop in classProps) {
  7587. if (_prop !== 'className') {
  7588. Object.defineProperty(ParseObjectSubclass, _prop, {
  7589. value: classProps[_prop],
  7590. enumerable: false,
  7591. writable: true,
  7592. configurable: true
  7593. });
  7594. }
  7595. }
  7596. }
  7597. ParseObjectSubclass.extend = function (name, protoProps, classProps) {
  7598. if (typeof name === 'string') {
  7599. return ParseObject.extend.call(ParseObjectSubclass, name, protoProps, classProps);
  7600. }
  7601. return ParseObject.extend.call(ParseObjectSubclass, adjustedClassName, name, protoProps);
  7602. };
  7603. ParseObjectSubclass.createWithoutData = ParseObject.createWithoutData;
  7604. classMap[adjustedClassName] = ParseObjectSubclass;
  7605. return ParseObjectSubclass;
  7606. }
  7607. /**
  7608. * Enable single instance objects, where any local objects with the same Id
  7609. * share the same attributes, and stay synchronized with each other.
  7610. * This is disabled by default in server environments, since it can lead to
  7611. * security issues.
  7612. * @static
  7613. */
  7614. }, {
  7615. key: "enableSingleInstance",
  7616. value: function () {
  7617. singleInstance = true;
  7618. _CoreManager.default.setObjectStateController(SingleInstanceStateController);
  7619. }
  7620. /**
  7621. * Disable single instance objects, where any local objects with the same Id
  7622. * share the same attributes, and stay synchronized with each other.
  7623. * When disabled, you can have two instances of the same object in memory
  7624. * without them sharing attributes.
  7625. * @static
  7626. */
  7627. }, {
  7628. key: "disableSingleInstance",
  7629. value: function () {
  7630. singleInstance = false;
  7631. _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
  7632. }
  7633. /**
  7634. * Asynchronously stores the objects and every object they point to in the local datastore,
  7635. * recursively, using a default pin name: _default.
  7636. *
  7637. * If those other objects have not been fetched from Parse, they will not be stored.
  7638. * However, if they have changed data, all the changes will be retained.
  7639. *
  7640. * <pre>
  7641. * await Parse.Object.pinAll([...]);
  7642. * </pre>
  7643. *
  7644. * To retrieve object:
  7645. * <code>query.fromLocalDatastore()</code> or <code>query.fromPin()</code>
  7646. *
  7647. * @param {Array} objects A list of <code>Parse.Object</code>.
  7648. * @return {Promise} A promise that is fulfilled when the pin completes.
  7649. * @static
  7650. */
  7651. }, {
  7652. key: "pinAll",
  7653. value: function (objects
  7654. /*: Array<ParseObject>*/
  7655. )
  7656. /*: Promise<void>*/
  7657. {
  7658. var localDatastore = _CoreManager.default.getLocalDatastore();
  7659. if (!localDatastore.isEnabled) {
  7660. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7661. }
  7662. return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
  7663. }
  7664. /**
  7665. * Asynchronously stores the objects and every object they point to in the local datastore, recursively.
  7666. *
  7667. * If those other objects have not been fetched from Parse, they will not be stored.
  7668. * However, if they have changed data, all the changes will be retained.
  7669. *
  7670. * <pre>
  7671. * await Parse.Object.pinAllWithName(name, [obj1, obj2, ...]);
  7672. * </pre>
  7673. *
  7674. * To retrieve object:
  7675. * <code>query.fromLocalDatastore()</code> or <code>query.fromPinWithName(name)</code>
  7676. *
  7677. * @param {String} name Name of Pin.
  7678. * @param {Array} objects A list of <code>Parse.Object</code>.
  7679. * @return {Promise} A promise that is fulfilled when the pin completes.
  7680. * @static
  7681. */
  7682. }, {
  7683. key: "pinAllWithName",
  7684. value: function (name
  7685. /*: string*/
  7686. , objects
  7687. /*: Array<ParseObject>*/
  7688. )
  7689. /*: Promise<void>*/
  7690. {
  7691. var localDatastore = _CoreManager.default.getLocalDatastore();
  7692. if (!localDatastore.isEnabled) {
  7693. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7694. }
  7695. return localDatastore._handlePinAllWithName(name, objects);
  7696. }
  7697. /**
  7698. * Asynchronously removes the objects and every object they point to in the local datastore,
  7699. * recursively, using a default pin name: _default.
  7700. *
  7701. * <pre>
  7702. * await Parse.Object.unPinAll([...]);
  7703. * </pre>
  7704. *
  7705. * @param {Array} objects A list of <code>Parse.Object</code>.
  7706. * @return {Promise} A promise that is fulfilled when the unPin completes.
  7707. * @static
  7708. */
  7709. }, {
  7710. key: "unPinAll",
  7711. value: function (objects
  7712. /*: Array<ParseObject>*/
  7713. )
  7714. /*: Promise<void>*/
  7715. {
  7716. var localDatastore = _CoreManager.default.getLocalDatastore();
  7717. if (!localDatastore.isEnabled) {
  7718. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7719. }
  7720. return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
  7721. }
  7722. /**
  7723. * Asynchronously removes the objects and every object they point to in the local datastore, recursively.
  7724. *
  7725. * <pre>
  7726. * await Parse.Object.unPinAllWithName(name, [obj1, obj2, ...]);
  7727. * </pre>
  7728. *
  7729. * @param {String} name Name of Pin.
  7730. * @param {Array} objects A list of <code>Parse.Object</code>.
  7731. * @return {Promise} A promise that is fulfilled when the unPin completes.
  7732. * @static
  7733. */
  7734. }, {
  7735. key: "unPinAllWithName",
  7736. value: function (name
  7737. /*: string*/
  7738. , objects
  7739. /*: Array<ParseObject>*/
  7740. )
  7741. /*: Promise<void>*/
  7742. {
  7743. var localDatastore = _CoreManager.default.getLocalDatastore();
  7744. if (!localDatastore.isEnabled) {
  7745. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7746. }
  7747. return localDatastore._handleUnPinAllWithName(name, objects);
  7748. }
  7749. /**
  7750. * Asynchronously removes all objects in the local datastore using a default pin name: _default.
  7751. *
  7752. * <pre>
  7753. * await Parse.Object.unPinAllObjects();
  7754. * </pre>
  7755. *
  7756. * @return {Promise} A promise that is fulfilled when the unPin completes.
  7757. * @static
  7758. */
  7759. }, {
  7760. key: "unPinAllObjects",
  7761. value: function ()
  7762. /*: Promise<void>*/
  7763. {
  7764. var localDatastore = _CoreManager.default.getLocalDatastore();
  7765. if (!localDatastore.isEnabled) {
  7766. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7767. }
  7768. return localDatastore.unPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
  7769. }
  7770. /**
  7771. * Asynchronously removes all objects with the specified pin name.
  7772. * Deletes the pin name also.
  7773. *
  7774. * <pre>
  7775. * await Parse.Object.unPinAllObjectsWithName(name);
  7776. * </pre>
  7777. *
  7778. * @param {String} name Name of Pin.
  7779. * @return {Promise} A promise that is fulfilled when the unPin completes.
  7780. * @static
  7781. */
  7782. }, {
  7783. key: "unPinAllObjectsWithName",
  7784. value: function (name
  7785. /*: string*/
  7786. )
  7787. /*: Promise<void>*/
  7788. {
  7789. var localDatastore = _CoreManager.default.getLocalDatastore();
  7790. if (!localDatastore.isEnabled) {
  7791. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  7792. }
  7793. return localDatastore.unPinWithName(_LocalDatastoreUtils.PIN_PREFIX + name);
  7794. }
  7795. }]);
  7796. return ParseObject;
  7797. }();
  7798. var DefaultController = {
  7799. fetch: function (target
  7800. /*: ParseObject | Array<ParseObject>*/
  7801. , forceFetch
  7802. /*: boolean*/
  7803. , options
  7804. /*: RequestOptions*/
  7805. )
  7806. /*: Promise<Array<void> | ParseObject>*/
  7807. {
  7808. var localDatastore = _CoreManager.default.getLocalDatastore();
  7809. if (Array.isArray(target)) {
  7810. if (target.length < 1) {
  7811. return Promise.resolve([]);
  7812. }
  7813. var objs = [];
  7814. var ids = [];
  7815. var className = null;
  7816. var results = [];
  7817. var error = null;
  7818. target.forEach(function (el) {
  7819. if (error) {
  7820. return;
  7821. }
  7822. if (!className) {
  7823. className = el.className;
  7824. }
  7825. if (className !== el.className) {
  7826. error = new _ParseError.default(_ParseError.default.INVALID_CLASS_NAME, 'All objects should be of the same class');
  7827. }
  7828. if (!el.id) {
  7829. error = new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'All objects must have an ID');
  7830. }
  7831. if (forceFetch || !el.isDataAvailable()) {
  7832. ids.push(el.id);
  7833. objs.push(el);
  7834. }
  7835. results.push(el);
  7836. });
  7837. if (error) {
  7838. return Promise.reject(error);
  7839. }
  7840. var query = new _ParseQuery.default(className);
  7841. query.containedIn('objectId', ids);
  7842. if (options && options.include) {
  7843. query.include(options.include);
  7844. }
  7845. query._limit = ids.length;
  7846. return query.find(options).then(
  7847. /*#__PURE__*/
  7848. function () {
  7849. var _ref = (0, _asyncToGenerator2.default)(
  7850. /*#__PURE__*/
  7851. _regenerator.default.mark(function _callee3(objects) {
  7852. var idMap, i, obj, _i2, _obj, id, _i3, _results, object;
  7853. return _regenerator.default.wrap(function (_context3) {
  7854. while (1) {
  7855. switch (_context3.prev = _context3.next) {
  7856. case 0:
  7857. idMap = {};
  7858. objects.forEach(function (o) {
  7859. idMap[o.id] = o;
  7860. });
  7861. i = 0;
  7862. case 3:
  7863. if (!(i < objs.length)) {
  7864. _context3.next = 11;
  7865. break;
  7866. }
  7867. obj = objs[i];
  7868. if (!(!obj || !obj.id || !idMap[obj.id])) {
  7869. _context3.next = 8;
  7870. break;
  7871. }
  7872. if (!forceFetch) {
  7873. _context3.next = 8;
  7874. break;
  7875. }
  7876. return _context3.abrupt("return", Promise.reject(new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'All objects must exist on the server.')));
  7877. case 8:
  7878. i++;
  7879. _context3.next = 3;
  7880. break;
  7881. case 11:
  7882. if (!singleInstance) {
  7883. // If single instance objects are disabled, we need to replace the
  7884. for (_i2 = 0; _i2 < results.length; _i2++) {
  7885. _obj = results[_i2];
  7886. if (_obj && _obj.id && idMap[_obj.id]) {
  7887. id = _obj.id;
  7888. _obj._finishFetch(idMap[id].toJSON());
  7889. results[_i2] = idMap[id];
  7890. }
  7891. }
  7892. }
  7893. _i3 = 0, _results = results;
  7894. case 13:
  7895. if (!(_i3 < _results.length)) {
  7896. _context3.next = 20;
  7897. break;
  7898. }
  7899. object = _results[_i3];
  7900. _context3.next = 17;
  7901. return localDatastore._updateObjectIfPinned(object);
  7902. case 17:
  7903. _i3++;
  7904. _context3.next = 13;
  7905. break;
  7906. case 20:
  7907. return _context3.abrupt("return", Promise.resolve(results));
  7908. case 21:
  7909. case "end":
  7910. return _context3.stop();
  7911. }
  7912. }
  7913. }, _callee3);
  7914. }));
  7915. return function () {
  7916. return _ref.apply(this, arguments);
  7917. };
  7918. }());
  7919. } else {
  7920. var RESTController = _CoreManager.default.getRESTController();
  7921. var params = {};
  7922. if (options && options.include) {
  7923. params.include = options.include.join();
  7924. }
  7925. return RESTController.request('GET', 'classes/' + target.className + '/' + target._getId(), params, options).then(
  7926. /*#__PURE__*/
  7927. function () {
  7928. var _ref2 = (0, _asyncToGenerator2.default)(
  7929. /*#__PURE__*/
  7930. _regenerator.default.mark(function _callee4(response) {
  7931. return _regenerator.default.wrap(function (_context4) {
  7932. while (1) {
  7933. switch (_context4.prev = _context4.next) {
  7934. case 0:
  7935. if (target instanceof ParseObject) {
  7936. target._clearPendingOps();
  7937. target._clearServerData();
  7938. target._finishFetch(response);
  7939. }
  7940. _context4.next = 3;
  7941. return localDatastore._updateObjectIfPinned(target);
  7942. case 3:
  7943. return _context4.abrupt("return", target);
  7944. case 4:
  7945. case "end":
  7946. return _context4.stop();
  7947. }
  7948. }
  7949. }, _callee4);
  7950. }));
  7951. return function () {
  7952. return _ref2.apply(this, arguments);
  7953. };
  7954. }());
  7955. }
  7956. },
  7957. destroy: function () {
  7958. var _destroy = (0, _asyncToGenerator2.default)(
  7959. /*#__PURE__*/
  7960. _regenerator.default.mark(function _callee7(target
  7961. /*: ParseObject | Array<ParseObject>*/
  7962. , options
  7963. /*: RequestOptions*/
  7964. ) {
  7965. var batchSize, localDatastore, RESTController, batches, deleteCompleted, errors;
  7966. return _regenerator.default.wrap(function (_context7) {
  7967. while (1) {
  7968. switch (_context7.prev = _context7.next) {
  7969. case 0:
  7970. batchSize = options && options.batchSize ? options.batchSize : DEFAULT_BATCH_SIZE;
  7971. localDatastore = _CoreManager.default.getLocalDatastore();
  7972. RESTController = _CoreManager.default.getRESTController();
  7973. if (!Array.isArray(target)) {
  7974. _context7.next = 15;
  7975. break;
  7976. }
  7977. if (!(target.length < 1)) {
  7978. _context7.next = 6;
  7979. break;
  7980. }
  7981. return _context7.abrupt("return", Promise.resolve([]));
  7982. case 6:
  7983. batches = [[]];
  7984. target.forEach(function (obj) {
  7985. if (!obj.id) {
  7986. return;
  7987. }
  7988. batches[batches.length - 1].push(obj);
  7989. if (batches[batches.length - 1].length >= batchSize) {
  7990. batches.push([]);
  7991. }
  7992. });
  7993. if (batches[batches.length - 1].length === 0) {
  7994. // If the last batch is empty, remove it
  7995. batches.pop();
  7996. }
  7997. deleteCompleted = Promise.resolve();
  7998. errors = [];
  7999. batches.forEach(function (batch) {
  8000. deleteCompleted = deleteCompleted.then(function () {
  8001. return RESTController.request('POST', 'batch', {
  8002. requests: batch.map(function (obj) {
  8003. return {
  8004. method: 'DELETE',
  8005. path: getServerUrlPath() + 'classes/' + obj.className + '/' + obj._getId(),
  8006. body: {}
  8007. };
  8008. })
  8009. }, options).then(function (results) {
  8010. for (var i = 0; i < results.length; i++) {
  8011. if (results[i] && results[i].hasOwnProperty('error')) {
  8012. var err = new _ParseError.default(results[i].error.code, results[i].error.error);
  8013. err.object = batch[i];
  8014. errors.push(err);
  8015. }
  8016. }
  8017. });
  8018. });
  8019. });
  8020. return _context7.abrupt("return", deleteCompleted.then(
  8021. /*#__PURE__*/
  8022. (0, _asyncToGenerator2.default)(
  8023. /*#__PURE__*/
  8024. _regenerator.default.mark(function _callee5() {
  8025. var aggregate, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, object;
  8026. return _regenerator.default.wrap(function (_context5) {
  8027. while (1) {
  8028. switch (_context5.prev = _context5.next) {
  8029. case 0:
  8030. if (!errors.length) {
  8031. _context5.next = 4;
  8032. break;
  8033. }
  8034. aggregate = new _ParseError.default(_ParseError.default.AGGREGATE_ERROR);
  8035. aggregate.errors = errors;
  8036. return _context5.abrupt("return", Promise.reject(aggregate));
  8037. case 4:
  8038. _iteratorNormalCompletion = true;
  8039. _didIteratorError = false;
  8040. _iteratorError = undefined;
  8041. _context5.prev = 7;
  8042. _iterator = target[Symbol.iterator]();
  8043. case 9:
  8044. if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
  8045. _context5.next = 16;
  8046. break;
  8047. }
  8048. object = _step.value;
  8049. _context5.next = 13;
  8050. return localDatastore._destroyObjectIfPinned(object);
  8051. case 13:
  8052. _iteratorNormalCompletion = true;
  8053. _context5.next = 9;
  8054. break;
  8055. case 16:
  8056. _context5.next = 22;
  8057. break;
  8058. case 18:
  8059. _context5.prev = 18;
  8060. _context5.t0 = _context5["catch"](7);
  8061. _didIteratorError = true;
  8062. _iteratorError = _context5.t0;
  8063. case 22:
  8064. _context5.prev = 22;
  8065. _context5.prev = 23;
  8066. if (!_iteratorNormalCompletion && _iterator.return != null) {
  8067. _iterator.return();
  8068. }
  8069. case 25:
  8070. _context5.prev = 25;
  8071. if (!_didIteratorError) {
  8072. _context5.next = 28;
  8073. break;
  8074. }
  8075. throw _iteratorError;
  8076. case 28:
  8077. return _context5.finish(25);
  8078. case 29:
  8079. return _context5.finish(22);
  8080. case 30:
  8081. return _context5.abrupt("return", Promise.resolve(target));
  8082. case 31:
  8083. case "end":
  8084. return _context5.stop();
  8085. }
  8086. }
  8087. }, _callee5, null, [[7, 18, 22, 30], [23,, 25, 29]]);
  8088. }))));
  8089. case 15:
  8090. if (!(target instanceof ParseObject)) {
  8091. _context7.next = 17;
  8092. break;
  8093. }
  8094. return _context7.abrupt("return", RESTController.request('DELETE', 'classes/' + target.className + '/' + target._getId(), {}, options).then(
  8095. /*#__PURE__*/
  8096. (0, _asyncToGenerator2.default)(
  8097. /*#__PURE__*/
  8098. _regenerator.default.mark(function _callee6() {
  8099. return _regenerator.default.wrap(function (_context6) {
  8100. while (1) {
  8101. switch (_context6.prev = _context6.next) {
  8102. case 0:
  8103. _context6.next = 2;
  8104. return localDatastore._destroyObjectIfPinned(target);
  8105. case 2:
  8106. return _context6.abrupt("return", Promise.resolve(target));
  8107. case 3:
  8108. case "end":
  8109. return _context6.stop();
  8110. }
  8111. }
  8112. }, _callee6);
  8113. }))));
  8114. case 17:
  8115. _context7.next = 19;
  8116. return localDatastore._destroyObjectIfPinned(target);
  8117. case 19:
  8118. return _context7.abrupt("return", Promise.resolve(target));
  8119. case 20:
  8120. case "end":
  8121. return _context7.stop();
  8122. }
  8123. }
  8124. }, _callee7);
  8125. }));
  8126. return function () {
  8127. return _destroy.apply(this, arguments);
  8128. };
  8129. }(),
  8130. save: function (target
  8131. /*: ParseObject | Array<ParseObject | ParseFile>*/
  8132. , options
  8133. /*: RequestOptions*/
  8134. ) {
  8135. var batchSize = options && options.batchSize ? options.batchSize : DEFAULT_BATCH_SIZE;
  8136. var localDatastore = _CoreManager.default.getLocalDatastore();
  8137. var mapIdForPin = {};
  8138. var RESTController = _CoreManager.default.getRESTController();
  8139. var stateController = _CoreManager.default.getObjectStateController();
  8140. options = options || {};
  8141. options.returnStatus = options.returnStatus || true;
  8142. if (Array.isArray(target)) {
  8143. if (target.length < 1) {
  8144. return Promise.resolve([]);
  8145. }
  8146. var unsaved = target.concat();
  8147. for (var i = 0; i < target.length; i++) {
  8148. if (target[i] instanceof ParseObject) {
  8149. unsaved = unsaved.concat((0, _unsavedChildren.default)(target[i], true));
  8150. }
  8151. }
  8152. unsaved = (0, _unique.default)(unsaved);
  8153. var filesSaved = Promise.resolve();
  8154. var pending
  8155. /*: Array<ParseObject>*/
  8156. = [];
  8157. unsaved.forEach(function (el) {
  8158. if (el instanceof _ParseFile.default) {
  8159. filesSaved = filesSaved.then(function () {
  8160. return el.save();
  8161. });
  8162. } else if (el instanceof ParseObject) {
  8163. pending.push(el);
  8164. }
  8165. });
  8166. return filesSaved.then(function () {
  8167. var objectError = null;
  8168. return (0, _promiseUtils.continueWhile)(function () {
  8169. return pending.length > 0;
  8170. }, function () {
  8171. var batch = [];
  8172. var nextPending = [];
  8173. pending.forEach(function (el) {
  8174. if (batch.length < batchSize && (0, _canBeSerialized.default)(el)) {
  8175. batch.push(el);
  8176. } else {
  8177. nextPending.push(el);
  8178. }
  8179. });
  8180. pending = nextPending;
  8181. if (batch.length < 1) {
  8182. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Tried to save a batch with a cycle.'));
  8183. } // Queue up tasks for each object in the batch.
  8184. // When every task is ready, the API request will execute
  8185. var res, rej;
  8186. var batchReturned = new Promise(function (resolve, reject) {
  8187. res = resolve;
  8188. rej = reject;
  8189. });
  8190. batchReturned.resolve = res;
  8191. batchReturned.reject = rej;
  8192. var batchReady = [];
  8193. var batchTasks = [];
  8194. batch.forEach(function (obj, index) {
  8195. var res, rej;
  8196. var ready = new Promise(function (resolve, reject) {
  8197. res = resolve;
  8198. rej = reject;
  8199. });
  8200. ready.resolve = res;
  8201. ready.reject = rej;
  8202. batchReady.push(ready);
  8203. stateController.pushPendingState(obj._getStateIdentifier());
  8204. batchTasks.push(stateController.enqueueTask(obj._getStateIdentifier(), function () {
  8205. ready.resolve();
  8206. return batchReturned.then(function (responses) {
  8207. if (responses[index].hasOwnProperty('success')) {
  8208. var objectId = responses[index].success.objectId;
  8209. var status = responses[index]._status;
  8210. delete responses[index]._status;
  8211. mapIdForPin[objectId] = obj._localId;
  8212. obj._handleSaveResponse(responses[index].success, status);
  8213. } else {
  8214. if (!objectError && responses[index].hasOwnProperty('error')) {
  8215. var serverError = responses[index].error;
  8216. objectError = new _ParseError.default(serverError.code, serverError.error); // Cancel the rest of the save
  8217. pending = [];
  8218. }
  8219. obj._handleSaveError();
  8220. }
  8221. });
  8222. }));
  8223. });
  8224. (0, _promiseUtils.when)(batchReady).then(function () {
  8225. // Kick off the batch request
  8226. return RESTController.request('POST', 'batch', {
  8227. requests: batch.map(function (obj) {
  8228. var params = obj._getSaveParams();
  8229. params.path = getServerUrlPath() + params.path;
  8230. return params;
  8231. })
  8232. }, options);
  8233. }).then(batchReturned.resolve, function (error) {
  8234. batchReturned.reject(new _ParseError.default(_ParseError.default.INCORRECT_TYPE, error.message));
  8235. });
  8236. return (0, _promiseUtils.when)(batchTasks);
  8237. }).then(
  8238. /*#__PURE__*/
  8239. (0, _asyncToGenerator2.default)(
  8240. /*#__PURE__*/
  8241. _regenerator.default.mark(function _callee8() {
  8242. var _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, object;
  8243. return _regenerator.default.wrap(function (_context8) {
  8244. while (1) {
  8245. switch (_context8.prev = _context8.next) {
  8246. case 0:
  8247. if (!objectError) {
  8248. _context8.next = 2;
  8249. break;
  8250. }
  8251. return _context8.abrupt("return", Promise.reject(objectError));
  8252. case 2:
  8253. _iteratorNormalCompletion2 = true;
  8254. _didIteratorError2 = false;
  8255. _iteratorError2 = undefined;
  8256. _context8.prev = 5;
  8257. _iterator2 = target[Symbol.iterator]();
  8258. case 7:
  8259. if (_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done) {
  8260. _context8.next = 16;
  8261. break;
  8262. }
  8263. object = _step2.value;
  8264. _context8.next = 11;
  8265. return localDatastore._updateLocalIdForObject(mapIdForPin[object.id], object);
  8266. case 11:
  8267. _context8.next = 13;
  8268. return localDatastore._updateObjectIfPinned(object);
  8269. case 13:
  8270. _iteratorNormalCompletion2 = true;
  8271. _context8.next = 7;
  8272. break;
  8273. case 16:
  8274. _context8.next = 22;
  8275. break;
  8276. case 18:
  8277. _context8.prev = 18;
  8278. _context8.t0 = _context8["catch"](5);
  8279. _didIteratorError2 = true;
  8280. _iteratorError2 = _context8.t0;
  8281. case 22:
  8282. _context8.prev = 22;
  8283. _context8.prev = 23;
  8284. if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
  8285. _iterator2.return();
  8286. }
  8287. case 25:
  8288. _context8.prev = 25;
  8289. if (!_didIteratorError2) {
  8290. _context8.next = 28;
  8291. break;
  8292. }
  8293. throw _iteratorError2;
  8294. case 28:
  8295. return _context8.finish(25);
  8296. case 29:
  8297. return _context8.finish(22);
  8298. case 30:
  8299. return _context8.abrupt("return", Promise.resolve(target));
  8300. case 31:
  8301. case "end":
  8302. return _context8.stop();
  8303. }
  8304. }
  8305. }, _callee8, null, [[5, 18, 22, 30], [23,, 25, 29]]);
  8306. })));
  8307. });
  8308. } else if (target instanceof ParseObject) {
  8309. // copying target lets Flow guarantee the pointer isn't modified elsewhere
  8310. var localId = target._localId;
  8311. var targetCopy = target;
  8312. var task = function () {
  8313. var params = targetCopy._getSaveParams();
  8314. return RESTController.request(params.method, params.path, params.body, options).then(function (response) {
  8315. var status = response._status;
  8316. delete response._status;
  8317. targetCopy._handleSaveResponse(response, status);
  8318. }, function (error) {
  8319. targetCopy._handleSaveError();
  8320. return Promise.reject(error);
  8321. });
  8322. };
  8323. stateController.pushPendingState(target._getStateIdentifier());
  8324. return stateController.enqueueTask(target._getStateIdentifier(), task).then(
  8325. /*#__PURE__*/
  8326. (0, _asyncToGenerator2.default)(
  8327. /*#__PURE__*/
  8328. _regenerator.default.mark(function _callee9() {
  8329. return _regenerator.default.wrap(function (_context9) {
  8330. while (1) {
  8331. switch (_context9.prev = _context9.next) {
  8332. case 0:
  8333. _context9.next = 2;
  8334. return localDatastore._updateLocalIdForObject(localId, target);
  8335. case 2:
  8336. _context9.next = 4;
  8337. return localDatastore._updateObjectIfPinned(target);
  8338. case 4:
  8339. return _context9.abrupt("return", target);
  8340. case 5:
  8341. case "end":
  8342. return _context9.stop();
  8343. }
  8344. }
  8345. }, _callee9);
  8346. })), function (error) {
  8347. return Promise.reject(error);
  8348. });
  8349. }
  8350. return Promise.resolve();
  8351. }
  8352. };
  8353. _CoreManager.default.setObjectController(DefaultController);
  8354. var _default = ParseObject;
  8355. exports.default = _default;
  8356. },{"./CoreManager":4,"./LocalDatastoreUtils":12,"./ParseACL":16,"./ParseError":18,"./ParseFile":19,"./ParseOp":24,"./ParseQuery":26,"./ParseRelation":27,"./SingleInstanceStateController":34,"./UniqueInstanceStateController":39,"./canBeSerialized":42,"./decode":43,"./encode":44,"./escape":46,"./parseDate":48,"./promiseUtils":49,"./unique":50,"./unsavedChildren":51,"@babel/runtime/helpers/asyncToGenerator":55,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/interopRequireWildcard":64,"@babel/runtime/helpers/typeof":75,"@babel/runtime/regenerator":78}],24:[function(_dereq_,module,exports){
  8357. "use strict";
  8358. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  8359. Object.defineProperty(exports, "__esModule", {
  8360. value: true
  8361. });
  8362. exports.opFromJSON = opFromJSON;
  8363. exports.RelationOp = exports.RemoveOp = exports.AddUniqueOp = exports.AddOp = exports.IncrementOp = exports.UnsetOp = exports.SetOp = exports.Op = void 0;
  8364. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  8365. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  8366. var _assertThisInitialized2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/assertThisInitialized"));
  8367. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  8368. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  8369. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  8370. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  8371. var _arrayContainsObject = _interopRequireDefault(_dereq_("./arrayContainsObject"));
  8372. var _decode = _interopRequireDefault(_dereq_("./decode"));
  8373. var _encode = _interopRequireDefault(_dereq_("./encode"));
  8374. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  8375. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  8376. var _unique = _interopRequireDefault(_dereq_("./unique"));
  8377. /**
  8378. * Copyright (c) 2015-present, Parse, LLC.
  8379. * All rights reserved.
  8380. *
  8381. * This source code is licensed under the BSD-style license found in the
  8382. * LICENSE file in the root directory of this source tree. An additional grant
  8383. * of patent rights can be found in the PATENTS file in the same directory.
  8384. *
  8385. * @flow
  8386. */
  8387. function opFromJSON(json
  8388. /*: { [key: string]: any }*/
  8389. )
  8390. /*: ?Op*/
  8391. {
  8392. if (!json || !json.__op) {
  8393. return null;
  8394. }
  8395. switch (json.__op) {
  8396. case 'Delete':
  8397. return new UnsetOp();
  8398. case 'Increment':
  8399. return new IncrementOp(json.amount);
  8400. case 'Add':
  8401. return new AddOp((0, _decode.default)(json.objects));
  8402. case 'AddUnique':
  8403. return new AddUniqueOp((0, _decode.default)(json.objects));
  8404. case 'Remove':
  8405. return new RemoveOp((0, _decode.default)(json.objects));
  8406. case 'AddRelation':
  8407. {
  8408. var toAdd = (0, _decode.default)(json.objects);
  8409. if (!Array.isArray(toAdd)) {
  8410. return new RelationOp([], []);
  8411. }
  8412. return new RelationOp(toAdd, []);
  8413. }
  8414. case 'RemoveRelation':
  8415. {
  8416. var toRemove = (0, _decode.default)(json.objects);
  8417. if (!Array.isArray(toRemove)) {
  8418. return new RelationOp([], []);
  8419. }
  8420. return new RelationOp([], toRemove);
  8421. }
  8422. case 'Batch':
  8423. {
  8424. var _toAdd = [];
  8425. var _toRemove = [];
  8426. for (var i = 0; i < json.ops.length; i++) {
  8427. if (json.ops[i].__op === 'AddRelation') {
  8428. _toAdd = _toAdd.concat((0, _decode.default)(json.ops[i].objects));
  8429. } else if (json.ops[i].__op === 'RemoveRelation') {
  8430. _toRemove = _toRemove.concat((0, _decode.default)(json.ops[i].objects));
  8431. }
  8432. }
  8433. return new RelationOp(_toAdd, _toRemove);
  8434. }
  8435. }
  8436. return null;
  8437. }
  8438. var Op =
  8439. /*#__PURE__*/
  8440. function () {
  8441. function Op() {
  8442. (0, _classCallCheck2.default)(this, Op);
  8443. }
  8444. (0, _createClass2.default)(Op, [{
  8445. key: "applyTo",
  8446. // Empty parent class
  8447. value: function ()
  8448. /*: mixed*/
  8449. /*: mixed*/
  8450. {}
  8451. /* eslint-disable-line no-unused-vars */
  8452. }, {
  8453. key: "mergeWith",
  8454. value: function ()
  8455. /*: Op*/
  8456. /*: ?Op*/
  8457. {}
  8458. /* eslint-disable-line no-unused-vars */
  8459. }, {
  8460. key: "toJSON",
  8461. value: function ()
  8462. /*: mixed*/
  8463. {}
  8464. }]);
  8465. return Op;
  8466. }();
  8467. exports.Op = Op;
  8468. var SetOp =
  8469. /*#__PURE__*/
  8470. function (_Op) {
  8471. (0, _inherits2.default)(SetOp, _Op);
  8472. function SetOp(value
  8473. /*: mixed*/
  8474. ) {
  8475. var _this;
  8476. (0, _classCallCheck2.default)(this, SetOp);
  8477. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(SetOp).call(this));
  8478. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "_value", void 0);
  8479. _this._value = value;
  8480. return _this;
  8481. }
  8482. (0, _createClass2.default)(SetOp, [{
  8483. key: "applyTo",
  8484. value: function ()
  8485. /*: mixed*/
  8486. {
  8487. return this._value;
  8488. }
  8489. }, {
  8490. key: "mergeWith",
  8491. value: function ()
  8492. /*: SetOp*/
  8493. {
  8494. return new SetOp(this._value);
  8495. }
  8496. }, {
  8497. key: "toJSON",
  8498. value: function () {
  8499. return (0, _encode.default)(this._value, false, true);
  8500. }
  8501. }]);
  8502. return SetOp;
  8503. }(Op);
  8504. exports.SetOp = SetOp;
  8505. var UnsetOp =
  8506. /*#__PURE__*/
  8507. function (_Op2) {
  8508. (0, _inherits2.default)(UnsetOp, _Op2);
  8509. function UnsetOp() {
  8510. (0, _classCallCheck2.default)(this, UnsetOp);
  8511. return (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(UnsetOp).apply(this, arguments));
  8512. }
  8513. (0, _createClass2.default)(UnsetOp, [{
  8514. key: "applyTo",
  8515. value: function () {
  8516. return undefined;
  8517. }
  8518. }, {
  8519. key: "mergeWith",
  8520. value: function ()
  8521. /*: UnsetOp*/
  8522. {
  8523. return new UnsetOp();
  8524. }
  8525. }, {
  8526. key: "toJSON",
  8527. value: function ()
  8528. /*: { __op: string }*/
  8529. {
  8530. return {
  8531. __op: 'Delete'
  8532. };
  8533. }
  8534. }]);
  8535. return UnsetOp;
  8536. }(Op);
  8537. exports.UnsetOp = UnsetOp;
  8538. var IncrementOp =
  8539. /*#__PURE__*/
  8540. function (_Op3) {
  8541. (0, _inherits2.default)(IncrementOp, _Op3);
  8542. function IncrementOp(amount
  8543. /*: number*/
  8544. ) {
  8545. var _this2;
  8546. (0, _classCallCheck2.default)(this, IncrementOp);
  8547. _this2 = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(IncrementOp).call(this));
  8548. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this2), "_amount", void 0);
  8549. if (typeof amount !== 'number') {
  8550. throw new TypeError('Increment Op must be initialized with a numeric amount.');
  8551. }
  8552. _this2._amount = amount;
  8553. return _this2;
  8554. }
  8555. (0, _createClass2.default)(IncrementOp, [{
  8556. key: "applyTo",
  8557. value: function (value
  8558. /*: ?mixed*/
  8559. )
  8560. /*: number*/
  8561. {
  8562. if (typeof value === 'undefined') {
  8563. return this._amount;
  8564. }
  8565. if (typeof value !== 'number') {
  8566. throw new TypeError('Cannot increment a non-numeric value.');
  8567. }
  8568. return this._amount + value;
  8569. }
  8570. }, {
  8571. key: "mergeWith",
  8572. value: function (previous
  8573. /*: Op*/
  8574. )
  8575. /*: Op*/
  8576. {
  8577. if (!previous) {
  8578. return this;
  8579. }
  8580. if (previous instanceof SetOp) {
  8581. return new SetOp(this.applyTo(previous._value));
  8582. }
  8583. if (previous instanceof UnsetOp) {
  8584. return new SetOp(this._amount);
  8585. }
  8586. if (previous instanceof IncrementOp) {
  8587. return new IncrementOp(this.applyTo(previous._amount));
  8588. }
  8589. throw new Error('Cannot merge Increment Op with the previous Op');
  8590. }
  8591. }, {
  8592. key: "toJSON",
  8593. value: function ()
  8594. /*: { __op: string; amount: number }*/
  8595. {
  8596. return {
  8597. __op: 'Increment',
  8598. amount: this._amount
  8599. };
  8600. }
  8601. }]);
  8602. return IncrementOp;
  8603. }(Op);
  8604. exports.IncrementOp = IncrementOp;
  8605. var AddOp =
  8606. /*#__PURE__*/
  8607. function (_Op4) {
  8608. (0, _inherits2.default)(AddOp, _Op4);
  8609. function AddOp(value
  8610. /*: mixed | Array<mixed>*/
  8611. ) {
  8612. var _this3;
  8613. (0, _classCallCheck2.default)(this, AddOp);
  8614. _this3 = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(AddOp).call(this));
  8615. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this3), "_value", void 0);
  8616. _this3._value = Array.isArray(value) ? value : [value];
  8617. return _this3;
  8618. }
  8619. (0, _createClass2.default)(AddOp, [{
  8620. key: "applyTo",
  8621. value: function (value
  8622. /*: mixed*/
  8623. )
  8624. /*: Array<mixed>*/
  8625. {
  8626. if (value == null) {
  8627. return this._value;
  8628. }
  8629. if (Array.isArray(value)) {
  8630. return value.concat(this._value);
  8631. }
  8632. throw new Error('Cannot add elements to a non-array value');
  8633. }
  8634. }, {
  8635. key: "mergeWith",
  8636. value: function (previous
  8637. /*: Op*/
  8638. )
  8639. /*: Op*/
  8640. {
  8641. if (!previous) {
  8642. return this;
  8643. }
  8644. if (previous instanceof SetOp) {
  8645. return new SetOp(this.applyTo(previous._value));
  8646. }
  8647. if (previous instanceof UnsetOp) {
  8648. return new SetOp(this._value);
  8649. }
  8650. if (previous instanceof AddOp) {
  8651. return new AddOp(this.applyTo(previous._value));
  8652. }
  8653. throw new Error('Cannot merge Add Op with the previous Op');
  8654. }
  8655. }, {
  8656. key: "toJSON",
  8657. value: function ()
  8658. /*: { __op: string; objects: mixed }*/
  8659. {
  8660. return {
  8661. __op: 'Add',
  8662. objects: (0, _encode.default)(this._value, false, true)
  8663. };
  8664. }
  8665. }]);
  8666. return AddOp;
  8667. }(Op);
  8668. exports.AddOp = AddOp;
  8669. var AddUniqueOp =
  8670. /*#__PURE__*/
  8671. function (_Op5) {
  8672. (0, _inherits2.default)(AddUniqueOp, _Op5);
  8673. function AddUniqueOp(value
  8674. /*: mixed | Array<mixed>*/
  8675. ) {
  8676. var _this4;
  8677. (0, _classCallCheck2.default)(this, AddUniqueOp);
  8678. _this4 = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(AddUniqueOp).call(this));
  8679. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this4), "_value", void 0);
  8680. _this4._value = (0, _unique.default)(Array.isArray(value) ? value : [value]);
  8681. return _this4;
  8682. }
  8683. (0, _createClass2.default)(AddUniqueOp, [{
  8684. key: "applyTo",
  8685. value: function (value
  8686. /*: mixed | Array<mixed>*/
  8687. )
  8688. /*: Array<mixed>*/
  8689. {
  8690. if (value == null) {
  8691. return this._value || [];
  8692. }
  8693. if (Array.isArray(value)) {
  8694. // copying value lets Flow guarantee the pointer isn't modified elsewhere
  8695. var valueCopy = value;
  8696. var toAdd = [];
  8697. this._value.forEach(function (v) {
  8698. if (v instanceof _ParseObject.default) {
  8699. if (!(0, _arrayContainsObject.default)(valueCopy, v)) {
  8700. toAdd.push(v);
  8701. }
  8702. } else {
  8703. if (valueCopy.indexOf(v) < 0) {
  8704. toAdd.push(v);
  8705. }
  8706. }
  8707. });
  8708. return value.concat(toAdd);
  8709. }
  8710. throw new Error('Cannot add elements to a non-array value');
  8711. }
  8712. }, {
  8713. key: "mergeWith",
  8714. value: function (previous
  8715. /*: Op*/
  8716. )
  8717. /*: Op*/
  8718. {
  8719. if (!previous) {
  8720. return this;
  8721. }
  8722. if (previous instanceof SetOp) {
  8723. return new SetOp(this.applyTo(previous._value));
  8724. }
  8725. if (previous instanceof UnsetOp) {
  8726. return new SetOp(this._value);
  8727. }
  8728. if (previous instanceof AddUniqueOp) {
  8729. return new AddUniqueOp(this.applyTo(previous._value));
  8730. }
  8731. throw new Error('Cannot merge AddUnique Op with the previous Op');
  8732. }
  8733. }, {
  8734. key: "toJSON",
  8735. value: function ()
  8736. /*: { __op: string; objects: mixed }*/
  8737. {
  8738. return {
  8739. __op: 'AddUnique',
  8740. objects: (0, _encode.default)(this._value, false, true)
  8741. };
  8742. }
  8743. }]);
  8744. return AddUniqueOp;
  8745. }(Op);
  8746. exports.AddUniqueOp = AddUniqueOp;
  8747. var RemoveOp =
  8748. /*#__PURE__*/
  8749. function (_Op6) {
  8750. (0, _inherits2.default)(RemoveOp, _Op6);
  8751. function RemoveOp(value
  8752. /*: mixed | Array<mixed>*/
  8753. ) {
  8754. var _this5;
  8755. (0, _classCallCheck2.default)(this, RemoveOp);
  8756. _this5 = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(RemoveOp).call(this));
  8757. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this5), "_value", void 0);
  8758. _this5._value = (0, _unique.default)(Array.isArray(value) ? value : [value]);
  8759. return _this5;
  8760. }
  8761. (0, _createClass2.default)(RemoveOp, [{
  8762. key: "applyTo",
  8763. value: function (value
  8764. /*: mixed | Array<mixed>*/
  8765. )
  8766. /*: Array<mixed>*/
  8767. {
  8768. if (value == null) {
  8769. return [];
  8770. }
  8771. if (Array.isArray(value)) {
  8772. // var i = value.indexOf(this._value);
  8773. var removed = value.concat([]);
  8774. for (var i = 0; i < this._value.length; i++) {
  8775. var index = removed.indexOf(this._value[i]);
  8776. while (index > -1) {
  8777. removed.splice(index, 1);
  8778. index = removed.indexOf(this._value[i]);
  8779. }
  8780. if (this._value[i] instanceof _ParseObject.default && this._value[i].id) {
  8781. for (var j = 0; j < removed.length; j++) {
  8782. if (removed[j] instanceof _ParseObject.default && this._value[i].id === removed[j].id) {
  8783. removed.splice(j, 1);
  8784. j--;
  8785. }
  8786. }
  8787. }
  8788. }
  8789. return removed;
  8790. }
  8791. throw new Error('Cannot remove elements from a non-array value');
  8792. }
  8793. }, {
  8794. key: "mergeWith",
  8795. value: function (previous
  8796. /*: Op*/
  8797. )
  8798. /*: Op*/
  8799. {
  8800. if (!previous) {
  8801. return this;
  8802. }
  8803. if (previous instanceof SetOp) {
  8804. return new SetOp(this.applyTo(previous._value));
  8805. }
  8806. if (previous instanceof UnsetOp) {
  8807. return new UnsetOp();
  8808. }
  8809. if (previous instanceof RemoveOp) {
  8810. var uniques = previous._value.concat([]);
  8811. for (var i = 0; i < this._value.length; i++) {
  8812. if (this._value[i] instanceof _ParseObject.default) {
  8813. if (!(0, _arrayContainsObject.default)(uniques, this._value[i])) {
  8814. uniques.push(this._value[i]);
  8815. }
  8816. } else {
  8817. if (uniques.indexOf(this._value[i]) < 0) {
  8818. uniques.push(this._value[i]);
  8819. }
  8820. }
  8821. }
  8822. return new RemoveOp(uniques);
  8823. }
  8824. throw new Error('Cannot merge Remove Op with the previous Op');
  8825. }
  8826. }, {
  8827. key: "toJSON",
  8828. value: function ()
  8829. /*: { __op: string; objects: mixed }*/
  8830. {
  8831. return {
  8832. __op: 'Remove',
  8833. objects: (0, _encode.default)(this._value, false, true)
  8834. };
  8835. }
  8836. }]);
  8837. return RemoveOp;
  8838. }(Op);
  8839. exports.RemoveOp = RemoveOp;
  8840. var RelationOp =
  8841. /*#__PURE__*/
  8842. function (_Op7) {
  8843. (0, _inherits2.default)(RelationOp, _Op7);
  8844. function RelationOp(adds
  8845. /*: Array<ParseObject | string>*/
  8846. , removes
  8847. /*: Array<ParseObject | string>*/
  8848. ) {
  8849. var _this6;
  8850. (0, _classCallCheck2.default)(this, RelationOp);
  8851. _this6 = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(RelationOp).call(this));
  8852. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this6), "_targetClassName", void 0);
  8853. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this6), "relationsToAdd", void 0);
  8854. (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this6), "relationsToRemove", void 0);
  8855. _this6._targetClassName = null;
  8856. if (Array.isArray(adds)) {
  8857. _this6.relationsToAdd = (0, _unique.default)(adds.map(_this6._extractId, (0, _assertThisInitialized2.default)(_this6)));
  8858. }
  8859. if (Array.isArray(removes)) {
  8860. _this6.relationsToRemove = (0, _unique.default)(removes.map(_this6._extractId, (0, _assertThisInitialized2.default)(_this6)));
  8861. }
  8862. return _this6;
  8863. }
  8864. (0, _createClass2.default)(RelationOp, [{
  8865. key: "_extractId",
  8866. value: function (obj
  8867. /*: string | ParseObject*/
  8868. )
  8869. /*: string*/
  8870. {
  8871. if (typeof obj === 'string') {
  8872. return obj;
  8873. }
  8874. if (!obj.id) {
  8875. throw new Error('You cannot add or remove an unsaved Parse Object from a relation');
  8876. }
  8877. if (!this._targetClassName) {
  8878. this._targetClassName = obj.className;
  8879. }
  8880. if (this._targetClassName !== obj.className) {
  8881. throw new Error('Tried to create a Relation with 2 different object types: ' + this._targetClassName + ' and ' + obj.className + '.');
  8882. }
  8883. return obj.id;
  8884. }
  8885. }, {
  8886. key: "applyTo",
  8887. value: function (value
  8888. /*: mixed*/
  8889. , object
  8890. /*:: ?: { className: string, id: ?string }*/
  8891. , key
  8892. /*:: ?: string*/
  8893. )
  8894. /*: ?ParseRelation*/
  8895. {
  8896. if (!value) {
  8897. if (!object || !key) {
  8898. throw new Error('Cannot apply a RelationOp without either a previous value, or an object and a key');
  8899. }
  8900. var parent = new _ParseObject.default(object.className);
  8901. if (object.id && object.id.indexOf('local') === 0) {
  8902. parent._localId = object.id;
  8903. } else if (object.id) {
  8904. parent.id = object.id;
  8905. }
  8906. var relation = new _ParseRelation.default(parent, key);
  8907. relation.targetClassName = this._targetClassName;
  8908. return relation;
  8909. }
  8910. if (value instanceof _ParseRelation.default) {
  8911. if (this._targetClassName) {
  8912. if (value.targetClassName) {
  8913. if (this._targetClassName !== value.targetClassName) {
  8914. throw new Error('Related object must be a ' + value.targetClassName + ', but a ' + this._targetClassName + ' was passed in.');
  8915. }
  8916. } else {
  8917. value.targetClassName = this._targetClassName;
  8918. }
  8919. }
  8920. return value;
  8921. } else {
  8922. throw new Error('Relation cannot be applied to a non-relation field');
  8923. }
  8924. }
  8925. }, {
  8926. key: "mergeWith",
  8927. value: function (previous
  8928. /*: Op*/
  8929. )
  8930. /*: Op*/
  8931. {
  8932. if (!previous) {
  8933. return this;
  8934. } else if (previous instanceof UnsetOp) {
  8935. throw new Error('You cannot modify a relation after deleting it.');
  8936. } else if (previous instanceof SetOp && previous._value instanceof _ParseRelation.default) {
  8937. return this;
  8938. } else if (previous instanceof RelationOp) {
  8939. if (previous._targetClassName && previous._targetClassName !== this._targetClassName) {
  8940. throw new Error('Related object must be of class ' + previous._targetClassName + ', but ' + (this._targetClassName || 'null') + ' was passed in.');
  8941. }
  8942. var newAdd = previous.relationsToAdd.concat([]);
  8943. this.relationsToRemove.forEach(function (r) {
  8944. var index = newAdd.indexOf(r);
  8945. if (index > -1) {
  8946. newAdd.splice(index, 1);
  8947. }
  8948. });
  8949. this.relationsToAdd.forEach(function (r) {
  8950. var index = newAdd.indexOf(r);
  8951. if (index < 0) {
  8952. newAdd.push(r);
  8953. }
  8954. });
  8955. var newRemove = previous.relationsToRemove.concat([]);
  8956. this.relationsToAdd.forEach(function (r) {
  8957. var index = newRemove.indexOf(r);
  8958. if (index > -1) {
  8959. newRemove.splice(index, 1);
  8960. }
  8961. });
  8962. this.relationsToRemove.forEach(function (r) {
  8963. var index = newRemove.indexOf(r);
  8964. if (index < 0) {
  8965. newRemove.push(r);
  8966. }
  8967. });
  8968. var newRelation = new RelationOp(newAdd, newRemove);
  8969. newRelation._targetClassName = this._targetClassName;
  8970. return newRelation;
  8971. }
  8972. throw new Error('Cannot merge Relation Op with the previous Op');
  8973. }
  8974. }, {
  8975. key: "toJSON",
  8976. value: function ()
  8977. /*: { __op?: string; objects?: mixed; ops?: mixed }*/
  8978. {
  8979. var _this7 = this;
  8980. var idToPointer = function (id) {
  8981. return {
  8982. __type: 'Pointer',
  8983. className: _this7._targetClassName,
  8984. objectId: id
  8985. };
  8986. };
  8987. var adds = null;
  8988. var removes = null;
  8989. var pointers = null;
  8990. if (this.relationsToAdd.length > 0) {
  8991. pointers = this.relationsToAdd.map(idToPointer);
  8992. adds = {
  8993. __op: 'AddRelation',
  8994. objects: pointers
  8995. };
  8996. }
  8997. if (this.relationsToRemove.length > 0) {
  8998. pointers = this.relationsToRemove.map(idToPointer);
  8999. removes = {
  9000. __op: 'RemoveRelation',
  9001. objects: pointers
  9002. };
  9003. }
  9004. if (adds && removes) {
  9005. return {
  9006. __op: 'Batch',
  9007. ops: [adds, removes]
  9008. };
  9009. }
  9010. return adds || removes || {};
  9011. }
  9012. }]);
  9013. return RelationOp;
  9014. }(Op);
  9015. exports.RelationOp = RelationOp;
  9016. },{"./ParseObject":23,"./ParseRelation":27,"./arrayContainsObject":41,"./decode":43,"./encode":44,"./unique":50,"@babel/runtime/helpers/assertThisInitialized":54,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/getPrototypeOf":61,"@babel/runtime/helpers/inherits":62,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/possibleConstructorReturn":70}],25:[function(_dereq_,module,exports){
  9017. "use strict";
  9018. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  9019. Object.defineProperty(exports, "__esModule", {
  9020. value: true
  9021. });
  9022. exports.default = void 0;
  9023. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  9024. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  9025. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  9026. var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
  9027. /**
  9028. * Copyright (c) 2015-present, Parse, LLC.
  9029. * All rights reserved.
  9030. *
  9031. * This source code is licensed under the BSD-style license found in the
  9032. * LICENSE file in the root directory of this source tree. An additional grant
  9033. * of patent rights can be found in the PATENTS file in the same directory.
  9034. *
  9035. * @flow
  9036. */
  9037. /**
  9038. * Creates a new Polygon with any of the following forms:<br>
  9039. * <pre>
  9040. * new Polygon([[0,0],[0,1],[1,1],[1,0]])
  9041. * new Polygon([GeoPoint, GeoPoint, GeoPoint])
  9042. * </pre>
  9043. *
  9044. * <p>Represents a coordinates that may be associated
  9045. * with a key in a ParseObject or used as a reference point for geo queries.
  9046. * This allows proximity-based queries on the key.</p>
  9047. *
  9048. * <p>Example:<pre>
  9049. * var polygon = new Parse.Polygon([[0,0],[0,1],[1,1],[1,0]]);
  9050. * var object = new Parse.Object("PlaceObject");
  9051. * object.set("area", polygon);
  9052. * object.save();</pre></p>
  9053. * @alias Parse.Polygon
  9054. */
  9055. var ParsePolygon =
  9056. /*#__PURE__*/
  9057. function () {
  9058. /**
  9059. * @param {(Number[][]|Parse.GeoPoint[])} coordinates An Array of coordinate pairs
  9060. */
  9061. function ParsePolygon(arg1
  9062. /*: Array<Array<number>> | Array<ParseGeoPoint>*/
  9063. ) {
  9064. (0, _classCallCheck2.default)(this, ParsePolygon);
  9065. (0, _defineProperty2.default)(this, "_coordinates", void 0);
  9066. this._coordinates = ParsePolygon._validate(arg1);
  9067. }
  9068. /**
  9069. * Coordinates value for this Polygon.
  9070. * Throws an exception if not valid type.
  9071. * @property coordinates
  9072. * @type Array
  9073. */
  9074. (0, _createClass2.default)(ParsePolygon, [{
  9075. key: "toJSON",
  9076. /**
  9077. * Returns a JSON representation of the Polygon, suitable for Parse.
  9078. * @return {Object}
  9079. */
  9080. value: function ()
  9081. /*: { __type: string; coordinates: Array<Array<number>>;}*/
  9082. {
  9083. ParsePolygon._validate(this._coordinates);
  9084. return {
  9085. __type: 'Polygon',
  9086. coordinates: this._coordinates
  9087. };
  9088. }
  9089. /**
  9090. * Checks if two polygons are equal
  9091. * @param {(Parse.Polygon|Object)} other
  9092. * @returns {Boolean}
  9093. */
  9094. }, {
  9095. key: "equals",
  9096. value: function (other
  9097. /*: mixed*/
  9098. )
  9099. /*: boolean*/
  9100. {
  9101. if (!(other instanceof ParsePolygon) || this.coordinates.length !== other.coordinates.length) {
  9102. return false;
  9103. }
  9104. var isEqual = true;
  9105. for (var i = 1; i < this._coordinates.length; i += 1) {
  9106. if (this._coordinates[i][0] != other.coordinates[i][0] || this._coordinates[i][1] != other.coordinates[i][1]) {
  9107. isEqual = false;
  9108. break;
  9109. }
  9110. }
  9111. return isEqual;
  9112. }
  9113. /**
  9114. *
  9115. * @param {Parse.GeoPoint} point
  9116. * @returns {Boolean} Returns if the point is contained in the polygon
  9117. */
  9118. }, {
  9119. key: "containsPoint",
  9120. value: function (point
  9121. /*: ParseGeoPoint*/
  9122. )
  9123. /*: boolean*/
  9124. {
  9125. var minX = this._coordinates[0][0];
  9126. var maxX = this._coordinates[0][0];
  9127. var minY = this._coordinates[0][1];
  9128. var maxY = this._coordinates[0][1];
  9129. for (var i = 1; i < this._coordinates.length; i += 1) {
  9130. var p = this._coordinates[i];
  9131. minX = Math.min(p[0], minX);
  9132. maxX = Math.max(p[0], maxX);
  9133. minY = Math.min(p[1], minY);
  9134. maxY = Math.max(p[1], maxY);
  9135. }
  9136. var outside = point.latitude < minX || point.latitude > maxX || point.longitude < minY || point.longitude > maxY;
  9137. if (outside) {
  9138. return false;
  9139. }
  9140. var inside = false;
  9141. for (var _i = 0, j = this._coordinates.length - 1; _i < this._coordinates.length; j = _i++) {
  9142. var startX = this._coordinates[_i][0];
  9143. var startY = this._coordinates[_i][1];
  9144. var endX = this._coordinates[j][0];
  9145. var endY = this._coordinates[j][1];
  9146. var intersect = startY > point.longitude != endY > point.longitude && point.latitude < (endX - startX) * (point.longitude - startY) / (endY - startY) + startX;
  9147. if (intersect) {
  9148. inside = !inside;
  9149. }
  9150. }
  9151. return inside;
  9152. }
  9153. /**
  9154. * Validates that the list of coordinates can form a valid polygon
  9155. * @param {Array} coords the list of coordinated to validate as a polygon
  9156. * @throws {TypeError}
  9157. */
  9158. }, {
  9159. key: "coordinates",
  9160. get: function ()
  9161. /*: Array<Array<number>>*/
  9162. {
  9163. return this._coordinates;
  9164. },
  9165. set: function (coords
  9166. /*: Array<Array<number>> | Array<ParseGeoPoint>*/
  9167. ) {
  9168. this._coordinates = ParsePolygon._validate(coords);
  9169. }
  9170. }], [{
  9171. key: "_validate",
  9172. value: function (coords
  9173. /*: Array<Array<number>> | Array<ParseGeoPoint>*/
  9174. )
  9175. /*: Array<Array<number>>*/
  9176. {
  9177. if (!Array.isArray(coords)) {
  9178. throw new TypeError('Coordinates must be an Array');
  9179. }
  9180. if (coords.length < 3) {
  9181. throw new TypeError('Polygon must have at least 3 GeoPoints or Points');
  9182. }
  9183. var points = [];
  9184. for (var i = 0; i < coords.length; i += 1) {
  9185. var coord = coords[i];
  9186. var geoPoint = void 0;
  9187. if (coord instanceof _ParseGeoPoint.default) {
  9188. geoPoint = coord;
  9189. } else if (Array.isArray(coord) && coord.length === 2) {
  9190. geoPoint = new _ParseGeoPoint.default(coord[0], coord[1]);
  9191. } else {
  9192. throw new TypeError('Coordinates must be an Array of GeoPoints or Points');
  9193. }
  9194. points.push([geoPoint.latitude, geoPoint.longitude]);
  9195. }
  9196. return points;
  9197. }
  9198. }]);
  9199. return ParsePolygon;
  9200. }();
  9201. var _default = ParsePolygon;
  9202. exports.default = _default;
  9203. },{"./ParseGeoPoint":20,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/interopRequireDefault":63}],26:[function(_dereq_,module,exports){
  9204. "use strict";
  9205. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  9206. Object.defineProperty(exports, "__esModule", {
  9207. value: true
  9208. });
  9209. exports.default = void 0;
  9210. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  9211. var _regenerator = _interopRequireDefault(_dereq_("@babel/runtime/regenerator"));
  9212. var _asyncToGenerator2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/asyncToGenerator"));
  9213. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  9214. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  9215. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  9216. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  9217. var _encode = _interopRequireDefault(_dereq_("./encode"));
  9218. var _promiseUtils = _dereq_("./promiseUtils");
  9219. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  9220. var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
  9221. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  9222. var _OfflineQuery = _interopRequireDefault(_dereq_("./OfflineQuery"));
  9223. var _LocalDatastoreUtils = _dereq_("./LocalDatastoreUtils");
  9224. /*
  9225. * Copyright (c) 2015-present, Parse, LLC.
  9226. * All rights reserved.
  9227. *
  9228. * This source code is licensed under the BSD-style license found in the
  9229. * LICENSE file in the root directory of this source tree. An additional grant
  9230. * of patent rights can be found in the PATENTS file in the same directory.
  9231. *
  9232. * @flow
  9233. */
  9234. /**
  9235. * Converts a string into a regex that matches it.
  9236. * Surrounding with \Q .. \E does this, we just need to escape any \E's in
  9237. * the text separately.
  9238. * @private
  9239. */
  9240. function quote(s
  9241. /*: string*/
  9242. ) {
  9243. return '\\Q' + s.replace('\\E', '\\E\\\\E\\Q') + '\\E';
  9244. }
  9245. /**
  9246. * Extracts the class name from queries. If not all queries have the same
  9247. * class name an error will be thrown.
  9248. */
  9249. function _getClassNameFromQueries(queries
  9250. /*: Array<ParseQuery>*/
  9251. )
  9252. /*: ?string*/
  9253. {
  9254. var className = null;
  9255. queries.forEach(function (q) {
  9256. if (!className) {
  9257. className = q.className;
  9258. }
  9259. if (className !== q.className) {
  9260. throw new Error('All queries must be for the same class.');
  9261. }
  9262. });
  9263. return className;
  9264. }
  9265. /*
  9266. * Handles pre-populating the result data of a query with select fields,
  9267. * making sure that the data object contains keys for all objects that have
  9268. * been requested with a select, so that our cached state updates correctly.
  9269. */
  9270. function handleSelectResult(data
  9271. /*: any*/
  9272. , select
  9273. /*: Array<string>*/
  9274. ) {
  9275. var serverDataMask = {};
  9276. select.forEach(function (field) {
  9277. var hasSubObjectSelect = field.indexOf(".") !== -1;
  9278. if (!hasSubObjectSelect && !data.hasOwnProperty(field)) {
  9279. // this field was selected, but is missing from the retrieved data
  9280. data[field] = undefined;
  9281. } else if (hasSubObjectSelect) {
  9282. // this field references a sub-object,
  9283. // so we need to walk down the path components
  9284. var pathComponents = field.split(".");
  9285. var _obj = data;
  9286. var serverMask = serverDataMask;
  9287. pathComponents.forEach(function (component, index, arr) {
  9288. // add keys if the expected data is missing
  9289. if (_obj && !_obj.hasOwnProperty(component)) {
  9290. _obj[component] = undefined;
  9291. }
  9292. if (_obj !== undefined) {
  9293. _obj = _obj[component];
  9294. } //add this path component to the server mask so we can fill it in later if needed
  9295. if (index < arr.length - 1) {
  9296. if (!serverMask[component]) {
  9297. serverMask[component] = {};
  9298. }
  9299. serverMask = serverMask[component];
  9300. }
  9301. });
  9302. }
  9303. });
  9304. if (Object.keys(serverDataMask).length > 0) {
  9305. // When selecting from sub-objects, we don't want to blow away the missing
  9306. // information that we may have retrieved before. We've already added any
  9307. // missing selected keys to sub-objects, but we still need to add in the
  9308. // data for any previously retrieved sub-objects that were not selected.
  9309. var serverData = _CoreManager.default.getObjectStateController().getServerData({
  9310. id: data.objectId,
  9311. className: data.className
  9312. });
  9313. copyMissingDataWithMask(serverData, data, serverDataMask, false);
  9314. }
  9315. }
  9316. function copyMissingDataWithMask(src, dest, mask, copyThisLevel) {
  9317. //copy missing elements at this level
  9318. if (copyThisLevel) {
  9319. for (var _key in src) {
  9320. if (src.hasOwnProperty(_key) && !dest.hasOwnProperty(_key)) {
  9321. dest[_key] = src[_key];
  9322. }
  9323. }
  9324. }
  9325. for (var _key2 in mask) {
  9326. if (dest[_key2] !== undefined && dest[_key2] !== null && src !== undefined && src !== null) {
  9327. //traverse into objects as needed
  9328. copyMissingDataWithMask(src[_key2], dest[_key2], mask[_key2], true);
  9329. }
  9330. }
  9331. }
  9332. function handleOfflineSort(a, b, sorts) {
  9333. var order = sorts[0];
  9334. var operator = order.slice(0, 1);
  9335. var isDescending = operator === '-';
  9336. if (isDescending) {
  9337. order = order.substring(1);
  9338. }
  9339. if (order === '_created_at') {
  9340. order = 'createdAt';
  9341. }
  9342. if (order === '_updated_at') {
  9343. order = 'updatedAt';
  9344. }
  9345. if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(order) || order === 'password') {
  9346. throw new _ParseError.default(_ParseError.default.INVALID_KEY_NAME, "Invalid Key: ".concat(order));
  9347. }
  9348. var field1 = a.get(order);
  9349. var field2 = b.get(order);
  9350. if (field1 < field2) {
  9351. return isDescending ? 1 : -1;
  9352. }
  9353. if (field1 > field2) {
  9354. return isDescending ? -1 : 1;
  9355. }
  9356. if (sorts.length > 1) {
  9357. var remainingSorts = sorts.slice(1);
  9358. return handleOfflineSort(a, b, remainingSorts);
  9359. }
  9360. return 0;
  9361. }
  9362. /**
  9363. * Creates a new parse Parse.Query for the given Parse.Object subclass.
  9364. *
  9365. * <p>Parse.Query defines a query that is used to fetch Parse.Objects. The
  9366. * most common use case is finding all objects that match a query through the
  9367. * <code>find</code> method. for example, this sample code fetches all objects
  9368. * of class <code>myclass</code>. it calls a different function depending on
  9369. * whether the fetch succeeded or not.
  9370. *
  9371. * <pre>
  9372. * var query = new Parse.Query(myclass);
  9373. * query.find().then((results) => {
  9374. * // results is an array of parse.object.
  9375. * }).catch((error) => {
  9376. * // error is an instance of parse.error.
  9377. * });</pre></p>
  9378. *
  9379. * <p>a Parse.Query can also be used to retrieve a single object whose id is
  9380. * known, through the get method. for example, this sample code fetches an
  9381. * object of class <code>myclass</code> and id <code>myid</code>. it calls a
  9382. * different function depending on whether the fetch succeeded or not.
  9383. *
  9384. * <pre>
  9385. * var query = new Parse.Query(myclass);
  9386. * query.get(myid).then((object) => {
  9387. * // object is an instance of parse.object.
  9388. * }).catch((error) => {
  9389. * // error is an instance of parse.error.
  9390. * });</pre></p>
  9391. *
  9392. * <p>a Parse.Query can also be used to count the number of objects that match
  9393. * the query without retrieving all of those objects. for example, this
  9394. * sample code counts the number of objects of the class <code>myclass</code>
  9395. * <pre>
  9396. * var query = new Parse.Query(myclass);
  9397. * query.count().then((number) => {
  9398. * // there are number instances of myclass.
  9399. * }).catch((error) => {
  9400. * // error is an instance of Parse.Error.
  9401. * });</pre></p>
  9402. * @alias Parse.Query
  9403. */
  9404. var ParseQuery =
  9405. /*#__PURE__*/
  9406. function () {
  9407. /**
  9408. * @property className
  9409. * @type String
  9410. */
  9411. /**
  9412. * @param {(String|Parse.Object)} objectClass An instance of a subclass of Parse.Object, or a Parse className string.
  9413. */
  9414. function ParseQuery(objectClass
  9415. /*: string | ParseObject*/
  9416. ) {
  9417. (0, _classCallCheck2.default)(this, ParseQuery);
  9418. (0, _defineProperty2.default)(this, "className", void 0);
  9419. (0, _defineProperty2.default)(this, "_where", void 0);
  9420. (0, _defineProperty2.default)(this, "_include", void 0);
  9421. (0, _defineProperty2.default)(this, "_exclude", void 0);
  9422. (0, _defineProperty2.default)(this, "_select", void 0);
  9423. (0, _defineProperty2.default)(this, "_limit", void 0);
  9424. (0, _defineProperty2.default)(this, "_skip", void 0);
  9425. (0, _defineProperty2.default)(this, "_count", void 0);
  9426. (0, _defineProperty2.default)(this, "_order", void 0);
  9427. (0, _defineProperty2.default)(this, "_readPreference", void 0);
  9428. (0, _defineProperty2.default)(this, "_includeReadPreference", void 0);
  9429. (0, _defineProperty2.default)(this, "_subqueryReadPreference", void 0);
  9430. (0, _defineProperty2.default)(this, "_queriesLocalDatastore", void 0);
  9431. (0, _defineProperty2.default)(this, "_localDatastorePinName", void 0);
  9432. (0, _defineProperty2.default)(this, "_extraOptions", void 0);
  9433. if (typeof objectClass === 'string') {
  9434. if (objectClass === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
  9435. this.className = '_User';
  9436. } else {
  9437. this.className = objectClass;
  9438. }
  9439. } else if (objectClass instanceof _ParseObject.default) {
  9440. this.className = objectClass.className;
  9441. } else if (typeof objectClass === 'function') {
  9442. if (typeof objectClass.className === 'string') {
  9443. this.className = objectClass.className;
  9444. } else {
  9445. var _obj2 = new objectClass();
  9446. this.className = _obj2.className;
  9447. }
  9448. } else {
  9449. throw new TypeError('A ParseQuery must be constructed with a ParseObject or class name.');
  9450. }
  9451. this._where = {};
  9452. this._include = [];
  9453. this._exclude = [];
  9454. this._count = false;
  9455. this._limit = -1; // negative limit is not sent in the server request
  9456. this._skip = 0;
  9457. this._readPreference = null;
  9458. this._includeReadPreference = null;
  9459. this._subqueryReadPreference = null;
  9460. this._queriesLocalDatastore = false;
  9461. this._localDatastorePinName = null;
  9462. this._extraOptions = {};
  9463. }
  9464. /**
  9465. * Adds constraint that at least one of the passed in queries matches.
  9466. * @param {Array} queries
  9467. * @return {Parse.Query} Returns the query, so you can chain this call.
  9468. */
  9469. (0, _createClass2.default)(ParseQuery, [{
  9470. key: "_orQuery",
  9471. value: function (queries
  9472. /*: Array<ParseQuery>*/
  9473. )
  9474. /*: ParseQuery*/
  9475. {
  9476. var queryJSON = queries.map(function (q) {
  9477. return q.toJSON().where;
  9478. });
  9479. this._where.$or = queryJSON;
  9480. return this;
  9481. }
  9482. /**
  9483. * Adds constraint that all of the passed in queries match.
  9484. * @param {Array} queries
  9485. * @return {Parse.Query} Returns the query, so you can chain this call.
  9486. */
  9487. }, {
  9488. key: "_andQuery",
  9489. value: function (queries
  9490. /*: Array<ParseQuery>*/
  9491. )
  9492. /*: ParseQuery*/
  9493. {
  9494. var queryJSON = queries.map(function (q) {
  9495. return q.toJSON().where;
  9496. });
  9497. this._where.$and = queryJSON;
  9498. return this;
  9499. }
  9500. /**
  9501. * Adds constraint that none of the passed in queries match.
  9502. * @param {Array} queries
  9503. * @return {Parse.Query} Returns the query, so you can chain this call.
  9504. */
  9505. }, {
  9506. key: "_norQuery",
  9507. value: function (queries
  9508. /*: Array<ParseQuery>*/
  9509. )
  9510. /*: ParseQuery*/
  9511. {
  9512. var queryJSON = queries.map(function (q) {
  9513. return q.toJSON().where;
  9514. });
  9515. this._where.$nor = queryJSON;
  9516. return this;
  9517. }
  9518. /**
  9519. * Helper for condition queries
  9520. */
  9521. }, {
  9522. key: "_addCondition",
  9523. value: function (key
  9524. /*: string*/
  9525. , condition
  9526. /*: string*/
  9527. , value
  9528. /*: mixed*/
  9529. )
  9530. /*: ParseQuery*/
  9531. {
  9532. if (!this._where[key] || typeof this._where[key] === 'string') {
  9533. this._where[key] = {};
  9534. }
  9535. this._where[key][condition] = (0, _encode.default)(value, false, true);
  9536. return this;
  9537. }
  9538. /**
  9539. * Converts string for regular expression at the beginning
  9540. */
  9541. }, {
  9542. key: "_regexStartWith",
  9543. value: function (string
  9544. /*: string*/
  9545. )
  9546. /*: string*/
  9547. {
  9548. return '^' + quote(string);
  9549. }
  9550. }, {
  9551. key: "_handleOfflineQuery",
  9552. value: function () {
  9553. var _handleOfflineQuery2 = (0, _asyncToGenerator2.default)(
  9554. /*#__PURE__*/
  9555. _regenerator.default.mark(function _callee(params
  9556. /*: any*/
  9557. ) {
  9558. var _this2 = this;
  9559. var localDatastore, objects, results, keys, alwaysSelectedKeys, sorts, count, limit;
  9560. return _regenerator.default.wrap(function (_context) {
  9561. while (1) {
  9562. switch (_context.prev = _context.next) {
  9563. case 0:
  9564. _OfflineQuery.default.validateQuery(this);
  9565. localDatastore = _CoreManager.default.getLocalDatastore();
  9566. _context.next = 4;
  9567. return localDatastore._serializeObjectsFromPinName(this._localDatastorePinName);
  9568. case 4:
  9569. objects = _context.sent;
  9570. results = objects.map(function (json, index, arr) {
  9571. var object = _ParseObject.default.fromJSON(json, false);
  9572. if (json._localId && !json.objectId) {
  9573. object._localId = json._localId;
  9574. }
  9575. if (!_OfflineQuery.default.matchesQuery(_this2.className, object, arr, _this2)) {
  9576. return null;
  9577. }
  9578. return object;
  9579. }).filter(function (object) {
  9580. return object !== null;
  9581. });
  9582. if (params.keys) {
  9583. keys = params.keys.split(',');
  9584. alwaysSelectedKeys = ['className', 'objectId', 'createdAt', 'updatedAt', 'ACL'];
  9585. keys = keys.concat(alwaysSelectedKeys);
  9586. results = results.map(function (object) {
  9587. var json = object._toFullJSON();
  9588. Object.keys(json).forEach(function (key) {
  9589. if (!keys.includes(key)) {
  9590. delete json[key];
  9591. }
  9592. });
  9593. return _ParseObject.default.fromJSON(json, false);
  9594. });
  9595. }
  9596. if (params.order) {
  9597. sorts = params.order.split(',');
  9598. results.sort(function (a, b) {
  9599. return handleOfflineSort(a, b, sorts);
  9600. });
  9601. } // count total before applying limit/skip
  9602. if (params.count) {
  9603. count = results.length; // total count from response
  9604. }
  9605. if (params.skip) {
  9606. if (params.skip >= results.length) {
  9607. results = [];
  9608. } else {
  9609. results = results.splice(params.skip, results.length);
  9610. }
  9611. }
  9612. limit = results.length;
  9613. if (params.limit !== 0 && params.limit < results.length) {
  9614. limit = params.limit;
  9615. }
  9616. results = results.splice(0, limit);
  9617. if (!(typeof count === 'number')) {
  9618. _context.next = 15;
  9619. break;
  9620. }
  9621. return _context.abrupt("return", {
  9622. results: results,
  9623. count: count
  9624. });
  9625. case 15:
  9626. return _context.abrupt("return", results);
  9627. case 16:
  9628. case "end":
  9629. return _context.stop();
  9630. }
  9631. }
  9632. }, _callee, this);
  9633. }));
  9634. return function () {
  9635. return _handleOfflineQuery2.apply(this, arguments);
  9636. };
  9637. }()
  9638. /**
  9639. * Returns a JSON representation of this query.
  9640. * @return {Object} The JSON representation of the query.
  9641. */
  9642. }, {
  9643. key: "toJSON",
  9644. value: function ()
  9645. /*: QueryJSON*/
  9646. {
  9647. var params
  9648. /*: QueryJSON*/
  9649. = {
  9650. where: this._where
  9651. };
  9652. if (this._include.length) {
  9653. params.include = this._include.join(',');
  9654. }
  9655. if (this._exclude.length) {
  9656. params.excludeKeys = this._exclude.join(',');
  9657. }
  9658. if (this._select) {
  9659. params.keys = this._select.join(',');
  9660. }
  9661. if (this._count) {
  9662. params.count = 1;
  9663. }
  9664. if (this._limit >= 0) {
  9665. params.limit = this._limit;
  9666. }
  9667. if (this._skip > 0) {
  9668. params.skip = this._skip;
  9669. }
  9670. if (this._order) {
  9671. params.order = this._order.join(',');
  9672. }
  9673. if (this._readPreference) {
  9674. params.readPreference = this._readPreference;
  9675. }
  9676. if (this._includeReadPreference) {
  9677. params.includeReadPreference = this._includeReadPreference;
  9678. }
  9679. if (this._subqueryReadPreference) {
  9680. params.subqueryReadPreference = this._subqueryReadPreference;
  9681. }
  9682. for (var _key3 in this._extraOptions) {
  9683. params[_key3] = this._extraOptions[_key3];
  9684. }
  9685. return params;
  9686. }
  9687. /**
  9688. * Return a query with conditions from json, can be useful to send query from server side to client
  9689. * Not static, all query conditions was set before calling this method will be deleted.
  9690. * For example on the server side we have
  9691. * var query = new Parse.Query("className");
  9692. * query.equalTo(key: value);
  9693. * query.limit(100);
  9694. * ... (others queries)
  9695. * Create JSON representation of Query Object
  9696. * var jsonFromServer = query.fromJSON();
  9697. *
  9698. * On client side getting query:
  9699. * var query = new Parse.Query("className");
  9700. * query.fromJSON(jsonFromServer);
  9701. *
  9702. * and continue to query...
  9703. * query.skip(100).find().then(...);
  9704. * @param {QueryJSON} json from Parse.Query.toJSON() method
  9705. * @return {Parse.Query} Returns the query, so you can chain this call.
  9706. */
  9707. }, {
  9708. key: "withJSON",
  9709. value: function (json
  9710. /*: QueryJSON*/
  9711. )
  9712. /*: ParseQuery*/
  9713. {
  9714. if (json.where) {
  9715. this._where = json.where;
  9716. }
  9717. if (json.include) {
  9718. this._include = json.include.split(",");
  9719. }
  9720. if (json.keys) {
  9721. this._select = json.keys.split(",");
  9722. }
  9723. if (json.excludeKeys) {
  9724. this._exclude = json.excludeKeys.split(",");
  9725. }
  9726. if (json.count) {
  9727. this._count = json.count === 1;
  9728. }
  9729. if (json.limit) {
  9730. this._limit = json.limit;
  9731. }
  9732. if (json.skip) {
  9733. this._skip = json.skip;
  9734. }
  9735. if (json.order) {
  9736. this._order = json.order.split(",");
  9737. }
  9738. if (json.readPreference) {
  9739. this._readPreference = json.readPreference;
  9740. }
  9741. if (json.includeReadPreference) {
  9742. this._includeReadPreference = json.includeReadPreference;
  9743. }
  9744. if (json.subqueryReadPreference) {
  9745. this._subqueryReadPreference = json.subqueryReadPreference;
  9746. }
  9747. for (var _key4 in json) {
  9748. if (json.hasOwnProperty(_key4)) {
  9749. if (["where", "include", "keys", "count", "limit", "skip", "order", "readPreference", "includeReadPreference", "subqueryReadPreference"].indexOf(_key4) === -1) {
  9750. this._extraOptions[_key4] = json[_key4];
  9751. }
  9752. }
  9753. }
  9754. return this;
  9755. }
  9756. /**
  9757. * Static method to restore Parse.Query by json representation
  9758. * Internally calling Parse.Query.withJSON
  9759. * @param {String} className
  9760. * @param {QueryJSON} json from Parse.Query.toJSON() method
  9761. * @returns {Parse.Query} new created query
  9762. */
  9763. }, {
  9764. key: "get",
  9765. /**
  9766. * Constructs a Parse.Object whose id is already known by fetching data from
  9767. * the server. Either options.success or options.error is called when the
  9768. * find completes. Unlike the <code>first</code> method, it never returns undefined.
  9769. *
  9770. * @param {String} objectId The id of the object to be fetched.
  9771. * @param {Object} options
  9772. * Valid options are:<ul>
  9773. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  9774. * be used for this request.
  9775. * <li>sessionToken: A valid session token, used for making a request on
  9776. * behalf of a specific user.
  9777. * </ul>
  9778. *
  9779. * @return {Promise} A promise that is resolved with the result when
  9780. * the query completes.
  9781. */
  9782. value: function (objectId
  9783. /*: string*/
  9784. , options
  9785. /*:: ?: FullOptions*/
  9786. )
  9787. /*: Promise<ParseObject>*/
  9788. {
  9789. this.equalTo('objectId', objectId);
  9790. var firstOptions = {};
  9791. if (options && options.hasOwnProperty('useMasterKey')) {
  9792. firstOptions.useMasterKey = options.useMasterKey;
  9793. }
  9794. if (options && options.hasOwnProperty('sessionToken')) {
  9795. firstOptions.sessionToken = options.sessionToken;
  9796. }
  9797. return this.first(firstOptions).then(function (response) {
  9798. if (response) {
  9799. return response;
  9800. }
  9801. var errorObject = new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'Object not found.');
  9802. return Promise.reject(errorObject);
  9803. });
  9804. }
  9805. /**
  9806. * Retrieves a list of ParseObjects that satisfy this query.
  9807. * Either options.success or options.error is called when the find
  9808. * completes.
  9809. *
  9810. * @param {Object} options Valid options
  9811. * are:<ul>
  9812. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  9813. * be used for this request.
  9814. * <li>sessionToken: A valid session token, used for making a request on
  9815. * behalf of a specific user.
  9816. * </ul>
  9817. *
  9818. * @return {Promise} A promise that is resolved with the results when
  9819. * the query completes.
  9820. */
  9821. }, {
  9822. key: "find",
  9823. value: function (options
  9824. /*:: ?: FullOptions*/
  9825. )
  9826. /*: Promise<Array<ParseObject>>*/
  9827. {
  9828. var _this3 = this;
  9829. options = options || {};
  9830. var findOptions = {};
  9831. if (options.hasOwnProperty('useMasterKey')) {
  9832. findOptions.useMasterKey = options.useMasterKey;
  9833. }
  9834. if (options.hasOwnProperty('sessionToken')) {
  9835. findOptions.sessionToken = options.sessionToken;
  9836. }
  9837. var controller = _CoreManager.default.getQueryController();
  9838. var select = this._select;
  9839. if (this._queriesLocalDatastore) {
  9840. return this._handleOfflineQuery(this.toJSON());
  9841. }
  9842. return controller.find(this.className, this.toJSON(), findOptions).then(function (response) {
  9843. var results = response.results.map(function (data) {
  9844. // In cases of relations, the server may send back a className
  9845. // on the top level of the payload
  9846. var override = response.className || _this3.className;
  9847. if (!data.className) {
  9848. data.className = override;
  9849. } // Make sure the data object contains keys for all objects that
  9850. // have been requested with a select, so that our cached state
  9851. // updates correctly.
  9852. if (select) {
  9853. handleSelectResult(data, select);
  9854. }
  9855. return _ParseObject.default.fromJSON(data, !select);
  9856. });
  9857. var count = response.count;
  9858. if (typeof count === "number") {
  9859. return {
  9860. results: results,
  9861. count: count
  9862. };
  9863. } else {
  9864. return results;
  9865. }
  9866. });
  9867. }
  9868. /**
  9869. * Counts the number of objects that match this query.
  9870. * Either options.success or options.error is called when the count
  9871. * completes.
  9872. *
  9873. * @param {Object} options
  9874. * Valid options are:<ul>
  9875. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  9876. * be used for this request.
  9877. * <li>sessionToken: A valid session token, used for making a request on
  9878. * behalf of a specific user.
  9879. * </ul>
  9880. *
  9881. * @return {Promise} A promise that is resolved with the count when
  9882. * the query completes.
  9883. */
  9884. }, {
  9885. key: "count",
  9886. value: function (options
  9887. /*:: ?: FullOptions*/
  9888. )
  9889. /*: Promise<number>*/
  9890. {
  9891. options = options || {};
  9892. var findOptions = {};
  9893. if (options.hasOwnProperty('useMasterKey')) {
  9894. findOptions.useMasterKey = options.useMasterKey;
  9895. }
  9896. if (options.hasOwnProperty('sessionToken')) {
  9897. findOptions.sessionToken = options.sessionToken;
  9898. }
  9899. var controller = _CoreManager.default.getQueryController();
  9900. var params = this.toJSON();
  9901. params.limit = 0;
  9902. params.count = 1;
  9903. return controller.find(this.className, params, findOptions).then(function (result) {
  9904. return result.count;
  9905. });
  9906. }
  9907. /**
  9908. * Executes a distinct query and returns unique values
  9909. *
  9910. * @param {String} key A field to find distinct values
  9911. * @param {Object} options
  9912. * Valid options are:<ul>
  9913. * <li>sessionToken: A valid session token, used for making a request on
  9914. * behalf of a specific user.
  9915. * </ul>
  9916. *
  9917. * @return {Promise} A promise that is resolved with the query completes.
  9918. */
  9919. }, {
  9920. key: "distinct",
  9921. value: function (key
  9922. /*: string*/
  9923. , options
  9924. /*:: ?: FullOptions*/
  9925. )
  9926. /*: Promise<Array<mixed>>*/
  9927. {
  9928. options = options || {};
  9929. var distinctOptions = {};
  9930. distinctOptions.useMasterKey = true;
  9931. if (options.hasOwnProperty('sessionToken')) {
  9932. distinctOptions.sessionToken = options.sessionToken;
  9933. }
  9934. var controller = _CoreManager.default.getQueryController();
  9935. var params = {
  9936. distinct: key,
  9937. where: this._where
  9938. };
  9939. return controller.aggregate(this.className, params, distinctOptions).then(function (results) {
  9940. return results.results;
  9941. });
  9942. }
  9943. /**
  9944. * Executes an aggregate query and returns aggregate results
  9945. *
  9946. * @param {Mixed} pipeline Array or Object of stages to process query
  9947. * @param {Object} options Valid options are:<ul>
  9948. * <li>sessionToken: A valid session token, used for making a request on
  9949. * behalf of a specific user.
  9950. * </ul>
  9951. *
  9952. * @return {Promise} A promise that is resolved with the query completes.
  9953. */
  9954. }, {
  9955. key: "aggregate",
  9956. value: function (pipeline
  9957. /*: mixed*/
  9958. , options
  9959. /*:: ?: FullOptions*/
  9960. )
  9961. /*: Promise<Array<mixed>>*/
  9962. {
  9963. options = options || {};
  9964. var aggregateOptions = {};
  9965. aggregateOptions.useMasterKey = true;
  9966. if (options.hasOwnProperty('sessionToken')) {
  9967. aggregateOptions.sessionToken = options.sessionToken;
  9968. }
  9969. var controller = _CoreManager.default.getQueryController();
  9970. if (!Array.isArray(pipeline) && (0, _typeof2.default)(pipeline) !== 'object') {
  9971. throw new Error('Invalid pipeline must be Array or Object');
  9972. }
  9973. return controller.aggregate(this.className, {
  9974. pipeline: pipeline
  9975. }, aggregateOptions).then(function (results) {
  9976. return results.results;
  9977. });
  9978. }
  9979. /**
  9980. * Retrieves at most one Parse.Object that satisfies this query.
  9981. *
  9982. * Either options.success or options.error is called when it completes.
  9983. * success is passed the object if there is one. otherwise, undefined.
  9984. *
  9985. * @param {Object} options Valid options are:<ul>
  9986. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  9987. * be used for this request.
  9988. * <li>sessionToken: A valid session token, used for making a request on
  9989. * behalf of a specific user.
  9990. * </ul>
  9991. *
  9992. * @return {Promise} A promise that is resolved with the object when
  9993. * the query completes.
  9994. */
  9995. }, {
  9996. key: "first",
  9997. value: function (options
  9998. /*:: ?: FullOptions*/
  9999. )
  10000. /*: Promise<ParseObject | void>*/
  10001. {
  10002. var _this4 = this;
  10003. options = options || {};
  10004. var findOptions = {};
  10005. if (options.hasOwnProperty('useMasterKey')) {
  10006. findOptions.useMasterKey = options.useMasterKey;
  10007. }
  10008. if (options.hasOwnProperty('sessionToken')) {
  10009. findOptions.sessionToken = options.sessionToken;
  10010. }
  10011. var controller = _CoreManager.default.getQueryController();
  10012. var params = this.toJSON();
  10013. params.limit = 1;
  10014. var select = this._select;
  10015. if (this._queriesLocalDatastore) {
  10016. return this._handleOfflineQuery(params).then(function (objects) {
  10017. if (!objects[0]) {
  10018. return undefined;
  10019. }
  10020. return objects[0];
  10021. });
  10022. }
  10023. return controller.find(this.className, params, findOptions).then(function (response) {
  10024. var objects = response.results;
  10025. if (!objects[0]) {
  10026. return undefined;
  10027. }
  10028. if (!objects[0].className) {
  10029. objects[0].className = _this4.className;
  10030. } // Make sure the data object contains keys for all objects that
  10031. // have been requested with a select, so that our cached state
  10032. // updates correctly.
  10033. if (select) {
  10034. handleSelectResult(objects[0], select);
  10035. }
  10036. return _ParseObject.default.fromJSON(objects[0], !select);
  10037. });
  10038. }
  10039. /**
  10040. * Iterates over each result of a query, calling a callback for each one. If
  10041. * the callback returns a promise, the iteration will not continue until
  10042. * that promise has been fulfilled. If the callback returns a rejected
  10043. * promise, then iteration will stop with that error. The items are
  10044. * processed in an unspecified order. The query may not have any sort order,
  10045. * and may not use limit or skip.
  10046. * @param {Function} callback Callback that will be called with each result
  10047. * of the query.
  10048. * @param {Object} options Valid options are:<ul>
  10049. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  10050. * be used for this request.
  10051. * <li>sessionToken: A valid session token, used for making a request on
  10052. * behalf of a specific user.
  10053. * </ul>
  10054. * @return {Promise} A promise that will be fulfilled once the
  10055. * iteration has completed.
  10056. */
  10057. }, {
  10058. key: "each",
  10059. value: function (callback
  10060. /*: (obj: ParseObject) => any*/
  10061. , options
  10062. /*:: ?: BatchOptions*/
  10063. )
  10064. /*: Promise<Array<ParseObject>>*/
  10065. {
  10066. options = options || {};
  10067. if (this._order || this._skip || this._limit >= 0) {
  10068. return Promise.reject('Cannot iterate on a query with sort, skip, or limit.');
  10069. }
  10070. var query = new ParseQuery(this.className); // We can override the batch size from the options.
  10071. // This is undocumented, but useful for testing.
  10072. query._limit = options.batchSize || 100;
  10073. query._include = this._include.map(function (i) {
  10074. return i;
  10075. });
  10076. if (this._select) {
  10077. query._select = this._select.map(function (s) {
  10078. return s;
  10079. });
  10080. }
  10081. query._where = {};
  10082. for (var _attr in this._where) {
  10083. var val = this._where[_attr];
  10084. if (Array.isArray(val)) {
  10085. query._where[_attr] = val.map(function (v) {
  10086. return v;
  10087. });
  10088. } else if (val && (0, _typeof2.default)(val) === 'object') {
  10089. var conditionMap = {};
  10090. query._where[_attr] = conditionMap;
  10091. for (var cond in val) {
  10092. conditionMap[cond] = val[cond];
  10093. }
  10094. } else {
  10095. query._where[_attr] = val;
  10096. }
  10097. }
  10098. query.ascending('objectId');
  10099. var findOptions = {};
  10100. if (options.hasOwnProperty('useMasterKey')) {
  10101. findOptions.useMasterKey = options.useMasterKey;
  10102. }
  10103. if (options.hasOwnProperty('sessionToken')) {
  10104. findOptions.sessionToken = options.sessionToken;
  10105. }
  10106. var finished = false;
  10107. return (0, _promiseUtils.continueWhile)(function () {
  10108. return !finished;
  10109. }, function () {
  10110. return query.find(findOptions).then(function (results) {
  10111. var callbacksDone = Promise.resolve();
  10112. results.forEach(function (result) {
  10113. callbacksDone = callbacksDone.then(function () {
  10114. return callback(result);
  10115. });
  10116. });
  10117. return callbacksDone.then(function () {
  10118. if (results.length >= query._limit) {
  10119. query.greaterThan('objectId', results[results.length - 1].id);
  10120. } else {
  10121. finished = true;
  10122. }
  10123. });
  10124. });
  10125. });
  10126. }
  10127. /** Query Conditions **/
  10128. /**
  10129. * Adds a constraint to the query that requires a particular key's value to
  10130. * be equal to the provided value.
  10131. * @param {String} key The key to check.
  10132. * @param value The value that the Parse.Object must contain.
  10133. * @return {Parse.Query} Returns the query, so you can chain this call.
  10134. */
  10135. }, {
  10136. key: "equalTo",
  10137. value: function (key
  10138. /*: string*/
  10139. , value
  10140. /*: mixed*/
  10141. )
  10142. /*: ParseQuery*/
  10143. {
  10144. if (typeof value === 'undefined') {
  10145. return this.doesNotExist(key);
  10146. }
  10147. this._where[key] = (0, _encode.default)(value, false, true);
  10148. return this;
  10149. }
  10150. /**
  10151. * Adds a constraint to the query that requires a particular key's value to
  10152. * be not equal to the provided value.
  10153. * @param {String} key The key to check.
  10154. * @param value The value that must not be equalled.
  10155. * @return {Parse.Query} Returns the query, so you can chain this call.
  10156. */
  10157. }, {
  10158. key: "notEqualTo",
  10159. value: function (key
  10160. /*: string*/
  10161. , value
  10162. /*: mixed*/
  10163. )
  10164. /*: ParseQuery*/
  10165. {
  10166. return this._addCondition(key, '$ne', value);
  10167. }
  10168. /**
  10169. * Adds a constraint to the query that requires a particular key's value to
  10170. * be less than the provided value.
  10171. * @param {String} key The key to check.
  10172. * @param value The value that provides an upper bound.
  10173. * @return {Parse.Query} Returns the query, so you can chain this call.
  10174. */
  10175. }, {
  10176. key: "lessThan",
  10177. value: function (key
  10178. /*: string*/
  10179. , value
  10180. /*: mixed*/
  10181. )
  10182. /*: ParseQuery*/
  10183. {
  10184. return this._addCondition(key, '$lt', value);
  10185. }
  10186. /**
  10187. * Adds a constraint to the query that requires a particular key's value to
  10188. * be greater than the provided value.
  10189. * @param {String} key The key to check.
  10190. * @param value The value that provides an lower bound.
  10191. * @return {Parse.Query} Returns the query, so you can chain this call.
  10192. */
  10193. }, {
  10194. key: "greaterThan",
  10195. value: function (key
  10196. /*: string*/
  10197. , value
  10198. /*: mixed*/
  10199. )
  10200. /*: ParseQuery*/
  10201. {
  10202. return this._addCondition(key, '$gt', value);
  10203. }
  10204. /**
  10205. * Adds a constraint to the query that requires a particular key's value to
  10206. * be less than or equal to the provided value.
  10207. * @param {String} key The key to check.
  10208. * @param value The value that provides an upper bound.
  10209. * @return {Parse.Query} Returns the query, so you can chain this call.
  10210. */
  10211. }, {
  10212. key: "lessThanOrEqualTo",
  10213. value: function (key
  10214. /*: string*/
  10215. , value
  10216. /*: mixed*/
  10217. )
  10218. /*: ParseQuery*/
  10219. {
  10220. return this._addCondition(key, '$lte', value);
  10221. }
  10222. /**
  10223. * Adds a constraint to the query that requires a particular key's value to
  10224. * be greater than or equal to the provided value.
  10225. * @param {String} key The key to check.
  10226. * @param value The value that provides an lower bound.
  10227. * @return {Parse.Query} Returns the query, so you can chain this call.
  10228. */
  10229. }, {
  10230. key: "greaterThanOrEqualTo",
  10231. value: function (key
  10232. /*: string*/
  10233. , value
  10234. /*: mixed*/
  10235. )
  10236. /*: ParseQuery*/
  10237. {
  10238. return this._addCondition(key, '$gte', value);
  10239. }
  10240. /**
  10241. * Adds a constraint to the query that requires a particular key's value to
  10242. * be contained in the provided list of values.
  10243. * @param {String} key The key to check.
  10244. * @param {Array} values The values that will match.
  10245. * @return {Parse.Query} Returns the query, so you can chain this call.
  10246. */
  10247. }, {
  10248. key: "containedIn",
  10249. value: function (key
  10250. /*: string*/
  10251. , value
  10252. /*: mixed*/
  10253. )
  10254. /*: ParseQuery*/
  10255. {
  10256. return this._addCondition(key, '$in', value);
  10257. }
  10258. /**
  10259. * Adds a constraint to the query that requires a particular key's value to
  10260. * not be contained in the provided list of values.
  10261. * @param {String} key The key to check.
  10262. * @param {Array} values The values that will not match.
  10263. * @return {Parse.Query} Returns the query, so you can chain this call.
  10264. */
  10265. }, {
  10266. key: "notContainedIn",
  10267. value: function (key
  10268. /*: string*/
  10269. , value
  10270. /*: mixed*/
  10271. )
  10272. /*: ParseQuery*/
  10273. {
  10274. return this._addCondition(key, '$nin', value);
  10275. }
  10276. /**
  10277. * Adds a constraint to the query that requires a particular key's value to
  10278. * be contained by the provided list of values. Get objects where all array elements match.
  10279. * @param {String} key The key to check.
  10280. * @param {Array} values The values that will match.
  10281. * @return {Parse.Query} Returns the query, so you can chain this call.
  10282. */
  10283. }, {
  10284. key: "containedBy",
  10285. value: function (key
  10286. /*: string*/
  10287. , value
  10288. /*: Array<mixed>*/
  10289. )
  10290. /*: ParseQuery*/
  10291. {
  10292. return this._addCondition(key, '$containedBy', value);
  10293. }
  10294. /**
  10295. * Adds a constraint to the query that requires a particular key's value to
  10296. * contain each one of the provided list of values.
  10297. * @param {String} key The key to check. This key's value must be an array.
  10298. * @param {Array} values The values that will match.
  10299. * @return {Parse.Query} Returns the query, so you can chain this call.
  10300. */
  10301. }, {
  10302. key: "containsAll",
  10303. value: function (key
  10304. /*: string*/
  10305. , values
  10306. /*: Array<mixed>*/
  10307. )
  10308. /*: ParseQuery*/
  10309. {
  10310. return this._addCondition(key, '$all', values);
  10311. }
  10312. /**
  10313. * Adds a constraint to the query that requires a particular key's value to
  10314. * contain each one of the provided list of values starting with given strings.
  10315. * @param {String} key The key to check. This key's value must be an array.
  10316. * @param {Array<String>} values The string values that will match as starting string.
  10317. * @return {Parse.Query} Returns the query, so you can chain this call.
  10318. */
  10319. }, {
  10320. key: "containsAllStartingWith",
  10321. value: function (key
  10322. /*: string*/
  10323. , values
  10324. /*: Array<string>*/
  10325. )
  10326. /*: ParseQuery*/
  10327. {
  10328. var _this = this;
  10329. if (!Array.isArray(values)) {
  10330. values = [values];
  10331. }
  10332. var regexObject = values.map(function (value) {
  10333. return {
  10334. '$regex': _this._regexStartWith(value)
  10335. };
  10336. });
  10337. return this.containsAll(key, regexObject);
  10338. }
  10339. /**
  10340. * Adds a constraint for finding objects that contain the given key.
  10341. * @param {String} key The key that should exist.
  10342. * @return {Parse.Query} Returns the query, so you can chain this call.
  10343. */
  10344. }, {
  10345. key: "exists",
  10346. value: function (key
  10347. /*: string*/
  10348. )
  10349. /*: ParseQuery*/
  10350. {
  10351. return this._addCondition(key, '$exists', true);
  10352. }
  10353. /**
  10354. * Adds a constraint for finding objects that do not contain a given key.
  10355. * @param {String} key The key that should not exist
  10356. * @return {Parse.Query} Returns the query, so you can chain this call.
  10357. */
  10358. }, {
  10359. key: "doesNotExist",
  10360. value: function (key
  10361. /*: string*/
  10362. )
  10363. /*: ParseQuery*/
  10364. {
  10365. return this._addCondition(key, '$exists', false);
  10366. }
  10367. /**
  10368. * Adds a regular expression constraint for finding string values that match
  10369. * the provided regular expression.
  10370. * This may be slow for large datasets.
  10371. * @param {String} key The key that the string to match is stored in.
  10372. * @param {RegExp} regex The regular expression pattern to match.
  10373. * @return {Parse.Query} Returns the query, so you can chain this call.
  10374. */
  10375. }, {
  10376. key: "matches",
  10377. value: function (key
  10378. /*: string*/
  10379. , regex
  10380. /*: RegExp*/
  10381. , modifiers
  10382. /*: string*/
  10383. )
  10384. /*: ParseQuery*/
  10385. {
  10386. this._addCondition(key, '$regex', regex);
  10387. if (!modifiers) {
  10388. modifiers = '';
  10389. }
  10390. if (regex.ignoreCase) {
  10391. modifiers += 'i';
  10392. }
  10393. if (regex.multiline) {
  10394. modifiers += 'm';
  10395. }
  10396. if (modifiers.length) {
  10397. this._addCondition(key, '$options', modifiers);
  10398. }
  10399. return this;
  10400. }
  10401. /**
  10402. * Adds a constraint that requires that a key's value matches a Parse.Query
  10403. * constraint.
  10404. * @param {String} key The key that the contains the object to match the
  10405. * query.
  10406. * @param {Parse.Query} query The query that should match.
  10407. * @return {Parse.Query} Returns the query, so you can chain this call.
  10408. */
  10409. }, {
  10410. key: "matchesQuery",
  10411. value: function (key
  10412. /*: string*/
  10413. , query
  10414. /*: ParseQuery*/
  10415. )
  10416. /*: ParseQuery*/
  10417. {
  10418. var queryJSON = query.toJSON();
  10419. queryJSON.className = query.className;
  10420. return this._addCondition(key, '$inQuery', queryJSON);
  10421. }
  10422. /**
  10423. * Adds a constraint that requires that a key's value not matches a
  10424. * Parse.Query constraint.
  10425. * @param {String} key The key that the contains the object to match the
  10426. * query.
  10427. * @param {Parse.Query} query The query that should not match.
  10428. * @return {Parse.Query} Returns the query, so you can chain this call.
  10429. */
  10430. }, {
  10431. key: "doesNotMatchQuery",
  10432. value: function (key
  10433. /*: string*/
  10434. , query
  10435. /*: ParseQuery*/
  10436. )
  10437. /*: ParseQuery*/
  10438. {
  10439. var queryJSON = query.toJSON();
  10440. queryJSON.className = query.className;
  10441. return this._addCondition(key, '$notInQuery', queryJSON);
  10442. }
  10443. /**
  10444. * Adds a constraint that requires that a key's value matches a value in
  10445. * an object returned by a different Parse.Query.
  10446. * @param {String} key The key that contains the value that is being
  10447. * matched.
  10448. * @param {String} queryKey The key in the objects returned by the query to
  10449. * match against.
  10450. * @param {Parse.Query} query The query to run.
  10451. * @return {Parse.Query} Returns the query, so you can chain this call.
  10452. */
  10453. }, {
  10454. key: "matchesKeyInQuery",
  10455. value: function (key
  10456. /*: string*/
  10457. , queryKey
  10458. /*: string*/
  10459. , query
  10460. /*: ParseQuery*/
  10461. )
  10462. /*: ParseQuery*/
  10463. {
  10464. var queryJSON = query.toJSON();
  10465. queryJSON.className = query.className;
  10466. return this._addCondition(key, '$select', {
  10467. key: queryKey,
  10468. query: queryJSON
  10469. });
  10470. }
  10471. /**
  10472. * Adds a constraint that requires that a key's value not match a value in
  10473. * an object returned by a different Parse.Query.
  10474. * @param {String} key The key that contains the value that is being
  10475. * excluded.
  10476. * @param {String} queryKey The key in the objects returned by the query to
  10477. * match against.
  10478. * @param {Parse.Query} query The query to run.
  10479. * @return {Parse.Query} Returns the query, so you can chain this call.
  10480. */
  10481. }, {
  10482. key: "doesNotMatchKeyInQuery",
  10483. value: function (key
  10484. /*: string*/
  10485. , queryKey
  10486. /*: string*/
  10487. , query
  10488. /*: ParseQuery*/
  10489. )
  10490. /*: ParseQuery*/
  10491. {
  10492. var queryJSON = query.toJSON();
  10493. queryJSON.className = query.className;
  10494. return this._addCondition(key, '$dontSelect', {
  10495. key: queryKey,
  10496. query: queryJSON
  10497. });
  10498. }
  10499. /**
  10500. * Adds a constraint for finding string values that contain a provided
  10501. * string. This may be slow for large datasets.
  10502. * @param {String} key The key that the string to match is stored in.
  10503. * @param {String} substring The substring that the value must contain.
  10504. * @return {Parse.Query} Returns the query, so you can chain this call.
  10505. */
  10506. }, {
  10507. key: "contains",
  10508. value: function (key
  10509. /*: string*/
  10510. , value
  10511. /*: string*/
  10512. )
  10513. /*: ParseQuery*/
  10514. {
  10515. if (typeof value !== 'string') {
  10516. throw new Error('The value being searched for must be a string.');
  10517. }
  10518. return this._addCondition(key, '$regex', quote(value));
  10519. }
  10520. /**
  10521. * Adds a constraint for finding string values that contain a provided
  10522. * string. This may be slow for large datasets. Requires Parse-Server > 2.5.0
  10523. *
  10524. * In order to sort you must use select and ascending ($score is required)
  10525. * <pre>
  10526. * query.fullText('field', 'term');
  10527. * query.ascending('$score');
  10528. * query.select('$score');
  10529. * </pre>
  10530. *
  10531. * To retrieve the weight / rank
  10532. * <pre>
  10533. * object->get('score');
  10534. * </pre>
  10535. *
  10536. * You can define optionals by providing an object as a third parameter
  10537. * <pre>
  10538. * query.fullText('field', 'term', { language: 'es', diacriticSensitive: true });
  10539. * </pre>
  10540. *
  10541. * @param {String} key The key that the string to match is stored in.
  10542. * @param {String} value The string to search
  10543. * @param {Object} options (Optional)
  10544. * @param {String} options.language The language that determines the list of stop words for the search and the rules for the stemmer and tokenizer.
  10545. * @param {Boolean} options.caseSensitive A boolean flag to enable or disable case sensitive search.
  10546. * @param {Boolean} options.diacriticSensitive A boolean flag to enable or disable diacritic sensitive search.
  10547. * @return {Parse.Query} Returns the query, so you can chain this call.
  10548. */
  10549. }, {
  10550. key: "fullText",
  10551. value: function (key
  10552. /*: string*/
  10553. , value
  10554. /*: string*/
  10555. , options
  10556. /*: ?Object*/
  10557. )
  10558. /*: ParseQuery*/
  10559. {
  10560. options = options || {};
  10561. if (!key) {
  10562. throw new Error('A key is required.');
  10563. }
  10564. if (!value) {
  10565. throw new Error('A search term is required');
  10566. }
  10567. if (typeof value !== 'string') {
  10568. throw new Error('The value being searched for must be a string.');
  10569. }
  10570. var fullOptions = {};
  10571. fullOptions.$term = value;
  10572. for (var option in options) {
  10573. switch (option) {
  10574. case 'language':
  10575. fullOptions.$language = options[option];
  10576. break;
  10577. case 'caseSensitive':
  10578. fullOptions.$caseSensitive = options[option];
  10579. break;
  10580. case 'diacriticSensitive':
  10581. fullOptions.$diacriticSensitive = options[option];
  10582. break;
  10583. default:
  10584. throw new Error("Unknown option: ".concat(option));
  10585. }
  10586. }
  10587. return this._addCondition(key, '$text', {
  10588. $search: fullOptions
  10589. });
  10590. }
  10591. /**
  10592. * Method to sort the full text search by text score
  10593. *
  10594. * @return {Parse.Query} Returns the query, so you can chain this call.
  10595. */
  10596. }, {
  10597. key: "sortByTextScore",
  10598. value: function () {
  10599. this.ascending('$score');
  10600. this.select(['$score']);
  10601. return this;
  10602. }
  10603. /**
  10604. * Adds a constraint for finding string values that start with a provided
  10605. * string. This query will use the backend index, so it will be fast even
  10606. * for large datasets.
  10607. * @param {String} key The key that the string to match is stored in.
  10608. * @param {String} prefix The substring that the value must start with.
  10609. * @return {Parse.Query} Returns the query, so you can chain this call.
  10610. */
  10611. }, {
  10612. key: "startsWith",
  10613. value: function (key
  10614. /*: string*/
  10615. , value
  10616. /*: string*/
  10617. )
  10618. /*: ParseQuery*/
  10619. {
  10620. if (typeof value !== 'string') {
  10621. throw new Error('The value being searched for must be a string.');
  10622. }
  10623. return this._addCondition(key, '$regex', this._regexStartWith(value));
  10624. }
  10625. /**
  10626. * Adds a constraint for finding string values that end with a provided
  10627. * string. This will be slow for large datasets.
  10628. * @param {String} key The key that the string to match is stored in.
  10629. * @param {String} suffix The substring that the value must end with.
  10630. * @return {Parse.Query} Returns the query, so you can chain this call.
  10631. */
  10632. }, {
  10633. key: "endsWith",
  10634. value: function (key
  10635. /*: string*/
  10636. , value
  10637. /*: string*/
  10638. )
  10639. /*: ParseQuery*/
  10640. {
  10641. if (typeof value !== 'string') {
  10642. throw new Error('The value being searched for must be a string.');
  10643. }
  10644. return this._addCondition(key, '$regex', quote(value) + '$');
  10645. }
  10646. /**
  10647. * Adds a proximity based constraint for finding objects with key point
  10648. * values near the point given.
  10649. * @param {String} key The key that the Parse.GeoPoint is stored in.
  10650. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  10651. * @return {Parse.Query} Returns the query, so you can chain this call.
  10652. */
  10653. }, {
  10654. key: "near",
  10655. value: function (key
  10656. /*: string*/
  10657. , point
  10658. /*: ParseGeoPoint*/
  10659. )
  10660. /*: ParseQuery*/
  10661. {
  10662. if (!(point instanceof _ParseGeoPoint.default)) {
  10663. // Try to cast it as a GeoPoint
  10664. point = new _ParseGeoPoint.default(point);
  10665. }
  10666. return this._addCondition(key, '$nearSphere', point);
  10667. }
  10668. /**
  10669. * Adds a proximity based constraint for finding objects with key point
  10670. * values near the point given and within the maximum distance given.
  10671. * @param {String} key The key that the Parse.GeoPoint is stored in.
  10672. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  10673. * @param {Number} maxDistance Maximum distance (in radians) of results to
  10674. * return.
  10675. * @param {Boolean} sorted A Bool value that is true if results should be
  10676. * sorted by distance ascending, false is no sorting is required,
  10677. * defaults to true.
  10678. * @return {Parse.Query} Returns the query, so you can chain this call.
  10679. */
  10680. }, {
  10681. key: "withinRadians",
  10682. value: function (key
  10683. /*: string*/
  10684. , point
  10685. /*: ParseGeoPoint*/
  10686. , distance
  10687. /*: number*/
  10688. , sorted
  10689. /*: boolean*/
  10690. )
  10691. /*: ParseQuery*/
  10692. {
  10693. if (sorted || sorted === undefined) {
  10694. this.near(key, point);
  10695. return this._addCondition(key, '$maxDistance', distance);
  10696. } else {
  10697. return this._addCondition(key, '$geoWithin', {
  10698. '$centerSphere': [[point.longitude, point.latitude], distance]
  10699. });
  10700. }
  10701. }
  10702. /**
  10703. * Adds a proximity based constraint for finding objects with key point
  10704. * values near the point given and within the maximum distance given.
  10705. * Radius of earth used is 3958.8 miles.
  10706. * @param {String} key The key that the Parse.GeoPoint is stored in.
  10707. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  10708. * @param {Number} maxDistance Maximum distance (in miles) of results to
  10709. * return.
  10710. * @param {Boolean} sorted A Bool value that is true if results should be
  10711. * sorted by distance ascending, false is no sorting is required,
  10712. * defaults to true.
  10713. * @return {Parse.Query} Returns the query, so you can chain this call.
  10714. */
  10715. }, {
  10716. key: "withinMiles",
  10717. value: function (key
  10718. /*: string*/
  10719. , point
  10720. /*: ParseGeoPoint*/
  10721. , distance
  10722. /*: number*/
  10723. , sorted
  10724. /*: boolean*/
  10725. )
  10726. /*: ParseQuery*/
  10727. {
  10728. return this.withinRadians(key, point, distance / 3958.8, sorted);
  10729. }
  10730. /**
  10731. * Adds a proximity based constraint for finding objects with key point
  10732. * values near the point given and within the maximum distance given.
  10733. * Radius of earth used is 6371.0 kilometers.
  10734. * @param {String} key The key that the Parse.GeoPoint is stored in.
  10735. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
  10736. * @param {Number} maxDistance Maximum distance (in kilometers) of results
  10737. * to return.
  10738. * @param {Boolean} sorted A Bool value that is true if results should be
  10739. * sorted by distance ascending, false is no sorting is required,
  10740. * defaults to true.
  10741. * @return {Parse.Query} Returns the query, so you can chain this call.
  10742. */
  10743. }, {
  10744. key: "withinKilometers",
  10745. value: function (key
  10746. /*: string*/
  10747. , point
  10748. /*: ParseGeoPoint*/
  10749. , distance
  10750. /*: number*/
  10751. , sorted
  10752. /*: boolean*/
  10753. )
  10754. /*: ParseQuery*/
  10755. {
  10756. return this.withinRadians(key, point, distance / 6371.0, sorted);
  10757. }
  10758. /**
  10759. * Adds a constraint to the query that requires a particular key's
  10760. * coordinates be contained within a given rectangular geographic bounding
  10761. * box.
  10762. * @param {String} key The key to be constrained.
  10763. * @param {Parse.GeoPoint} southwest
  10764. * The lower-left inclusive corner of the box.
  10765. * @param {Parse.GeoPoint} northeast
  10766. * The upper-right inclusive corner of the box.
  10767. * @return {Parse.Query} Returns the query, so you can chain this call.
  10768. */
  10769. }, {
  10770. key: "withinGeoBox",
  10771. value: function (key
  10772. /*: string*/
  10773. , southwest
  10774. /*: ParseGeoPoint*/
  10775. , northeast
  10776. /*: ParseGeoPoint*/
  10777. )
  10778. /*: ParseQuery*/
  10779. {
  10780. if (!(southwest instanceof _ParseGeoPoint.default)) {
  10781. southwest = new _ParseGeoPoint.default(southwest);
  10782. }
  10783. if (!(northeast instanceof _ParseGeoPoint.default)) {
  10784. northeast = new _ParseGeoPoint.default(northeast);
  10785. }
  10786. this._addCondition(key, '$within', {
  10787. '$box': [southwest, northeast]
  10788. });
  10789. return this;
  10790. }
  10791. /**
  10792. * Adds a constraint to the query that requires a particular key's
  10793. * coordinates be contained within and on the bounds of a given polygon.
  10794. * Supports closed and open (last point is connected to first) paths
  10795. *
  10796. * Polygon must have at least 3 points
  10797. *
  10798. * @param {String} key The key to be constrained.
  10799. * @param {Array} array of geopoints
  10800. * @return {Parse.Query} Returns the query, so you can chain this call.
  10801. */
  10802. }, {
  10803. key: "withinPolygon",
  10804. value: function (key
  10805. /*: string*/
  10806. , points
  10807. /*: Array<Array<number>>*/
  10808. )
  10809. /*: ParseQuery*/
  10810. {
  10811. return this._addCondition(key, '$geoWithin', {
  10812. '$polygon': points
  10813. });
  10814. }
  10815. /**
  10816. * Add a constraint to the query that requires a particular key's
  10817. * coordinates that contains a ParseGeoPoint
  10818. *
  10819. * @param {String} key The key to be constrained.
  10820. * @param {Parse.GeoPoint} GeoPoint
  10821. * @return {Parse.Query} Returns the query, so you can chain this call.
  10822. */
  10823. }, {
  10824. key: "polygonContains",
  10825. value: function (key
  10826. /*: string*/
  10827. , point
  10828. /*: ParseGeoPoint*/
  10829. )
  10830. /*: ParseQuery*/
  10831. {
  10832. return this._addCondition(key, '$geoIntersects', {
  10833. '$point': point
  10834. });
  10835. }
  10836. /** Query Orderings **/
  10837. /**
  10838. * Sorts the results in ascending order by the given key.
  10839. *
  10840. * @param {(String|String[]|...String)} key The key to order by, which is a
  10841. * string of comma separated values, or an Array of keys, or multiple keys.
  10842. * @return {Parse.Query} Returns the query, so you can chain this call.
  10843. */
  10844. }, {
  10845. key: "ascending",
  10846. value: function ()
  10847. /*: ParseQuery*/
  10848. {
  10849. this._order = [];
  10850. for (var _len = arguments.length, keys = new Array(_len), _key5 = 0; _key5 < _len; _key5++) {
  10851. keys[_key5] = arguments[_key5];
  10852. }
  10853. return this.addAscending.apply(this, keys);
  10854. }
  10855. /**
  10856. * Sorts the results in ascending order by the given key,
  10857. * but can also add secondary sort descriptors without overwriting _order.
  10858. *
  10859. * @param {(String|String[]|...String)} key The key to order by, which is a
  10860. * string of comma separated values, or an Array of keys, or multiple keys.
  10861. * @return {Parse.Query} Returns the query, so you can chain this call.
  10862. */
  10863. }, {
  10864. key: "addAscending",
  10865. value: function ()
  10866. /*: ParseQuery*/
  10867. {
  10868. var _this5 = this;
  10869. if (!this._order) {
  10870. this._order = [];
  10871. }
  10872. for (var _len2 = arguments.length, keys = new Array(_len2), _key6 = 0; _key6 < _len2; _key6++) {
  10873. keys[_key6] = arguments[_key6];
  10874. }
  10875. keys.forEach(function (key) {
  10876. if (Array.isArray(key)) {
  10877. key = key.join();
  10878. }
  10879. _this5._order = _this5._order.concat(key.replace(/\s/g, '').split(','));
  10880. });
  10881. return this;
  10882. }
  10883. /**
  10884. * Sorts the results in descending order by the given key.
  10885. *
  10886. * @param {(String|String[]|...String)} key The key to order by, which is a
  10887. * string of comma separated values, or an Array of keys, or multiple keys.
  10888. * @return {Parse.Query} Returns the query, so you can chain this call.
  10889. */
  10890. }, {
  10891. key: "descending",
  10892. value: function ()
  10893. /*: ParseQuery*/
  10894. {
  10895. this._order = [];
  10896. for (var _len3 = arguments.length, keys = new Array(_len3), _key7 = 0; _key7 < _len3; _key7++) {
  10897. keys[_key7] = arguments[_key7];
  10898. }
  10899. return this.addDescending.apply(this, keys);
  10900. }
  10901. /**
  10902. * Sorts the results in descending order by the given key,
  10903. * but can also add secondary sort descriptors without overwriting _order.
  10904. *
  10905. * @param {(String|String[]|...String)} key The key to order by, which is a
  10906. * string of comma separated values, or an Array of keys, or multiple keys.
  10907. * @return {Parse.Query} Returns the query, so you can chain this call.
  10908. */
  10909. }, {
  10910. key: "addDescending",
  10911. value: function ()
  10912. /*: ParseQuery*/
  10913. {
  10914. var _this6 = this;
  10915. if (!this._order) {
  10916. this._order = [];
  10917. }
  10918. for (var _len4 = arguments.length, keys = new Array(_len4), _key8 = 0; _key8 < _len4; _key8++) {
  10919. keys[_key8] = arguments[_key8];
  10920. }
  10921. keys.forEach(function (key) {
  10922. if (Array.isArray(key)) {
  10923. key = key.join();
  10924. }
  10925. _this6._order = _this6._order.concat(key.replace(/\s/g, '').split(',').map(function (k) {
  10926. return '-' + k;
  10927. }));
  10928. });
  10929. return this;
  10930. }
  10931. /** Query Options **/
  10932. /**
  10933. * Sets the number of results to skip before returning any results.
  10934. * This is useful for pagination.
  10935. * Default is to skip zero results.
  10936. * @param {Number} n the number of results to skip.
  10937. * @return {Parse.Query} Returns the query, so you can chain this call.
  10938. */
  10939. }, {
  10940. key: "skip",
  10941. value: function (n
  10942. /*: number*/
  10943. )
  10944. /*: ParseQuery*/
  10945. {
  10946. if (typeof n !== 'number' || n < 0) {
  10947. throw new Error('You can only skip by a positive number');
  10948. }
  10949. this._skip = n;
  10950. return this;
  10951. }
  10952. /**
  10953. * Sets the limit of the number of results to return. The default limit is
  10954. * 100, with a maximum of 1000 results being returned at a time.
  10955. * @param {Number} n the number of results to limit to.
  10956. * @return {Parse.Query} Returns the query, so you can chain this call.
  10957. */
  10958. }, {
  10959. key: "limit",
  10960. value: function (n
  10961. /*: number*/
  10962. )
  10963. /*: ParseQuery*/
  10964. {
  10965. if (typeof n !== 'number') {
  10966. throw new Error('You can only set the limit to a numeric value');
  10967. }
  10968. this._limit = n;
  10969. return this;
  10970. }
  10971. /**
  10972. * Sets the flag to include with response the total number of objects satisfying this query,
  10973. * despite limits/skip. Might be useful for pagination.
  10974. * Note that result of this query will be wrapped as an object with
  10975. *`results`: holding {ParseObject} array and `count`: integer holding total number
  10976. * @param {boolean} b false - disable, true - enable.
  10977. * @return {Parse.Query} Returns the query, so you can chain this call.
  10978. */
  10979. }, {
  10980. key: "withCount",
  10981. value: function ()
  10982. /*: ParseQuery*/
  10983. {
  10984. var includeCount
  10985. /*: boolean*/
  10986. = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  10987. if (typeof includeCount !== 'boolean') {
  10988. throw new Error('You can only set withCount to a boolean value');
  10989. }
  10990. this._count = includeCount;
  10991. return this;
  10992. }
  10993. /**
  10994. * Includes nested Parse.Objects for the provided key. You can use dot
  10995. * notation to specify which fields in the included object are also fetched.
  10996. *
  10997. * You can include all nested Parse.Objects by passing in '*'.
  10998. * Requires Parse Server 3.0.0+
  10999. * <pre>query.include('*');</pre>
  11000. *
  11001. * @param {...String|Array<String>} key The name(s) of the key(s) to include.
  11002. * @return {Parse.Query} Returns the query, so you can chain this call.
  11003. */
  11004. }, {
  11005. key: "include",
  11006. value: function ()
  11007. /*: ParseQuery*/
  11008. {
  11009. var _this7 = this;
  11010. for (var _len5 = arguments.length, keys = new Array(_len5), _key9 = 0; _key9 < _len5; _key9++) {
  11011. keys[_key9] = arguments[_key9];
  11012. }
  11013. keys.forEach(function (key) {
  11014. if (Array.isArray(key)) {
  11015. _this7._include = _this7._include.concat(key);
  11016. } else {
  11017. _this7._include.push(key);
  11018. }
  11019. });
  11020. return this;
  11021. }
  11022. /**
  11023. * Includes all nested Parse.Objects.
  11024. *
  11025. * Requires Parse Server 3.0.0+
  11026. *
  11027. * @return {Parse.Query} Returns the query, so you can chain this call.
  11028. */
  11029. }, {
  11030. key: "includeAll",
  11031. value: function ()
  11032. /*: ParseQuery*/
  11033. {
  11034. return this.include('*');
  11035. }
  11036. /**
  11037. * Restricts the fields of the returned Parse.Objects to include only the
  11038. * provided keys. If this is called multiple times, then all of the keys
  11039. * specified in each of the calls will be included.
  11040. * @param {...String|Array<String>} keys The name(s) of the key(s) to include.
  11041. * @return {Parse.Query} Returns the query, so you can chain this call.
  11042. */
  11043. }, {
  11044. key: "select",
  11045. value: function ()
  11046. /*: ParseQuery*/
  11047. {
  11048. var _this8 = this;
  11049. if (!this._select) {
  11050. this._select = [];
  11051. }
  11052. for (var _len6 = arguments.length, keys = new Array(_len6), _key10 = 0; _key10 < _len6; _key10++) {
  11053. keys[_key10] = arguments[_key10];
  11054. }
  11055. keys.forEach(function (key) {
  11056. if (Array.isArray(key)) {
  11057. _this8._select = _this8._select.concat(key);
  11058. } else {
  11059. _this8._select.push(key);
  11060. }
  11061. });
  11062. return this;
  11063. }
  11064. /**
  11065. * Restricts the fields of the returned Parse.Objects to all keys except the
  11066. * provided keys. Exclude takes precedence over select and include.
  11067. *
  11068. * Requires Parse Server 3.6.0+
  11069. *
  11070. * @param {...String|Array<String>} keys The name(s) of the key(s) to exclude.
  11071. * @return {Parse.Query} Returns the query, so you can chain this call.
  11072. */
  11073. }, {
  11074. key: "exclude",
  11075. value: function ()
  11076. /*: ParseQuery*/
  11077. {
  11078. var _this9 = this;
  11079. for (var _len7 = arguments.length, keys = new Array(_len7), _key11 = 0; _key11 < _len7; _key11++) {
  11080. keys[_key11] = arguments[_key11];
  11081. }
  11082. keys.forEach(function (key) {
  11083. if (Array.isArray(key)) {
  11084. _this9._exclude = _this9._exclude.concat(key);
  11085. } else {
  11086. _this9._exclude.push(key);
  11087. }
  11088. });
  11089. return this;
  11090. }
  11091. /**
  11092. * Changes the read preference that the backend will use when performing the query to the database.
  11093. * @param {String} readPreference The read preference for the main query.
  11094. * @param {String} includeReadPreference The read preference for the queries to include pointers.
  11095. * @param {String} subqueryReadPreference The read preference for the sub queries.
  11096. * @return {Parse.Query} Returns the query, so you can chain this call.
  11097. */
  11098. }, {
  11099. key: "readPreference",
  11100. value: function (_readPreference
  11101. /*: string*/
  11102. , includeReadPreference
  11103. /*:: ?: string*/
  11104. , subqueryReadPreference
  11105. /*:: ?: string*/
  11106. )
  11107. /*: ParseQuery*/
  11108. {
  11109. this._readPreference = _readPreference;
  11110. this._includeReadPreference = includeReadPreference;
  11111. this._subqueryReadPreference = subqueryReadPreference;
  11112. return this;
  11113. }
  11114. /**
  11115. * Subscribe this query to get liveQuery updates
  11116. *
  11117. * @param {String} sessionToken (optional) Defaults to the currentUser
  11118. * @return {Promise<LiveQuerySubscription>} Returns the liveQuerySubscription, it's an event emitter
  11119. * which can be used to get liveQuery updates.
  11120. */
  11121. }, {
  11122. key: "subscribe",
  11123. value: function () {
  11124. var _subscribe = (0, _asyncToGenerator2.default)(
  11125. /*#__PURE__*/
  11126. _regenerator.default.mark(function _callee2(sessionToken
  11127. /*:: ?: string*/
  11128. ) {
  11129. var currentUser, liveQueryClient, subscription;
  11130. return _regenerator.default.wrap(function (_context2) {
  11131. while (1) {
  11132. switch (_context2.prev = _context2.next) {
  11133. case 0:
  11134. _context2.next = 2;
  11135. return _CoreManager.default.getUserController().currentUserAsync();
  11136. case 2:
  11137. currentUser = _context2.sent;
  11138. if (!sessionToken) {
  11139. sessionToken = currentUser ? currentUser.getSessionToken() : undefined;
  11140. }
  11141. _context2.next = 6;
  11142. return _CoreManager.default.getLiveQueryController().getDefaultLiveQueryClient();
  11143. case 6:
  11144. liveQueryClient = _context2.sent;
  11145. if (liveQueryClient.shouldOpen()) {
  11146. liveQueryClient.open();
  11147. }
  11148. subscription = liveQueryClient.subscribe(this, sessionToken);
  11149. return _context2.abrupt("return", subscription);
  11150. case 10:
  11151. case "end":
  11152. return _context2.stop();
  11153. }
  11154. }
  11155. }, _callee2, this);
  11156. }));
  11157. return function () {
  11158. return _subscribe.apply(this, arguments);
  11159. };
  11160. }()
  11161. /**
  11162. * Constructs a Parse.Query that is the OR of the passed in queries. For
  11163. * example:
  11164. * <pre>var compoundQuery = Parse.Query.or(query1, query2, query3);</pre>
  11165. *
  11166. * will create a compoundQuery that is an or of the query1, query2, and
  11167. * query3.
  11168. * @param {...Parse.Query} var_args The list of queries to OR.
  11169. * @static
  11170. * @return {Parse.Query} The query that is the OR of the passed in queries.
  11171. */
  11172. }, {
  11173. key: "fromLocalDatastore",
  11174. /**
  11175. * Changes the source of this query to all pinned objects.
  11176. *
  11177. * @return {Parse.Query} Returns the query, so you can chain this call.
  11178. */
  11179. value: function ()
  11180. /*: ParseQuery*/
  11181. {
  11182. return this.fromPinWithName(null);
  11183. }
  11184. /**
  11185. * Changes the source of this query to the default group of pinned objects.
  11186. *
  11187. * @return {Parse.Query} Returns the query, so you can chain this call.
  11188. */
  11189. }, {
  11190. key: "fromPin",
  11191. value: function ()
  11192. /*: ParseQuery*/
  11193. {
  11194. return this.fromPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
  11195. }
  11196. /**
  11197. * Changes the source of this query to a specific group of pinned objects.
  11198. *
  11199. * @param {String} name The name of query source.
  11200. * @return {Parse.Query} Returns the query, so you can chain this call.
  11201. */
  11202. }, {
  11203. key: "fromPinWithName",
  11204. value: function (name
  11205. /*:: ?: string*/
  11206. )
  11207. /*: ParseQuery*/
  11208. {
  11209. var localDatastore = _CoreManager.default.getLocalDatastore();
  11210. if (localDatastore.checkIfEnabled()) {
  11211. this._queriesLocalDatastore = true;
  11212. this._localDatastorePinName = name;
  11213. }
  11214. return this;
  11215. }
  11216. }], [{
  11217. key: "fromJSON",
  11218. value: function (className
  11219. /*: string*/
  11220. , json
  11221. /*: QueryJSON*/
  11222. )
  11223. /*: ParseQuery*/
  11224. {
  11225. var query = new ParseQuery(className);
  11226. return query.withJSON(json);
  11227. }
  11228. }, {
  11229. key: "or",
  11230. value: function ()
  11231. /*: ParseQuery*/
  11232. {
  11233. for (var _len8 = arguments.length, queries = new Array(_len8), _key12 = 0; _key12 < _len8; _key12++) {
  11234. queries[_key12] = arguments[_key12];
  11235. }
  11236. var className = _getClassNameFromQueries(queries);
  11237. var query = new ParseQuery(className);
  11238. query._orQuery(queries);
  11239. return query;
  11240. }
  11241. /**
  11242. * Constructs a Parse.Query that is the AND of the passed in queries. For
  11243. * example:
  11244. * <pre>var compoundQuery = Parse.Query.and(query1, query2, query3);</pre>
  11245. *
  11246. * will create a compoundQuery that is an and of the query1, query2, and
  11247. * query3.
  11248. * @param {...Parse.Query} var_args The list of queries to AND.
  11249. * @static
  11250. * @return {Parse.Query} The query that is the AND of the passed in queries.
  11251. */
  11252. }, {
  11253. key: "and",
  11254. value: function ()
  11255. /*: ParseQuery*/
  11256. {
  11257. for (var _len9 = arguments.length, queries = new Array(_len9), _key13 = 0; _key13 < _len9; _key13++) {
  11258. queries[_key13] = arguments[_key13];
  11259. }
  11260. var className = _getClassNameFromQueries(queries);
  11261. var query = new ParseQuery(className);
  11262. query._andQuery(queries);
  11263. return query;
  11264. }
  11265. /**
  11266. * Constructs a Parse.Query that is the NOR of the passed in queries. For
  11267. * example:
  11268. * <pre>const compoundQuery = Parse.Query.nor(query1, query2, query3);</pre>
  11269. *
  11270. * will create a compoundQuery that is a nor of the query1, query2, and
  11271. * query3.
  11272. * @param {...Parse.Query} var_args The list of queries to NOR.
  11273. * @static
  11274. * @return {Parse.Query} The query that is the NOR of the passed in queries.
  11275. */
  11276. }, {
  11277. key: "nor",
  11278. value: function ()
  11279. /*: ParseQuery*/
  11280. {
  11281. for (var _len10 = arguments.length, queries = new Array(_len10), _key14 = 0; _key14 < _len10; _key14++) {
  11282. queries[_key14] = arguments[_key14];
  11283. }
  11284. var className = _getClassNameFromQueries(queries);
  11285. var query = new ParseQuery(className);
  11286. query._norQuery(queries);
  11287. return query;
  11288. }
  11289. }]);
  11290. return ParseQuery;
  11291. }();
  11292. var DefaultController = {
  11293. find: function (className
  11294. /*: string*/
  11295. , params
  11296. /*: QueryJSON*/
  11297. , options
  11298. /*: RequestOptions*/
  11299. )
  11300. /*: Promise<Array<ParseObject>>*/
  11301. {
  11302. var RESTController = _CoreManager.default.getRESTController();
  11303. return RESTController.request('GET', 'classes/' + className, params, options);
  11304. },
  11305. aggregate: function (className
  11306. /*: string*/
  11307. , params
  11308. /*: any*/
  11309. , options
  11310. /*: RequestOptions*/
  11311. )
  11312. /*: Promise<Array<mixed>>*/
  11313. {
  11314. var RESTController = _CoreManager.default.getRESTController();
  11315. return RESTController.request('GET', 'aggregate/' + className, params, options);
  11316. }
  11317. };
  11318. _CoreManager.default.setQueryController(DefaultController);
  11319. var _default = ParseQuery;
  11320. exports.default = _default;
  11321. },{"./CoreManager":4,"./LocalDatastoreUtils":12,"./OfflineQuery":14,"./ParseError":18,"./ParseGeoPoint":20,"./ParseObject":23,"./encode":44,"./promiseUtils":49,"@babel/runtime/helpers/asyncToGenerator":55,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75,"@babel/runtime/regenerator":78}],27:[function(_dereq_,module,exports){
  11322. "use strict";
  11323. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  11324. Object.defineProperty(exports, "__esModule", {
  11325. value: true
  11326. });
  11327. exports.default = void 0;
  11328. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  11329. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  11330. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  11331. var _ParseOp = _dereq_("./ParseOp");
  11332. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  11333. var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
  11334. /**
  11335. * Copyright (c) 2015-present, Parse, LLC.
  11336. * All rights reserved.
  11337. *
  11338. * This source code is licensed under the BSD-style license found in the
  11339. * LICENSE file in the root directory of this source tree. An additional grant
  11340. * of patent rights can be found in the PATENTS file in the same directory.
  11341. *
  11342. * @flow
  11343. */
  11344. /**
  11345. * Creates a new Relation for the given parent object and key. This
  11346. * constructor should rarely be used directly, but rather created by
  11347. * Parse.Object.relation.
  11348. *
  11349. * <p>
  11350. * A class that is used to access all of the children of a many-to-many
  11351. * relationship. Each instance of Parse.Relation is associated with a
  11352. * particular parent object and key.
  11353. * </p>
  11354. * @alias Parse.Relation
  11355. */
  11356. var ParseRelation =
  11357. /*#__PURE__*/
  11358. function () {
  11359. /**
  11360. * @param {Parse.Object} parent The parent of this relation.
  11361. * @param {String} key The key for this relation on the parent.
  11362. */
  11363. function ParseRelation(parent
  11364. /*: ?ParseObject*/
  11365. , key
  11366. /*: ?string*/
  11367. ) {
  11368. (0, _classCallCheck2.default)(this, ParseRelation);
  11369. (0, _defineProperty2.default)(this, "parent", void 0);
  11370. (0, _defineProperty2.default)(this, "key", void 0);
  11371. (0, _defineProperty2.default)(this, "targetClassName", void 0);
  11372. this.parent = parent;
  11373. this.key = key;
  11374. this.targetClassName = null;
  11375. }
  11376. /*
  11377. * Makes sure that this relation has the right parent and key.
  11378. */
  11379. (0, _createClass2.default)(ParseRelation, [{
  11380. key: "_ensureParentAndKey",
  11381. value: function (parent
  11382. /*: ParseObject*/
  11383. , key
  11384. /*: string*/
  11385. ) {
  11386. this.key = this.key || key;
  11387. if (this.key !== key) {
  11388. throw new Error('Internal Error. Relation retrieved from two different keys.');
  11389. }
  11390. if (this.parent) {
  11391. if (this.parent.className !== parent.className) {
  11392. throw new Error('Internal Error. Relation retrieved from two different Objects.');
  11393. }
  11394. if (this.parent.id) {
  11395. if (this.parent.id !== parent.id) {
  11396. throw new Error('Internal Error. Relation retrieved from two different Objects.');
  11397. }
  11398. } else if (parent.id) {
  11399. this.parent = parent;
  11400. }
  11401. } else {
  11402. this.parent = parent;
  11403. }
  11404. }
  11405. /**
  11406. * Adds a Parse.Object or an array of Parse.Objects to the relation.
  11407. * @param {} objects The item or items to add.
  11408. */
  11409. }, {
  11410. key: "add",
  11411. value: function (objects
  11412. /*: ParseObject | Array<ParseObject | string>*/
  11413. )
  11414. /*: ParseObject*/
  11415. {
  11416. if (!Array.isArray(objects)) {
  11417. objects = [objects];
  11418. }
  11419. var change = new _ParseOp.RelationOp(objects, []);
  11420. var parent = this.parent;
  11421. if (!parent) {
  11422. throw new Error('Cannot add to a Relation without a parent');
  11423. }
  11424. parent.set(this.key, change);
  11425. this.targetClassName = change._targetClassName;
  11426. return parent;
  11427. }
  11428. /**
  11429. * Removes a Parse.Object or an array of Parse.Objects from this relation.
  11430. * @param {} objects The item or items to remove.
  11431. */
  11432. }, {
  11433. key: "remove",
  11434. value: function (objects
  11435. /*: ParseObject | Array<ParseObject | string>*/
  11436. ) {
  11437. if (!Array.isArray(objects)) {
  11438. objects = [objects];
  11439. }
  11440. var change = new _ParseOp.RelationOp([], objects);
  11441. if (!this.parent) {
  11442. throw new Error('Cannot remove from a Relation without a parent');
  11443. }
  11444. this.parent.set(this.key, change);
  11445. this.targetClassName = change._targetClassName;
  11446. }
  11447. /**
  11448. * Returns a JSON version of the object suitable for saving to disk.
  11449. * @return {Object}
  11450. */
  11451. }, {
  11452. key: "toJSON",
  11453. value: function ()
  11454. /*: { __type: 'Relation', className: ?string }*/
  11455. {
  11456. return {
  11457. __type: 'Relation',
  11458. className: this.targetClassName
  11459. };
  11460. }
  11461. /**
  11462. * Returns a Parse.Query that is limited to objects in this
  11463. * relation.
  11464. * @return {Parse.Query}
  11465. */
  11466. }, {
  11467. key: "query",
  11468. value: function query()
  11469. /*: ParseQuery*/
  11470. {
  11471. var query;
  11472. var parent = this.parent;
  11473. if (!parent) {
  11474. throw new Error('Cannot construct a query for a Relation without a parent');
  11475. }
  11476. if (!this.targetClassName) {
  11477. query = new _ParseQuery.default(parent.className);
  11478. query._extraOptions.redirectClassNameForKey = this.key;
  11479. } else {
  11480. query = new _ParseQuery.default(this.targetClassName);
  11481. }
  11482. query._addCondition('$relatedTo', 'object', {
  11483. __type: 'Pointer',
  11484. className: parent.className,
  11485. objectId: parent.id
  11486. });
  11487. query._addCondition('$relatedTo', 'key', this.key);
  11488. return query;
  11489. }
  11490. }]);
  11491. return ParseRelation;
  11492. }();
  11493. var _default = ParseRelation;
  11494. exports.default = _default;
  11495. },{"./ParseObject":23,"./ParseOp":24,"./ParseQuery":26,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/interopRequireDefault":63}],28:[function(_dereq_,module,exports){
  11496. "use strict";
  11497. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  11498. Object.defineProperty(exports, "__esModule", {
  11499. value: true
  11500. });
  11501. exports.default = void 0;
  11502. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  11503. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  11504. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  11505. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  11506. var _get2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/get"));
  11507. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  11508. var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
  11509. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  11510. var _ParseObject2 = _interopRequireDefault(_dereq_("./ParseObject"));
  11511. /**
  11512. * Copyright (c) 2015-present, Parse, LLC.
  11513. * All rights reserved.
  11514. *
  11515. * This source code is licensed under the BSD-style license found in the
  11516. * LICENSE file in the root directory of this source tree. An additional grant
  11517. * of patent rights can be found in the PATENTS file in the same directory.
  11518. *
  11519. * @flow
  11520. */
  11521. /**
  11522. * Represents a Role on the Parse server. Roles represent groupings of
  11523. * Users for the purposes of granting permissions (e.g. specifying an ACL
  11524. * for an Object). Roles are specified by their sets of child users and
  11525. * child roles, all of which are granted any permissions that the parent
  11526. * role has.
  11527. *
  11528. * <p>Roles must have a name (which cannot be changed after creation of the
  11529. * role), and must specify an ACL.</p>
  11530. * @alias Parse.Role
  11531. * @extends Parse.Object
  11532. */
  11533. var ParseRole =
  11534. /*#__PURE__*/
  11535. function (_ParseObject) {
  11536. (0, _inherits2.default)(ParseRole, _ParseObject);
  11537. /**
  11538. * @param {String} name The name of the Role to create.
  11539. * @param {Parse.ACL} acl The ACL for this role. Roles must have an ACL.
  11540. * A Parse.Role is a local representation of a role persisted to the Parse
  11541. * cloud.
  11542. */
  11543. function ParseRole(name
  11544. /*: string*/
  11545. , acl
  11546. /*: ParseACL*/
  11547. ) {
  11548. var _this;
  11549. (0, _classCallCheck2.default)(this, ParseRole);
  11550. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(ParseRole).call(this, '_Role'));
  11551. if (typeof name === 'string' && acl instanceof _ParseACL.default) {
  11552. _this.setName(name);
  11553. _this.setACL(acl);
  11554. }
  11555. return _this;
  11556. }
  11557. /**
  11558. * Gets the name of the role. You can alternatively call role.get("name")
  11559. *
  11560. * @return {String} the name of the role.
  11561. */
  11562. (0, _createClass2.default)(ParseRole, [{
  11563. key: "getName",
  11564. value: function ()
  11565. /*: ?string*/
  11566. {
  11567. var name = this.get('name');
  11568. if (name == null || typeof name === 'string') {
  11569. return name;
  11570. }
  11571. return '';
  11572. }
  11573. /**
  11574. * Sets the name for a role. This value must be set before the role has
  11575. * been saved to the server, and cannot be set once the role has been
  11576. * saved.
  11577. *
  11578. * <p>
  11579. * A role's name can only contain alphanumeric characters, _, -, and
  11580. * spaces.
  11581. * </p>
  11582. *
  11583. * <p>This is equivalent to calling role.set("name", name)</p>
  11584. *
  11585. * @param {String} name The name of the role.
  11586. * @param {Object} options Standard options object with success and error
  11587. * callbacks.
  11588. */
  11589. }, {
  11590. key: "setName",
  11591. value: function (name
  11592. /*: string*/
  11593. , options
  11594. /*:: ?: mixed*/
  11595. )
  11596. /*: ParseObject | boolean*/
  11597. {
  11598. return this.set('name', name, options);
  11599. }
  11600. /**
  11601. * Gets the Parse.Relation for the Parse.Users that are direct
  11602. * children of this role. These users are granted any privileges that this
  11603. * role has been granted (e.g. read or write access through ACLs). You can
  11604. * add or remove users from the role through this relation.
  11605. *
  11606. * <p>This is equivalent to calling role.relation("users")</p>
  11607. *
  11608. * @return {Parse.Relation} the relation for the users belonging to this
  11609. * role.
  11610. */
  11611. }, {
  11612. key: "getUsers",
  11613. value: function ()
  11614. /*: ParseRelation*/
  11615. {
  11616. return this.relation('users');
  11617. }
  11618. /**
  11619. * Gets the Parse.Relation for the Parse.Roles that are direct
  11620. * children of this role. These roles' users are granted any privileges that
  11621. * this role has been granted (e.g. read or write access through ACLs). You
  11622. * can add or remove child roles from this role through this relation.
  11623. *
  11624. * <p>This is equivalent to calling role.relation("roles")</p>
  11625. *
  11626. * @return {Parse.Relation} the relation for the roles belonging to this
  11627. * role.
  11628. */
  11629. }, {
  11630. key: "getRoles",
  11631. value: function ()
  11632. /*: ParseRelation*/
  11633. {
  11634. return this.relation('roles');
  11635. }
  11636. }, {
  11637. key: "validate",
  11638. value: function (attrs
  11639. /*: AttributeMap*/
  11640. , options
  11641. /*:: ?: mixed*/
  11642. )
  11643. /*: ParseError | boolean*/
  11644. {
  11645. var isInvalid = (0, _get2.default)((0, _getPrototypeOf2.default)(ParseRole.prototype), "validate", this).call(this, attrs, options);
  11646. if (isInvalid) {
  11647. return isInvalid;
  11648. }
  11649. if ('name' in attrs && attrs.name !== this.getName()) {
  11650. var newName = attrs.name;
  11651. if (this.id && this.id !== attrs.objectId) {
  11652. // Check to see if the objectId being set matches this.id
  11653. // This happens during a fetch -- the id is set before calling fetch
  11654. // Let the name be set in this case
  11655. return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'A role\'s name can only be set before it has been saved.');
  11656. }
  11657. if (typeof newName !== 'string') {
  11658. return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'A role\'s name must be a String.');
  11659. }
  11660. if (!/^[0-9a-zA-Z\-_ ]+$/.test(newName)) {
  11661. return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'A role\'s name can be only contain alphanumeric characters, _, ' + '-, and spaces.');
  11662. }
  11663. }
  11664. return false;
  11665. }
  11666. }]);
  11667. return ParseRole;
  11668. }(_ParseObject2.default);
  11669. _ParseObject2.default.registerSubclass('_Role', ParseRole);
  11670. var _default = ParseRole;
  11671. exports.default = _default;
  11672. },{"./ParseACL":16,"./ParseError":18,"./ParseObject":23,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/get":60,"@babel/runtime/helpers/getPrototypeOf":61,"@babel/runtime/helpers/inherits":62,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/possibleConstructorReturn":70}],29:[function(_dereq_,module,exports){
  11673. "use strict";
  11674. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  11675. Object.defineProperty(exports, "__esModule", {
  11676. value: true
  11677. });
  11678. exports.default = void 0;
  11679. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  11680. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  11681. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  11682. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  11683. /**
  11684. * Copyright (c) 2015-present, Parse, LLC.
  11685. * All rights reserved.
  11686. *
  11687. * This source code is licensed under the BSD-style license found in the
  11688. * LICENSE file in the root directory of this source tree. An additional grant
  11689. * of patent rights can be found in the PATENTS file in the same directory.
  11690. *
  11691. * @flow
  11692. */
  11693. var FIELD_TYPES = ['String', 'Number', 'Boolean', 'Date', 'File', 'GeoPoint', 'Polygon', 'Array', 'Object', 'Pointer', 'Relation'];
  11694. /**
  11695. * A Parse.Schema object is for handling schema data from Parse.
  11696. * <p>All the schemas methods require MasterKey.
  11697. *
  11698. * <pre>
  11699. * const schema = new Parse.Schema('MyClass');
  11700. * schema.addString('field');
  11701. * schema.addIndex('index_name', {'field', 1});
  11702. * schema.save();
  11703. * </pre>
  11704. * </p>
  11705. * @alias Parse.Schema
  11706. */
  11707. var ParseSchema =
  11708. /*#__PURE__*/
  11709. function () {
  11710. /**
  11711. * @param {String} className Parse Class string.
  11712. */
  11713. function ParseSchema(className
  11714. /*: string*/
  11715. ) {
  11716. (0, _classCallCheck2.default)(this, ParseSchema);
  11717. (0, _defineProperty2.default)(this, "className", void 0);
  11718. (0, _defineProperty2.default)(this, "_fields", void 0);
  11719. (0, _defineProperty2.default)(this, "_indexes", void 0);
  11720. if (typeof className === 'string') {
  11721. if (className === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
  11722. this.className = '_User';
  11723. } else {
  11724. this.className = className;
  11725. }
  11726. }
  11727. this._fields = {};
  11728. this._indexes = {};
  11729. }
  11730. /**
  11731. * Static method to get all schemas
  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. (0, _createClass2.default)(ParseSchema, [{
  11745. key: "get",
  11746. /**
  11747. * Get the Schema from Parse
  11748. *
  11749. * @param {Object} options
  11750. * Valid options are:<ul>
  11751. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  11752. * be used for this request.
  11753. * <li>sessionToken: A valid session token, used for making a request on
  11754. * behalf of a specific user.
  11755. * </ul>
  11756. *
  11757. * @return {Promise} A promise that is resolved with the result when
  11758. * the query completes.
  11759. */
  11760. value: function (options
  11761. /*: FullOptions*/
  11762. ) {
  11763. this.assertClassName();
  11764. options = options || {};
  11765. var controller = _CoreManager.default.getSchemaController();
  11766. return controller.get(this.className, options).then(function (response) {
  11767. if (!response) {
  11768. throw new Error('Schema not found.');
  11769. }
  11770. return response;
  11771. });
  11772. }
  11773. /**
  11774. * Create a new Schema on Parse
  11775. *
  11776. * @param {Object} options
  11777. * Valid options are:<ul>
  11778. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  11779. * be used for this request.
  11780. * <li>sessionToken: A valid session token, used for making a request on
  11781. * behalf of a specific user.
  11782. * </ul>
  11783. *
  11784. * @return {Promise} A promise that is resolved with the result when
  11785. * the query completes.
  11786. */
  11787. }, {
  11788. key: "save",
  11789. value: function (options
  11790. /*: FullOptions*/
  11791. ) {
  11792. this.assertClassName();
  11793. options = options || {};
  11794. var controller = _CoreManager.default.getSchemaController();
  11795. var params = {
  11796. className: this.className,
  11797. fields: this._fields,
  11798. indexes: this._indexes
  11799. };
  11800. return controller.create(this.className, params, options).then(function (response) {
  11801. return response;
  11802. });
  11803. }
  11804. /**
  11805. * Update a Schema on Parse
  11806. *
  11807. * @param {Object} options
  11808. * Valid options are:<ul>
  11809. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  11810. * be used for this request.
  11811. * <li>sessionToken: A valid session token, used for making a request on
  11812. * behalf of a specific user.
  11813. * </ul>
  11814. *
  11815. * @return {Promise} A promise that is resolved with the result when
  11816. * the query completes.
  11817. */
  11818. }, {
  11819. key: "update",
  11820. value: function (options
  11821. /*: FullOptions*/
  11822. ) {
  11823. this.assertClassName();
  11824. options = options || {};
  11825. var controller = _CoreManager.default.getSchemaController();
  11826. var params = {
  11827. className: this.className,
  11828. fields: this._fields,
  11829. indexes: this._indexes
  11830. };
  11831. this._fields = {};
  11832. this._indexes = {};
  11833. return controller.update(this.className, params, options).then(function (response) {
  11834. return response;
  11835. });
  11836. }
  11837. /**
  11838. * Removing a Schema from Parse
  11839. * Can only be used on Schema without objects
  11840. *
  11841. * @param {Object} options
  11842. * Valid options are:<ul>
  11843. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  11844. * be used for this request.
  11845. * <li>sessionToken: A valid session token, used for making a request on
  11846. * behalf of a specific user.
  11847. * </ul>
  11848. *
  11849. * @return {Promise} A promise that is resolved with the result when
  11850. * the query completes.
  11851. */
  11852. }, {
  11853. key: "delete",
  11854. value: function (options
  11855. /*: FullOptions*/
  11856. ) {
  11857. this.assertClassName();
  11858. options = options || {};
  11859. var controller = _CoreManager.default.getSchemaController();
  11860. return controller.delete(this.className, options).then(function (response) {
  11861. return response;
  11862. });
  11863. }
  11864. /**
  11865. * Removes all objects from a Schema (class) in Parse.
  11866. * EXERCISE CAUTION, running this will delete all objects for this schema and cannot be reversed
  11867. * @return {Promise} A promise that is resolved with the result when
  11868. * the query completes.
  11869. */
  11870. }, {
  11871. key: "purge",
  11872. value: function () {
  11873. this.assertClassName();
  11874. var controller = _CoreManager.default.getSchemaController();
  11875. return controller.purge(this.className).then(function (response) {
  11876. return response;
  11877. });
  11878. }
  11879. /**
  11880. * Assert if ClassName has been filled
  11881. * @private
  11882. */
  11883. }, {
  11884. key: "assertClassName",
  11885. value: function () {
  11886. if (!this.className) {
  11887. throw new Error('You must set a Class Name before making any request.');
  11888. }
  11889. }
  11890. /**
  11891. * Adding a Field to Create / Update a Schema
  11892. *
  11893. * @param {String} name Name of the field that will be created on Parse
  11894. * @param {String} type TheCan be a (String|Number|Boolean|Date|Parse.File|Parse.GeoPoint|Array|Object|Pointer|Parse.Relation)
  11895. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11896. */
  11897. }, {
  11898. key: "addField",
  11899. value: function (name
  11900. /*: string*/
  11901. , type
  11902. /*: string*/
  11903. ) {
  11904. type = type || 'String';
  11905. if (!name) {
  11906. throw new Error('field name may not be null.');
  11907. }
  11908. if (FIELD_TYPES.indexOf(type) === -1) {
  11909. throw new Error("".concat(type, " is not a valid type."));
  11910. }
  11911. this._fields[name] = {
  11912. type: type
  11913. };
  11914. return this;
  11915. }
  11916. /**
  11917. * Adding an Index to Create / Update a Schema
  11918. *
  11919. * @param {String} name Name of the field that will be created on Parse
  11920. * @param {String} type Can be a (String|Number|Boolean|Date|Parse.File|Parse.GeoPoint|Array|Object|Pointer|Parse.Relation)
  11921. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11922. */
  11923. }, {
  11924. key: "addIndex",
  11925. value: function (name
  11926. /*: string*/
  11927. , index
  11928. /*: any*/
  11929. ) {
  11930. if (!name) {
  11931. throw new Error('index name may not be null.');
  11932. }
  11933. if (!index) {
  11934. throw new Error('index may not be null.');
  11935. }
  11936. this._indexes[name] = index;
  11937. return this;
  11938. }
  11939. /**
  11940. * Adding String Field
  11941. *
  11942. * @param {String} name Name of the field that will be created on Parse
  11943. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11944. */
  11945. }, {
  11946. key: "addString",
  11947. value: function (name
  11948. /*: string*/
  11949. ) {
  11950. return this.addField(name, 'String');
  11951. }
  11952. /**
  11953. * Adding Number Field
  11954. *
  11955. * @param {String} name Name of the field that will be created on Parse
  11956. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11957. */
  11958. }, {
  11959. key: "addNumber",
  11960. value: function (name
  11961. /*: string*/
  11962. ) {
  11963. return this.addField(name, 'Number');
  11964. }
  11965. /**
  11966. * Adding Boolean Field
  11967. *
  11968. * @param {String} name Name of the field that will be created on Parse
  11969. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11970. */
  11971. }, {
  11972. key: "addBoolean",
  11973. value: function (name
  11974. /*: string*/
  11975. ) {
  11976. return this.addField(name, 'Boolean');
  11977. }
  11978. /**
  11979. * Adding Date Field
  11980. *
  11981. * @param {String} name Name of the field that will be created on Parse
  11982. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11983. */
  11984. }, {
  11985. key: "addDate",
  11986. value: function (name
  11987. /*: string*/
  11988. ) {
  11989. return this.addField(name, 'Date');
  11990. }
  11991. /**
  11992. * Adding File Field
  11993. *
  11994. * @param {String} name Name of the field that will be created on Parse
  11995. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  11996. */
  11997. }, {
  11998. key: "addFile",
  11999. value: function (name
  12000. /*: string*/
  12001. ) {
  12002. return this.addField(name, 'File');
  12003. }
  12004. /**
  12005. * Adding GeoPoint Field
  12006. *
  12007. * @param {String} name Name of the field that will be created on Parse
  12008. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12009. */
  12010. }, {
  12011. key: "addGeoPoint",
  12012. value: function (name
  12013. /*: string*/
  12014. ) {
  12015. return this.addField(name, 'GeoPoint');
  12016. }
  12017. /**
  12018. * Adding Polygon Field
  12019. *
  12020. * @param {String} name Name of the field that will be created on Parse
  12021. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12022. */
  12023. }, {
  12024. key: "addPolygon",
  12025. value: function (name
  12026. /*: string*/
  12027. ) {
  12028. return this.addField(name, 'Polygon');
  12029. }
  12030. /**
  12031. * Adding Array Field
  12032. *
  12033. * @param {String} name Name of the field that will be created on Parse
  12034. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12035. */
  12036. }, {
  12037. key: "addArray",
  12038. value: function (name
  12039. /*: string*/
  12040. ) {
  12041. return this.addField(name, 'Array');
  12042. }
  12043. /**
  12044. * Adding Object Field
  12045. *
  12046. * @param {String} name Name of the field that will be created on Parse
  12047. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12048. */
  12049. }, {
  12050. key: "addObject",
  12051. value: function (name
  12052. /*: string*/
  12053. ) {
  12054. return this.addField(name, 'Object');
  12055. }
  12056. /**
  12057. * Adding Pointer Field
  12058. *
  12059. * @param {String} name Name of the field that will be created on Parse
  12060. * @param {String} targetClass Name of the target Pointer Class
  12061. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12062. */
  12063. }, {
  12064. key: "addPointer",
  12065. value: function (name
  12066. /*: string*/
  12067. , targetClass
  12068. /*: string*/
  12069. ) {
  12070. if (!name) {
  12071. throw new Error('field name may not be null.');
  12072. }
  12073. if (!targetClass) {
  12074. throw new Error('You need to set the targetClass of the Pointer.');
  12075. }
  12076. this._fields[name] = {
  12077. type: 'Pointer',
  12078. targetClass: targetClass
  12079. };
  12080. return this;
  12081. }
  12082. /**
  12083. * Adding Relation Field
  12084. *
  12085. * @param {String} name Name of the field that will be created on Parse
  12086. * @param {String} targetClass Name of the target Pointer Class
  12087. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12088. */
  12089. }, {
  12090. key: "addRelation",
  12091. value: function (name
  12092. /*: string*/
  12093. , targetClass
  12094. /*: string*/
  12095. ) {
  12096. if (!name) {
  12097. throw new Error('field name may not be null.');
  12098. }
  12099. if (!targetClass) {
  12100. throw new Error('You need to set the targetClass of the Relation.');
  12101. }
  12102. this._fields[name] = {
  12103. type: 'Relation',
  12104. targetClass: targetClass
  12105. };
  12106. return this;
  12107. }
  12108. /**
  12109. * Deleting a Field to Update on a Schema
  12110. *
  12111. * @param {String} name Name of the field that will be created on Parse
  12112. * @param {String} targetClass Name of the target Pointer Class
  12113. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12114. */
  12115. }, {
  12116. key: "deleteField",
  12117. value: function (name
  12118. /*: string*/
  12119. ) {
  12120. this._fields[name] = {
  12121. __op: 'Delete'
  12122. };
  12123. }
  12124. /**
  12125. * Deleting an Index to Update on a Schema
  12126. *
  12127. * @param {String} name Name of the field that will be created on Parse
  12128. * @param {String} targetClass Name of the target Pointer Class
  12129. * @return {Parse.Schema} Returns the schema, so you can chain this call.
  12130. */
  12131. }, {
  12132. key: "deleteIndex",
  12133. value: function (name
  12134. /*: string*/
  12135. ) {
  12136. this._indexes[name] = {
  12137. __op: 'Delete'
  12138. };
  12139. }
  12140. }], [{
  12141. key: "all",
  12142. value: function (options
  12143. /*: FullOptions*/
  12144. ) {
  12145. options = options || {};
  12146. var controller = _CoreManager.default.getSchemaController();
  12147. return controller.get('', options).then(function (response) {
  12148. if (response.results.length === 0) {
  12149. throw new Error('Schema not found.');
  12150. }
  12151. return response.results;
  12152. });
  12153. }
  12154. }]);
  12155. return ParseSchema;
  12156. }();
  12157. var DefaultController = {
  12158. send: function (className
  12159. /*: string*/
  12160. , method
  12161. /*: string*/
  12162. , params
  12163. /*: any*/
  12164. , options
  12165. /*: RequestOptions*/
  12166. )
  12167. /*: Promise*/
  12168. {
  12169. var RESTController = _CoreManager.default.getRESTController();
  12170. var requestOptions = {
  12171. useMasterKey: true
  12172. };
  12173. if (options.hasOwnProperty('sessionToken')) {
  12174. requestOptions.sessionToken = options.sessionToken;
  12175. }
  12176. return RESTController.request(method, "schemas/".concat(className), params, requestOptions);
  12177. },
  12178. get: function (className
  12179. /*: string*/
  12180. , options
  12181. /*: RequestOptions*/
  12182. )
  12183. /*: Promise*/
  12184. {
  12185. return this.send(className, 'GET', {}, options);
  12186. },
  12187. create: function (className
  12188. /*: string*/
  12189. , params
  12190. /*: any*/
  12191. , options
  12192. /*: RequestOptions*/
  12193. )
  12194. /*: Promise*/
  12195. {
  12196. return this.send(className, 'POST', params, options);
  12197. },
  12198. update: function (className
  12199. /*: string*/
  12200. , params
  12201. /*: any*/
  12202. , options
  12203. /*: RequestOptions*/
  12204. )
  12205. /*: Promise*/
  12206. {
  12207. return this.send(className, 'PUT', params, options);
  12208. },
  12209. delete: function (className
  12210. /*: string*/
  12211. , options
  12212. /*: RequestOptions*/
  12213. )
  12214. /*: Promise*/
  12215. {
  12216. return this.send(className, 'DELETE', {}, options);
  12217. },
  12218. purge: function (className
  12219. /*: string*/
  12220. )
  12221. /*: Promise*/
  12222. {
  12223. var RESTController = _CoreManager.default.getRESTController();
  12224. return RESTController.request('DELETE', "purge/".concat(className), {}, {
  12225. useMasterKey: true
  12226. });
  12227. }
  12228. };
  12229. _CoreManager.default.setSchemaController(DefaultController);
  12230. var _default = ParseSchema;
  12231. exports.default = _default;
  12232. },{"./CoreManager":4,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/interopRequireDefault":63}],30:[function(_dereq_,module,exports){
  12233. "use strict";
  12234. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  12235. Object.defineProperty(exports, "__esModule", {
  12236. value: true
  12237. });
  12238. exports.default = void 0;
  12239. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  12240. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  12241. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  12242. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  12243. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  12244. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  12245. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  12246. var _isRevocableSession = _interopRequireDefault(_dereq_("./isRevocableSession"));
  12247. var _ParseObject2 = _interopRequireDefault(_dereq_("./ParseObject"));
  12248. var _ParseUser = _interopRequireDefault(_dereq_("./ParseUser"));
  12249. /**
  12250. * Copyright (c) 2015-present, Parse, LLC.
  12251. * All rights reserved.
  12252. *
  12253. * This source code is licensed under the BSD-style license found in the
  12254. * LICENSE file in the root directory of this source tree. An additional grant
  12255. * of patent rights can be found in the PATENTS file in the same directory.
  12256. *
  12257. * @flow
  12258. */
  12259. /**
  12260. * <p>A Parse.Session object is a local representation of a revocable session.
  12261. * This class is a subclass of a Parse.Object, and retains the same
  12262. * functionality of a Parse.Object.</p>
  12263. * @alias Parse.Session
  12264. * @extends Parse.Object
  12265. */
  12266. var ParseSession =
  12267. /*#__PURE__*/
  12268. function (_ParseObject) {
  12269. (0, _inherits2.default)(ParseSession, _ParseObject);
  12270. /**
  12271. *
  12272. * @param {Object} attributes The initial set of data to store in the user.
  12273. */
  12274. function ParseSession(attributes
  12275. /*: ?AttributeMap*/
  12276. ) {
  12277. var _this;
  12278. (0, _classCallCheck2.default)(this, ParseSession);
  12279. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(ParseSession).call(this, '_Session'));
  12280. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  12281. if (!_this.set(attributes || {})) {
  12282. throw new Error('Can\'t create an invalid Session');
  12283. }
  12284. }
  12285. return _this;
  12286. }
  12287. /**
  12288. * Returns the session token string.
  12289. * @return {String}
  12290. */
  12291. (0, _createClass2.default)(ParseSession, [{
  12292. key: "getSessionToken",
  12293. value: function ()
  12294. /*: string*/
  12295. {
  12296. var token = this.get('sessionToken');
  12297. if (typeof token === 'string') {
  12298. return token;
  12299. }
  12300. return '';
  12301. }
  12302. }], [{
  12303. key: "readOnlyAttributes",
  12304. value: function () {
  12305. return ['createdWith', 'expiresAt', 'installationId', 'restricted', 'sessionToken', 'user'];
  12306. }
  12307. /**
  12308. * Retrieves the Session object for the currently logged in session.
  12309. * @static
  12310. * @return {Promise} A promise that is resolved with the Parse.Session
  12311. * object after it has been fetched. If there is no current user, the
  12312. * promise will be rejected.
  12313. */
  12314. }, {
  12315. key: "current",
  12316. value: function (options
  12317. /*: FullOptions*/
  12318. ) {
  12319. options = options || {};
  12320. var controller = _CoreManager.default.getSessionController();
  12321. var sessionOptions = {};
  12322. if (options.hasOwnProperty('useMasterKey')) {
  12323. sessionOptions.useMasterKey = options.useMasterKey;
  12324. }
  12325. return _ParseUser.default.currentAsync().then(function (user) {
  12326. if (!user) {
  12327. return Promise.reject('There is no current user.');
  12328. }
  12329. sessionOptions.sessionToken = user.getSessionToken();
  12330. return controller.getSession(sessionOptions);
  12331. });
  12332. }
  12333. /**
  12334. * Determines whether the current session token is revocable.
  12335. * This method is useful for migrating Express.js or Node.js web apps to
  12336. * use revocable sessions. If you are migrating an app that uses the Parse
  12337. * SDK in the browser only, please use Parse.User.enableRevocableSession()
  12338. * instead, so that sessions can be automatically upgraded.
  12339. * @static
  12340. * @return {Boolean}
  12341. */
  12342. }, {
  12343. key: "isCurrentSessionRevocable",
  12344. value: function ()
  12345. /*: boolean*/
  12346. {
  12347. var currentUser = _ParseUser.default.current();
  12348. if (currentUser) {
  12349. return (0, _isRevocableSession.default)(currentUser.getSessionToken() || '');
  12350. }
  12351. return false;
  12352. }
  12353. }]);
  12354. return ParseSession;
  12355. }(_ParseObject2.default);
  12356. _ParseObject2.default.registerSubclass('_Session', ParseSession);
  12357. var DefaultController = {
  12358. getSession: function (options
  12359. /*: RequestOptions*/
  12360. )
  12361. /*: Promise<ParseSession>*/
  12362. {
  12363. var RESTController = _CoreManager.default.getRESTController();
  12364. var session = new ParseSession();
  12365. return RESTController.request('GET', 'sessions/me', {}, options).then(function (sessionData) {
  12366. session._finishFetch(sessionData);
  12367. session._setExisted(true);
  12368. return session;
  12369. });
  12370. }
  12371. };
  12372. _CoreManager.default.setSessionController(DefaultController);
  12373. var _default = ParseSession;
  12374. exports.default = _default;
  12375. },{"./CoreManager":4,"./ParseObject":23,"./ParseUser":31,"./isRevocableSession":47,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/getPrototypeOf":61,"@babel/runtime/helpers/inherits":62,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/possibleConstructorReturn":70,"@babel/runtime/helpers/typeof":75}],31:[function(_dereq_,module,exports){
  12376. "use strict";
  12377. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  12378. Object.defineProperty(exports, "__esModule", {
  12379. value: true
  12380. });
  12381. exports.default = void 0;
  12382. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  12383. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  12384. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  12385. var _possibleConstructorReturn2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/possibleConstructorReturn"));
  12386. var _getPrototypeOf2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/getPrototypeOf"));
  12387. var _get2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/get"));
  12388. var _inherits2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/inherits"));
  12389. var _AnonymousUtils = _interopRequireDefault(_dereq_("./AnonymousUtils"));
  12390. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  12391. var _isRevocableSession = _interopRequireDefault(_dereq_("./isRevocableSession"));
  12392. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  12393. var _ParseObject2 = _interopRequireDefault(_dereq_("./ParseObject"));
  12394. var _ParseSession = _interopRequireDefault(_dereq_("./ParseSession"));
  12395. var _Storage = _interopRequireDefault(_dereq_("./Storage"));
  12396. /**
  12397. * Copyright (c) 2015-present, Parse, LLC.
  12398. * All rights reserved.
  12399. *
  12400. * This source code is licensed under the BSD-style license found in the
  12401. * LICENSE file in the root directory of this source tree. An additional grant
  12402. * of patent rights can be found in the PATENTS file in the same directory.
  12403. *
  12404. * @flow
  12405. */
  12406. var CURRENT_USER_KEY = 'currentUser';
  12407. var canUseCurrentUser = !_CoreManager.default.get('IS_NODE');
  12408. var currentUserCacheMatchesDisk = false;
  12409. var currentUserCache = null;
  12410. var authProviders = {};
  12411. /**
  12412. * <p>A Parse.User object is a local representation of a user persisted to the
  12413. * Parse cloud. This class is a subclass of a Parse.Object, and retains the
  12414. * same functionality of a Parse.Object, but also extends it with various
  12415. * user specific methods, like authentication, signing up, and validation of
  12416. * uniqueness.</p>
  12417. * @alias Parse.User
  12418. * @extends Parse.Object
  12419. */
  12420. var ParseUser =
  12421. /*#__PURE__*/
  12422. function (_ParseObject) {
  12423. (0, _inherits2.default)(ParseUser, _ParseObject);
  12424. /**
  12425. * @param {Object} attributes The initial set of data to store in the user.
  12426. */
  12427. function ParseUser(attributes
  12428. /*: ?AttributeMap*/
  12429. ) {
  12430. var _this;
  12431. (0, _classCallCheck2.default)(this, ParseUser);
  12432. _this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(ParseUser).call(this, '_User'));
  12433. if (attributes && (0, _typeof2.default)(attributes) === 'object') {
  12434. if (!_this.set(attributes || {})) {
  12435. throw new Error('Can\'t create an invalid Parse User');
  12436. }
  12437. }
  12438. return _this;
  12439. }
  12440. /**
  12441. * Request a revocable session token to replace the older style of token.
  12442. * @param {Object} options
  12443. * @return {Promise} A promise that is resolved when the replacement
  12444. * token has been fetched.
  12445. */
  12446. (0, _createClass2.default)(ParseUser, [{
  12447. key: "_upgradeToRevocableSession",
  12448. value: function (options
  12449. /*: RequestOptions*/
  12450. )
  12451. /*: Promise<void>*/
  12452. {
  12453. options = options || {};
  12454. var upgradeOptions = {};
  12455. if (options.hasOwnProperty('useMasterKey')) {
  12456. upgradeOptions.useMasterKey = options.useMasterKey;
  12457. }
  12458. var controller = _CoreManager.default.getUserController();
  12459. return controller.upgradeToRevocableSession(this, upgradeOptions);
  12460. }
  12461. /**
  12462. * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can
  12463. * call linkWith on the user (even if it doesn't exist yet on the server).
  12464. */
  12465. }, {
  12466. key: "_linkWith",
  12467. value: function (provider
  12468. /*: any*/
  12469. , options
  12470. /*: { authData?: AuthData }*/
  12471. )
  12472. /*: Promise<ParseUser>*/
  12473. {
  12474. var _this2 = this;
  12475. var saveOpts
  12476. /*:: ?: FullOptions*/
  12477. = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  12478. saveOpts.sessionToken = saveOpts.sessionToken || this.getSessionToken() || '';
  12479. var authType;
  12480. if (typeof provider === 'string') {
  12481. authType = provider;
  12482. if (authProviders[provider]) {
  12483. provider = authProviders[provider];
  12484. } else {
  12485. var authProvider = {
  12486. restoreAuthentication: function () {
  12487. return true;
  12488. },
  12489. getAuthType: function () {
  12490. return authType;
  12491. }
  12492. };
  12493. authProviders[authType] = authProvider;
  12494. provider = authProvider;
  12495. }
  12496. } else {
  12497. authType = provider.getAuthType();
  12498. }
  12499. if (options && options.hasOwnProperty('authData')) {
  12500. var authData = this.get('authData') || {};
  12501. if ((0, _typeof2.default)(authData) !== 'object') {
  12502. throw new Error('Invalid type: authData field should be an object');
  12503. }
  12504. authData[authType] = options.authData;
  12505. var controller = _CoreManager.default.getUserController();
  12506. return controller.linkWith(this, authData, saveOpts);
  12507. } else {
  12508. return new Promise(function (resolve, reject) {
  12509. provider.authenticate({
  12510. success: function (provider, result) {
  12511. var opts = {};
  12512. opts.authData = result;
  12513. _this2._linkWith(provider, opts, saveOpts).then(function () {
  12514. resolve(_this2);
  12515. }, function (error) {
  12516. reject(error);
  12517. });
  12518. },
  12519. error: function (provider, _error) {
  12520. reject(_error);
  12521. }
  12522. });
  12523. });
  12524. }
  12525. }
  12526. /**
  12527. * Synchronizes auth data for a provider (e.g. puts the access token in the
  12528. * right place to be used by the Facebook SDK).
  12529. */
  12530. }, {
  12531. key: "_synchronizeAuthData",
  12532. value: function (provider
  12533. /*: string*/
  12534. ) {
  12535. if (!this.isCurrent() || !provider) {
  12536. return;
  12537. }
  12538. var authType;
  12539. if (typeof provider === 'string') {
  12540. authType = provider;
  12541. provider = authProviders[authType];
  12542. } else {
  12543. authType = provider.getAuthType();
  12544. }
  12545. var authData = this.get('authData');
  12546. if (!provider || !authData || (0, _typeof2.default)(authData) !== 'object') {
  12547. return;
  12548. }
  12549. var success = provider.restoreAuthentication(authData[authType]);
  12550. if (!success) {
  12551. this._unlinkFrom(provider);
  12552. }
  12553. }
  12554. /**
  12555. * Synchronizes authData for all providers.
  12556. */
  12557. }, {
  12558. key: "_synchronizeAllAuthData",
  12559. value: function () {
  12560. var authData = this.get('authData');
  12561. if ((0, _typeof2.default)(authData) !== 'object') {
  12562. return;
  12563. }
  12564. for (var _key in authData) {
  12565. this._synchronizeAuthData(_key);
  12566. }
  12567. }
  12568. /**
  12569. * Removes null values from authData (which exist temporarily for
  12570. * unlinking)
  12571. */
  12572. }, {
  12573. key: "_cleanupAuthData",
  12574. value: function () {
  12575. if (!this.isCurrent()) {
  12576. return;
  12577. }
  12578. var authData = this.get('authData');
  12579. if ((0, _typeof2.default)(authData) !== 'object') {
  12580. return;
  12581. }
  12582. for (var _key2 in authData) {
  12583. if (!authData[_key2]) {
  12584. delete authData[_key2];
  12585. }
  12586. }
  12587. }
  12588. /**
  12589. * Unlinks a user from a service.
  12590. */
  12591. }, {
  12592. key: "_unlinkFrom",
  12593. value: function (provider
  12594. /*: any*/
  12595. , options
  12596. /*:: ?: FullOptions*/
  12597. ) {
  12598. var _this3 = this;
  12599. if (typeof provider === 'string') {
  12600. provider = authProviders[provider];
  12601. }
  12602. return this._linkWith(provider, {
  12603. authData: null
  12604. }, options).then(function () {
  12605. _this3._synchronizeAuthData(provider);
  12606. return Promise.resolve(_this3);
  12607. });
  12608. }
  12609. /**
  12610. * Checks whether a user is linked to a service.
  12611. */
  12612. }, {
  12613. key: "_isLinked",
  12614. value: function (provider
  12615. /*: any*/
  12616. )
  12617. /*: boolean*/
  12618. {
  12619. var authType;
  12620. if (typeof provider === 'string') {
  12621. authType = provider;
  12622. } else {
  12623. authType = provider.getAuthType();
  12624. }
  12625. var authData = this.get('authData') || {};
  12626. if ((0, _typeof2.default)(authData) !== 'object') {
  12627. return false;
  12628. }
  12629. return !!authData[authType];
  12630. }
  12631. /**
  12632. * Deauthenticates all providers.
  12633. */
  12634. }, {
  12635. key: "_logOutWithAll",
  12636. value: function () {
  12637. var authData = this.get('authData');
  12638. if ((0, _typeof2.default)(authData) !== 'object') {
  12639. return;
  12640. }
  12641. for (var _key3 in authData) {
  12642. this._logOutWith(_key3);
  12643. }
  12644. }
  12645. /**
  12646. * Deauthenticates a single provider (e.g. removing access tokens from the
  12647. * Facebook SDK).
  12648. */
  12649. }, {
  12650. key: "_logOutWith",
  12651. value: function (provider
  12652. /*: any*/
  12653. ) {
  12654. if (!this.isCurrent()) {
  12655. return;
  12656. }
  12657. if (typeof provider === 'string') {
  12658. provider = authProviders[provider];
  12659. }
  12660. if (provider && provider.deauthenticate) {
  12661. provider.deauthenticate();
  12662. }
  12663. }
  12664. /**
  12665. * Class instance method used to maintain specific keys when a fetch occurs.
  12666. * Used to ensure that the session token is not lost.
  12667. */
  12668. }, {
  12669. key: "_preserveFieldsOnFetch",
  12670. value: function ()
  12671. /*: AttributeMap*/
  12672. {
  12673. return {
  12674. sessionToken: this.get('sessionToken')
  12675. };
  12676. }
  12677. /**
  12678. * Returns true if <code>current</code> would return this user.
  12679. * @return {Boolean}
  12680. */
  12681. }, {
  12682. key: "isCurrent",
  12683. value: function ()
  12684. /*: boolean*/
  12685. {
  12686. var current = ParseUser.current();
  12687. return !!current && current.id === this.id;
  12688. }
  12689. /**
  12690. * Returns get("username").
  12691. * @return {String}
  12692. */
  12693. }, {
  12694. key: "getUsername",
  12695. value: function ()
  12696. /*: ?string*/
  12697. {
  12698. var username = this.get('username');
  12699. if (username == null || typeof username === 'string') {
  12700. return username;
  12701. }
  12702. return '';
  12703. }
  12704. /**
  12705. * Calls set("username", username, options) and returns the result.
  12706. * @param {String} username
  12707. * @param {Object} options
  12708. * @return {Boolean}
  12709. */
  12710. }, {
  12711. key: "setUsername",
  12712. value: function (username
  12713. /*: string*/
  12714. ) {
  12715. // Strip anonymity, even we do not support anonymous user in js SDK, we may
  12716. // encounter anonymous user created by android/iOS in cloud code.
  12717. var authData = this.get('authData');
  12718. if (authData && (0, _typeof2.default)(authData) === 'object' && authData.hasOwnProperty('anonymous')) {
  12719. // We need to set anonymous to null instead of deleting it in order to remove it from Parse.
  12720. authData.anonymous = null;
  12721. }
  12722. this.set('username', username);
  12723. }
  12724. /**
  12725. * Calls set("password", password, options) and returns the result.
  12726. * @param {String} password
  12727. * @param {Object} options
  12728. * @return {Boolean}
  12729. */
  12730. }, {
  12731. key: "setPassword",
  12732. value: function (password
  12733. /*: string*/
  12734. ) {
  12735. this.set('password', password);
  12736. }
  12737. /**
  12738. * Returns get("email").
  12739. * @return {String}
  12740. */
  12741. }, {
  12742. key: "getEmail",
  12743. value: function ()
  12744. /*: ?string*/
  12745. {
  12746. var email = this.get('email');
  12747. if (email == null || typeof email === 'string') {
  12748. return email;
  12749. }
  12750. return '';
  12751. }
  12752. /**
  12753. * Calls set("email", email) and returns the result.
  12754. * @param {String} email
  12755. * @return {Boolean}
  12756. */
  12757. }, {
  12758. key: "setEmail",
  12759. value: function (email
  12760. /*: string*/
  12761. ) {
  12762. return this.set('email', email);
  12763. }
  12764. /**
  12765. * Returns the session token for this user, if the user has been logged in,
  12766. * or if it is the result of a query with the master key. Otherwise, returns
  12767. * undefined.
  12768. * @return {String} the session token, or undefined
  12769. */
  12770. }, {
  12771. key: "getSessionToken",
  12772. value: function ()
  12773. /*: ?string*/
  12774. {
  12775. var token = this.get('sessionToken');
  12776. if (token == null || typeof token === 'string') {
  12777. return token;
  12778. }
  12779. return '';
  12780. }
  12781. /**
  12782. * Checks whether this user is the current user and has been authenticated.
  12783. * @return (Boolean) whether this user is the current user and is logged in.
  12784. */
  12785. }, {
  12786. key: "authenticated",
  12787. value: function ()
  12788. /*: boolean*/
  12789. {
  12790. var current = ParseUser.current();
  12791. return !!this.get('sessionToken') && !!current && current.id === this.id;
  12792. }
  12793. /**
  12794. * Signs up a new user. You should call this instead of save for
  12795. * new Parse.Users. This will create a new Parse.User on the server, and
  12796. * also persist the session on disk so that you can access the user using
  12797. * <code>current</code>.
  12798. *
  12799. * <p>A username and password must be set before calling signUp.</p>
  12800. *
  12801. * <p>Calls options.success or options.error on completion.</p>
  12802. *
  12803. * @param {Object} attrs Extra fields to set on the new user, or null.
  12804. * @param {Object} options
  12805. * @return {Promise} A promise that is fulfilled when the signup
  12806. * finishes.
  12807. */
  12808. }, {
  12809. key: "signUp",
  12810. value: function (attrs
  12811. /*: AttributeMap*/
  12812. , options
  12813. /*:: ?: FullOptions*/
  12814. )
  12815. /*: Promise<ParseUser>*/
  12816. {
  12817. options = options || {};
  12818. var signupOptions = {};
  12819. if (options.hasOwnProperty('useMasterKey')) {
  12820. signupOptions.useMasterKey = options.useMasterKey;
  12821. }
  12822. if (options.hasOwnProperty('installationId')) {
  12823. signupOptions.installationId = options.installationId;
  12824. }
  12825. var controller = _CoreManager.default.getUserController();
  12826. return controller.signUp(this, attrs, signupOptions);
  12827. }
  12828. /**
  12829. * Logs in a Parse.User. On success, this saves the session to disk,
  12830. * so you can retrieve the currently logged in user using
  12831. * <code>current</code>.
  12832. *
  12833. * <p>A username and password must be set before calling logIn.</p>
  12834. *
  12835. * <p>Calls options.success or options.error on completion.</p>
  12836. *
  12837. * @param {Object} options
  12838. * @return {Promise} A promise that is fulfilled with the user when
  12839. * the login is complete.
  12840. */
  12841. }, {
  12842. key: "logIn",
  12843. value: function (options
  12844. /*:: ?: FullOptions*/
  12845. )
  12846. /*: Promise<ParseUser>*/
  12847. {
  12848. options = options || {};
  12849. var loginOptions = {};
  12850. if (options.hasOwnProperty('useMasterKey')) {
  12851. loginOptions.useMasterKey = options.useMasterKey;
  12852. }
  12853. if (options.hasOwnProperty('installationId')) {
  12854. loginOptions.installationId = options.installationId;
  12855. }
  12856. var controller = _CoreManager.default.getUserController();
  12857. return controller.logIn(this, loginOptions);
  12858. }
  12859. /**
  12860. * Wrap the default save behavior with functionality to save to local
  12861. * storage if this is current user.
  12862. */
  12863. }, {
  12864. key: "save",
  12865. value: function ()
  12866. /*: Promise<ParseUser>*/
  12867. {
  12868. var _this4 = this;
  12869. for (var _len = arguments.length, args = new Array(_len), _key4 = 0; _key4 < _len; _key4++) {
  12870. args[_key4] = arguments[_key4];
  12871. }
  12872. return (0, _get2.default)((0, _getPrototypeOf2.default)(ParseUser.prototype), "save", this).apply(this, args).then(function () {
  12873. if (_this4.isCurrent()) {
  12874. return _CoreManager.default.getUserController().updateUserOnDisk(_this4);
  12875. }
  12876. return _this4;
  12877. });
  12878. }
  12879. /**
  12880. * Wrap the default destroy behavior with functionality that logs out
  12881. * the current user when it is destroyed
  12882. */
  12883. }, {
  12884. key: "destroy",
  12885. value: function ()
  12886. /*: Promise<ParseUser>*/
  12887. {
  12888. var _this5 = this;
  12889. for (var _len2 = arguments.length, args = new Array(_len2), _key5 = 0; _key5 < _len2; _key5++) {
  12890. args[_key5] = arguments[_key5];
  12891. }
  12892. return (0, _get2.default)((0, _getPrototypeOf2.default)(ParseUser.prototype), "destroy", this).apply(this, args).then(function () {
  12893. if (_this5.isCurrent()) {
  12894. return _CoreManager.default.getUserController().removeUserFromDisk();
  12895. }
  12896. return _this5;
  12897. });
  12898. }
  12899. /**
  12900. * Wrap the default fetch behavior with functionality to save to local
  12901. * storage if this is current user.
  12902. */
  12903. }, {
  12904. key: "fetch",
  12905. value: function ()
  12906. /*: Promise<ParseUser>*/
  12907. {
  12908. var _this6 = this;
  12909. for (var _len3 = arguments.length, args = new Array(_len3), _key6 = 0; _key6 < _len3; _key6++) {
  12910. args[_key6] = arguments[_key6];
  12911. }
  12912. return (0, _get2.default)((0, _getPrototypeOf2.default)(ParseUser.prototype), "fetch", this).apply(this, args).then(function () {
  12913. if (_this6.isCurrent()) {
  12914. return _CoreManager.default.getUserController().updateUserOnDisk(_this6);
  12915. }
  12916. return _this6;
  12917. });
  12918. }
  12919. /**
  12920. * Wrap the default fetchWithInclude behavior with functionality to save to local
  12921. * storage if this is current user.
  12922. */
  12923. }, {
  12924. key: "fetchWithInclude",
  12925. value: function ()
  12926. /*: Promise<ParseUser>*/
  12927. {
  12928. var _this7 = this;
  12929. for (var _len4 = arguments.length, args = new Array(_len4), _key7 = 0; _key7 < _len4; _key7++) {
  12930. args[_key7] = arguments[_key7];
  12931. }
  12932. return (0, _get2.default)((0, _getPrototypeOf2.default)(ParseUser.prototype), "fetchWithInclude", this).apply(this, args).then(function () {
  12933. if (_this7.isCurrent()) {
  12934. return _CoreManager.default.getUserController().updateUserOnDisk(_this7);
  12935. }
  12936. return _this7;
  12937. });
  12938. }
  12939. }], [{
  12940. key: "readOnlyAttributes",
  12941. value: function () {
  12942. return ['sessionToken'];
  12943. }
  12944. /**
  12945. * Adds functionality to the existing Parse.User class
  12946. * @param {Object} protoProps A set of properties to add to the prototype
  12947. * @param {Object} classProps A set of static properties to add to the class
  12948. * @static
  12949. * @return {Class} The newly extended Parse.User class
  12950. */
  12951. }, {
  12952. key: "extend",
  12953. value: function (protoProps
  12954. /*: {[prop: string]: any}*/
  12955. , classProps
  12956. /*: {[prop: string]: any}*/
  12957. ) {
  12958. if (protoProps) {
  12959. for (var _prop in protoProps) {
  12960. if (_prop !== 'className') {
  12961. Object.defineProperty(ParseUser.prototype, _prop, {
  12962. value: protoProps[_prop],
  12963. enumerable: false,
  12964. writable: true,
  12965. configurable: true
  12966. });
  12967. }
  12968. }
  12969. }
  12970. if (classProps) {
  12971. for (var _prop2 in classProps) {
  12972. if (_prop2 !== 'className') {
  12973. Object.defineProperty(ParseUser, _prop2, {
  12974. value: classProps[_prop2],
  12975. enumerable: false,
  12976. writable: true,
  12977. configurable: true
  12978. });
  12979. }
  12980. }
  12981. }
  12982. return ParseUser;
  12983. }
  12984. /**
  12985. * Retrieves the currently logged in ParseUser with a valid session,
  12986. * either from memory or localStorage, if necessary.
  12987. * @static
  12988. * @return {Parse.Object} The currently logged in Parse.User.
  12989. */
  12990. }, {
  12991. key: "current",
  12992. value: function ()
  12993. /*: ?ParseUser*/
  12994. {
  12995. if (!canUseCurrentUser) {
  12996. return null;
  12997. }
  12998. var controller = _CoreManager.default.getUserController();
  12999. return controller.currentUser();
  13000. }
  13001. /**
  13002. * Retrieves the currently logged in ParseUser from asynchronous Storage.
  13003. * @static
  13004. * @return {Promise} A Promise that is resolved with the currently
  13005. * logged in Parse User
  13006. */
  13007. }, {
  13008. key: "currentAsync",
  13009. value: function ()
  13010. /*: Promise<?ParseUser>*/
  13011. {
  13012. if (!canUseCurrentUser) {
  13013. return Promise.resolve(null);
  13014. }
  13015. var controller = _CoreManager.default.getUserController();
  13016. return controller.currentUserAsync();
  13017. }
  13018. /**
  13019. * Signs up a new user with a username (or email) and password.
  13020. * This will create a new Parse.User on the server, and also persist the
  13021. * session in localStorage so that you can access the user using
  13022. * {@link #current}.
  13023. *
  13024. * <p>Calls options.success or options.error on completion.</p>
  13025. *
  13026. * @param {String} username The username (or email) to sign up with.
  13027. * @param {String} password The password to sign up with.
  13028. * @param {Object} attrs Extra fields to set on the new user.
  13029. * @param {Object} options
  13030. * @static
  13031. * @return {Promise} A promise that is fulfilled with the user when
  13032. * the signup completes.
  13033. */
  13034. }, {
  13035. key: "signUp",
  13036. value: function (username
  13037. /*: string*/
  13038. , password
  13039. /*: string*/
  13040. , attrs
  13041. /*: AttributeMap*/
  13042. , options
  13043. /*:: ?: FullOptions*/
  13044. ) {
  13045. attrs = attrs || {};
  13046. attrs.username = username;
  13047. attrs.password = password;
  13048. var user = new this(attrs);
  13049. return user.signUp({}, options);
  13050. }
  13051. /**
  13052. * Logs in a user with a username (or email) and password. On success, this
  13053. * saves the session to disk, so you can retrieve the currently logged in
  13054. * user using <code>current</code>.
  13055. *
  13056. * <p>Calls options.success or options.error on completion.</p>
  13057. *
  13058. * @param {String} username The username (or email) to log in with.
  13059. * @param {String} password The password to log in with.
  13060. * @param {Object} options
  13061. * @static
  13062. * @return {Promise} A promise that is fulfilled with the user when
  13063. * the login completes.
  13064. */
  13065. }, {
  13066. key: "logIn",
  13067. value: function (username
  13068. /*: string*/
  13069. , password
  13070. /*: string*/
  13071. , options
  13072. /*:: ?: FullOptions*/
  13073. ) {
  13074. if (typeof username !== 'string') {
  13075. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Username must be a string.'));
  13076. } else if (typeof password !== 'string') {
  13077. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Password must be a string.'));
  13078. }
  13079. var user = new this();
  13080. user._finishFetch({
  13081. username: username,
  13082. password: password
  13083. });
  13084. return user.logIn(options);
  13085. }
  13086. /**
  13087. * Logs in a user with a session token. On success, this saves the session
  13088. * to disk, so you can retrieve the currently logged in user using
  13089. * <code>current</code>.
  13090. *
  13091. * <p>Calls options.success or options.error on completion.</p>
  13092. *
  13093. * @param {String} sessionToken The sessionToken to log in with.
  13094. * @param {Object} options
  13095. * @static
  13096. * @return {Promise} A promise that is fulfilled with the user when
  13097. * the login completes.
  13098. */
  13099. }, {
  13100. key: "become",
  13101. value: function (sessionToken
  13102. /*: string*/
  13103. , options
  13104. /*:: ?: RequestOptions*/
  13105. ) {
  13106. if (!canUseCurrentUser) {
  13107. throw new Error('It is not memory-safe to become a user in a server environment');
  13108. }
  13109. options = options || {};
  13110. var becomeOptions
  13111. /*: RequestOptions*/
  13112. = {
  13113. sessionToken: sessionToken
  13114. };
  13115. if (options.hasOwnProperty('useMasterKey')) {
  13116. becomeOptions.useMasterKey = options.useMasterKey;
  13117. }
  13118. var controller = _CoreManager.default.getUserController();
  13119. return controller.become(becomeOptions);
  13120. }
  13121. /**
  13122. * Retrieves a user with a session token.
  13123. *
  13124. * @param {String} sessionToken The sessionToken to get user with.
  13125. * @param {Object} options
  13126. * @static
  13127. * @return {Promise} A promise that is fulfilled with the user is fetched.
  13128. */
  13129. }, {
  13130. key: "me",
  13131. value: function (sessionToken
  13132. /*: string*/
  13133. ) {
  13134. var options
  13135. /*:: ?: RequestOptions*/
  13136. = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  13137. var controller = _CoreManager.default.getUserController();
  13138. var meOptions
  13139. /*: RequestOptions*/
  13140. = {
  13141. sessionToken: sessionToken
  13142. };
  13143. if (options.useMasterKey) {
  13144. meOptions.useMasterKey = options.useMasterKey;
  13145. }
  13146. return controller.me(meOptions);
  13147. }
  13148. /**
  13149. * Logs in a user with a session token. On success, this saves the session
  13150. * to disk, so you can retrieve the currently logged in user using
  13151. * <code>current</code>. If there is no session token the user will not logged in.
  13152. *
  13153. * @param {Object} userJSON The JSON map of the User's data
  13154. * @static
  13155. * @return {Promise} A promise that is fulfilled with the user when
  13156. * the login completes.
  13157. */
  13158. }, {
  13159. key: "hydrate",
  13160. value: function (userJSON
  13161. /*: AttributeMap*/
  13162. ) {
  13163. var controller = _CoreManager.default.getUserController();
  13164. return controller.hydrate(userJSON);
  13165. }
  13166. }, {
  13167. key: "logInWith",
  13168. value: function (provider
  13169. /*: any*/
  13170. , options
  13171. /*: { authData?: AuthData }*/
  13172. , saveOpts
  13173. /*:: ?: FullOptions*/
  13174. ) {
  13175. return ParseUser._logInWith(provider, options, saveOpts);
  13176. }
  13177. /**
  13178. * Logs out the currently logged in user session. This will remove the
  13179. * session from disk, log out of linked services, and future calls to
  13180. * <code>current</code> will return <code>null</code>.
  13181. *
  13182. * @param {Object} options
  13183. * @static
  13184. * @return {Promise} A promise that is resolved when the session is
  13185. * destroyed on the server.
  13186. */
  13187. }, {
  13188. key: "logOut",
  13189. value: function () {
  13190. var options
  13191. /*: RequestOptions*/
  13192. = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  13193. var controller = _CoreManager.default.getUserController();
  13194. return controller.logOut(options);
  13195. }
  13196. /**
  13197. * Requests a password reset email to be sent to the specified email address
  13198. * associated with the user account. This email allows the user to securely
  13199. * reset their password on the Parse site.
  13200. *
  13201. * <p>Calls options.success or options.error on completion.</p>
  13202. *
  13203. * @param {String} email The email address associated with the user that
  13204. * forgot their password.
  13205. * @param {Object} options
  13206. * @static
  13207. * @returns {Promise}
  13208. */
  13209. }, {
  13210. key: "requestPasswordReset",
  13211. value: function (email
  13212. /*: string*/
  13213. , options
  13214. /*:: ?: RequestOptions*/
  13215. ) {
  13216. options = options || {};
  13217. var requestOptions = {};
  13218. if (options.hasOwnProperty('useMasterKey')) {
  13219. requestOptions.useMasterKey = options.useMasterKey;
  13220. }
  13221. var controller = _CoreManager.default.getUserController();
  13222. return controller.requestPasswordReset(email, requestOptions);
  13223. }
  13224. /**
  13225. * Allow someone to define a custom User class without className
  13226. * being rewritten to _User. The default behavior is to rewrite
  13227. * User to _User for legacy reasons. This allows developers to
  13228. * override that behavior.
  13229. *
  13230. * @param {Boolean} isAllowed Whether or not to allow custom User class
  13231. * @static
  13232. */
  13233. }, {
  13234. key: "allowCustomUserClass",
  13235. value: function (isAllowed
  13236. /*: boolean*/
  13237. ) {
  13238. _CoreManager.default.set('PERFORM_USER_REWRITE', !isAllowed);
  13239. }
  13240. /**
  13241. * Allows a legacy application to start using revocable sessions. If the
  13242. * current session token is not revocable, a request will be made for a new,
  13243. * revocable session.
  13244. * It is not necessary to call this method from cloud code unless you are
  13245. * handling user signup or login from the server side. In a cloud code call,
  13246. * this function will not attempt to upgrade the current token.
  13247. * @param {Object} options
  13248. * @static
  13249. * @return {Promise} A promise that is resolved when the process has
  13250. * completed. If a replacement session token is requested, the promise
  13251. * will be resolved after a new token has been fetched.
  13252. */
  13253. }, {
  13254. key: "enableRevocableSession",
  13255. value: function (options
  13256. /*:: ?: RequestOptions*/
  13257. ) {
  13258. options = options || {};
  13259. _CoreManager.default.set('FORCE_REVOCABLE_SESSION', true);
  13260. if (canUseCurrentUser) {
  13261. var current = ParseUser.current();
  13262. if (current) {
  13263. return current._upgradeToRevocableSession(options);
  13264. }
  13265. }
  13266. return Promise.resolve();
  13267. }
  13268. /**
  13269. * Enables the use of become or the current user in a server
  13270. * environment. These features are disabled by default, since they depend on
  13271. * global objects that are not memory-safe for most servers.
  13272. * @static
  13273. */
  13274. }, {
  13275. key: "enableUnsafeCurrentUser",
  13276. value: function () {
  13277. canUseCurrentUser = true;
  13278. }
  13279. /**
  13280. * Disables the use of become or the current user in any environment.
  13281. * These features are disabled on servers by default, since they depend on
  13282. * global objects that are not memory-safe for most servers.
  13283. * @static
  13284. */
  13285. }, {
  13286. key: "disableUnsafeCurrentUser",
  13287. value: function () {
  13288. canUseCurrentUser = false;
  13289. }
  13290. }, {
  13291. key: "_registerAuthenticationProvider",
  13292. value: function (provider
  13293. /*: any*/
  13294. ) {
  13295. authProviders[provider.getAuthType()] = provider; // Synchronize the current user with the auth provider.
  13296. ParseUser.currentAsync().then(function (current) {
  13297. if (current) {
  13298. current._synchronizeAuthData(provider.getAuthType());
  13299. }
  13300. });
  13301. }
  13302. }, {
  13303. key: "_logInWith",
  13304. value: function (provider
  13305. /*: any*/
  13306. , options
  13307. /*: { authData?: AuthData }*/
  13308. , saveOpts
  13309. /*:: ?: FullOptions*/
  13310. ) {
  13311. var user = new ParseUser();
  13312. return user._linkWith(provider, options, saveOpts);
  13313. }
  13314. }, {
  13315. key: "_clearCache",
  13316. value: function () {
  13317. currentUserCache = null;
  13318. currentUserCacheMatchesDisk = false;
  13319. }
  13320. }, {
  13321. key: "_setCurrentUserCache",
  13322. value: function (user
  13323. /*: ParseUser*/
  13324. ) {
  13325. currentUserCache = user;
  13326. }
  13327. }]);
  13328. return ParseUser;
  13329. }(_ParseObject2.default);
  13330. _ParseObject2.default.registerSubclass('_User', ParseUser);
  13331. var DefaultController = {
  13332. updateUserOnDisk: function (user) {
  13333. var path = _Storage.default.generatePath(CURRENT_USER_KEY);
  13334. var json = user.toJSON();
  13335. json.className = '_User';
  13336. return _Storage.default.setItemAsync(path, JSON.stringify(json)).then(function () {
  13337. return user;
  13338. });
  13339. },
  13340. removeUserFromDisk: function () {
  13341. var path = _Storage.default.generatePath(CURRENT_USER_KEY);
  13342. currentUserCacheMatchesDisk = true;
  13343. currentUserCache = null;
  13344. return _Storage.default.removeItemAsync(path);
  13345. },
  13346. setCurrentUser: function (user) {
  13347. var currentUser = this.currentUser();
  13348. var promise = Promise.resolve();
  13349. if (currentUser && !user.equals(currentUser) && _AnonymousUtils.default.isLinked(currentUser)) {
  13350. promise = currentUser.destroy({
  13351. sessionToken: currentUser.getSessionToken()
  13352. });
  13353. }
  13354. currentUserCache = user;
  13355. user._cleanupAuthData();
  13356. user._synchronizeAllAuthData();
  13357. return promise.then(function () {
  13358. return DefaultController.updateUserOnDisk(user);
  13359. });
  13360. },
  13361. currentUser: function ()
  13362. /*: ?ParseUser*/
  13363. {
  13364. if (currentUserCache) {
  13365. return currentUserCache;
  13366. }
  13367. if (currentUserCacheMatchesDisk) {
  13368. return null;
  13369. }
  13370. if (_Storage.default.async()) {
  13371. throw new Error('Cannot call currentUser() when using a platform with an async ' + 'storage system. Call currentUserAsync() instead.');
  13372. }
  13373. var path = _Storage.default.generatePath(CURRENT_USER_KEY);
  13374. var userData = _Storage.default.getItem(path);
  13375. currentUserCacheMatchesDisk = true;
  13376. if (!userData) {
  13377. currentUserCache = null;
  13378. return null;
  13379. }
  13380. userData = JSON.parse(userData);
  13381. if (!userData.className) {
  13382. userData.className = '_User';
  13383. }
  13384. if (userData._id) {
  13385. if (userData.objectId !== userData._id) {
  13386. userData.objectId = userData._id;
  13387. }
  13388. delete userData._id;
  13389. }
  13390. if (userData._sessionToken) {
  13391. userData.sessionToken = userData._sessionToken;
  13392. delete userData._sessionToken;
  13393. }
  13394. var current = _ParseObject2.default.fromJSON(userData);
  13395. currentUserCache = current;
  13396. current._synchronizeAllAuthData();
  13397. return current;
  13398. },
  13399. currentUserAsync: function ()
  13400. /*: Promise<?ParseUser>*/
  13401. {
  13402. if (currentUserCache) {
  13403. return Promise.resolve(currentUserCache);
  13404. }
  13405. if (currentUserCacheMatchesDisk) {
  13406. return Promise.resolve(null);
  13407. }
  13408. var path = _Storage.default.generatePath(CURRENT_USER_KEY);
  13409. return _Storage.default.getItemAsync(path).then(function (userData) {
  13410. currentUserCacheMatchesDisk = true;
  13411. if (!userData) {
  13412. currentUserCache = null;
  13413. return Promise.resolve(null);
  13414. }
  13415. userData = JSON.parse(userData);
  13416. if (!userData.className) {
  13417. userData.className = '_User';
  13418. }
  13419. if (userData._id) {
  13420. if (userData.objectId !== userData._id) {
  13421. userData.objectId = userData._id;
  13422. }
  13423. delete userData._id;
  13424. }
  13425. if (userData._sessionToken) {
  13426. userData.sessionToken = userData._sessionToken;
  13427. delete userData._sessionToken;
  13428. }
  13429. var current = _ParseObject2.default.fromJSON(userData);
  13430. currentUserCache = current;
  13431. current._synchronizeAllAuthData();
  13432. return Promise.resolve(current);
  13433. });
  13434. },
  13435. signUp: function (user
  13436. /*: ParseUser*/
  13437. , attrs
  13438. /*: AttributeMap*/
  13439. , options
  13440. /*: RequestOptions*/
  13441. )
  13442. /*: Promise<ParseUser>*/
  13443. {
  13444. var username = attrs && attrs.username || user.get('username');
  13445. var password = attrs && attrs.password || user.get('password');
  13446. if (!username || !username.length) {
  13447. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Cannot sign up user with an empty name.'));
  13448. }
  13449. if (!password || !password.length) {
  13450. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Cannot sign up user with an empty password.'));
  13451. }
  13452. return user.save(attrs, options).then(function () {
  13453. // Clear the password field
  13454. user._finishFetch({
  13455. password: undefined
  13456. });
  13457. if (canUseCurrentUser) {
  13458. return DefaultController.setCurrentUser(user);
  13459. }
  13460. return user;
  13461. });
  13462. },
  13463. logIn: function (user
  13464. /*: ParseUser*/
  13465. , options
  13466. /*: RequestOptions*/
  13467. )
  13468. /*: Promise<ParseUser>*/
  13469. {
  13470. var RESTController = _CoreManager.default.getRESTController();
  13471. var stateController = _CoreManager.default.getObjectStateController();
  13472. var auth = {
  13473. username: user.get('username'),
  13474. password: user.get('password')
  13475. };
  13476. return RESTController.request('GET', 'login', auth, options).then(function (response) {
  13477. user._migrateId(response.objectId);
  13478. user._setExisted(true);
  13479. stateController.setPendingOp(user._getStateIdentifier(), 'username', undefined);
  13480. stateController.setPendingOp(user._getStateIdentifier(), 'password', undefined);
  13481. response.password = undefined;
  13482. user._finishFetch(response);
  13483. if (!canUseCurrentUser) {
  13484. // We can't set the current user, so just return the one we logged in
  13485. return Promise.resolve(user);
  13486. }
  13487. return DefaultController.setCurrentUser(user);
  13488. });
  13489. },
  13490. become: function (options
  13491. /*: RequestOptions*/
  13492. )
  13493. /*: Promise<ParseUser>*/
  13494. {
  13495. var user = new ParseUser();
  13496. var RESTController = _CoreManager.default.getRESTController();
  13497. return RESTController.request('GET', 'users/me', {}, options).then(function (response) {
  13498. user._finishFetch(response);
  13499. user._setExisted(true);
  13500. return DefaultController.setCurrentUser(user);
  13501. });
  13502. },
  13503. hydrate: function (userJSON
  13504. /*: AttributeMap*/
  13505. )
  13506. /*: Promise<ParseUser>*/
  13507. {
  13508. var user = new ParseUser();
  13509. user._finishFetch(userJSON);
  13510. user._setExisted(true);
  13511. if (userJSON.sessionToken && canUseCurrentUser) {
  13512. return DefaultController.setCurrentUser(user);
  13513. } else {
  13514. return Promise.resolve(user);
  13515. }
  13516. },
  13517. me: function (options
  13518. /*: RequestOptions*/
  13519. )
  13520. /*: Promise<ParseUser>*/
  13521. {
  13522. var RESTController = _CoreManager.default.getRESTController();
  13523. return RESTController.request('GET', 'users/me', {}, options).then(function (response) {
  13524. var user = new ParseUser();
  13525. user._finishFetch(response);
  13526. user._setExisted(true);
  13527. return user;
  13528. });
  13529. },
  13530. logOut: function (options
  13531. /*: RequestOptions*/
  13532. )
  13533. /*: Promise<ParseUser>*/
  13534. {
  13535. var RESTController = _CoreManager.default.getRESTController();
  13536. if (options.sessionToken) {
  13537. return RESTController.request('POST', 'logout', {}, options);
  13538. }
  13539. return DefaultController.currentUserAsync().then(function (currentUser) {
  13540. var path = _Storage.default.generatePath(CURRENT_USER_KEY);
  13541. var promise = _Storage.default.removeItemAsync(path);
  13542. if (currentUser !== null) {
  13543. var isAnonymous = _AnonymousUtils.default.isLinked(currentUser);
  13544. var currentSession = currentUser.getSessionToken();
  13545. if (currentSession && (0, _isRevocableSession.default)(currentSession)) {
  13546. promise = promise.then(function () {
  13547. if (isAnonymous) {
  13548. return currentUser.destroy({
  13549. sessionToken: currentSession
  13550. });
  13551. }
  13552. }).then(function () {
  13553. return RESTController.request('POST', 'logout', {}, {
  13554. sessionToken: currentSession
  13555. });
  13556. });
  13557. }
  13558. currentUser._logOutWithAll();
  13559. currentUser._finishFetch({
  13560. sessionToken: undefined
  13561. });
  13562. }
  13563. currentUserCacheMatchesDisk = true;
  13564. currentUserCache = null;
  13565. return promise;
  13566. });
  13567. },
  13568. requestPasswordReset: function (email
  13569. /*: string*/
  13570. , options
  13571. /*: RequestOptions*/
  13572. ) {
  13573. var RESTController = _CoreManager.default.getRESTController();
  13574. return RESTController.request('POST', 'requestPasswordReset', {
  13575. email: email
  13576. }, options);
  13577. },
  13578. upgradeToRevocableSession: function (user
  13579. /*: ParseUser*/
  13580. , options
  13581. /*: RequestOptions*/
  13582. ) {
  13583. var token = user.getSessionToken();
  13584. if (!token) {
  13585. return Promise.reject(new _ParseError.default(_ParseError.default.SESSION_MISSING, 'Cannot upgrade a user with no session token'));
  13586. }
  13587. options.sessionToken = token;
  13588. var RESTController = _CoreManager.default.getRESTController();
  13589. return RESTController.request('POST', 'upgradeToRevocableSession', {}, options).then(function (result) {
  13590. var session = new _ParseSession.default();
  13591. session._finishFetch(result);
  13592. user._finishFetch({
  13593. sessionToken: session.getSessionToken()
  13594. });
  13595. if (user.isCurrent()) {
  13596. return DefaultController.setCurrentUser(user);
  13597. }
  13598. return Promise.resolve(user);
  13599. });
  13600. },
  13601. linkWith: function (user
  13602. /*: ParseUser*/
  13603. , authData
  13604. /*: AuthData*/
  13605. , options
  13606. /*: FullOptions*/
  13607. ) {
  13608. return user.save({
  13609. authData: authData
  13610. }, options).then(function () {
  13611. if (canUseCurrentUser) {
  13612. return DefaultController.setCurrentUser(user);
  13613. }
  13614. return user;
  13615. });
  13616. }
  13617. };
  13618. _CoreManager.default.setUserController(DefaultController);
  13619. var _default = ParseUser;
  13620. exports.default = _default;
  13621. },{"./AnonymousUtils":2,"./CoreManager":4,"./ParseError":18,"./ParseObject":23,"./ParseSession":30,"./Storage":36,"./isRevocableSession":47,"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/get":60,"@babel/runtime/helpers/getPrototypeOf":61,"@babel/runtime/helpers/inherits":62,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/possibleConstructorReturn":70,"@babel/runtime/helpers/typeof":75}],32:[function(_dereq_,module,exports){
  13622. "use strict";
  13623. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  13624. Object.defineProperty(exports, "__esModule", {
  13625. value: true
  13626. });
  13627. exports.send = send;
  13628. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  13629. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  13630. var _ParseQuery = _interopRequireDefault(_dereq_("./ParseQuery"));
  13631. /**
  13632. * Copyright (c) 2015-present, Parse, LLC.
  13633. * All rights reserved.
  13634. *
  13635. * This source code is licensed under the BSD-style license found in the
  13636. * LICENSE file in the root directory of this source tree. An additional grant
  13637. * of patent rights can be found in the PATENTS file in the same directory.
  13638. *
  13639. * @flow
  13640. */
  13641. /**
  13642. * Contains functions to deal with Push in Parse.
  13643. * @class Parse.Push
  13644. * @static
  13645. * @hideconstructor
  13646. */
  13647. /**
  13648. * Sends a push notification.
  13649. * @method send
  13650. * @name Parse.Push.send
  13651. * @param {Object} data - The data of the push notification. Valid fields
  13652. * are:
  13653. * <ol>
  13654. * <li>channels - An Array of channels to push to.</li>
  13655. * <li>push_time - A Date object for when to send the push.</li>
  13656. * <li>expiration_time - A Date object for when to expire
  13657. * the push.</li>
  13658. * <li>expiration_interval - The seconds from now to expire the push.</li>
  13659. * <li>where - A Parse.Query over Parse.Installation that is used to match
  13660. * a set of installations to push to.</li>
  13661. * <li>data - The data to send as part of the push</li>
  13662. * <ol>
  13663. * @param {Object} options An object that has an optional success function,
  13664. * that takes no arguments and will be called on a successful push, and
  13665. * an error function that takes a Parse.Error and will be called if the push
  13666. * failed.
  13667. * @return {Promise} A promise that is fulfilled when the push request
  13668. * completes.
  13669. */
  13670. function send(data
  13671. /*: PushData*/
  13672. , options
  13673. /*:: ?: { useMasterKey?: boolean, success?: any, error?: any }*/
  13674. )
  13675. /*: Promise*/
  13676. {
  13677. options = options || {};
  13678. if (data.where && data.where instanceof _ParseQuery.default) {
  13679. data.where = data.where.toJSON().where;
  13680. }
  13681. if (data.push_time && (0, _typeof2.default)(data.push_time) === 'object') {
  13682. data.push_time = data.push_time.toJSON();
  13683. }
  13684. if (data.expiration_time && (0, _typeof2.default)(data.expiration_time) === 'object') {
  13685. data.expiration_time = data.expiration_time.toJSON();
  13686. }
  13687. if (data.expiration_time && data.expiration_interval) {
  13688. throw new Error('expiration_time and expiration_interval cannot both be set.');
  13689. }
  13690. return _CoreManager.default.getPushController().send(data, {
  13691. useMasterKey: options.useMasterKey
  13692. });
  13693. }
  13694. var DefaultController = {
  13695. send: function (data
  13696. /*: PushData*/
  13697. , options
  13698. /*: RequestOptions*/
  13699. ) {
  13700. var RESTController = _CoreManager.default.getRESTController();
  13701. var request = RESTController.request('POST', 'push', data, {
  13702. useMasterKey: !!options.useMasterKey
  13703. });
  13704. return request;
  13705. }
  13706. };
  13707. _CoreManager.default.setPushController(DefaultController);
  13708. },{"./CoreManager":4,"./ParseQuery":26,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],33:[function(_dereq_,module,exports){
  13709. (function (process){
  13710. "use strict";
  13711. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  13712. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  13713. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  13714. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  13715. var _ParseError = _interopRequireDefault(_dereq_("./ParseError"));
  13716. function ownKeys(object, enumerableOnly) {
  13717. var keys = Object.keys(object);
  13718. if (Object.getOwnPropertySymbols) {
  13719. var symbols = Object.getOwnPropertySymbols(object);
  13720. if (enumerableOnly) symbols = symbols.filter(function (sym) {
  13721. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  13722. });
  13723. keys.push.apply(keys, symbols);
  13724. }
  13725. return keys;
  13726. }
  13727. function _objectSpread(target) {
  13728. for (var i = 1; i < arguments.length; i++) {
  13729. var source = arguments[i] != null ? arguments[i] : {};
  13730. if (i % 2) {
  13731. ownKeys(source, true).forEach(function (key) {
  13732. (0, _defineProperty2.default)(target, key, source[key]);
  13733. });
  13734. } else if (Object.getOwnPropertyDescriptors) {
  13735. Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  13736. } else {
  13737. ownKeys(source).forEach(function (key) {
  13738. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  13739. });
  13740. }
  13741. }
  13742. return target;
  13743. }
  13744. var XHR = null;
  13745. if (typeof XMLHttpRequest !== 'undefined') {
  13746. XHR = XMLHttpRequest;
  13747. }
  13748. XHR = _dereq_('./Xhr.weapp');
  13749. var useXDomainRequest = false;
  13750. if (typeof XDomainRequest !== 'undefined' && !('withCredentials' in new XMLHttpRequest())) {
  13751. useXDomainRequest = true;
  13752. }
  13753. function ajaxIE9(method
  13754. /*: string*/
  13755. , url
  13756. /*: string*/
  13757. , data
  13758. /*: any*/
  13759. , options
  13760. /*:: ?: FullOptions*/
  13761. ) {
  13762. return new Promise(function (resolve, reject) {
  13763. var xdr = new XDomainRequest();
  13764. xdr.onload = function () {
  13765. var response;
  13766. try {
  13767. response = JSON.parse(xdr.responseText);
  13768. } catch (e) {
  13769. reject(e);
  13770. }
  13771. if (response) {
  13772. resolve({
  13773. response: response
  13774. });
  13775. }
  13776. };
  13777. xdr.onerror = xdr.ontimeout = function () {
  13778. // Let's fake a real error message.
  13779. var fakeResponse = {
  13780. responseText: JSON.stringify({
  13781. code: _ParseError.default.X_DOMAIN_REQUEST,
  13782. error: 'IE\'s XDomainRequest does not supply error info.'
  13783. })
  13784. };
  13785. reject(fakeResponse);
  13786. };
  13787. xdr.onprogress = function () {
  13788. if (options && typeof options.progress === 'function') {
  13789. options.progress(xdr.responseText);
  13790. }
  13791. };
  13792. xdr.open(method, url);
  13793. xdr.send(data);
  13794. });
  13795. }
  13796. var RESTController = {
  13797. ajax: function (method
  13798. /*: string*/
  13799. , url
  13800. /*: string*/
  13801. , data
  13802. /*: any*/
  13803. , headers
  13804. /*:: ?: any*/
  13805. , options
  13806. /*:: ?: FullOptions*/
  13807. ) {
  13808. if (useXDomainRequest) {
  13809. return ajaxIE9(method, url, data, headers, options);
  13810. }
  13811. var res, rej;
  13812. var promise = new Promise(function (resolve, reject) {
  13813. res = resolve;
  13814. rej = reject;
  13815. });
  13816. promise.resolve = res;
  13817. promise.reject = rej;
  13818. var attempts = 0;
  13819. var dispatch = function dispatch() {
  13820. if (XHR == null) {
  13821. throw new Error('Cannot make a request: No definition of XMLHttpRequest was found.');
  13822. }
  13823. var handled = false;
  13824. var xhr = new XHR();
  13825. xhr.onreadystatechange = function () {
  13826. if (xhr.readyState !== 4 || handled) {
  13827. return;
  13828. }
  13829. handled = true;
  13830. if (xhr.status >= 200 && xhr.status < 300) {
  13831. var response;
  13832. try {
  13833. response = JSON.parse(xhr.responseText);
  13834. if (typeof xhr.getResponseHeader === 'function') {
  13835. if ((xhr.getAllResponseHeaders() || '').includes('x-parse-job-status-id: ')) {
  13836. response = xhr.getResponseHeader('x-parse-job-status-id');
  13837. }
  13838. }
  13839. } catch (e) {
  13840. promise.reject(e.toString());
  13841. }
  13842. if (response) {
  13843. promise.resolve({
  13844. response: response,
  13845. status: xhr.status,
  13846. xhr: xhr
  13847. });
  13848. }
  13849. } else if (xhr.status >= 500 || xhr.status === 0) {
  13850. // retry on 5XX or node-xmlhttprequest error
  13851. if (++attempts < _CoreManager.default.get('REQUEST_ATTEMPT_LIMIT')) {
  13852. // Exponentially-growing random delay
  13853. var delay = Math.round(Math.random() * 125 * Math.pow(2, attempts));
  13854. setTimeout(dispatch, delay);
  13855. } else if (xhr.status === 0) {
  13856. promise.reject('Unable to connect to the Parse API');
  13857. } else {
  13858. // After the retry limit is reached, fail
  13859. promise.reject(xhr);
  13860. }
  13861. } else {
  13862. promise.reject(xhr);
  13863. }
  13864. };
  13865. headers = headers || {};
  13866. if (typeof headers['Content-Type'] !== 'string') {
  13867. headers['Content-Type'] = 'text/plain'; // Avoid pre-flight
  13868. }
  13869. if (_CoreManager.default.get('IS_NODE')) {
  13870. headers['User-Agent'] = 'Parse/' + _CoreManager.default.get('VERSION') + ' (NodeJS ' + process.versions.node + ')';
  13871. }
  13872. if (_CoreManager.default.get('SERVER_AUTH_TYPE') && _CoreManager.default.get('SERVER_AUTH_TOKEN')) {
  13873. headers['Authorization'] = _CoreManager.default.get('SERVER_AUTH_TYPE') + ' ' + _CoreManager.default.get('SERVER_AUTH_TOKEN');
  13874. }
  13875. if (options && typeof options.progress === 'function') {
  13876. if (xhr.upload) {
  13877. xhr.upload.addEventListener('progress', function (oEvent) {
  13878. if (oEvent.lengthComputable) {
  13879. options.progress(oEvent.loaded / oEvent.total);
  13880. } else {
  13881. options.progress(null);
  13882. }
  13883. });
  13884. } else if (xhr.addEventListener) {
  13885. xhr.addEventListener('progress', function (oEvent) {
  13886. if (oEvent.lengthComputable) {
  13887. options.progress(oEvent.loaded / oEvent.total);
  13888. } else {
  13889. options.progress(null);
  13890. }
  13891. });
  13892. }
  13893. }
  13894. xhr.open(method, url, true);
  13895. for (var h in headers) {
  13896. xhr.setRequestHeader(h, headers[h]);
  13897. }
  13898. xhr.send(data);
  13899. };
  13900. dispatch();
  13901. return promise;
  13902. },
  13903. request: function (method
  13904. /*: string*/
  13905. , path
  13906. /*: string*/
  13907. , data
  13908. /*: mixed*/
  13909. , options
  13910. /*:: ?: RequestOptions*/
  13911. ) {
  13912. options = options || {};
  13913. var url = _CoreManager.default.get('SERVER_URL');
  13914. if (url[url.length - 1] !== '/') {
  13915. url += '/';
  13916. }
  13917. url += path;
  13918. var payload = {};
  13919. if (data && (0, _typeof2.default)(data) === 'object') {
  13920. for (var k in data) {
  13921. payload[k] = data[k];
  13922. }
  13923. }
  13924. if (method !== 'POST') {
  13925. payload._method = method;
  13926. method = 'POST';
  13927. }
  13928. payload._ApplicationId = _CoreManager.default.get('APPLICATION_ID');
  13929. var jsKey = _CoreManager.default.get('JAVASCRIPT_KEY');
  13930. if (jsKey) {
  13931. payload._JavaScriptKey = jsKey;
  13932. }
  13933. payload._ClientVersion = _CoreManager.default.get('VERSION');
  13934. var useMasterKey = options.useMasterKey;
  13935. if (typeof useMasterKey === 'undefined') {
  13936. useMasterKey = _CoreManager.default.get('USE_MASTER_KEY');
  13937. }
  13938. if (useMasterKey) {
  13939. if (_CoreManager.default.get('MASTER_KEY')) {
  13940. delete payload._JavaScriptKey;
  13941. payload._MasterKey = _CoreManager.default.get('MASTER_KEY');
  13942. } else {
  13943. throw new Error('Cannot use the Master Key, it has not been provided.');
  13944. }
  13945. }
  13946. if (_CoreManager.default.get('FORCE_REVOCABLE_SESSION')) {
  13947. payload._RevocableSession = '1';
  13948. }
  13949. var installationId = options.installationId;
  13950. var installationIdPromise;
  13951. if (installationId && typeof installationId === 'string') {
  13952. installationIdPromise = Promise.resolve(installationId);
  13953. } else {
  13954. var installationController = _CoreManager.default.getInstallationController();
  13955. installationIdPromise = installationController.currentInstallationId();
  13956. }
  13957. return installationIdPromise.then(function (iid) {
  13958. payload._InstallationId = iid;
  13959. var userController = _CoreManager.default.getUserController();
  13960. if (options && typeof options.sessionToken === 'string') {
  13961. return Promise.resolve(options.sessionToken);
  13962. } else if (userController) {
  13963. return userController.currentUserAsync().then(function (user) {
  13964. if (user) {
  13965. return Promise.resolve(user.getSessionToken());
  13966. }
  13967. return Promise.resolve(null);
  13968. });
  13969. }
  13970. return Promise.resolve(null);
  13971. }).then(function (token) {
  13972. if (token) {
  13973. payload._SessionToken = token;
  13974. }
  13975. var payloadString = JSON.stringify(payload);
  13976. return RESTController.ajax(method, url, payloadString, {}, options).then(function (_ref) {
  13977. var response = _ref.response,
  13978. status = _ref.status;
  13979. if (options.returnStatus) {
  13980. return _objectSpread({}, response, {
  13981. _status: status
  13982. });
  13983. } else {
  13984. return response;
  13985. }
  13986. });
  13987. }).catch(function (response
  13988. /*: { responseText: string }*/
  13989. ) {
  13990. // Transform the error into an instance of ParseError by trying to parse
  13991. // the error string as JSON
  13992. var error;
  13993. if (response && response.responseText) {
  13994. try {
  13995. var errorJSON = JSON.parse(response.responseText);
  13996. error = new _ParseError.default(errorJSON.code, errorJSON.error);
  13997. } catch (e) {
  13998. // If we fail to parse the error text, that's okay.
  13999. error = new _ParseError.default(_ParseError.default.INVALID_JSON, 'Received an error with invalid JSON from Parse: ' + response.responseText);
  14000. }
  14001. } else {
  14002. error = new _ParseError.default(_ParseError.default.CONNECTION_FAILED, 'XMLHttpRequest failed: ' + JSON.stringify(response));
  14003. }
  14004. return Promise.reject(error);
  14005. });
  14006. },
  14007. _setXHR: function (xhr
  14008. /*: any*/
  14009. ) {
  14010. XHR = xhr;
  14011. }
  14012. };
  14013. module.exports = RESTController;
  14014. }).call(this,_dereq_('_process'))
  14015. },{"./CoreManager":4,"./ParseError":18,"./Xhr.weapp":40,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75,"_process":79}],34:[function(_dereq_,module,exports){
  14016. "use strict";
  14017. var _interopRequireWildcard = _dereq_("@babel/runtime/helpers/interopRequireWildcard");
  14018. Object.defineProperty(exports, "__esModule", {
  14019. value: true
  14020. });
  14021. exports.getState = getState;
  14022. exports.initializeState = initializeState;
  14023. exports.removeState = removeState;
  14024. exports.getServerData = getServerData;
  14025. exports.setServerData = setServerData;
  14026. exports.getPendingOps = getPendingOps;
  14027. exports.setPendingOp = setPendingOp;
  14028. exports.pushPendingState = pushPendingState;
  14029. exports.popPendingState = popPendingState;
  14030. exports.mergeFirstPendingState = mergeFirstPendingState;
  14031. exports.getObjectCache = getObjectCache;
  14032. exports.estimateAttribute = estimateAttribute;
  14033. exports.estimateAttributes = estimateAttributes;
  14034. exports.commitServerChanges = commitServerChanges;
  14035. exports.enqueueTask = enqueueTask;
  14036. exports.clearAllState = clearAllState;
  14037. exports.duplicateState = duplicateState;
  14038. var ObjectStateMutations = _interopRequireWildcard(_dereq_("./ObjectStateMutations"));
  14039. /**
  14040. * Copyright (c) 2015-present, Parse, LLC.
  14041. * All rights reserved.
  14042. *
  14043. * This source code is licensed under the BSD-style license found in the
  14044. * LICENSE file in the root directory of this source tree. An additional grant
  14045. * of patent rights can be found in the PATENTS file in the same directory.
  14046. *
  14047. * @flow
  14048. */
  14049. var objectState
  14050. /*: {
  14051. [className: string]: {
  14052. [id: string]: State
  14053. }
  14054. }*/
  14055. = {};
  14056. function getState(obj
  14057. /*: ObjectIdentifier*/
  14058. )
  14059. /*: ?State*/
  14060. {
  14061. var classData = objectState[obj.className];
  14062. if (classData) {
  14063. return classData[obj.id] || null;
  14064. }
  14065. return null;
  14066. }
  14067. function initializeState(obj
  14068. /*: ObjectIdentifier*/
  14069. , initial
  14070. /*:: ?: State*/
  14071. )
  14072. /*: State*/
  14073. {
  14074. var state = getState(obj);
  14075. if (state) {
  14076. return state;
  14077. }
  14078. if (!objectState[obj.className]) {
  14079. objectState[obj.className] = {};
  14080. }
  14081. if (!initial) {
  14082. initial = ObjectStateMutations.defaultState();
  14083. }
  14084. state = objectState[obj.className][obj.id] = initial;
  14085. return state;
  14086. }
  14087. function removeState(obj
  14088. /*: ObjectIdentifier*/
  14089. )
  14090. /*: ?State*/
  14091. {
  14092. var state = getState(obj);
  14093. if (state === null) {
  14094. return null;
  14095. }
  14096. delete objectState[obj.className][obj.id];
  14097. return state;
  14098. }
  14099. function getServerData(obj
  14100. /*: ObjectIdentifier*/
  14101. )
  14102. /*: AttributeMap*/
  14103. {
  14104. var state = getState(obj);
  14105. if (state) {
  14106. return state.serverData;
  14107. }
  14108. return {};
  14109. }
  14110. function setServerData(obj
  14111. /*: ObjectIdentifier*/
  14112. , attributes
  14113. /*: AttributeMap*/
  14114. ) {
  14115. var serverData = initializeState(obj).serverData;
  14116. ObjectStateMutations.setServerData(serverData, attributes);
  14117. }
  14118. function getPendingOps(obj
  14119. /*: ObjectIdentifier*/
  14120. )
  14121. /*: Array<OpsMap>*/
  14122. {
  14123. var state = getState(obj);
  14124. if (state) {
  14125. return state.pendingOps;
  14126. }
  14127. return [{}];
  14128. }
  14129. function setPendingOp(obj
  14130. /*: ObjectIdentifier*/
  14131. , attr
  14132. /*: string*/
  14133. , op
  14134. /*: ?Op*/
  14135. ) {
  14136. var pendingOps = initializeState(obj).pendingOps;
  14137. ObjectStateMutations.setPendingOp(pendingOps, attr, op);
  14138. }
  14139. function pushPendingState(obj
  14140. /*: ObjectIdentifier*/
  14141. ) {
  14142. var pendingOps = initializeState(obj).pendingOps;
  14143. ObjectStateMutations.pushPendingState(pendingOps);
  14144. }
  14145. function popPendingState(obj
  14146. /*: ObjectIdentifier*/
  14147. )
  14148. /*: OpsMap*/
  14149. {
  14150. var pendingOps = initializeState(obj).pendingOps;
  14151. return ObjectStateMutations.popPendingState(pendingOps);
  14152. }
  14153. function mergeFirstPendingState(obj
  14154. /*: ObjectIdentifier*/
  14155. ) {
  14156. var pendingOps = getPendingOps(obj);
  14157. ObjectStateMutations.mergeFirstPendingState(pendingOps);
  14158. }
  14159. function getObjectCache(obj
  14160. /*: ObjectIdentifier*/
  14161. )
  14162. /*: ObjectCache*/
  14163. {
  14164. var state = getState(obj);
  14165. if (state) {
  14166. return state.objectCache;
  14167. }
  14168. return {};
  14169. }
  14170. function estimateAttribute(obj
  14171. /*: ObjectIdentifier*/
  14172. , attr
  14173. /*: string*/
  14174. )
  14175. /*: mixed*/
  14176. {
  14177. var serverData = getServerData(obj);
  14178. var pendingOps = getPendingOps(obj);
  14179. return ObjectStateMutations.estimateAttribute(serverData, pendingOps, obj.className, obj.id, attr);
  14180. }
  14181. function estimateAttributes(obj
  14182. /*: ObjectIdentifier*/
  14183. )
  14184. /*: AttributeMap*/
  14185. {
  14186. var serverData = getServerData(obj);
  14187. var pendingOps = getPendingOps(obj);
  14188. return ObjectStateMutations.estimateAttributes(serverData, pendingOps, obj.className, obj.id);
  14189. }
  14190. function commitServerChanges(obj
  14191. /*: ObjectIdentifier*/
  14192. , changes
  14193. /*: AttributeMap*/
  14194. ) {
  14195. var state = initializeState(obj);
  14196. ObjectStateMutations.commitServerChanges(state.serverData, state.objectCache, changes);
  14197. }
  14198. function enqueueTask(obj
  14199. /*: ObjectIdentifier*/
  14200. , task
  14201. /*: () => Promise*/
  14202. )
  14203. /*: Promise*/
  14204. {
  14205. var state = initializeState(obj);
  14206. return state.tasks.enqueue(task);
  14207. }
  14208. function clearAllState() {
  14209. objectState = {};
  14210. }
  14211. function duplicateState(source
  14212. /*: {id: string}*/
  14213. , dest
  14214. /*: {id: string}*/
  14215. ) {
  14216. dest.id = source.id;
  14217. }
  14218. },{"./ObjectStateMutations":13,"@babel/runtime/helpers/interopRequireWildcard":64}],35:[function(_dereq_,module,exports){
  14219. "use strict";
  14220. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14221. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  14222. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  14223. module.exports =
  14224. /*#__PURE__*/
  14225. function () {
  14226. function SocketWeapp(serverURL) {
  14227. var _this = this;
  14228. (0, _classCallCheck2.default)(this, SocketWeapp);
  14229. this.onopen = function () {};
  14230. this.onmessage = function () {};
  14231. this.onclose = function () {};
  14232. this.onerror = function () {};
  14233. wx.connectSocket({
  14234. url: serverURL
  14235. });
  14236. wx.onSocketOpen(function () {
  14237. _this.onopen();
  14238. });
  14239. wx.onSocketMessage(function (msg) {
  14240. _this.onmessage(msg);
  14241. });
  14242. wx.onSocketClose(function () {
  14243. _this.onclose();
  14244. });
  14245. wx.onSocketError(function (error) {
  14246. _this.onerror(error);
  14247. });
  14248. }
  14249. (0, _createClass2.default)(SocketWeapp, [{
  14250. key: "send",
  14251. value: function (data) {
  14252. wx.sendSocketMessage({
  14253. data: data
  14254. });
  14255. }
  14256. }, {
  14257. key: "close",
  14258. value: function () {
  14259. wx.closeSocket();
  14260. }
  14261. }]);
  14262. return SocketWeapp;
  14263. }();
  14264. },{"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/interopRequireDefault":63}],36:[function(_dereq_,module,exports){
  14265. "use strict";
  14266. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14267. var _CoreManager = _interopRequireDefault(_dereq_("./CoreManager"));
  14268. /**
  14269. * Copyright (c) 2015-present, Parse, LLC.
  14270. * All rights reserved.
  14271. *
  14272. * This source code is licensed under the BSD-style license found in the
  14273. * LICENSE file in the root directory of this source tree. An additional grant
  14274. * of patent rights can be found in the PATENTS file in the same directory.
  14275. *
  14276. * @flow
  14277. */
  14278. var Storage = {
  14279. async: function ()
  14280. /*: boolean*/
  14281. {
  14282. var controller = _CoreManager.default.getStorageController();
  14283. return !!controller.async;
  14284. },
  14285. getItem: function (path
  14286. /*: string*/
  14287. )
  14288. /*: ?string*/
  14289. {
  14290. var controller = _CoreManager.default.getStorageController();
  14291. if (controller.async === 1) {
  14292. throw new Error('Synchronous storage is not supported by the current storage controller');
  14293. }
  14294. return controller.getItem(path);
  14295. },
  14296. getItemAsync: function (path
  14297. /*: string*/
  14298. )
  14299. /*: Promise<string>*/
  14300. {
  14301. var controller = _CoreManager.default.getStorageController();
  14302. if (controller.async === 1) {
  14303. return controller.getItemAsync(path);
  14304. }
  14305. return Promise.resolve(controller.getItem(path));
  14306. },
  14307. setItem: function (path
  14308. /*: string*/
  14309. , value
  14310. /*: string*/
  14311. )
  14312. /*: void*/
  14313. {
  14314. var controller = _CoreManager.default.getStorageController();
  14315. if (controller.async === 1) {
  14316. throw new Error('Synchronous storage is not supported by the current storage controller');
  14317. }
  14318. return controller.setItem(path, value);
  14319. },
  14320. setItemAsync: function (path
  14321. /*: string*/
  14322. , value
  14323. /*: string*/
  14324. )
  14325. /*: Promise<void>*/
  14326. {
  14327. var controller = _CoreManager.default.getStorageController();
  14328. if (controller.async === 1) {
  14329. return controller.setItemAsync(path, value);
  14330. }
  14331. return Promise.resolve(controller.setItem(path, value));
  14332. },
  14333. removeItem: function (path
  14334. /*: string*/
  14335. )
  14336. /*: void*/
  14337. {
  14338. var controller = _CoreManager.default.getStorageController();
  14339. if (controller.async === 1) {
  14340. throw new Error('Synchronous storage is not supported by the current storage controller');
  14341. }
  14342. return controller.removeItem(path);
  14343. },
  14344. removeItemAsync: function (path
  14345. /*: string*/
  14346. )
  14347. /*: Promise<void>*/
  14348. {
  14349. var controller = _CoreManager.default.getStorageController();
  14350. if (controller.async === 1) {
  14351. return controller.removeItemAsync(path);
  14352. }
  14353. return Promise.resolve(controller.removeItem(path));
  14354. },
  14355. generatePath: function (path
  14356. /*: string*/
  14357. )
  14358. /*: string*/
  14359. {
  14360. if (!_CoreManager.default.get('APPLICATION_ID')) {
  14361. throw new Error('You need to call Parse.initialize before using Parse.');
  14362. }
  14363. if (typeof path !== 'string') {
  14364. throw new Error('Tried to get a Storage path that was not a String.');
  14365. }
  14366. if (path[0] === '/') {
  14367. path = path.substr(1);
  14368. }
  14369. return 'Parse/' + _CoreManager.default.get('APPLICATION_ID') + '/' + path;
  14370. },
  14371. _clear: function () {
  14372. var controller = _CoreManager.default.getStorageController();
  14373. if (controller.hasOwnProperty('clear')) {
  14374. controller.clear();
  14375. }
  14376. }
  14377. };
  14378. module.exports = Storage;
  14379. _CoreManager.default.setStorageController(_dereq_('./StorageController.weapp'));
  14380. },{"./CoreManager":4,"./StorageController.weapp":37,"@babel/runtime/helpers/interopRequireDefault":63}],37:[function(_dereq_,module,exports){
  14381. "use strict";
  14382. /**
  14383. * Copyright (c) 2015-present, Parse, LLC.
  14384. * All rights reserved.
  14385. *
  14386. * This source code is licensed under the BSD-style license found in the
  14387. * LICENSE file in the root directory of this source tree. An additional grant
  14388. * of patent rights can be found in the PATENTS file in the same directory.
  14389. *
  14390. * @flow
  14391. */
  14392. var StorageController = {
  14393. async: 0,
  14394. getItem: function (path
  14395. /*: string*/
  14396. )
  14397. /*: ?string*/
  14398. {
  14399. return wx.getStorageSync(path);
  14400. },
  14401. setItem: function (path
  14402. /*: string*/
  14403. , value
  14404. /*: string*/
  14405. ) {
  14406. try {
  14407. wx.setStorageSync(path, value);
  14408. } catch (e) {// Quota exceeded
  14409. }
  14410. },
  14411. removeItem: function (path
  14412. /*: string*/
  14413. ) {
  14414. wx.removeStorageSync(path);
  14415. },
  14416. clear: function () {
  14417. wx.clearStorageSync();
  14418. }
  14419. };
  14420. module.exports = StorageController;
  14421. },{}],38:[function(_dereq_,module,exports){
  14422. /*:: type Task = {
  14423. task: () => Promise;
  14424. _completion: Promise
  14425. };*/
  14426. "use strict";
  14427. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14428. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  14429. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  14430. var _defineProperty2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/defineProperty"));
  14431. /**
  14432. * Copyright (c) 2015-present, Parse, LLC.
  14433. * All rights reserved.
  14434. *
  14435. * This source code is licensed under the BSD-style license found in the
  14436. * LICENSE file in the root directory of this source tree. An additional grant
  14437. * of patent rights can be found in the PATENTS file in the same directory.
  14438. *
  14439. * @flow
  14440. */
  14441. var TaskQueue =
  14442. /*#__PURE__*/
  14443. function () {
  14444. function TaskQueue() {
  14445. (0, _classCallCheck2.default)(this, TaskQueue);
  14446. (0, _defineProperty2.default)(this, "queue", void 0);
  14447. this.queue = [];
  14448. }
  14449. (0, _createClass2.default)(TaskQueue, [{
  14450. key: "enqueue",
  14451. value: function (task
  14452. /*: () => Promise*/
  14453. )
  14454. /*: Promise*/
  14455. {
  14456. var _this = this;
  14457. var res;
  14458. var rej;
  14459. var taskComplete = new Promise(function (resolve, reject) {
  14460. res = resolve;
  14461. rej = reject;
  14462. });
  14463. taskComplete.resolve = res;
  14464. taskComplete.reject = rej;
  14465. this.queue.push({
  14466. task: task,
  14467. _completion: taskComplete
  14468. });
  14469. if (this.queue.length === 1) {
  14470. task().then(function () {
  14471. _this._dequeue();
  14472. taskComplete.resolve();
  14473. }, function (error) {
  14474. _this._dequeue();
  14475. taskComplete.reject(error);
  14476. });
  14477. }
  14478. return taskComplete;
  14479. }
  14480. }, {
  14481. key: "_dequeue",
  14482. value: function () {
  14483. var _this2 = this;
  14484. this.queue.shift();
  14485. if (this.queue.length) {
  14486. var next = this.queue[0];
  14487. next.task().then(function () {
  14488. _this2._dequeue();
  14489. next._completion.resolve();
  14490. }, function (error) {
  14491. _this2._dequeue();
  14492. next._completion.reject(error);
  14493. });
  14494. }
  14495. }
  14496. }]);
  14497. return TaskQueue;
  14498. }();
  14499. module.exports = TaskQueue;
  14500. },{"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/defineProperty":59,"@babel/runtime/helpers/interopRequireDefault":63}],39:[function(_dereq_,module,exports){
  14501. "use strict";
  14502. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14503. var _interopRequireWildcard = _dereq_("@babel/runtime/helpers/interopRequireWildcard");
  14504. Object.defineProperty(exports, "__esModule", {
  14505. value: true
  14506. });
  14507. exports.getState = getState;
  14508. exports.initializeState = initializeState;
  14509. exports.removeState = removeState;
  14510. exports.getServerData = getServerData;
  14511. exports.setServerData = setServerData;
  14512. exports.getPendingOps = getPendingOps;
  14513. exports.setPendingOp = setPendingOp;
  14514. exports.pushPendingState = pushPendingState;
  14515. exports.popPendingState = popPendingState;
  14516. exports.mergeFirstPendingState = mergeFirstPendingState;
  14517. exports.getObjectCache = getObjectCache;
  14518. exports.estimateAttribute = estimateAttribute;
  14519. exports.estimateAttributes = estimateAttributes;
  14520. exports.commitServerChanges = commitServerChanges;
  14521. exports.enqueueTask = enqueueTask;
  14522. exports.duplicateState = duplicateState;
  14523. exports.clearAllState = clearAllState;
  14524. var ObjectStateMutations = _interopRequireWildcard(_dereq_("./ObjectStateMutations"));
  14525. var _TaskQueue = _interopRequireDefault(_dereq_("./TaskQueue"));
  14526. /**
  14527. * Copyright (c) 2015-present, Parse, LLC.
  14528. * All rights reserved.
  14529. *
  14530. * This source code is licensed under the BSD-style license found in the
  14531. * LICENSE file in the root directory of this source tree. An additional grant
  14532. * of patent rights can be found in the PATENTS file in the same directory.
  14533. *
  14534. * @flow
  14535. */
  14536. var objectState = new WeakMap();
  14537. function getState(obj
  14538. /*: ParseObject*/
  14539. )
  14540. /*: ?State*/
  14541. {
  14542. var classData = objectState.get(obj);
  14543. return classData || null;
  14544. }
  14545. function initializeState(obj
  14546. /*: ParseObject*/
  14547. , initial
  14548. /*:: ?: State*/
  14549. )
  14550. /*: State*/
  14551. {
  14552. var state = getState(obj);
  14553. if (state) {
  14554. return state;
  14555. }
  14556. if (!initial) {
  14557. initial = {
  14558. serverData: {},
  14559. pendingOps: [{}],
  14560. objectCache: {},
  14561. tasks: new _TaskQueue.default(),
  14562. existed: false
  14563. };
  14564. }
  14565. state = initial;
  14566. objectState.set(obj, state);
  14567. return state;
  14568. }
  14569. function removeState(obj
  14570. /*: ParseObject*/
  14571. )
  14572. /*: ?State*/
  14573. {
  14574. var state = getState(obj);
  14575. if (state === null) {
  14576. return null;
  14577. }
  14578. objectState.delete(obj);
  14579. return state;
  14580. }
  14581. function getServerData(obj
  14582. /*: ParseObject*/
  14583. )
  14584. /*: AttributeMap*/
  14585. {
  14586. var state = getState(obj);
  14587. if (state) {
  14588. return state.serverData;
  14589. }
  14590. return {};
  14591. }
  14592. function setServerData(obj
  14593. /*: ParseObject*/
  14594. , attributes
  14595. /*: AttributeMap*/
  14596. ) {
  14597. var serverData = initializeState(obj).serverData;
  14598. ObjectStateMutations.setServerData(serverData, attributes);
  14599. }
  14600. function getPendingOps(obj
  14601. /*: ParseObject*/
  14602. )
  14603. /*: Array<OpsMap>*/
  14604. {
  14605. var state = getState(obj);
  14606. if (state) {
  14607. return state.pendingOps;
  14608. }
  14609. return [{}];
  14610. }
  14611. function setPendingOp(obj
  14612. /*: ParseObject*/
  14613. , attr
  14614. /*: string*/
  14615. , op
  14616. /*: ?Op*/
  14617. ) {
  14618. var pendingOps = initializeState(obj).pendingOps;
  14619. ObjectStateMutations.setPendingOp(pendingOps, attr, op);
  14620. }
  14621. function pushPendingState(obj
  14622. /*: ParseObject*/
  14623. ) {
  14624. var pendingOps = initializeState(obj).pendingOps;
  14625. ObjectStateMutations.pushPendingState(pendingOps);
  14626. }
  14627. function popPendingState(obj
  14628. /*: ParseObject*/
  14629. )
  14630. /*: OpsMap*/
  14631. {
  14632. var pendingOps = initializeState(obj).pendingOps;
  14633. return ObjectStateMutations.popPendingState(pendingOps);
  14634. }
  14635. function mergeFirstPendingState(obj
  14636. /*: ParseObject*/
  14637. ) {
  14638. var pendingOps = getPendingOps(obj);
  14639. ObjectStateMutations.mergeFirstPendingState(pendingOps);
  14640. }
  14641. function getObjectCache(obj
  14642. /*: ParseObject*/
  14643. )
  14644. /*: ObjectCache*/
  14645. {
  14646. var state = getState(obj);
  14647. if (state) {
  14648. return state.objectCache;
  14649. }
  14650. return {};
  14651. }
  14652. function estimateAttribute(obj
  14653. /*: ParseObject*/
  14654. , attr
  14655. /*: string*/
  14656. )
  14657. /*: mixed*/
  14658. {
  14659. var serverData = getServerData(obj);
  14660. var pendingOps = getPendingOps(obj);
  14661. return ObjectStateMutations.estimateAttribute(serverData, pendingOps, obj.className, obj.id, attr);
  14662. }
  14663. function estimateAttributes(obj
  14664. /*: ParseObject*/
  14665. )
  14666. /*: AttributeMap*/
  14667. {
  14668. var serverData = getServerData(obj);
  14669. var pendingOps = getPendingOps(obj);
  14670. return ObjectStateMutations.estimateAttributes(serverData, pendingOps, obj.className, obj.id);
  14671. }
  14672. function commitServerChanges(obj
  14673. /*: ParseObject*/
  14674. , changes
  14675. /*: AttributeMap*/
  14676. ) {
  14677. var state = initializeState(obj);
  14678. ObjectStateMutations.commitServerChanges(state.serverData, state.objectCache, changes);
  14679. }
  14680. function enqueueTask(obj
  14681. /*: ParseObject*/
  14682. , task
  14683. /*: () => Promise*/
  14684. )
  14685. /*: Promise*/
  14686. {
  14687. var state = initializeState(obj);
  14688. return state.tasks.enqueue(task);
  14689. }
  14690. function duplicateState(source
  14691. /*: ParseObject*/
  14692. , dest
  14693. /*: ParseObject*/
  14694. )
  14695. /*: void*/
  14696. {
  14697. var oldState = initializeState(source);
  14698. var newState = initializeState(dest);
  14699. for (var key in oldState.serverData) {
  14700. newState.serverData[key] = oldState.serverData[key];
  14701. }
  14702. for (var index = 0; index < oldState.pendingOps.length; index++) {
  14703. for (var _key in oldState.pendingOps[index]) {
  14704. newState.pendingOps[index][_key] = oldState.pendingOps[index][_key];
  14705. }
  14706. }
  14707. for (var _key2 in oldState.objectCache) {
  14708. newState.objectCache[_key2] = oldState.objectCache[_key2];
  14709. }
  14710. newState.existed = oldState.existed;
  14711. }
  14712. function clearAllState() {
  14713. objectState = new WeakMap();
  14714. }
  14715. },{"./ObjectStateMutations":13,"./TaskQueue":38,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/interopRequireWildcard":64}],40:[function(_dereq_,module,exports){
  14716. "use strict";
  14717. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14718. var _classCallCheck2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/classCallCheck"));
  14719. var _createClass2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/createClass"));
  14720. module.exports =
  14721. /*#__PURE__*/
  14722. function () {
  14723. function XhrWeapp() {
  14724. (0, _classCallCheck2.default)(this, XhrWeapp);
  14725. this.header = {};
  14726. this.readyState = 4;
  14727. this.status = 0;
  14728. this.response = '';
  14729. this.responseType = '';
  14730. this.responseText = '';
  14731. this.responseHeader = {};
  14732. this.method = '';
  14733. this.url = '';
  14734. this.onerror = function () {};
  14735. this.onreadystatechange = function () {};
  14736. }
  14737. (0, _createClass2.default)(XhrWeapp, [{
  14738. key: "getAllResponseHeaders",
  14739. value: function () {
  14740. var header = '';
  14741. for (var key in this.responseHeader) {
  14742. header += key + ':' + this.getResponseHeader(key) + '\r\n';
  14743. }
  14744. return header;
  14745. }
  14746. }, {
  14747. key: "getResponseHeader",
  14748. value: function (key) {
  14749. return this.responseHeader[key];
  14750. }
  14751. }, {
  14752. key: "setRequestHeader",
  14753. value: function (key, value) {
  14754. this.header[key] = value;
  14755. }
  14756. }, {
  14757. key: "open",
  14758. value: function (method, url) {
  14759. this.method = method;
  14760. this.url = url;
  14761. }
  14762. }, {
  14763. key: "send",
  14764. value: function (data) {
  14765. var _this = this;
  14766. wx.request({
  14767. url: this.url,
  14768. method: this.method,
  14769. data: data,
  14770. header: this.header,
  14771. responseType: this.responseType,
  14772. success: function (res) {
  14773. _this.status = res.statusCode;
  14774. _this.response = res.data;
  14775. _this.responseHeader = res.header;
  14776. _this.responseText = JSON.stringify(res.data);
  14777. _this.onreadystatechange();
  14778. },
  14779. fail: function (err) {
  14780. _this.onerror(err);
  14781. }
  14782. });
  14783. }
  14784. }]);
  14785. return XhrWeapp;
  14786. }();
  14787. },{"@babel/runtime/helpers/classCallCheck":56,"@babel/runtime/helpers/createClass":58,"@babel/runtime/helpers/interopRequireDefault":63}],41:[function(_dereq_,module,exports){
  14788. "use strict";
  14789. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14790. Object.defineProperty(exports, "__esModule", {
  14791. value: true
  14792. });
  14793. exports.default = arrayContainsObject;
  14794. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  14795. /**
  14796. * Copyright (c) 2015-present, Parse, LLC.
  14797. * All rights reserved.
  14798. *
  14799. * This source code is licensed under the BSD-style license found in the
  14800. * LICENSE file in the root directory of this source tree. An additional grant
  14801. * of patent rights can be found in the PATENTS file in the same directory.
  14802. *
  14803. * @flow
  14804. */
  14805. function arrayContainsObject(array
  14806. /*: Array<any>*/
  14807. , object
  14808. /*: ParseObject*/
  14809. )
  14810. /*: boolean*/
  14811. {
  14812. if (array.indexOf(object) > -1) {
  14813. return true;
  14814. }
  14815. for (var i = 0; i < array.length; i++) {
  14816. if (array[i] instanceof _ParseObject.default && array[i].className === object.className && array[i]._getId() === object._getId()) {
  14817. return true;
  14818. }
  14819. }
  14820. return false;
  14821. }
  14822. },{"./ParseObject":23,"@babel/runtime/helpers/interopRequireDefault":63}],42:[function(_dereq_,module,exports){
  14823. "use strict";
  14824. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14825. Object.defineProperty(exports, "__esModule", {
  14826. value: true
  14827. });
  14828. exports.default = canBeSerialized;
  14829. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  14830. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  14831. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  14832. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  14833. /**
  14834. * Copyright (c) 2015-present, Parse, LLC.
  14835. * All rights reserved.
  14836. *
  14837. * This source code is licensed under the BSD-style license found in the
  14838. * LICENSE file in the root directory of this source tree. An additional grant
  14839. * of patent rights can be found in the PATENTS file in the same directory.
  14840. *
  14841. * @flow
  14842. */
  14843. function canBeSerialized(obj
  14844. /*: ParseObject*/
  14845. )
  14846. /*: boolean*/
  14847. {
  14848. if (!(obj instanceof _ParseObject.default)) {
  14849. return true;
  14850. }
  14851. var attributes = obj.attributes;
  14852. for (var attr in attributes) {
  14853. var val = attributes[attr];
  14854. if (!canBeSerializedHelper(val)) {
  14855. return false;
  14856. }
  14857. }
  14858. return true;
  14859. }
  14860. function canBeSerializedHelper(value
  14861. /*: any*/
  14862. )
  14863. /*: boolean*/
  14864. {
  14865. if ((0, _typeof2.default)(value) !== 'object') {
  14866. return true;
  14867. }
  14868. if (value instanceof _ParseRelation.default) {
  14869. return true;
  14870. }
  14871. if (value instanceof _ParseObject.default) {
  14872. return !!value.id;
  14873. }
  14874. if (value instanceof _ParseFile.default) {
  14875. if (value.url()) {
  14876. return true;
  14877. }
  14878. return false;
  14879. }
  14880. if (Array.isArray(value)) {
  14881. for (var i = 0; i < value.length; i++) {
  14882. if (!canBeSerializedHelper(value[i])) {
  14883. return false;
  14884. }
  14885. }
  14886. return true;
  14887. }
  14888. for (var k in value) {
  14889. if (!canBeSerializedHelper(value[k])) {
  14890. return false;
  14891. }
  14892. }
  14893. return true;
  14894. }
  14895. },{"./ParseFile":19,"./ParseObject":23,"./ParseRelation":27,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],43:[function(_dereq_,module,exports){
  14896. "use strict";
  14897. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14898. Object.defineProperty(exports, "__esModule", {
  14899. value: true
  14900. });
  14901. exports.default = decode;
  14902. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  14903. var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
  14904. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  14905. var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
  14906. var _ParsePolygon = _interopRequireDefault(_dereq_("./ParsePolygon"));
  14907. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  14908. var _ParseOp = _dereq_("./ParseOp");
  14909. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  14910. /**
  14911. * Copyright (c) 2015-present, Parse, LLC.
  14912. * All rights reserved.
  14913. *
  14914. * This source code is licensed under the BSD-style license found in the
  14915. * LICENSE file in the root directory of this source tree. An additional grant
  14916. * of patent rights can be found in the PATENTS file in the same directory.
  14917. *
  14918. * @flow
  14919. */
  14920. // eslint-disable-line no-unused-vars
  14921. function decode(value
  14922. /*: any*/
  14923. )
  14924. /*: any*/
  14925. {
  14926. if (value === null || (0, _typeof2.default)(value) !== 'object') {
  14927. return value;
  14928. }
  14929. if (Array.isArray(value)) {
  14930. var dup = [];
  14931. value.forEach(function (v, i) {
  14932. dup[i] = decode(v);
  14933. });
  14934. return dup;
  14935. }
  14936. if (typeof value.__op === 'string') {
  14937. return (0, _ParseOp.opFromJSON)(value);
  14938. }
  14939. if (value.__type === 'Pointer' && value.className) {
  14940. return _ParseObject.default.fromJSON(value);
  14941. }
  14942. if (value.__type === 'Object' && value.className) {
  14943. return _ParseObject.default.fromJSON(value);
  14944. }
  14945. if (value.__type === 'Relation') {
  14946. // The parent and key fields will be populated by the parent
  14947. var relation = new _ParseRelation.default(null, null);
  14948. relation.targetClassName = value.className;
  14949. return relation;
  14950. }
  14951. if (value.__type === 'Date') {
  14952. return new Date(value.iso);
  14953. }
  14954. if (value.__type === 'File') {
  14955. return _ParseFile.default.fromJSON(value);
  14956. }
  14957. if (value.__type === 'GeoPoint') {
  14958. return new _ParseGeoPoint.default({
  14959. latitude: value.latitude,
  14960. longitude: value.longitude
  14961. });
  14962. }
  14963. if (value.__type === 'Polygon') {
  14964. return new _ParsePolygon.default(value.coordinates);
  14965. }
  14966. var copy = {};
  14967. for (var k in value) {
  14968. copy[k] = decode(value[k]);
  14969. }
  14970. return copy;
  14971. }
  14972. },{"./ParseACL":16,"./ParseFile":19,"./ParseGeoPoint":20,"./ParseObject":23,"./ParseOp":24,"./ParsePolygon":25,"./ParseRelation":27,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],44:[function(_dereq_,module,exports){
  14973. "use strict";
  14974. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  14975. Object.defineProperty(exports, "__esModule", {
  14976. value: true
  14977. });
  14978. exports.default = _default;
  14979. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  14980. var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
  14981. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  14982. var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
  14983. var _ParsePolygon = _interopRequireDefault(_dereq_("./ParsePolygon"));
  14984. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  14985. var _ParseOp = _dereq_("./ParseOp");
  14986. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  14987. /**
  14988. * Copyright (c) 2015-present, Parse, LLC.
  14989. * All rights reserved.
  14990. *
  14991. * This source code is licensed under the BSD-style license found in the
  14992. * LICENSE file in the root directory of this source tree. An additional grant
  14993. * of patent rights can be found in the PATENTS file in the same directory.
  14994. *
  14995. * @flow
  14996. */
  14997. var toString = Object.prototype.toString;
  14998. function encode(value
  14999. /*: mixed*/
  15000. , disallowObjects
  15001. /*: boolean*/
  15002. , forcePointers
  15003. /*: boolean*/
  15004. , seen
  15005. /*: Array<mixed>*/
  15006. )
  15007. /*: any*/
  15008. {
  15009. if (value instanceof _ParseObject.default) {
  15010. if (disallowObjects) {
  15011. throw new Error('Parse Objects not allowed here');
  15012. }
  15013. var seenEntry = value.id ? value.className + ':' + value.id : value;
  15014. if (forcePointers || !seen || seen.indexOf(seenEntry) > -1 || value.dirty() || Object.keys(value._getServerData()).length < 1) {
  15015. return value.toPointer();
  15016. }
  15017. seen = seen.concat(seenEntry);
  15018. return value._toFullJSON(seen);
  15019. }
  15020. if (value instanceof _ParseOp.Op || value instanceof _ParseACL.default || value instanceof _ParseGeoPoint.default || value instanceof _ParsePolygon.default || value instanceof _ParseRelation.default) {
  15021. return value.toJSON();
  15022. }
  15023. if (value instanceof _ParseFile.default) {
  15024. if (!value.url()) {
  15025. throw new Error('Tried to encode an unsaved file.');
  15026. }
  15027. return value.toJSON();
  15028. }
  15029. if (toString.call(value) === '[object Date]') {
  15030. if (isNaN(value)) {
  15031. throw new Error('Tried to encode an invalid date.');
  15032. }
  15033. return {
  15034. __type: 'Date',
  15035. iso: value
  15036. /*: any*/
  15037. .toJSON()
  15038. };
  15039. }
  15040. if (toString.call(value) === '[object RegExp]' && typeof value.source === 'string') {
  15041. return value.source;
  15042. }
  15043. if (Array.isArray(value)) {
  15044. return value.map(function (v) {
  15045. return encode(v, disallowObjects, forcePointers, seen);
  15046. });
  15047. }
  15048. if (value && (0, _typeof2.default)(value) === 'object') {
  15049. var output = {};
  15050. for (var k in value) {
  15051. output[k] = encode(value[k], disallowObjects, forcePointers, seen);
  15052. }
  15053. return output;
  15054. }
  15055. return value;
  15056. }
  15057. function _default(value
  15058. /*: mixed*/
  15059. , disallowObjects
  15060. /*:: ?: boolean*/
  15061. , forcePointers
  15062. /*:: ?: boolean*/
  15063. , seen
  15064. /*:: ?: Array<mixed>*/
  15065. )
  15066. /*: any*/
  15067. {
  15068. return encode(value, !!disallowObjects, !!forcePointers, seen || []);
  15069. }
  15070. },{"./ParseACL":16,"./ParseFile":19,"./ParseGeoPoint":20,"./ParseObject":23,"./ParseOp":24,"./ParsePolygon":25,"./ParseRelation":27,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],45:[function(_dereq_,module,exports){
  15071. "use strict";
  15072. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  15073. Object.defineProperty(exports, "__esModule", {
  15074. value: true
  15075. });
  15076. exports.default = equals;
  15077. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  15078. var _ParseACL = _interopRequireDefault(_dereq_("./ParseACL"));
  15079. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  15080. var _ParseGeoPoint = _interopRequireDefault(_dereq_("./ParseGeoPoint"));
  15081. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  15082. /**
  15083. * Copyright (c) 2015-present, Parse, LLC.
  15084. * All rights reserved.
  15085. *
  15086. * This source code is licensed under the BSD-style license found in the
  15087. * LICENSE file in the root directory of this source tree. An additional grant
  15088. * of patent rights can be found in the PATENTS file in the same directory.
  15089. */
  15090. var toString = Object.prototype.toString;
  15091. function equals(a, b) {
  15092. if (toString.call(a) === '[object Date]' || toString.call(b) === '[object Date]') {
  15093. var dateA = new Date(a);
  15094. var dateB = new Date(b);
  15095. return +dateA === +dateB;
  15096. }
  15097. if ((0, _typeof2.default)(a) !== (0, _typeof2.default)(b)) {
  15098. return false;
  15099. }
  15100. if (!a || (0, _typeof2.default)(a) !== 'object') {
  15101. // a is a primitive
  15102. return a === b;
  15103. }
  15104. if (Array.isArray(a) || Array.isArray(b)) {
  15105. if (!Array.isArray(a) || !Array.isArray(b)) {
  15106. return false;
  15107. }
  15108. if (a.length !== b.length) {
  15109. return false;
  15110. }
  15111. for (var i = a.length; i--;) {
  15112. if (!equals(a[i], b[i])) {
  15113. return false;
  15114. }
  15115. }
  15116. return true;
  15117. }
  15118. if (a instanceof _ParseACL.default || a instanceof _ParseFile.default || a instanceof _ParseGeoPoint.default || a instanceof _ParseObject.default) {
  15119. return a.equals(b);
  15120. }
  15121. if (b instanceof _ParseObject.default) {
  15122. if (a.__type === 'Object' || a.__type === 'Pointer') {
  15123. return a.objectId === b.id && a.className === b.className;
  15124. }
  15125. }
  15126. if (Object.keys(a).length !== Object.keys(b).length) {
  15127. return false;
  15128. }
  15129. for (var k in a) {
  15130. if (!equals(a[k], b[k])) {
  15131. return false;
  15132. }
  15133. }
  15134. return true;
  15135. }
  15136. },{"./ParseACL":16,"./ParseFile":19,"./ParseGeoPoint":20,"./ParseObject":23,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],46:[function(_dereq_,module,exports){
  15137. "use strict";
  15138. Object.defineProperty(exports, "__esModule", {
  15139. value: true
  15140. });
  15141. exports.default = escape;
  15142. /*
  15143. * Copyright (c) 2015-present, Parse, LLC.
  15144. * All rights reserved.
  15145. *
  15146. * This source code is licensed under the BSD-style license found in the
  15147. * LICENSE file in the root directory of this source tree. An additional grant
  15148. * of patent rights can be found in the PATENTS file in the same directory.
  15149. *
  15150. * @flow
  15151. */
  15152. var encoded = {
  15153. '&': '&amp;',
  15154. '<': '&lt;',
  15155. '>': '&gt;',
  15156. '/': '&#x2F;',
  15157. '\'': '&#x27;',
  15158. '"': '&quot;'
  15159. };
  15160. function escape(str
  15161. /*: string*/
  15162. )
  15163. /*: string*/
  15164. {
  15165. return str.replace(/[&<>\/'"]/g, function (char) {
  15166. return encoded[char];
  15167. });
  15168. }
  15169. },{}],47:[function(_dereq_,module,exports){
  15170. "use strict";
  15171. Object.defineProperty(exports, "__esModule", {
  15172. value: true
  15173. });
  15174. exports.default = isRevocableSession;
  15175. /**
  15176. * Copyright (c) 2015-present, Parse, LLC.
  15177. * All rights reserved.
  15178. *
  15179. * This source code is licensed under the BSD-style license found in the
  15180. * LICENSE file in the root directory of this source tree. An additional grant
  15181. * of patent rights can be found in the PATENTS file in the same directory.
  15182. *
  15183. * @flow
  15184. */
  15185. function isRevocableSession(token
  15186. /*: string*/
  15187. )
  15188. /*: boolean*/
  15189. {
  15190. return token.indexOf('r:') > -1;
  15191. }
  15192. },{}],48:[function(_dereq_,module,exports){
  15193. "use strict";
  15194. Object.defineProperty(exports, "__esModule", {
  15195. value: true
  15196. });
  15197. exports.default = parseDate;
  15198. /**
  15199. * Copyright (c) 2015-present, Parse, LLC.
  15200. * All rights reserved.
  15201. *
  15202. * This source code is licensed under the BSD-style license found in the
  15203. * LICENSE file in the root directory of this source tree. An additional grant
  15204. * of patent rights can be found in the PATENTS file in the same directory.
  15205. *
  15206. * @flow
  15207. */
  15208. function parseDate(iso8601
  15209. /*: string*/
  15210. )
  15211. /*: ?Date*/
  15212. {
  15213. 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$');
  15214. var match = regexp.exec(iso8601);
  15215. if (!match) {
  15216. return null;
  15217. }
  15218. var year = parseInt(match[1]) || 0;
  15219. var month = (parseInt(match[2]) || 1) - 1;
  15220. var day = parseInt(match[3]) || 0;
  15221. var hour = parseInt(match[4]) || 0;
  15222. var minute = parseInt(match[5]) || 0;
  15223. var second = parseInt(match[6]) || 0;
  15224. var milli = parseInt(match[8]) || 0;
  15225. return new Date(Date.UTC(year, month, day, hour, minute, second, milli));
  15226. }
  15227. },{}],49:[function(_dereq_,module,exports){
  15228. "use strict";
  15229. Object.defineProperty(exports, "__esModule", {
  15230. value: true
  15231. });
  15232. exports.resolvingPromise = resolvingPromise;
  15233. exports.when = when;
  15234. exports.continueWhile = continueWhile;
  15235. function resolvingPromise() {
  15236. var res;
  15237. var rej;
  15238. var promise = new Promise(function (resolve, reject) {
  15239. res = resolve;
  15240. rej = reject;
  15241. });
  15242. promise.resolve = res;
  15243. promise.reject = rej;
  15244. return promise;
  15245. }
  15246. function when(promises) {
  15247. var objects;
  15248. var arrayArgument = Array.isArray(promises);
  15249. if (arrayArgument) {
  15250. objects = promises;
  15251. } else {
  15252. objects = arguments;
  15253. }
  15254. var total = objects.length;
  15255. var hadError = false;
  15256. var results = [];
  15257. var returnValue = arrayArgument ? [results] : results;
  15258. var errors = [];
  15259. results.length = objects.length;
  15260. errors.length = objects.length;
  15261. if (total === 0) {
  15262. return Promise.resolve(returnValue);
  15263. }
  15264. var promise = new resolvingPromise();
  15265. var resolveOne = function () {
  15266. total--;
  15267. if (total <= 0) {
  15268. if (hadError) {
  15269. promise.reject(errors);
  15270. } else {
  15271. promise.resolve(returnValue);
  15272. }
  15273. }
  15274. };
  15275. var chain = function (object, index) {
  15276. if (object && typeof object.then === 'function') {
  15277. object.then(function (result) {
  15278. results[index] = result;
  15279. resolveOne();
  15280. }, function (error) {
  15281. errors[index] = error;
  15282. hadError = true;
  15283. resolveOne();
  15284. });
  15285. } else {
  15286. results[index] = object;
  15287. resolveOne();
  15288. }
  15289. };
  15290. for (var i = 0; i < objects.length; i++) {
  15291. chain(objects[i], i);
  15292. }
  15293. return promise;
  15294. }
  15295. function continueWhile(test, emitter) {
  15296. if (test()) {
  15297. return emitter().then(function () {
  15298. return continueWhile(test, emitter);
  15299. });
  15300. }
  15301. return Promise.resolve();
  15302. }
  15303. },{}],50:[function(_dereq_,module,exports){
  15304. "use strict";
  15305. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  15306. Object.defineProperty(exports, "__esModule", {
  15307. value: true
  15308. });
  15309. exports.default = unique;
  15310. var _arrayContainsObject = _interopRequireDefault(_dereq_("./arrayContainsObject"));
  15311. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  15312. /**
  15313. * Copyright (c) 2015-present, Parse, LLC.
  15314. * All rights reserved.
  15315. *
  15316. * This source code is licensed under the BSD-style license found in the
  15317. * LICENSE file in the root directory of this source tree. An additional grant
  15318. * of patent rights can be found in the PATENTS file in the same directory.
  15319. *
  15320. * @flow
  15321. */
  15322. function unique
  15323. /*:: <T>*/
  15324. (arr
  15325. /*: Array<T>*/
  15326. )
  15327. /*: Array<T>*/
  15328. {
  15329. var uniques = [];
  15330. arr.forEach(function (value) {
  15331. if (value instanceof _ParseObject.default) {
  15332. if (!(0, _arrayContainsObject.default)(uniques, value)) {
  15333. uniques.push(value);
  15334. }
  15335. } else {
  15336. if (uniques.indexOf(value) < 0) {
  15337. uniques.push(value);
  15338. }
  15339. }
  15340. });
  15341. return uniques;
  15342. }
  15343. },{"./ParseObject":23,"./arrayContainsObject":41,"@babel/runtime/helpers/interopRequireDefault":63}],51:[function(_dereq_,module,exports){
  15344. "use strict";
  15345. var _interopRequireDefault = _dereq_("@babel/runtime/helpers/interopRequireDefault");
  15346. Object.defineProperty(exports, "__esModule", {
  15347. value: true
  15348. });
  15349. exports.default = unsavedChildren;
  15350. var _typeof2 = _interopRequireDefault(_dereq_("@babel/runtime/helpers/typeof"));
  15351. var _ParseFile = _interopRequireDefault(_dereq_("./ParseFile"));
  15352. var _ParseObject = _interopRequireDefault(_dereq_("./ParseObject"));
  15353. var _ParseRelation = _interopRequireDefault(_dereq_("./ParseRelation"));
  15354. /**
  15355. * Copyright (c) 2015-present, Parse, LLC.
  15356. * All rights reserved.
  15357. *
  15358. * This source code is licensed under the BSD-style license found in the
  15359. * LICENSE file in the root directory of this source tree. An additional grant
  15360. * of patent rights can be found in the PATENTS file in the same directory.
  15361. *
  15362. * @flow
  15363. */
  15364. /**
  15365. * Return an array of unsaved children, which are either Parse Objects or Files.
  15366. * If it encounters any dirty Objects without Ids, it will throw an exception.
  15367. */
  15368. function unsavedChildren(obj
  15369. /*: ParseObject*/
  15370. , allowDeepUnsaved
  15371. /*:: ?: boolean*/
  15372. )
  15373. /*: Array<ParseFile | ParseObject>*/
  15374. {
  15375. var encountered = {
  15376. objects: {},
  15377. files: []
  15378. };
  15379. var identifier = obj.className + ':' + obj._getId();
  15380. encountered.objects[identifier] = obj.dirty() ? obj : true;
  15381. var attributes = obj.attributes;
  15382. for (var attr in attributes) {
  15383. if ((0, _typeof2.default)(attributes[attr]) === 'object') {
  15384. traverse(attributes[attr], encountered, false, !!allowDeepUnsaved);
  15385. }
  15386. }
  15387. var unsaved = [];
  15388. for (var id in encountered.objects) {
  15389. if (id !== identifier && encountered.objects[id] !== true) {
  15390. unsaved.push(encountered.objects[id]);
  15391. }
  15392. }
  15393. return unsaved.concat(encountered.files);
  15394. }
  15395. function traverse(obj
  15396. /*: ParseObject*/
  15397. , encountered
  15398. /*: EncounterMap*/
  15399. , shouldThrow
  15400. /*: boolean*/
  15401. , allowDeepUnsaved
  15402. /*: boolean*/
  15403. ) {
  15404. if (obj instanceof _ParseObject.default) {
  15405. if (!obj.id && shouldThrow) {
  15406. throw new Error('Cannot create a pointer to an unsaved Object.');
  15407. }
  15408. var _identifier = obj.className + ':' + obj._getId();
  15409. if (!encountered.objects[_identifier]) {
  15410. encountered.objects[_identifier] = obj.dirty() ? obj : true;
  15411. var attributes = obj.attributes;
  15412. for (var attr in attributes) {
  15413. if ((0, _typeof2.default)(attributes[attr]) === 'object') {
  15414. traverse(attributes[attr], encountered, !allowDeepUnsaved, allowDeepUnsaved);
  15415. }
  15416. }
  15417. }
  15418. return;
  15419. }
  15420. if (obj instanceof _ParseFile.default) {
  15421. if (!obj.url() && encountered.files.indexOf(obj) < 0) {
  15422. encountered.files.push(obj);
  15423. }
  15424. return;
  15425. }
  15426. if (obj instanceof _ParseRelation.default) {
  15427. return;
  15428. }
  15429. if (Array.isArray(obj)) {
  15430. obj.forEach(function (el) {
  15431. if ((0, _typeof2.default)(el) === 'object') {
  15432. traverse(el, encountered, shouldThrow, allowDeepUnsaved);
  15433. }
  15434. });
  15435. }
  15436. for (var k in obj) {
  15437. if ((0, _typeof2.default)(obj[k]) === 'object') {
  15438. traverse(obj[k], encountered, shouldThrow, allowDeepUnsaved);
  15439. }
  15440. }
  15441. }
  15442. },{"./ParseFile":19,"./ParseObject":23,"./ParseRelation":27,"@babel/runtime/helpers/interopRequireDefault":63,"@babel/runtime/helpers/typeof":75}],52:[function(_dereq_,module,exports){
  15443. function _arrayWithHoles(arr) {
  15444. if (Array.isArray(arr)) return arr;
  15445. }
  15446. module.exports = _arrayWithHoles;
  15447. },{}],53:[function(_dereq_,module,exports){
  15448. function _arrayWithoutHoles(arr) {
  15449. if (Array.isArray(arr)) {
  15450. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
  15451. arr2[i] = arr[i];
  15452. }
  15453. return arr2;
  15454. }
  15455. }
  15456. module.exports = _arrayWithoutHoles;
  15457. },{}],54:[function(_dereq_,module,exports){
  15458. function _assertThisInitialized(self) {
  15459. if (self === void 0) {
  15460. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  15461. }
  15462. return self;
  15463. }
  15464. module.exports = _assertThisInitialized;
  15465. },{}],55:[function(_dereq_,module,exports){
  15466. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  15467. try {
  15468. var info = gen[key](arg);
  15469. var value = info.value;
  15470. } catch (error) {
  15471. reject(error);
  15472. return;
  15473. }
  15474. if (info.done) {
  15475. resolve(value);
  15476. } else {
  15477. Promise.resolve(value).then(_next, _throw);
  15478. }
  15479. }
  15480. function _asyncToGenerator(fn) {
  15481. return function () {
  15482. var self = this,
  15483. args = arguments;
  15484. return new Promise(function (resolve, reject) {
  15485. var gen = fn.apply(self, args);
  15486. function _next(value) {
  15487. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
  15488. }
  15489. function _throw(err) {
  15490. asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
  15491. }
  15492. _next(undefined);
  15493. });
  15494. };
  15495. }
  15496. module.exports = _asyncToGenerator;
  15497. },{}],56:[function(_dereq_,module,exports){
  15498. function _classCallCheck(instance, Constructor) {
  15499. if (!(instance instanceof Constructor)) {
  15500. throw new TypeError("Cannot call a class as a function");
  15501. }
  15502. }
  15503. module.exports = _classCallCheck;
  15504. },{}],57:[function(_dereq_,module,exports){
  15505. var setPrototypeOf = _dereq_("./setPrototypeOf");
  15506. function isNativeReflectConstruct() {
  15507. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  15508. if (Reflect.construct.sham) return false;
  15509. if (typeof Proxy === "function") return true;
  15510. try {
  15511. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  15512. return true;
  15513. } catch (e) {
  15514. return false;
  15515. }
  15516. }
  15517. function _construct(Parent, args, Class) {
  15518. if (isNativeReflectConstruct()) {
  15519. module.exports = _construct = Reflect.construct;
  15520. } else {
  15521. module.exports = _construct = function _construct(Parent, args, Class) {
  15522. var a = [null];
  15523. a.push.apply(a, args);
  15524. var Constructor = Function.bind.apply(Parent, a);
  15525. var instance = new Constructor();
  15526. if (Class) setPrototypeOf(instance, Class.prototype);
  15527. return instance;
  15528. };
  15529. }
  15530. return _construct.apply(null, arguments);
  15531. }
  15532. module.exports = _construct;
  15533. },{"./setPrototypeOf":71}],58:[function(_dereq_,module,exports){
  15534. function _defineProperties(target, props) {
  15535. for (var i = 0; i < props.length; i++) {
  15536. var descriptor = props[i];
  15537. descriptor.enumerable = descriptor.enumerable || false;
  15538. descriptor.configurable = true;
  15539. if ("value" in descriptor) descriptor.writable = true;
  15540. Object.defineProperty(target, descriptor.key, descriptor);
  15541. }
  15542. }
  15543. function _createClass(Constructor, protoProps, staticProps) {
  15544. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  15545. if (staticProps) _defineProperties(Constructor, staticProps);
  15546. return Constructor;
  15547. }
  15548. module.exports = _createClass;
  15549. },{}],59:[function(_dereq_,module,exports){
  15550. function _defineProperty(obj, key, value) {
  15551. if (key in obj) {
  15552. Object.defineProperty(obj, key, {
  15553. value: value,
  15554. enumerable: true,
  15555. configurable: true,
  15556. writable: true
  15557. });
  15558. } else {
  15559. obj[key] = value;
  15560. }
  15561. return obj;
  15562. }
  15563. module.exports = _defineProperty;
  15564. },{}],60:[function(_dereq_,module,exports){
  15565. var superPropBase = _dereq_("./superPropBase");
  15566. function _get(target, property, receiver) {
  15567. if (typeof Reflect !== "undefined" && Reflect.get) {
  15568. module.exports = _get = Reflect.get;
  15569. } else {
  15570. module.exports = _get = function _get(target, property, receiver) {
  15571. var base = superPropBase(target, property);
  15572. if (!base) return;
  15573. var desc = Object.getOwnPropertyDescriptor(base, property);
  15574. if (desc.get) {
  15575. return desc.get.call(receiver);
  15576. }
  15577. return desc.value;
  15578. };
  15579. }
  15580. return _get(target, property, receiver || target);
  15581. }
  15582. module.exports = _get;
  15583. },{"./superPropBase":73}],61:[function(_dereq_,module,exports){
  15584. function _getPrototypeOf(o) {
  15585. module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  15586. return o.__proto__ || Object.getPrototypeOf(o);
  15587. };
  15588. return _getPrototypeOf(o);
  15589. }
  15590. module.exports = _getPrototypeOf;
  15591. },{}],62:[function(_dereq_,module,exports){
  15592. var setPrototypeOf = _dereq_("./setPrototypeOf");
  15593. function _inherits(subClass, superClass) {
  15594. if (typeof superClass !== "function" && superClass !== null) {
  15595. throw new TypeError("Super expression must either be null or a function");
  15596. }
  15597. subClass.prototype = Object.create(superClass && superClass.prototype, {
  15598. constructor: {
  15599. value: subClass,
  15600. writable: true,
  15601. configurable: true
  15602. }
  15603. });
  15604. if (superClass) setPrototypeOf(subClass, superClass);
  15605. }
  15606. module.exports = _inherits;
  15607. },{"./setPrototypeOf":71}],63:[function(_dereq_,module,exports){
  15608. function _interopRequireDefault(obj) {
  15609. return obj && obj.__esModule ? obj : {
  15610. "default": obj
  15611. };
  15612. }
  15613. module.exports = _interopRequireDefault;
  15614. },{}],64:[function(_dereq_,module,exports){
  15615. function _interopRequireWildcard(obj) {
  15616. if (obj && obj.__esModule) {
  15617. return obj;
  15618. } else {
  15619. var newObj = {};
  15620. if (obj != null) {
  15621. for (var key in obj) {
  15622. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  15623. var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
  15624. if (desc.get || desc.set) {
  15625. Object.defineProperty(newObj, key, desc);
  15626. } else {
  15627. newObj[key] = obj[key];
  15628. }
  15629. }
  15630. }
  15631. }
  15632. newObj["default"] = obj;
  15633. return newObj;
  15634. }
  15635. }
  15636. module.exports = _interopRequireWildcard;
  15637. },{}],65:[function(_dereq_,module,exports){
  15638. function _isNativeFunction(fn) {
  15639. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  15640. }
  15641. module.exports = _isNativeFunction;
  15642. },{}],66:[function(_dereq_,module,exports){
  15643. function _iterableToArray(iter) {
  15644. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  15645. }
  15646. module.exports = _iterableToArray;
  15647. },{}],67:[function(_dereq_,module,exports){
  15648. function _iterableToArrayLimit(arr, i) {
  15649. var _arr = [];
  15650. var _n = true;
  15651. var _d = false;
  15652. var _e = undefined;
  15653. try {
  15654. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  15655. _arr.push(_s.value);
  15656. if (i && _arr.length === i) break;
  15657. }
  15658. } catch (err) {
  15659. _d = true;
  15660. _e = err;
  15661. } finally {
  15662. try {
  15663. if (!_n && _i["return"] != null) _i["return"]();
  15664. } finally {
  15665. if (_d) throw _e;
  15666. }
  15667. }
  15668. return _arr;
  15669. }
  15670. module.exports = _iterableToArrayLimit;
  15671. },{}],68:[function(_dereq_,module,exports){
  15672. function _nonIterableRest() {
  15673. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  15674. }
  15675. module.exports = _nonIterableRest;
  15676. },{}],69:[function(_dereq_,module,exports){
  15677. function _nonIterableSpread() {
  15678. throw new TypeError("Invalid attempt to spread non-iterable instance");
  15679. }
  15680. module.exports = _nonIterableSpread;
  15681. },{}],70:[function(_dereq_,module,exports){
  15682. var _typeof = _dereq_("../helpers/typeof");
  15683. var assertThisInitialized = _dereq_("./assertThisInitialized");
  15684. function _possibleConstructorReturn(self, call) {
  15685. if (call && (_typeof(call) === "object" || typeof call === "function")) {
  15686. return call;
  15687. }
  15688. return assertThisInitialized(self);
  15689. }
  15690. module.exports = _possibleConstructorReturn;
  15691. },{"../helpers/typeof":75,"./assertThisInitialized":54}],71:[function(_dereq_,module,exports){
  15692. function _setPrototypeOf(o, p) {
  15693. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  15694. o.__proto__ = p;
  15695. return o;
  15696. };
  15697. return _setPrototypeOf(o, p);
  15698. }
  15699. module.exports = _setPrototypeOf;
  15700. },{}],72:[function(_dereq_,module,exports){
  15701. var arrayWithHoles = _dereq_("./arrayWithHoles");
  15702. var iterableToArrayLimit = _dereq_("./iterableToArrayLimit");
  15703. var nonIterableRest = _dereq_("./nonIterableRest");
  15704. function _slicedToArray(arr, i) {
  15705. return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();
  15706. }
  15707. module.exports = _slicedToArray;
  15708. },{"./arrayWithHoles":52,"./iterableToArrayLimit":67,"./nonIterableRest":68}],73:[function(_dereq_,module,exports){
  15709. var getPrototypeOf = _dereq_("./getPrototypeOf");
  15710. function _superPropBase(object, property) {
  15711. while (!Object.prototype.hasOwnProperty.call(object, property)) {
  15712. object = getPrototypeOf(object);
  15713. if (object === null) break;
  15714. }
  15715. return object;
  15716. }
  15717. module.exports = _superPropBase;
  15718. },{"./getPrototypeOf":61}],74:[function(_dereq_,module,exports){
  15719. var arrayWithoutHoles = _dereq_("./arrayWithoutHoles");
  15720. var iterableToArray = _dereq_("./iterableToArray");
  15721. var nonIterableSpread = _dereq_("./nonIterableSpread");
  15722. function _toConsumableArray(arr) {
  15723. return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
  15724. }
  15725. module.exports = _toConsumableArray;
  15726. },{"./arrayWithoutHoles":53,"./iterableToArray":66,"./nonIterableSpread":69}],75:[function(_dereq_,module,exports){
  15727. 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); }
  15728. function _typeof(obj) {
  15729. if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
  15730. module.exports = _typeof = function _typeof(obj) {
  15731. return _typeof2(obj);
  15732. };
  15733. } else {
  15734. module.exports = _typeof = function _typeof(obj) {
  15735. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
  15736. };
  15737. }
  15738. return _typeof(obj);
  15739. }
  15740. module.exports = _typeof;
  15741. },{}],76:[function(_dereq_,module,exports){
  15742. var getPrototypeOf = _dereq_("./getPrototypeOf");
  15743. var setPrototypeOf = _dereq_("./setPrototypeOf");
  15744. var isNativeFunction = _dereq_("./isNativeFunction");
  15745. var construct = _dereq_("./construct");
  15746. function _wrapNativeSuper(Class) {
  15747. var _cache = typeof Map === "function" ? new Map() : undefined;
  15748. module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) {
  15749. if (Class === null || !isNativeFunction(Class)) return Class;
  15750. if (typeof Class !== "function") {
  15751. throw new TypeError("Super expression must either be null or a function");
  15752. }
  15753. if (typeof _cache !== "undefined") {
  15754. if (_cache.has(Class)) return _cache.get(Class);
  15755. _cache.set(Class, Wrapper);
  15756. }
  15757. function Wrapper() {
  15758. return construct(Class, arguments, getPrototypeOf(this).constructor);
  15759. }
  15760. Wrapper.prototype = Object.create(Class.prototype, {
  15761. constructor: {
  15762. value: Wrapper,
  15763. enumerable: false,
  15764. writable: true,
  15765. configurable: true
  15766. }
  15767. });
  15768. return setPrototypeOf(Wrapper, Class);
  15769. };
  15770. return _wrapNativeSuper(Class);
  15771. }
  15772. module.exports = _wrapNativeSuper;
  15773. },{"./construct":57,"./getPrototypeOf":61,"./isNativeFunction":65,"./setPrototypeOf":71}],77:[function(_dereq_,module,exports){
  15774. /**
  15775. * Copyright (c) 2014-present, Facebook, Inc.
  15776. *
  15777. * This source code is licensed under the MIT license found in the
  15778. * LICENSE file in the root directory of this source tree.
  15779. */
  15780. var runtime = (function (exports) {
  15781. "use strict";
  15782. var Op = Object.prototype;
  15783. var hasOwn = Op.hasOwnProperty;
  15784. var undefined; // More compressible than void 0.
  15785. var $Symbol = typeof Symbol === "function" ? Symbol : {};
  15786. var iteratorSymbol = $Symbol.iterator || "@@iterator";
  15787. var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  15788. var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  15789. function wrap(innerFn, outerFn, self, tryLocsList) {
  15790. // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
  15791. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
  15792. var generator = Object.create(protoGenerator.prototype);
  15793. var context = new Context(tryLocsList || []);
  15794. // The ._invoke method unifies the implementations of the .next,
  15795. // .throw, and .return methods.
  15796. generator._invoke = makeInvokeMethod(innerFn, self, context);
  15797. return generator;
  15798. }
  15799. exports.wrap = wrap;
  15800. // Try/catch helper to minimize deoptimizations. Returns a completion
  15801. // record like context.tryEntries[i].completion. This interface could
  15802. // have been (and was previously) designed to take a closure to be
  15803. // invoked without arguments, but in all the cases we care about we
  15804. // already have an existing method we want to call, so there's no need
  15805. // to create a new function object. We can even get away with assuming
  15806. // the method takes exactly one argument, since that happens to be true
  15807. // in every case, so we don't have to touch the arguments object. The
  15808. // only additional allocation required is the completion record, which
  15809. // has a stable shape and so hopefully should be cheap to allocate.
  15810. function tryCatch(fn, obj, arg) {
  15811. try {
  15812. return { type: "normal", arg: fn.call(obj, arg) };
  15813. } catch (err) {
  15814. return { type: "throw", arg: err };
  15815. }
  15816. }
  15817. var GenStateSuspendedStart = "suspendedStart";
  15818. var GenStateSuspendedYield = "suspendedYield";
  15819. var GenStateExecuting = "executing";
  15820. var GenStateCompleted = "completed";
  15821. // Returning this object from the innerFn has the same effect as
  15822. // breaking out of the dispatch switch statement.
  15823. var ContinueSentinel = {};
  15824. // Dummy constructor functions that we use as the .constructor and
  15825. // .constructor.prototype properties for functions that return Generator
  15826. // objects. For full spec compliance, you may wish to configure your
  15827. // minifier not to mangle the names of these two functions.
  15828. function Generator() {}
  15829. function GeneratorFunction() {}
  15830. function GeneratorFunctionPrototype() {}
  15831. // This is a polyfill for %IteratorPrototype% for environments that
  15832. // don't natively support it.
  15833. var IteratorPrototype = {};
  15834. IteratorPrototype[iteratorSymbol] = function () {
  15835. return this;
  15836. };
  15837. var getProto = Object.getPrototypeOf;
  15838. var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  15839. if (NativeIteratorPrototype &&
  15840. NativeIteratorPrototype !== Op &&
  15841. hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
  15842. // This environment has a native %IteratorPrototype%; use it instead
  15843. // of the polyfill.
  15844. IteratorPrototype = NativeIteratorPrototype;
  15845. }
  15846. var Gp = GeneratorFunctionPrototype.prototype =
  15847. Generator.prototype = Object.create(IteratorPrototype);
  15848. GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  15849. GeneratorFunctionPrototype.constructor = GeneratorFunction;
  15850. GeneratorFunctionPrototype[toStringTagSymbol] =
  15851. GeneratorFunction.displayName = "GeneratorFunction";
  15852. // Helper for defining the .next, .throw, and .return methods of the
  15853. // Iterator interface in terms of a single ._invoke method.
  15854. function defineIteratorMethods(prototype) {
  15855. ["next", "throw", "return"].forEach(function(method) {
  15856. prototype[method] = function(arg) {
  15857. return this._invoke(method, arg);
  15858. };
  15859. });
  15860. }
  15861. exports.isGeneratorFunction = function(genFun) {
  15862. var ctor = typeof genFun === "function" && genFun.constructor;
  15863. return ctor
  15864. ? ctor === GeneratorFunction ||
  15865. // For the native GeneratorFunction constructor, the best we can
  15866. // do is to check its .name property.
  15867. (ctor.displayName || ctor.name) === "GeneratorFunction"
  15868. : false;
  15869. };
  15870. exports.mark = function(genFun) {
  15871. if (Object.setPrototypeOf) {
  15872. Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
  15873. } else {
  15874. genFun.__proto__ = GeneratorFunctionPrototype;
  15875. if (!(toStringTagSymbol in genFun)) {
  15876. genFun[toStringTagSymbol] = "GeneratorFunction";
  15877. }
  15878. }
  15879. genFun.prototype = Object.create(Gp);
  15880. return genFun;
  15881. };
  15882. // Within the body of any async function, `await x` is transformed to
  15883. // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  15884. // `hasOwn.call(value, "__await")` to determine if the yielded value is
  15885. // meant to be awaited.
  15886. exports.awrap = function(arg) {
  15887. return { __await: arg };
  15888. };
  15889. function AsyncIterator(generator) {
  15890. function invoke(method, arg, resolve, reject) {
  15891. var record = tryCatch(generator[method], generator, arg);
  15892. if (record.type === "throw") {
  15893. reject(record.arg);
  15894. } else {
  15895. var result = record.arg;
  15896. var value = result.value;
  15897. if (value &&
  15898. typeof value === "object" &&
  15899. hasOwn.call(value, "__await")) {
  15900. return Promise.resolve(value.__await).then(function(value) {
  15901. invoke("next", value, resolve, reject);
  15902. }, function(err) {
  15903. invoke("throw", err, resolve, reject);
  15904. });
  15905. }
  15906. return Promise.resolve(value).then(function(unwrapped) {
  15907. // When a yielded Promise is resolved, its final value becomes
  15908. // the .value of the Promise<{value,done}> result for the
  15909. // current iteration.
  15910. result.value = unwrapped;
  15911. resolve(result);
  15912. }, function(error) {
  15913. // If a rejected Promise was yielded, throw the rejection back
  15914. // into the async generator function so it can be handled there.
  15915. return invoke("throw", error, resolve, reject);
  15916. });
  15917. }
  15918. }
  15919. var previousPromise;
  15920. function enqueue(method, arg) {
  15921. function callInvokeWithMethodAndArg() {
  15922. return new Promise(function(resolve, reject) {
  15923. invoke(method, arg, resolve, reject);
  15924. });
  15925. }
  15926. return previousPromise =
  15927. // If enqueue has been called before, then we want to wait until
  15928. // all previous Promises have been resolved before calling invoke,
  15929. // so that results are always delivered in the correct order. If
  15930. // enqueue has not been called before, then it is important to
  15931. // call invoke immediately, without waiting on a callback to fire,
  15932. // so that the async generator function has the opportunity to do
  15933. // any necessary setup in a predictable way. This predictability
  15934. // is why the Promise constructor synchronously invokes its
  15935. // executor callback, and why async functions synchronously
  15936. // execute code before the first await. Since we implement simple
  15937. // async functions in terms of async generators, it is especially
  15938. // important to get this right, even though it requires care.
  15939. previousPromise ? previousPromise.then(
  15940. callInvokeWithMethodAndArg,
  15941. // Avoid propagating failures to Promises returned by later
  15942. // invocations of the iterator.
  15943. callInvokeWithMethodAndArg
  15944. ) : callInvokeWithMethodAndArg();
  15945. }
  15946. // Define the unified helper method that is used to implement .next,
  15947. // .throw, and .return (see defineIteratorMethods).
  15948. this._invoke = enqueue;
  15949. }
  15950. defineIteratorMethods(AsyncIterator.prototype);
  15951. AsyncIterator.prototype[asyncIteratorSymbol] = function () {
  15952. return this;
  15953. };
  15954. exports.AsyncIterator = AsyncIterator;
  15955. // Note that simple async functions are implemented on top of
  15956. // AsyncIterator objects; they just return a Promise for the value of
  15957. // the final result produced by the iterator.
  15958. exports.async = function(innerFn, outerFn, self, tryLocsList) {
  15959. var iter = new AsyncIterator(
  15960. wrap(innerFn, outerFn, self, tryLocsList)
  15961. );
  15962. return exports.isGeneratorFunction(outerFn)
  15963. ? iter // If outerFn is a generator, return the full iterator.
  15964. : iter.next().then(function(result) {
  15965. return result.done ? result.value : iter.next();
  15966. });
  15967. };
  15968. function makeInvokeMethod(innerFn, self, context) {
  15969. var state = GenStateSuspendedStart;
  15970. return function invoke(method, arg) {
  15971. if (state === GenStateExecuting) {
  15972. throw new Error("Generator is already running");
  15973. }
  15974. if (state === GenStateCompleted) {
  15975. if (method === "throw") {
  15976. throw arg;
  15977. }
  15978. // Be forgiving, per 25.3.3.3.3 of the spec:
  15979. // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
  15980. return doneResult();
  15981. }
  15982. context.method = method;
  15983. context.arg = arg;
  15984. while (true) {
  15985. var delegate = context.delegate;
  15986. if (delegate) {
  15987. var delegateResult = maybeInvokeDelegate(delegate, context);
  15988. if (delegateResult) {
  15989. if (delegateResult === ContinueSentinel) continue;
  15990. return delegateResult;
  15991. }
  15992. }
  15993. if (context.method === "next") {
  15994. // Setting context._sent for legacy support of Babel's
  15995. // function.sent implementation.
  15996. context.sent = context._sent = context.arg;
  15997. } else if (context.method === "throw") {
  15998. if (state === GenStateSuspendedStart) {
  15999. state = GenStateCompleted;
  16000. throw context.arg;
  16001. }
  16002. context.dispatchException(context.arg);
  16003. } else if (context.method === "return") {
  16004. context.abrupt("return", context.arg);
  16005. }
  16006. state = GenStateExecuting;
  16007. var record = tryCatch(innerFn, self, context);
  16008. if (record.type === "normal") {
  16009. // If an exception is thrown from innerFn, we leave state ===
  16010. // GenStateExecuting and loop back for another invocation.
  16011. state = context.done
  16012. ? GenStateCompleted
  16013. : GenStateSuspendedYield;
  16014. if (record.arg === ContinueSentinel) {
  16015. continue;
  16016. }
  16017. return {
  16018. value: record.arg,
  16019. done: context.done
  16020. };
  16021. } else if (record.type === "throw") {
  16022. state = GenStateCompleted;
  16023. // Dispatch the exception by looping back around to the
  16024. // context.dispatchException(context.arg) call above.
  16025. context.method = "throw";
  16026. context.arg = record.arg;
  16027. }
  16028. }
  16029. };
  16030. }
  16031. // Call delegate.iterator[context.method](context.arg) and handle the
  16032. // result, either by returning a { value, done } result from the
  16033. // delegate iterator, or by modifying context.method and context.arg,
  16034. // setting context.delegate to null, and returning the ContinueSentinel.
  16035. function maybeInvokeDelegate(delegate, context) {
  16036. var method = delegate.iterator[context.method];
  16037. if (method === undefined) {
  16038. // A .throw or .return when the delegate iterator has no .throw
  16039. // method always terminates the yield* loop.
  16040. context.delegate = null;
  16041. if (context.method === "throw") {
  16042. // Note: ["return"] must be used for ES3 parsing compatibility.
  16043. if (delegate.iterator["return"]) {
  16044. // If the delegate iterator has a return method, give it a
  16045. // chance to clean up.
  16046. context.method = "return";
  16047. context.arg = undefined;
  16048. maybeInvokeDelegate(delegate, context);
  16049. if (context.method === "throw") {
  16050. // If maybeInvokeDelegate(context) changed context.method from
  16051. // "return" to "throw", let that override the TypeError below.
  16052. return ContinueSentinel;
  16053. }
  16054. }
  16055. context.method = "throw";
  16056. context.arg = new TypeError(
  16057. "The iterator does not provide a 'throw' method");
  16058. }
  16059. return ContinueSentinel;
  16060. }
  16061. var record = tryCatch(method, delegate.iterator, context.arg);
  16062. if (record.type === "throw") {
  16063. context.method = "throw";
  16064. context.arg = record.arg;
  16065. context.delegate = null;
  16066. return ContinueSentinel;
  16067. }
  16068. var info = record.arg;
  16069. if (! info) {
  16070. context.method = "throw";
  16071. context.arg = new TypeError("iterator result is not an object");
  16072. context.delegate = null;
  16073. return ContinueSentinel;
  16074. }
  16075. if (info.done) {
  16076. // Assign the result of the finished delegate to the temporary
  16077. // variable specified by delegate.resultName (see delegateYield).
  16078. context[delegate.resultName] = info.value;
  16079. // Resume execution at the desired location (see delegateYield).
  16080. context.next = delegate.nextLoc;
  16081. // If context.method was "throw" but the delegate handled the
  16082. // exception, let the outer generator proceed normally. If
  16083. // context.method was "next", forget context.arg since it has been
  16084. // "consumed" by the delegate iterator. If context.method was
  16085. // "return", allow the original .return call to continue in the
  16086. // outer generator.
  16087. if (context.method !== "return") {
  16088. context.method = "next";
  16089. context.arg = undefined;
  16090. }
  16091. } else {
  16092. // Re-yield the result returned by the delegate method.
  16093. return info;
  16094. }
  16095. // The delegate iterator is finished, so forget it and continue with
  16096. // the outer generator.
  16097. context.delegate = null;
  16098. return ContinueSentinel;
  16099. }
  16100. // Define Generator.prototype.{next,throw,return} in terms of the
  16101. // unified ._invoke helper method.
  16102. defineIteratorMethods(Gp);
  16103. Gp[toStringTagSymbol] = "Generator";
  16104. // A Generator should always return itself as the iterator object when the
  16105. // @@iterator function is called on it. Some browsers' implementations of the
  16106. // iterator prototype chain incorrectly implement this, causing the Generator
  16107. // object to not be returned from this call. This ensures that doesn't happen.
  16108. // See https://github.com/facebook/regenerator/issues/274 for more details.
  16109. Gp[iteratorSymbol] = function() {
  16110. return this;
  16111. };
  16112. Gp.toString = function() {
  16113. return "[object Generator]";
  16114. };
  16115. function pushTryEntry(locs) {
  16116. var entry = { tryLoc: locs[0] };
  16117. if (1 in locs) {
  16118. entry.catchLoc = locs[1];
  16119. }
  16120. if (2 in locs) {
  16121. entry.finallyLoc = locs[2];
  16122. entry.afterLoc = locs[3];
  16123. }
  16124. this.tryEntries.push(entry);
  16125. }
  16126. function resetTryEntry(entry) {
  16127. var record = entry.completion || {};
  16128. record.type = "normal";
  16129. delete record.arg;
  16130. entry.completion = record;
  16131. }
  16132. function Context(tryLocsList) {
  16133. // The root entry object (effectively a try statement without a catch
  16134. // or a finally block) gives us a place to store values thrown from
  16135. // locations where there is no enclosing try statement.
  16136. this.tryEntries = [{ tryLoc: "root" }];
  16137. tryLocsList.forEach(pushTryEntry, this);
  16138. this.reset(true);
  16139. }
  16140. exports.keys = function(object) {
  16141. var keys = [];
  16142. for (var key in object) {
  16143. keys.push(key);
  16144. }
  16145. keys.reverse();
  16146. // Rather than returning an object with a next method, we keep
  16147. // things simple and return the next function itself.
  16148. return function next() {
  16149. while (keys.length) {
  16150. var key = keys.pop();
  16151. if (key in object) {
  16152. next.value = key;
  16153. next.done = false;
  16154. return next;
  16155. }
  16156. }
  16157. // To avoid creating an additional object, we just hang the .value
  16158. // and .done properties off the next function object itself. This
  16159. // also ensures that the minifier will not anonymize the function.
  16160. next.done = true;
  16161. return next;
  16162. };
  16163. };
  16164. function values(iterable) {
  16165. if (iterable) {
  16166. var iteratorMethod = iterable[iteratorSymbol];
  16167. if (iteratorMethod) {
  16168. return iteratorMethod.call(iterable);
  16169. }
  16170. if (typeof iterable.next === "function") {
  16171. return iterable;
  16172. }
  16173. if (!isNaN(iterable.length)) {
  16174. var i = -1, next = function next() {
  16175. while (++i < iterable.length) {
  16176. if (hasOwn.call(iterable, i)) {
  16177. next.value = iterable[i];
  16178. next.done = false;
  16179. return next;
  16180. }
  16181. }
  16182. next.value = undefined;
  16183. next.done = true;
  16184. return next;
  16185. };
  16186. return next.next = next;
  16187. }
  16188. }
  16189. // Return an iterator with no values.
  16190. return { next: doneResult };
  16191. }
  16192. exports.values = values;
  16193. function doneResult() {
  16194. return { value: undefined, done: true };
  16195. }
  16196. Context.prototype = {
  16197. constructor: Context,
  16198. reset: function(skipTempReset) {
  16199. this.prev = 0;
  16200. this.next = 0;
  16201. // Resetting context._sent for legacy support of Babel's
  16202. // function.sent implementation.
  16203. this.sent = this._sent = undefined;
  16204. this.done = false;
  16205. this.delegate = null;
  16206. this.method = "next";
  16207. this.arg = undefined;
  16208. this.tryEntries.forEach(resetTryEntry);
  16209. if (!skipTempReset) {
  16210. for (var name in this) {
  16211. // Not sure about the optimal order of these conditions:
  16212. if (name.charAt(0) === "t" &&
  16213. hasOwn.call(this, name) &&
  16214. !isNaN(+name.slice(1))) {
  16215. this[name] = undefined;
  16216. }
  16217. }
  16218. }
  16219. },
  16220. stop: function() {
  16221. this.done = true;
  16222. var rootEntry = this.tryEntries[0];
  16223. var rootRecord = rootEntry.completion;
  16224. if (rootRecord.type === "throw") {
  16225. throw rootRecord.arg;
  16226. }
  16227. return this.rval;
  16228. },
  16229. dispatchException: function(exception) {
  16230. if (this.done) {
  16231. throw exception;
  16232. }
  16233. var context = this;
  16234. function handle(loc, caught) {
  16235. record.type = "throw";
  16236. record.arg = exception;
  16237. context.next = loc;
  16238. if (caught) {
  16239. // If the dispatched exception was caught by a catch block,
  16240. // then let that catch block handle the exception normally.
  16241. context.method = "next";
  16242. context.arg = undefined;
  16243. }
  16244. return !! caught;
  16245. }
  16246. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  16247. var entry = this.tryEntries[i];
  16248. var record = entry.completion;
  16249. if (entry.tryLoc === "root") {
  16250. // Exception thrown outside of any try block that could handle
  16251. // it, so set the completion value of the entire function to
  16252. // throw the exception.
  16253. return handle("end");
  16254. }
  16255. if (entry.tryLoc <= this.prev) {
  16256. var hasCatch = hasOwn.call(entry, "catchLoc");
  16257. var hasFinally = hasOwn.call(entry, "finallyLoc");
  16258. if (hasCatch && hasFinally) {
  16259. if (this.prev < entry.catchLoc) {
  16260. return handle(entry.catchLoc, true);
  16261. } else if (this.prev < entry.finallyLoc) {
  16262. return handle(entry.finallyLoc);
  16263. }
  16264. } else if (hasCatch) {
  16265. if (this.prev < entry.catchLoc) {
  16266. return handle(entry.catchLoc, true);
  16267. }
  16268. } else if (hasFinally) {
  16269. if (this.prev < entry.finallyLoc) {
  16270. return handle(entry.finallyLoc);
  16271. }
  16272. } else {
  16273. throw new Error("try statement without catch or finally");
  16274. }
  16275. }
  16276. }
  16277. },
  16278. abrupt: function(type, arg) {
  16279. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  16280. var entry = this.tryEntries[i];
  16281. if (entry.tryLoc <= this.prev &&
  16282. hasOwn.call(entry, "finallyLoc") &&
  16283. this.prev < entry.finallyLoc) {
  16284. var finallyEntry = entry;
  16285. break;
  16286. }
  16287. }
  16288. if (finallyEntry &&
  16289. (type === "break" ||
  16290. type === "continue") &&
  16291. finallyEntry.tryLoc <= arg &&
  16292. arg <= finallyEntry.finallyLoc) {
  16293. // Ignore the finally entry if control is not jumping to a
  16294. // location outside the try/catch block.
  16295. finallyEntry = null;
  16296. }
  16297. var record = finallyEntry ? finallyEntry.completion : {};
  16298. record.type = type;
  16299. record.arg = arg;
  16300. if (finallyEntry) {
  16301. this.method = "next";
  16302. this.next = finallyEntry.finallyLoc;
  16303. return ContinueSentinel;
  16304. }
  16305. return this.complete(record);
  16306. },
  16307. complete: function(record, afterLoc) {
  16308. if (record.type === "throw") {
  16309. throw record.arg;
  16310. }
  16311. if (record.type === "break" ||
  16312. record.type === "continue") {
  16313. this.next = record.arg;
  16314. } else if (record.type === "return") {
  16315. this.rval = this.arg = record.arg;
  16316. this.method = "return";
  16317. this.next = "end";
  16318. } else if (record.type === "normal" && afterLoc) {
  16319. this.next = afterLoc;
  16320. }
  16321. return ContinueSentinel;
  16322. },
  16323. finish: function(finallyLoc) {
  16324. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  16325. var entry = this.tryEntries[i];
  16326. if (entry.finallyLoc === finallyLoc) {
  16327. this.complete(entry.completion, entry.afterLoc);
  16328. resetTryEntry(entry);
  16329. return ContinueSentinel;
  16330. }
  16331. }
  16332. },
  16333. "catch": function(tryLoc) {
  16334. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  16335. var entry = this.tryEntries[i];
  16336. if (entry.tryLoc === tryLoc) {
  16337. var record = entry.completion;
  16338. if (record.type === "throw") {
  16339. var thrown = record.arg;
  16340. resetTryEntry(entry);
  16341. }
  16342. return thrown;
  16343. }
  16344. }
  16345. // The context.catch method must only be called with a location
  16346. // argument that corresponds to a known catch block.
  16347. throw new Error("illegal catch attempt");
  16348. },
  16349. delegateYield: function(iterable, resultName, nextLoc) {
  16350. this.delegate = {
  16351. iterator: values(iterable),
  16352. resultName: resultName,
  16353. nextLoc: nextLoc
  16354. };
  16355. if (this.method === "next") {
  16356. // Deliberately forget the last sent value so that we don't
  16357. // accidentally pass it on to the delegate.
  16358. this.arg = undefined;
  16359. }
  16360. return ContinueSentinel;
  16361. }
  16362. };
  16363. // Regardless of whether this script is executing as a CommonJS module
  16364. // or not, return the runtime object so that we can declare the variable
  16365. // regeneratorRuntime in the outer scope, which allows this module to be
  16366. // injected easily by `bin/regenerator --include-runtime script.js`.
  16367. return exports;
  16368. }(
  16369. // If this script is executing as a CommonJS module, use module.exports
  16370. // as the regeneratorRuntime namespace. Otherwise create a new empty
  16371. // object. Either way, the resulting object will be used to initialize
  16372. // the regeneratorRuntime variable at the top of this file.
  16373. typeof module === "object" ? module.exports : {}
  16374. ));
  16375. try {
  16376. regeneratorRuntime = runtime;
  16377. } catch (accidentalStrictMode) {
  16378. // This module should not be running in strict mode, so the above
  16379. // assignment should always work unless something is misconfigured. Just
  16380. // in case runtime.js accidentally runs in strict mode, we can escape
  16381. // strict mode using a global Function call. This could conceivably fail
  16382. // if a Content Security Policy forbids using Function, but in that case
  16383. // the proper solution is to fix the accidental strict mode problem. If
  16384. // you've misconfigured your bundler to force strict mode and applied a
  16385. // CSP to forbid Function, and you're not willing to fix either of those
  16386. // problems, please detail your unique predicament in a GitHub issue.
  16387. Function("r", "regeneratorRuntime = r")(runtime);
  16388. }
  16389. },{}],78:[function(_dereq_,module,exports){
  16390. module.exports = _dereq_("regenerator-runtime");
  16391. },{"regenerator-runtime":77}],79:[function(_dereq_,module,exports){
  16392. },{}],80:[function(_dereq_,module,exports){
  16393. // Copyright Joyent, Inc. and other Node contributors.
  16394. //
  16395. // Permission is hereby granted, free of charge, to any person obtaining a
  16396. // copy of this software and associated documentation files (the
  16397. // "Software"), to deal in the Software without restriction, including
  16398. // without limitation the rights to use, copy, modify, merge, publish,
  16399. // distribute, sublicense, and/or sell copies of the Software, and to permit
  16400. // persons to whom the Software is furnished to do so, subject to the
  16401. // following conditions:
  16402. //
  16403. // The above copyright notice and this permission notice shall be included
  16404. // in all copies or substantial portions of the Software.
  16405. //
  16406. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16407. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16408. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  16409. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  16410. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  16411. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  16412. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  16413. var objectCreate = Object.create || objectCreatePolyfill
  16414. var objectKeys = Object.keys || objectKeysPolyfill
  16415. var bind = Function.prototype.bind || functionBindPolyfill
  16416. function EventEmitter() {
  16417. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  16418. this._events = objectCreate(null);
  16419. this._eventsCount = 0;
  16420. }
  16421. this._maxListeners = this._maxListeners || undefined;
  16422. }
  16423. module.exports = EventEmitter;
  16424. // Backwards-compat with node 0.10.x
  16425. EventEmitter.EventEmitter = EventEmitter;
  16426. EventEmitter.prototype._events = undefined;
  16427. EventEmitter.prototype._maxListeners = undefined;
  16428. // By default EventEmitters will print a warning if more than 10 listeners are
  16429. // added to it. This is a useful default which helps finding memory leaks.
  16430. var defaultMaxListeners = 10;
  16431. var hasDefineProperty;
  16432. try {
  16433. var o = {};
  16434. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  16435. hasDefineProperty = o.x === 0;
  16436. } catch (err) { hasDefineProperty = false }
  16437. if (hasDefineProperty) {
  16438. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  16439. enumerable: true,
  16440. get: function() {
  16441. return defaultMaxListeners;
  16442. },
  16443. set: function(arg) {
  16444. // check whether the input is a positive number (whose value is zero or
  16445. // greater and not a NaN).
  16446. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  16447. throw new TypeError('"defaultMaxListeners" must be a positive number');
  16448. defaultMaxListeners = arg;
  16449. }
  16450. });
  16451. } else {
  16452. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  16453. }
  16454. // Obviously not all Emitters should be limited to 10. This function allows
  16455. // that to be increased. Set to zero for unlimited.
  16456. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  16457. if (typeof n !== 'number' || n < 0 || isNaN(n))
  16458. throw new TypeError('"n" argument must be a positive number');
  16459. this._maxListeners = n;
  16460. return this;
  16461. };
  16462. function $getMaxListeners(that) {
  16463. if (that._maxListeners === undefined)
  16464. return EventEmitter.defaultMaxListeners;
  16465. return that._maxListeners;
  16466. }
  16467. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  16468. return $getMaxListeners(this);
  16469. };
  16470. // These standalone emit* functions are used to optimize calling of event
  16471. // handlers for fast cases because emit() itself often has a variable number of
  16472. // arguments and can be deoptimized because of that. These functions always have
  16473. // the same number of arguments and thus do not get deoptimized, so the code
  16474. // inside them can execute faster.
  16475. function emitNone(handler, isFn, self) {
  16476. if (isFn)
  16477. handler.call(self);
  16478. else {
  16479. var len = handler.length;
  16480. var listeners = arrayClone(handler, len);
  16481. for (var i = 0; i < len; ++i)
  16482. listeners[i].call(self);
  16483. }
  16484. }
  16485. function emitOne(handler, isFn, self, arg1) {
  16486. if (isFn)
  16487. handler.call(self, arg1);
  16488. else {
  16489. var len = handler.length;
  16490. var listeners = arrayClone(handler, len);
  16491. for (var i = 0; i < len; ++i)
  16492. listeners[i].call(self, arg1);
  16493. }
  16494. }
  16495. function emitTwo(handler, isFn, self, arg1, arg2) {
  16496. if (isFn)
  16497. handler.call(self, arg1, arg2);
  16498. else {
  16499. var len = handler.length;
  16500. var listeners = arrayClone(handler, len);
  16501. for (var i = 0; i < len; ++i)
  16502. listeners[i].call(self, arg1, arg2);
  16503. }
  16504. }
  16505. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  16506. if (isFn)
  16507. handler.call(self, arg1, arg2, arg3);
  16508. else {
  16509. var len = handler.length;
  16510. var listeners = arrayClone(handler, len);
  16511. for (var i = 0; i < len; ++i)
  16512. listeners[i].call(self, arg1, arg2, arg3);
  16513. }
  16514. }
  16515. function emitMany(handler, isFn, self, args) {
  16516. if (isFn)
  16517. handler.apply(self, args);
  16518. else {
  16519. var len = handler.length;
  16520. var listeners = arrayClone(handler, len);
  16521. for (var i = 0; i < len; ++i)
  16522. listeners[i].apply(self, args);
  16523. }
  16524. }
  16525. EventEmitter.prototype.emit = function emit(type) {
  16526. var er, handler, len, args, i, events;
  16527. var doError = (type === 'error');
  16528. events = this._events;
  16529. if (events)
  16530. doError = (doError && events.error == null);
  16531. else if (!doError)
  16532. return false;
  16533. // If there is no 'error' event listener then throw.
  16534. if (doError) {
  16535. if (arguments.length > 1)
  16536. er = arguments[1];
  16537. if (er instanceof Error) {
  16538. throw er; // Unhandled 'error' event
  16539. } else {
  16540. // At least give some kind of context to the user
  16541. var err = new Error('Unhandled "error" event. (' + er + ')');
  16542. err.context = er;
  16543. throw err;
  16544. }
  16545. return false;
  16546. }
  16547. handler = events[type];
  16548. if (!handler)
  16549. return false;
  16550. var isFn = typeof handler === 'function';
  16551. len = arguments.length;
  16552. switch (len) {
  16553. // fast cases
  16554. case 1:
  16555. emitNone(handler, isFn, this);
  16556. break;
  16557. case 2:
  16558. emitOne(handler, isFn, this, arguments[1]);
  16559. break;
  16560. case 3:
  16561. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  16562. break;
  16563. case 4:
  16564. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  16565. break;
  16566. // slower
  16567. default:
  16568. args = new Array(len - 1);
  16569. for (i = 1; i < len; i++)
  16570. args[i - 1] = arguments[i];
  16571. emitMany(handler, isFn, this, args);
  16572. }
  16573. return true;
  16574. };
  16575. function _addListener(target, type, listener, prepend) {
  16576. var m;
  16577. var events;
  16578. var existing;
  16579. if (typeof listener !== 'function')
  16580. throw new TypeError('"listener" argument must be a function');
  16581. events = target._events;
  16582. if (!events) {
  16583. events = target._events = objectCreate(null);
  16584. target._eventsCount = 0;
  16585. } else {
  16586. // To avoid recursion in the case that type === "newListener"! Before
  16587. // adding it to the listeners, first emit "newListener".
  16588. if (events.newListener) {
  16589. target.emit('newListener', type,
  16590. listener.listener ? listener.listener : listener);
  16591. // Re-assign `events` because a newListener handler could have caused the
  16592. // this._events to be assigned to a new object
  16593. events = target._events;
  16594. }
  16595. existing = events[type];
  16596. }
  16597. if (!existing) {
  16598. // Optimize the case of one listener. Don't need the extra array object.
  16599. existing = events[type] = listener;
  16600. ++target._eventsCount;
  16601. } else {
  16602. if (typeof existing === 'function') {
  16603. // Adding the second element, need to change to array.
  16604. existing = events[type] =
  16605. prepend ? [listener, existing] : [existing, listener];
  16606. } else {
  16607. // If we've already got an array, just append.
  16608. if (prepend) {
  16609. existing.unshift(listener);
  16610. } else {
  16611. existing.push(listener);
  16612. }
  16613. }
  16614. // Check for listener leak
  16615. if (!existing.warned) {
  16616. m = $getMaxListeners(target);
  16617. if (m && m > 0 && existing.length > m) {
  16618. existing.warned = true;
  16619. var w = new Error('Possible EventEmitter memory leak detected. ' +
  16620. existing.length + ' "' + String(type) + '" listeners ' +
  16621. 'added. Use emitter.setMaxListeners() to ' +
  16622. 'increase limit.');
  16623. w.name = 'MaxListenersExceededWarning';
  16624. w.emitter = target;
  16625. w.type = type;
  16626. w.count = existing.length;
  16627. if (typeof console === 'object' && console.warn) {
  16628. console.warn('%s: %s', w.name, w.message);
  16629. }
  16630. }
  16631. }
  16632. }
  16633. return target;
  16634. }
  16635. EventEmitter.prototype.addListener = function addListener(type, listener) {
  16636. return _addListener(this, type, listener, false);
  16637. };
  16638. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  16639. EventEmitter.prototype.prependListener =
  16640. function prependListener(type, listener) {
  16641. return _addListener(this, type, listener, true);
  16642. };
  16643. function onceWrapper() {
  16644. if (!this.fired) {
  16645. this.target.removeListener(this.type, this.wrapFn);
  16646. this.fired = true;
  16647. switch (arguments.length) {
  16648. case 0:
  16649. return this.listener.call(this.target);
  16650. case 1:
  16651. return this.listener.call(this.target, arguments[0]);
  16652. case 2:
  16653. return this.listener.call(this.target, arguments[0], arguments[1]);
  16654. case 3:
  16655. return this.listener.call(this.target, arguments[0], arguments[1],
  16656. arguments[2]);
  16657. default:
  16658. var args = new Array(arguments.length);
  16659. for (var i = 0; i < args.length; ++i)
  16660. args[i] = arguments[i];
  16661. this.listener.apply(this.target, args);
  16662. }
  16663. }
  16664. }
  16665. function _onceWrap(target, type, listener) {
  16666. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  16667. var wrapped = bind.call(onceWrapper, state);
  16668. wrapped.listener = listener;
  16669. state.wrapFn = wrapped;
  16670. return wrapped;
  16671. }
  16672. EventEmitter.prototype.once = function once(type, listener) {
  16673. if (typeof listener !== 'function')
  16674. throw new TypeError('"listener" argument must be a function');
  16675. this.on(type, _onceWrap(this, type, listener));
  16676. return this;
  16677. };
  16678. EventEmitter.prototype.prependOnceListener =
  16679. function prependOnceListener(type, listener) {
  16680. if (typeof listener !== 'function')
  16681. throw new TypeError('"listener" argument must be a function');
  16682. this.prependListener(type, _onceWrap(this, type, listener));
  16683. return this;
  16684. };
  16685. // Emits a 'removeListener' event if and only if the listener was removed.
  16686. EventEmitter.prototype.removeListener =
  16687. function removeListener(type, listener) {
  16688. var list, events, position, i, originalListener;
  16689. if (typeof listener !== 'function')
  16690. throw new TypeError('"listener" argument must be a function');
  16691. events = this._events;
  16692. if (!events)
  16693. return this;
  16694. list = events[type];
  16695. if (!list)
  16696. return this;
  16697. if (list === listener || list.listener === listener) {
  16698. if (--this._eventsCount === 0)
  16699. this._events = objectCreate(null);
  16700. else {
  16701. delete events[type];
  16702. if (events.removeListener)
  16703. this.emit('removeListener', type, list.listener || listener);
  16704. }
  16705. } else if (typeof list !== 'function') {
  16706. position = -1;
  16707. for (i = list.length - 1; i >= 0; i--) {
  16708. if (list[i] === listener || list[i].listener === listener) {
  16709. originalListener = list[i].listener;
  16710. position = i;
  16711. break;
  16712. }
  16713. }
  16714. if (position < 0)
  16715. return this;
  16716. if (position === 0)
  16717. list.shift();
  16718. else
  16719. spliceOne(list, position);
  16720. if (list.length === 1)
  16721. events[type] = list[0];
  16722. if (events.removeListener)
  16723. this.emit('removeListener', type, originalListener || listener);
  16724. }
  16725. return this;
  16726. };
  16727. EventEmitter.prototype.removeAllListeners =
  16728. function removeAllListeners(type) {
  16729. var listeners, events, i;
  16730. events = this._events;
  16731. if (!events)
  16732. return this;
  16733. // not listening for removeListener, no need to emit
  16734. if (!events.removeListener) {
  16735. if (arguments.length === 0) {
  16736. this._events = objectCreate(null);
  16737. this._eventsCount = 0;
  16738. } else if (events[type]) {
  16739. if (--this._eventsCount === 0)
  16740. this._events = objectCreate(null);
  16741. else
  16742. delete events[type];
  16743. }
  16744. return this;
  16745. }
  16746. // emit removeListener for all listeners on all events
  16747. if (arguments.length === 0) {
  16748. var keys = objectKeys(events);
  16749. var key;
  16750. for (i = 0; i < keys.length; ++i) {
  16751. key = keys[i];
  16752. if (key === 'removeListener') continue;
  16753. this.removeAllListeners(key);
  16754. }
  16755. this.removeAllListeners('removeListener');
  16756. this._events = objectCreate(null);
  16757. this._eventsCount = 0;
  16758. return this;
  16759. }
  16760. listeners = events[type];
  16761. if (typeof listeners === 'function') {
  16762. this.removeListener(type, listeners);
  16763. } else if (listeners) {
  16764. // LIFO order
  16765. for (i = listeners.length - 1; i >= 0; i--) {
  16766. this.removeListener(type, listeners[i]);
  16767. }
  16768. }
  16769. return this;
  16770. };
  16771. function _listeners(target, type, unwrap) {
  16772. var events = target._events;
  16773. if (!events)
  16774. return [];
  16775. var evlistener = events[type];
  16776. if (!evlistener)
  16777. return [];
  16778. if (typeof evlistener === 'function')
  16779. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  16780. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  16781. }
  16782. EventEmitter.prototype.listeners = function listeners(type) {
  16783. return _listeners(this, type, true);
  16784. };
  16785. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  16786. return _listeners(this, type, false);
  16787. };
  16788. EventEmitter.listenerCount = function(emitter, type) {
  16789. if (typeof emitter.listenerCount === 'function') {
  16790. return emitter.listenerCount(type);
  16791. } else {
  16792. return listenerCount.call(emitter, type);
  16793. }
  16794. };
  16795. EventEmitter.prototype.listenerCount = listenerCount;
  16796. function listenerCount(type) {
  16797. var events = this._events;
  16798. if (events) {
  16799. var evlistener = events[type];
  16800. if (typeof evlistener === 'function') {
  16801. return 1;
  16802. } else if (evlistener) {
  16803. return evlistener.length;
  16804. }
  16805. }
  16806. return 0;
  16807. }
  16808. EventEmitter.prototype.eventNames = function eventNames() {
  16809. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  16810. };
  16811. // About 1.5x faster than the two-arg version of Array#splice().
  16812. function spliceOne(list, index) {
  16813. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  16814. list[i] = list[k];
  16815. list.pop();
  16816. }
  16817. function arrayClone(arr, n) {
  16818. var copy = new Array(n);
  16819. for (var i = 0; i < n; ++i)
  16820. copy[i] = arr[i];
  16821. return copy;
  16822. }
  16823. function unwrapListeners(arr) {
  16824. var ret = new Array(arr.length);
  16825. for (var i = 0; i < ret.length; ++i) {
  16826. ret[i] = arr[i].listener || arr[i];
  16827. }
  16828. return ret;
  16829. }
  16830. function objectCreatePolyfill(proto) {
  16831. var F = function() {};
  16832. F.prototype = proto;
  16833. return new F;
  16834. }
  16835. function objectKeysPolyfill(obj) {
  16836. var keys = [];
  16837. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  16838. keys.push(k);
  16839. }
  16840. return k;
  16841. }
  16842. function functionBindPolyfill(context) {
  16843. var fn = this;
  16844. return function () {
  16845. return fn.apply(context, arguments);
  16846. };
  16847. }
  16848. },{}],81:[function(_dereq_,module,exports){
  16849. /**
  16850. * Convert array of 16 byte values to UUID string format of the form:
  16851. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  16852. */
  16853. var byteToHex = [];
  16854. for (var i = 0; i < 256; ++i) {
  16855. byteToHex[i] = (i + 0x100).toString(16).substr(1);
  16856. }
  16857. function bytesToUuid(buf, offset) {
  16858. var i = offset || 0;
  16859. var bth = byteToHex;
  16860. // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
  16861. return ([bth[buf[i++]], bth[buf[i++]],
  16862. bth[buf[i++]], bth[buf[i++]], '-',
  16863. bth[buf[i++]], bth[buf[i++]], '-',
  16864. bth[buf[i++]], bth[buf[i++]], '-',
  16865. bth[buf[i++]], bth[buf[i++]], '-',
  16866. bth[buf[i++]], bth[buf[i++]],
  16867. bth[buf[i++]], bth[buf[i++]],
  16868. bth[buf[i++]], bth[buf[i++]]]).join('');
  16869. }
  16870. module.exports = bytesToUuid;
  16871. },{}],82:[function(_dereq_,module,exports){
  16872. // Unique ID creation requires a high quality random # generator. In the
  16873. // browser this is a little complicated due to unknown quality of Math.random()
  16874. // and inconsistent support for the `crypto` API. We do the best we can via
  16875. // feature-detection
  16876. // getRandomValues needs to be invoked in a context where "this" is a Crypto
  16877. // implementation. Also, find the complete implementation of crypto on IE11.
  16878. var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
  16879. (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
  16880. if (getRandomValues) {
  16881. // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
  16882. var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
  16883. module.exports = function whatwgRNG() {
  16884. getRandomValues(rnds8);
  16885. return rnds8;
  16886. };
  16887. } else {
  16888. // Math.random()-based (RNG)
  16889. //
  16890. // If all else fails, use Math.random(). It's fast, but is of unspecified
  16891. // quality.
  16892. var rnds = new Array(16);
  16893. module.exports = function mathRNG() {
  16894. for (var i = 0, r; i < 16; i++) {
  16895. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  16896. rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  16897. }
  16898. return rnds;
  16899. };
  16900. }
  16901. },{}],83:[function(_dereq_,module,exports){
  16902. var rng = _dereq_('./lib/rng');
  16903. var bytesToUuid = _dereq_('./lib/bytesToUuid');
  16904. function v4(options, buf, offset) {
  16905. var i = buf && offset || 0;
  16906. if (typeof(options) == 'string') {
  16907. buf = options === 'binary' ? new Array(16) : null;
  16908. options = null;
  16909. }
  16910. options = options || {};
  16911. var rnds = options.random || (options.rng || rng)();
  16912. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  16913. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  16914. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  16915. // Copy bytes to buffer, if provided
  16916. if (buf) {
  16917. for (var ii = 0; ii < 16; ++ii) {
  16918. buf[i + ii] = rnds[ii];
  16919. }
  16920. }
  16921. return buf || bytesToUuid(rnds);
  16922. }
  16923. module.exports = v4;
  16924. },{"./lib/bytesToUuid":81,"./lib/rng":82}]},{},[15])(15)
  16925. });