lively.vm_standalone.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885
  1. // INLINED /Users/user/git/lively.vm/node_modules/babel-regenerator-runtime/runtime.js
  2. /**
  3. * Copyright (c) 2014, Facebook, Inc.
  4. * All rights reserved.
  5. *
  6. * This source code is licensed under the BSD-style license found in the
  7. * https://raw.github.com/facebook/regenerator/master/LICENSE file. An
  8. * additional grant of patent rights can be found in the PATENTS file in
  9. * the same directory.
  10. */
  11. !(function(global) {
  12. "use strict";
  13. var hasOwn = Object.prototype.hasOwnProperty;
  14. var undefined; // More compressible than void 0.
  15. var iteratorSymbol =
  16. typeof Symbol === "function" && Symbol.iterator || "@@iterator";
  17. var inModule = typeof module === "object";
  18. var runtime = global.regeneratorRuntime;
  19. if (runtime) {
  20. if (inModule) {
  21. // If regeneratorRuntime is defined globally and we're in a module,
  22. // make the exports object identical to regeneratorRuntime.
  23. module.exports = runtime;
  24. }
  25. // Don't bother evaluating the rest of this file if the runtime was
  26. // already defined globally.
  27. return;
  28. }
  29. // Define the runtime globally (as expected by generated code) as either
  30. // module.exports (if we're in a module) or a new, empty object.
  31. runtime = global.regeneratorRuntime = inModule ? module.exports : {};
  32. function wrap(innerFn, outerFn, self, tryLocsList) {
  33. // If outerFn provided, then outerFn.prototype instanceof Generator.
  34. var generator = Object.create((outerFn || Generator).prototype);
  35. var context = new Context(tryLocsList || []);
  36. // The ._invoke method unifies the implementations of the .next,
  37. // .throw, and .return methods.
  38. generator._invoke = makeInvokeMethod(innerFn, self, context);
  39. return generator;
  40. }
  41. runtime.wrap = wrap;
  42. // Try/catch helper to minimize deoptimizations. Returns a completion
  43. // record like context.tryEntries[i].completion. This interface could
  44. // have been (and was previously) designed to take a closure to be
  45. // invoked without arguments, but in all the cases we care about we
  46. // already have an existing method we want to call, so there's no need
  47. // to create a new function object. We can even get away with assuming
  48. // the method takes exactly one argument, since that happens to be true
  49. // in every case, so we don't have to touch the arguments object. The
  50. // only additional allocation required is the completion record, which
  51. // has a stable shape and so hopefully should be cheap to allocate.
  52. function tryCatch(fn, obj, arg) {
  53. try {
  54. return { type: "normal", arg: fn.call(obj, arg) };
  55. } catch (err) {
  56. return { type: "throw", arg: err };
  57. }
  58. }
  59. var GenStateSuspendedStart = "suspendedStart";
  60. var GenStateSuspendedYield = "suspendedYield";
  61. var GenStateExecuting = "executing";
  62. var GenStateCompleted = "completed";
  63. // Returning this object from the innerFn has the same effect as
  64. // breaking out of the dispatch switch statement.
  65. var ContinueSentinel = {};
  66. // Dummy constructor functions that we use as the .constructor and
  67. // .constructor.prototype properties for functions that return Generator
  68. // objects. For full spec compliance, you may wish to configure your
  69. // minifier not to mangle the names of these two functions.
  70. function Generator() {}
  71. function GeneratorFunction() {}
  72. function GeneratorFunctionPrototype() {}
  73. var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype;
  74. GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  75. GeneratorFunctionPrototype.constructor = GeneratorFunction;
  76. GeneratorFunction.displayName = "GeneratorFunction";
  77. // Helper for defining the .next, .throw, and .return methods of the
  78. // Iterator interface in terms of a single ._invoke method.
  79. function defineIteratorMethods(prototype) {
  80. ["next", "throw", "return"].forEach(function(method) {
  81. prototype[method] = function(arg) {
  82. return this._invoke(method, arg);
  83. };
  84. });
  85. }
  86. runtime.isGeneratorFunction = function(genFun) {
  87. var ctor = typeof genFun === "function" && genFun.constructor;
  88. return ctor
  89. ? ctor === GeneratorFunction ||
  90. // For the native GeneratorFunction constructor, the best we can
  91. // do is to check its .name property.
  92. (ctor.displayName || ctor.name) === "GeneratorFunction"
  93. : false;
  94. };
  95. runtime.mark = function(genFun) {
  96. if (Object.setPrototypeOf) {
  97. Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
  98. } else {
  99. genFun.__proto__ = GeneratorFunctionPrototype;
  100. }
  101. genFun.prototype = Object.create(Gp);
  102. return genFun;
  103. };
  104. // Within the body of any async function, `await x` is transformed to
  105. // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  106. // `value instanceof AwaitArgument` to determine if the yielded value is
  107. // meant to be awaited. Some may consider the name of this method too
  108. // cutesy, but they are curmudgeons.
  109. runtime.awrap = function(arg) {
  110. return new AwaitArgument(arg);
  111. };
  112. function AwaitArgument(arg) {
  113. this.arg = arg;
  114. }
  115. function AsyncIterator(generator) {
  116. // This invoke function is written in a style that assumes some
  117. // calling function (or Promise) will handle exceptions.
  118. function invoke(method, arg) {
  119. var result = generator[method](arg);
  120. var value = result.value;
  121. return value instanceof AwaitArgument
  122. ? Promise.resolve(value.arg).then(invokeNext, invokeThrow)
  123. : Promise.resolve(value).then(function(unwrapped) {
  124. // When a yielded Promise is resolved, its final value becomes
  125. // the .value of the Promise<{value,done}> result for the
  126. // current iteration. If the Promise is rejected, however, the
  127. // result for this iteration will be rejected with the same
  128. // reason. Note that rejections of yielded Promises are not
  129. // thrown back into the generator function, as is the case
  130. // when an awaited Promise is rejected. This difference in
  131. // behavior between yield and await is important, because it
  132. // allows the consumer to decide what to do with the yielded
  133. // rejection (swallow it and continue, manually .throw it back
  134. // into the generator, abandon iteration, whatever). With
  135. // await, by contrast, there is no opportunity to examine the
  136. // rejection reason outside the generator function, so the
  137. // only option is to throw it from the await expression, and
  138. // let the generator function handle the exception.
  139. result.value = unwrapped;
  140. return result;
  141. });
  142. }
  143. if (typeof process === "object" && process.domain) {
  144. invoke = process.domain.bind(invoke);
  145. }
  146. var invokeNext = invoke.bind(generator, "next");
  147. var invokeThrow = invoke.bind(generator, "throw");
  148. var invokeReturn = invoke.bind(generator, "return");
  149. var previousPromise;
  150. function enqueue(method, arg) {
  151. function callInvokeWithMethodAndArg() {
  152. return invoke(method, arg);
  153. }
  154. return previousPromise =
  155. // If enqueue has been called before, then we want to wait until
  156. // all previous Promises have been resolved before calling invoke,
  157. // so that results are always delivered in the correct order. If
  158. // enqueue has not been called before, then it is important to
  159. // call invoke immediately, without waiting on a callback to fire,
  160. // so that the async generator function has the opportunity to do
  161. // any necessary setup in a predictable way. This predictability
  162. // is why the Promise constructor synchronously invokes its
  163. // executor callback, and why async functions synchronously
  164. // execute code before the first await. Since we implement simple
  165. // async functions in terms of async generators, it is especially
  166. // important to get this right, even though it requires care.
  167. previousPromise ? previousPromise.then(
  168. callInvokeWithMethodAndArg,
  169. // Avoid propagating failures to Promises returned by later
  170. // invocations of the iterator.
  171. callInvokeWithMethodAndArg
  172. ) : new Promise(function (resolve) {
  173. resolve(callInvokeWithMethodAndArg());
  174. });
  175. }
  176. // Define the unified helper method that is used to implement .next,
  177. // .throw, and .return (see defineIteratorMethods).
  178. this._invoke = enqueue;
  179. }
  180. defineIteratorMethods(AsyncIterator.prototype);
  181. // Note that simple async functions are implemented on top of
  182. // AsyncIterator objects; they just return a Promise for the value of
  183. // the final result produced by the iterator.
  184. runtime.async = function(innerFn, outerFn, self, tryLocsList) {
  185. var iter = new AsyncIterator(
  186. wrap(innerFn, outerFn, self, tryLocsList)
  187. );
  188. return runtime.isGeneratorFunction(outerFn)
  189. ? iter // If outerFn is a generator, return the full iterator.
  190. : iter.next().then(function(result) {
  191. return result.done ? result.value : iter.next();
  192. });
  193. };
  194. function makeInvokeMethod(innerFn, self, context) {
  195. var state = GenStateSuspendedStart;
  196. return function invoke(method, arg) {
  197. if (state === GenStateExecuting) {
  198. throw new Error("Generator is already running");
  199. }
  200. if (state === GenStateCompleted) {
  201. if (method === "throw") {
  202. throw arg;
  203. }
  204. // Be forgiving, per 25.3.3.3.3 of the spec:
  205. // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
  206. return doneResult();
  207. }
  208. while (true) {
  209. var delegate = context.delegate;
  210. if (delegate) {
  211. if (method === "return" ||
  212. (method === "throw" && delegate.iterator[method] === undefined)) {
  213. // A return or throw (when the delegate iterator has no throw
  214. // method) always terminates the yield* loop.
  215. context.delegate = null;
  216. // If the delegate iterator has a return method, give it a
  217. // chance to clean up.
  218. var returnMethod = delegate.iterator["return"];
  219. if (returnMethod) {
  220. var record = tryCatch(returnMethod, delegate.iterator, arg);
  221. if (record.type === "throw") {
  222. // If the return method threw an exception, let that
  223. // exception prevail over the original return or throw.
  224. method = "throw";
  225. arg = record.arg;
  226. continue;
  227. }
  228. }
  229. if (method === "return") {
  230. // Continue with the outer return, now that the delegate
  231. // iterator has been terminated.
  232. continue;
  233. }
  234. }
  235. var record = tryCatch(
  236. delegate.iterator[method],
  237. delegate.iterator,
  238. arg
  239. );
  240. if (record.type === "throw") {
  241. context.delegate = null;
  242. // Like returning generator.throw(uncaught), but without the
  243. // overhead of an extra function call.
  244. method = "throw";
  245. arg = record.arg;
  246. continue;
  247. }
  248. // Delegate generator ran and handled its own exceptions so
  249. // regardless of what the method was, we continue as if it is
  250. // "next" with an undefined arg.
  251. method = "next";
  252. arg = undefined;
  253. var info = record.arg;
  254. if (info.done) {
  255. context[delegate.resultName] = info.value;
  256. context.next = delegate.nextLoc;
  257. } else {
  258. state = GenStateSuspendedYield;
  259. return info;
  260. }
  261. context.delegate = null;
  262. }
  263. if (method === "next") {
  264. context._sent = arg;
  265. if (state === GenStateSuspendedYield) {
  266. context.sent = arg;
  267. } else {
  268. context.sent = undefined;
  269. }
  270. } else if (method === "throw") {
  271. if (state === GenStateSuspendedStart) {
  272. state = GenStateCompleted;
  273. throw arg;
  274. }
  275. if (context.dispatchException(arg)) {
  276. // If the dispatched exception was caught by a catch block,
  277. // then let that catch block handle the exception normally.
  278. method = "next";
  279. arg = undefined;
  280. }
  281. } else if (method === "return") {
  282. context.abrupt("return", arg);
  283. }
  284. state = GenStateExecuting;
  285. var record = tryCatch(innerFn, self, context);
  286. if (record.type === "normal") {
  287. // If an exception is thrown from innerFn, we leave state ===
  288. // GenStateExecuting and loop back for another invocation.
  289. state = context.done
  290. ? GenStateCompleted
  291. : GenStateSuspendedYield;
  292. var info = {
  293. value: record.arg,
  294. done: context.done
  295. };
  296. if (record.arg === ContinueSentinel) {
  297. if (context.delegate && method === "next") {
  298. // Deliberately forget the last sent value so that we don't
  299. // accidentally pass it on to the delegate.
  300. arg = undefined;
  301. }
  302. } else {
  303. return info;
  304. }
  305. } else if (record.type === "throw") {
  306. state = GenStateCompleted;
  307. // Dispatch the exception by looping back around to the
  308. // context.dispatchException(arg) call above.
  309. method = "throw";
  310. arg = record.arg;
  311. }
  312. }
  313. };
  314. }
  315. // Define Generator.prototype.{next,throw,return} in terms of the
  316. // unified ._invoke helper method.
  317. defineIteratorMethods(Gp);
  318. Gp[iteratorSymbol] = function() {
  319. return this;
  320. };
  321. Gp.toString = function() {
  322. return "[object Generator]";
  323. };
  324. function pushTryEntry(locs) {
  325. var entry = { tryLoc: locs[0] };
  326. if (1 in locs) {
  327. entry.catchLoc = locs[1];
  328. }
  329. if (2 in locs) {
  330. entry.finallyLoc = locs[2];
  331. entry.afterLoc = locs[3];
  332. }
  333. this.tryEntries.push(entry);
  334. }
  335. function resetTryEntry(entry) {
  336. var record = entry.completion || {};
  337. record.type = "normal";
  338. delete record.arg;
  339. entry.completion = record;
  340. }
  341. function Context(tryLocsList) {
  342. // The root entry object (effectively a try statement without a catch
  343. // or a finally block) gives us a place to store values thrown from
  344. // locations where there is no enclosing try statement.
  345. this.tryEntries = [{ tryLoc: "root" }];
  346. tryLocsList.forEach(pushTryEntry, this);
  347. this.reset(true);
  348. }
  349. runtime.keys = function(object) {
  350. var keys = [];
  351. for (var key in object) {
  352. keys.push(key);
  353. }
  354. keys.reverse();
  355. // Rather than returning an object with a next method, we keep
  356. // things simple and return the next function itself.
  357. return function next() {
  358. while (keys.length) {
  359. var key = keys.pop();
  360. if (key in object) {
  361. next.value = key;
  362. next.done = false;
  363. return next;
  364. }
  365. }
  366. // To avoid creating an additional object, we just hang the .value
  367. // and .done properties off the next function object itself. This
  368. // also ensures that the minifier will not anonymize the function.
  369. next.done = true;
  370. return next;
  371. };
  372. };
  373. function values(iterable) {
  374. if (iterable) {
  375. var iteratorMethod = iterable[iteratorSymbol];
  376. if (iteratorMethod) {
  377. return iteratorMethod.call(iterable);
  378. }
  379. if (typeof iterable.next === "function") {
  380. return iterable;
  381. }
  382. if (!isNaN(iterable.length)) {
  383. var i = -1, next = function next() {
  384. while (++i < iterable.length) {
  385. if (hasOwn.call(iterable, i)) {
  386. next.value = iterable[i];
  387. next.done = false;
  388. return next;
  389. }
  390. }
  391. next.value = undefined;
  392. next.done = true;
  393. return next;
  394. };
  395. return next.next = next;
  396. }
  397. }
  398. // Return an iterator with no values.
  399. return { next: doneResult };
  400. }
  401. runtime.values = values;
  402. function doneResult() {
  403. return { value: undefined, done: true };
  404. }
  405. Context.prototype = {
  406. constructor: Context,
  407. reset: function(skipTempReset) {
  408. this.prev = 0;
  409. this.next = 0;
  410. this.sent = undefined;
  411. this.done = false;
  412. this.delegate = null;
  413. this.tryEntries.forEach(resetTryEntry);
  414. if (!skipTempReset) {
  415. for (var name in this) {
  416. // Not sure about the optimal order of these conditions:
  417. if (name.charAt(0) === "t" &&
  418. hasOwn.call(this, name) &&
  419. !isNaN(+name.slice(1))) {
  420. this[name] = undefined;
  421. }
  422. }
  423. }
  424. },
  425. stop: function() {
  426. this.done = true;
  427. var rootEntry = this.tryEntries[0];
  428. var rootRecord = rootEntry.completion;
  429. if (rootRecord.type === "throw") {
  430. throw rootRecord.arg;
  431. }
  432. return this.rval;
  433. },
  434. dispatchException: function(exception) {
  435. if (this.done) {
  436. throw exception;
  437. }
  438. var context = this;
  439. function handle(loc, caught) {
  440. record.type = "throw";
  441. record.arg = exception;
  442. context.next = loc;
  443. return !!caught;
  444. }
  445. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  446. var entry = this.tryEntries[i];
  447. var record = entry.completion;
  448. if (entry.tryLoc === "root") {
  449. // Exception thrown outside of any try block that could handle
  450. // it, so set the completion value of the entire function to
  451. // throw the exception.
  452. return handle("end");
  453. }
  454. if (entry.tryLoc <= this.prev) {
  455. var hasCatch = hasOwn.call(entry, "catchLoc");
  456. var hasFinally = hasOwn.call(entry, "finallyLoc");
  457. if (hasCatch && hasFinally) {
  458. if (this.prev < entry.catchLoc) {
  459. return handle(entry.catchLoc, true);
  460. } else if (this.prev < entry.finallyLoc) {
  461. return handle(entry.finallyLoc);
  462. }
  463. } else if (hasCatch) {
  464. if (this.prev < entry.catchLoc) {
  465. return handle(entry.catchLoc, true);
  466. }
  467. } else if (hasFinally) {
  468. if (this.prev < entry.finallyLoc) {
  469. return handle(entry.finallyLoc);
  470. }
  471. } else {
  472. throw new Error("try statement without catch or finally");
  473. }
  474. }
  475. }
  476. },
  477. abrupt: function(type, arg) {
  478. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  479. var entry = this.tryEntries[i];
  480. if (entry.tryLoc <= this.prev &&
  481. hasOwn.call(entry, "finallyLoc") &&
  482. this.prev < entry.finallyLoc) {
  483. var finallyEntry = entry;
  484. break;
  485. }
  486. }
  487. if (finallyEntry &&
  488. (type === "break" ||
  489. type === "continue") &&
  490. finallyEntry.tryLoc <= arg &&
  491. arg <= finallyEntry.finallyLoc) {
  492. // Ignore the finally entry if control is not jumping to a
  493. // location outside the try/catch block.
  494. finallyEntry = null;
  495. }
  496. var record = finallyEntry ? finallyEntry.completion : {};
  497. record.type = type;
  498. record.arg = arg;
  499. if (finallyEntry) {
  500. this.next = finallyEntry.finallyLoc;
  501. } else {
  502. this.complete(record);
  503. }
  504. return ContinueSentinel;
  505. },
  506. complete: function(record, afterLoc) {
  507. if (record.type === "throw") {
  508. throw record.arg;
  509. }
  510. if (record.type === "break" ||
  511. record.type === "continue") {
  512. this.next = record.arg;
  513. } else if (record.type === "return") {
  514. this.rval = record.arg;
  515. this.next = "end";
  516. } else if (record.type === "normal" && afterLoc) {
  517. this.next = afterLoc;
  518. }
  519. },
  520. finish: function(finallyLoc) {
  521. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  522. var entry = this.tryEntries[i];
  523. if (entry.finallyLoc === finallyLoc) {
  524. this.complete(entry.completion, entry.afterLoc);
  525. resetTryEntry(entry);
  526. return ContinueSentinel;
  527. }
  528. }
  529. },
  530. "catch": function(tryLoc) {
  531. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  532. var entry = this.tryEntries[i];
  533. if (entry.tryLoc === tryLoc) {
  534. var record = entry.completion;
  535. if (record.type === "throw") {
  536. var thrown = record.arg;
  537. resetTryEntry(entry);
  538. }
  539. return thrown;
  540. }
  541. }
  542. // The context.catch method must only be called with a location
  543. // argument that corresponds to a known catch block.
  544. throw new Error("illegal catch attempt");
  545. },
  546. delegateYield: function(iterable, resultName, nextLoc) {
  547. this.delegate = {
  548. iterator: values(iterable),
  549. resultName: resultName,
  550. nextLoc: nextLoc
  551. };
  552. return ContinueSentinel;
  553. }
  554. };
  555. })(
  556. // Among the various tricks for obtaining a reference to the global
  557. // object, this seems to be the most reliable technique that does not
  558. // use indirect eval (which violates Content Security Policy).
  559. typeof global === "object" ? global :
  560. typeof window === "object" ? window :
  561. typeof self === "object" ? self : this
  562. );
  563. // INLINED END /Users/user/git/lively.vm/node_modules/babel-regenerator-runtime/runtime.js
  564. // INLINED /Users/user/git/lively.vm/node_modules/lively.lang/dist/lively.lang.js
  565. (function() {
  566. var GLOBAL = typeof window !== "undefined" ? window :
  567. typeof global!=="undefined" ? global :
  568. typeof self!=="undefined" ? self : this;
  569. if (typeof GLOBAL.lively === "undefined") GLOBAL.lively = {};
  570. (function() {
  571. this.lively = this.lively || {};
  572. (function (exports,lively_sourceTransform) {
  573. 'use strict';
  574. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  575. return typeof obj;
  576. } : function (obj) {
  577. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  578. };
  579. var asyncGenerator = function () {
  580. function AwaitValue(value) {
  581. this.value = value;
  582. }
  583. function AsyncGenerator(gen) {
  584. var front, back;
  585. function send(key, arg) {
  586. return new Promise(function (resolve, reject) {
  587. var request = {
  588. key: key,
  589. arg: arg,
  590. resolve: resolve,
  591. reject: reject,
  592. next: null
  593. };
  594. if (back) {
  595. back = back.next = request;
  596. } else {
  597. front = back = request;
  598. resume(key, arg);
  599. }
  600. });
  601. }
  602. function resume(key, arg) {
  603. try {
  604. var result = gen[key](arg);
  605. var value = result.value;
  606. if (value instanceof AwaitValue) {
  607. Promise.resolve(value.value).then(function (arg) {
  608. resume("next", arg);
  609. }, function (arg) {
  610. resume("throw", arg);
  611. });
  612. } else {
  613. settle(result.done ? "return" : "normal", result.value);
  614. }
  615. } catch (err) {
  616. settle("throw", err);
  617. }
  618. }
  619. function settle(type, value) {
  620. switch (type) {
  621. case "return":
  622. front.resolve({
  623. value: value,
  624. done: true
  625. });
  626. break;
  627. case "throw":
  628. front.reject(value);
  629. break;
  630. default:
  631. front.resolve({
  632. value: value,
  633. done: false
  634. });
  635. break;
  636. }
  637. front = front.next;
  638. if (front) {
  639. resume(front.key, front.arg);
  640. } else {
  641. back = null;
  642. }
  643. }
  644. this._invoke = send;
  645. if (typeof gen.return !== "function") {
  646. this.return = undefined;
  647. }
  648. }
  649. if (typeof Symbol === "function" && Symbol.asyncIterator) {
  650. AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
  651. return this;
  652. };
  653. }
  654. AsyncGenerator.prototype.next = function (arg) {
  655. return this._invoke("next", arg);
  656. };
  657. AsyncGenerator.prototype.throw = function (arg) {
  658. return this._invoke("throw", arg);
  659. };
  660. AsyncGenerator.prototype.return = function (arg) {
  661. return this._invoke("return", arg);
  662. };
  663. return {
  664. wrap: function (fn) {
  665. return function () {
  666. return new AsyncGenerator(fn.apply(this, arguments));
  667. };
  668. },
  669. await: function (value) {
  670. return new AwaitValue(value);
  671. }
  672. };
  673. }();
  674. var classCallCheck = function (instance, Constructor) {
  675. if (!(instance instanceof Constructor)) {
  676. throw new TypeError("Cannot call a class as a function");
  677. }
  678. };
  679. var createClass = function () {
  680. function defineProperties(target, props) {
  681. for (var i = 0; i < props.length; i++) {
  682. var descriptor = props[i];
  683. descriptor.enumerable = descriptor.enumerable || false;
  684. descriptor.configurable = true;
  685. if ("value" in descriptor) descriptor.writable = true;
  686. Object.defineProperty(target, descriptor.key, descriptor);
  687. }
  688. }
  689. return function (Constructor, protoProps, staticProps) {
  690. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  691. if (staticProps) defineProperties(Constructor, staticProps);
  692. return Constructor;
  693. };
  694. }();
  695. var get$1 = function get$1(object, property, receiver) {
  696. if (object === null) object = Function.prototype;
  697. var desc = Object.getOwnPropertyDescriptor(object, property);
  698. if (desc === undefined) {
  699. var parent = Object.getPrototypeOf(object);
  700. if (parent === null) {
  701. return undefined;
  702. } else {
  703. return get$1(parent, property, receiver);
  704. }
  705. } else if ("value" in desc) {
  706. return desc.value;
  707. } else {
  708. var getter = desc.get;
  709. if (getter === undefined) {
  710. return undefined;
  711. }
  712. return getter.call(receiver);
  713. }
  714. };
  715. var set$1 = function set$1(object, property, value, receiver) {
  716. var desc = Object.getOwnPropertyDescriptor(object, property);
  717. if (desc === undefined) {
  718. var parent = Object.getPrototypeOf(object);
  719. if (parent !== null) {
  720. set$1(parent, property, value, receiver);
  721. }
  722. } else if ("value" in desc && desc.writable) {
  723. desc.value = value;
  724. } else {
  725. var setter = desc.set;
  726. if (setter !== undefined) {
  727. setter.call(receiver, value);
  728. }
  729. }
  730. return value;
  731. };
  732. var slicedToArray = function () {
  733. function sliceIterator(arr, i) {
  734. var _arr = [];
  735. var _n = true;
  736. var _d = false;
  737. var _e = undefined;
  738. try {
  739. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  740. _arr.push(_s.value);
  741. if (i && _arr.length === i) break;
  742. }
  743. } catch (err) {
  744. _d = true;
  745. _e = err;
  746. } finally {
  747. try {
  748. if (!_n && _i["return"]) _i["return"]();
  749. } finally {
  750. if (_d) throw _e;
  751. }
  752. }
  753. return _arr;
  754. }
  755. return function (arr, i) {
  756. if (Array.isArray(arr)) {
  757. return arr;
  758. } else if (Symbol.iterator in Object(arr)) {
  759. return sliceIterator(arr, i);
  760. } else {
  761. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  762. }
  763. };
  764. }();
  765. var toConsumableArray = function (arr) {
  766. if (Array.isArray(arr)) {
  767. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  768. return arr2;
  769. } else {
  770. return Array.from(arr);
  771. }
  772. };
  773. // A `Closure` is a representation of a JavaScript function that controls what
  774. // values are bound to out-of-scope variables. By default JavaScript has no
  775. // reflection capabilities over closed values in functions. When needing to
  776. // serialize execution or when behavior should become part of the state of a
  777. // system it is often necessary to have first-class control over this language
  778. // aspect.
  779. //
  780. // Typically closures aren't created directly but with the help of [`asScriptOf`](#)
  781. //
  782. // Example:
  783. // function func(a) { return a + b; }
  784. // var closureFunc = Closure.fromFunction(func, {b: 3}).recreateFunc();
  785. // closureFunc(4) // => 7
  786. // var closure = closureFunc.livelyClosure // => {
  787. // // varMapping: { b: 3 },
  788. // // originalFunc: function func(a) {/*...*/}
  789. // // }
  790. // closure.lookup("b") // => 3
  791. // closure.getFuncSource() // => "function func(a) { return a + b; }"
  792. var parameterRegex = /function[^\(]*\(([^\)]*)\)|\(?([^\)=]*)\)?\s*=>/;
  793. var Closure = function () {
  794. createClass(Closure, null, [{
  795. key: "fromFunction",
  796. value: function fromFunction(func, varMapping) {
  797. /*show-in-doc*/
  798. return new this(func, varMapping || {});
  799. }
  800. }, {
  801. key: "fromSource",
  802. value: function fromSource(source, varMapping) {
  803. /*show-in-doc*/
  804. return new this(null, varMapping || {}, source);
  805. }
  806. }]);
  807. function Closure(func, varMapping, source, funcProperties) {
  808. classCallCheck(this, Closure);
  809. this.originalFunc = func;
  810. this.varMapping = varMapping || {};
  811. this.setFuncSource(source || func);
  812. this.setFuncProperties(func || funcProperties);
  813. }
  814. createClass(Closure, [{
  815. key: "setFuncSource",
  816. // accessing
  817. value: function setFuncSource(src) {
  818. /*show-in-doc*/
  819. src = typeof lively !== "undefined" && lively.sourceTransform && typeof lively.sourceTransform.stringifyFunctionWithoutToplevelRecorder === "function" ? lively.sourceTransform.stringifyFunctionWithoutToplevelRecorder(src) : String(src);
  820. return this.source = src;
  821. }
  822. }, {
  823. key: "getFuncSource",
  824. value: function getFuncSource() {
  825. /*show-in-doc*/
  826. return this.source || this.setFuncSource(this.originalFunc);
  827. }
  828. }, {
  829. key: "hasFuncSource",
  830. value: function hasFuncSource() {
  831. /*show-in-doc*/
  832. return this.source && true;
  833. }
  834. }, {
  835. key: "getFunc",
  836. value: function getFunc() {
  837. /*show-in-doc*/
  838. return this.originalFunc || this.recreateFunc();
  839. }
  840. }, {
  841. key: "getFuncProperties",
  842. value: function getFuncProperties() {
  843. // ignore-in-doc
  844. // a function may have state attached
  845. return this.funcProperties || (this.funcProperties = {});
  846. }
  847. }, {
  848. key: "setFuncProperties",
  849. value: function setFuncProperties(obj) {
  850. // ignore-in-doc
  851. var props = this.getFuncProperties();
  852. for (var name in obj) {
  853. // The AST implementation assumes that Function objects are some
  854. // kind of value object. When their identity changes cached state
  855. // should not be carried over to new function instances. This is a
  856. // pretty intransparent way to invalidate attributes that are used
  857. // for caches.
  858. // @cschuster, can you please fix this by making invalidation more
  859. // explicit?
  860. if (obj.hasOwnProperty(name)) props[name] = obj[name];
  861. }
  862. }
  863. }, {
  864. key: "lookup",
  865. value: function lookup(name) {
  866. /*show-in-doc*/
  867. return this.varMapping[name];
  868. }
  869. }, {
  870. key: "parameterNames",
  871. value: function parameterNames(methodString) {
  872. // ignore-in-doc
  873. if (typeof lively !== "undefined" && lively.ast && lively.ast.parseFunction) {
  874. return (lively.ast.parseFunction(methodString).params || []).map(function (ea) {
  875. if (ea.type === "Identifier") return ea.name;
  876. if (ea.left && ea.left.type === "Identifier") return ea.left.name;
  877. return null;
  878. }).filter(Boolean);
  879. }
  880. var paramsMatch = parameterRegex.exec(methodString);
  881. if (!paramsMatch) return [];
  882. var paramsString = paramsMatch[1] || paramsMatch[2] || "";
  883. return paramsString.split(",").map(function (ea) {
  884. return ea.trim();
  885. });
  886. }
  887. }, {
  888. key: "firstParameter",
  889. value: function firstParameter(src) {
  890. // ignore-in-doc
  891. return this.parameterNames(src)[0] || null;
  892. }
  893. // -=-=-=-=-=-=-=-=-=-
  894. // function creation
  895. // -=-=-=-=-=-=-=-=-=-
  896. }, {
  897. key: "recreateFunc",
  898. value: function recreateFunc() {
  899. // Creates a real function object
  900. return this.recreateFuncFromSource(this.getFuncSource(), this.originalFunc);
  901. }
  902. }, {
  903. key: "recreateFuncFromSource",
  904. value: function recreateFuncFromSource(funcSource, optFunc) {
  905. // ignore-in-doc
  906. // what about objects that are copied by value, e.g. numbers?
  907. // when those are modified after the originalFunc we captured
  908. // varMapping then we will have divergent state
  909. var closureVars = [],
  910. thisFound = false,
  911. specificSuperHandling = this.firstParameter(funcSource) === '$super';
  912. for (var name in this.varMapping) {
  913. if (!this.varMapping.hasOwnProperty(name)) continue;
  914. if (name == 'this') {
  915. thisFound = true;continue;
  916. }
  917. // closureVars.push(`var ${name} = this.varMapping.${name};\n`);
  918. closureVars.push("var " + name + " = this.varMapping." + name + ";\n");
  919. }
  920. var src = "";
  921. if (closureVars.length > 0) src += closureVars.join("\n");
  922. if (specificSuperHandling) src += '(function superWrapperForClosure() { return ';
  923. src += "(" + funcSource + ")";
  924. if (specificSuperHandling) src += '.apply(this, [$super.bind(this)]' + '.concat(Array.from(arguments))) })';
  925. try {
  926. var func = evalJS.call(this, src) || this.couldNotCreateFunc(src);
  927. this.addFuncProperties(func);
  928. this.originalFunc = func;
  929. return func;
  930. } catch (e) {
  931. // var msg = `Cannot create function ${e} src: ${src}`;
  932. var msg = "Cannot create function " + e + " src: " + src;
  933. console.error(msg);
  934. throw new Error(msg);
  935. }
  936. }
  937. }, {
  938. key: "addFuncProperties",
  939. value: function addFuncProperties(func) {
  940. // ignore-in-doc
  941. var props = this.getFuncProperties();
  942. for (var name in props) {
  943. if (props.hasOwnProperty(name)) func[name] = props[name];
  944. }this.addClosureInformation(func);
  945. }
  946. }, {
  947. key: "couldNotCreateFunc",
  948. value: function couldNotCreateFunc(src) {
  949. // ignore-in-doc
  950. var msg = 'Could not recreate closure from source: \n' + src;
  951. console.error(msg);
  952. return function () {
  953. throw new Error(msg);
  954. };
  955. }
  956. // -=-=-=-=-=-
  957. // conversion
  958. // -=-=-=-=-=-
  959. }, {
  960. key: "asFunction",
  961. value: function asFunction() {
  962. /*ignore-in-doc*/
  963. return this.recreateFunc();
  964. }
  965. // -=-=-=-=-=-=-=-=-=-=-=-
  966. // function modification
  967. // -=-=-=-=-=-=-=-=-=-=-=-
  968. }, {
  969. key: "addClosureInformation",
  970. value: function addClosureInformation(f) {
  971. /*ignore-in-doc-in-doc*/
  972. f.hasLivelyClosure = true;
  973. f.livelyClosure = this;
  974. return f;
  975. }
  976. }, {
  977. key: "isLivelyClosure",
  978. get: function get() {
  979. return true;
  980. }
  981. // serialization
  982. }, {
  983. key: "doNotSerialize",
  984. get: function get() {
  985. return ['originalFunc'];
  986. }
  987. }]);
  988. return Closure;
  989. }();
  990. /*global clearTimeout, setTimeout*/
  991. /*
  992. * Abstractions around first class functions like augmenting and inspecting
  993. * functions as well as to control function calls like dealing with asynchronous
  994. * control flows.
  995. */
  996. // -=-=-=-=-=-=-=-=-
  997. // static functions
  998. // -=-=-=-=-=-=-=-=-
  999. function Empty() {
  1000. /*`function() {}`*/return function () {};
  1001. }
  1002. function K() {
  1003. /*`function(arg) { return arg; }`*/return function (arg) {
  1004. return arg;
  1005. };
  1006. }
  1007. function Null() {
  1008. /*`function() { return null; }`*/return function () {
  1009. return null;
  1010. };
  1011. }
  1012. function False() {
  1013. /*`function() { return false; }`*/return function () {
  1014. return false;
  1015. };
  1016. }
  1017. function True() {
  1018. /*`function() { return true; }`*/return function () {
  1019. return true;
  1020. };
  1021. }
  1022. function notYetImplemented() {
  1023. return function () {
  1024. throw new Error('Not yet implemented');
  1025. };
  1026. }
  1027. // -=-=-=-=-=-
  1028. // accessing
  1029. // -=-=-=-=-=-
  1030. function all(object) {
  1031. // Returns all property names of `object` that reference a function.
  1032. // Example:
  1033. // var obj = {foo: 23, bar: function() { return 42; }};
  1034. // all(obj) // => ["bar"]
  1035. var a = [];
  1036. for (var name in object) {
  1037. if (!object.__lookupGetter__(name) && typeof object[name] === 'function') a.push(name);
  1038. }
  1039. return a;
  1040. }
  1041. function own(object) {
  1042. // Returns all local (non-prototype) property names of `object` that
  1043. // reference a function.
  1044. // Example:
  1045. // var obj1 = {foo: 23, bar: function() { return 42; }};
  1046. // var obj2 = {baz: function() { return 43; }};
  1047. // obj2.__proto__ = obj1
  1048. // own(obj2) // => ["baz"]
  1049. // /*vs.*/ all(obj2) // => ["baz","bar"]
  1050. var a = [];
  1051. for (var name in object) {
  1052. if (!object.__lookupGetter__(name) && object.hasOwnProperty(name) && typeof object[name] === 'function') a.push(name);
  1053. }
  1054. return a;
  1055. }
  1056. // -=-=-=-=-=-
  1057. // inspection
  1058. // -=-=-=-=-=-
  1059. function argumentNames(f) {
  1060. // Example:
  1061. // argumentNames(function(arg1, arg2) {}) // => ["arg1","arg2"]
  1062. // argumentNames(function(/*var args*/) {}) // => []
  1063. if (f.superclass) return []; // it's a class...
  1064. var src = f.toString(),
  1065. names = "",
  1066. arrowMatch = src.match(/(?:\(([^\)]*)\)|([^\(\)-+!]+))\s*=>/);
  1067. if (arrowMatch) names = arrowMatch[1] || arrowMatch[2] || "";else {
  1068. var headerMatch = src.match(/^[\s\(]*function[^(]*\(([^)]*)\)/);
  1069. if (headerMatch && headerMatch[1]) names = headerMatch[1];
  1070. }
  1071. return names.replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '').replace(/\s+/g, '').split(',').map(function (ea) {
  1072. return ea.trim();
  1073. }).filter(function (name) {
  1074. return !!name;
  1075. });
  1076. }
  1077. function qualifiedMethodName(f) {
  1078. // ignore-in-doc
  1079. var objString = "";
  1080. if (f.declaredClass) {
  1081. objString += f.declaredClass + '>>';
  1082. } else if (f.declaredObject) {
  1083. objString += f.declaredObject + '.';
  1084. }
  1085. return objString + (f.methodName || f.displayName || f.name || "anonymous");
  1086. }
  1087. function extractBody(func) {
  1088. // superflous indent. Useful when you have to stringify code but not want
  1089. // to construct strings by hand.
  1090. // Example:
  1091. // extractBody(function(arg) {
  1092. // var x = 34;
  1093. // alert(2 + arg);
  1094. // }) => "var x = 34;\nalert(2 + arg);"
  1095. var codeString = String(func).replace(/^function[^\{]+\{\s*/, '').replace(/\}$/, '').trim(),
  1096. lines = codeString.split(/\n|\r/),
  1097. indent = undefined;
  1098. for (var i = 0; i < lines.length; i++) {
  1099. var m = lines[i].match(/^(\s+)[^\s]/);
  1100. if (m && (indent === undefined || m[1].length < indent.length)) indent = m[1];
  1101. }
  1102. return indent ? codeString.replace(new RegExp("^" + indent, 'gm'), '') : codeString;
  1103. }
  1104. // -=-=-=-
  1105. // timing
  1106. // -=-=-=-
  1107. function timeToRun(func) {
  1108. // returns synchronous runtime of calling `func` in ms
  1109. // Example:
  1110. // timeToRun(function() { new WebResource("http://google.de").beSync().get() });
  1111. // // => 278 (or something else...)
  1112. var startTime = Date.now();
  1113. func();
  1114. return Date.now() - startTime;
  1115. }
  1116. function timeToRunN$1(func, n) {
  1117. // Like `timeToRun` but calls function `n` times instead of once. Returns
  1118. // the average runtime of a call in ms.
  1119. var startTime = Date.now();
  1120. for (var i = 0; i < n; i++) {
  1121. func();
  1122. }return (Date.now() - startTime) / n;
  1123. }
  1124. function delay(func, timeout /*, arg1...argN*/) {
  1125. // Delays calling `func` for `timeout` seconds(!).
  1126. // Example:
  1127. // (function() { alert("Run in the future!"); }).delay(1);
  1128. var args = Array.prototype.slice.call(arguments),
  1129. __method = args.shift(),
  1130. timeout = args.shift() * 1000;
  1131. return setTimeout(function delayed() {
  1132. return __method.apply(__method, args);
  1133. }, timeout);
  1134. }
  1135. // these last two methods are Underscore.js 1.3.3 and are slightly adapted
  1136. // Underscore.js license:
  1137. // (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
  1138. // Underscore is distributed under the MIT license.
  1139. function throttle(func, wait) {
  1140. // Exec func at most once every wait ms even when called more often
  1141. // useful to calm down eagerly running updaters and such.
  1142. // Example:
  1143. // var i = 0;
  1144. // var throttled = throttle(function() { alert(++i + '-' + Date.now()) }, 500);
  1145. // Array.range(0,100).forEach(function(n) { throttled() });
  1146. var context,
  1147. args,
  1148. timeout,
  1149. throttling,
  1150. more,
  1151. result,
  1152. whenDone = debounce(wait, function () {
  1153. more = throttling = false;
  1154. });
  1155. return function () {
  1156. context = this;args = arguments;
  1157. var later = function later() {
  1158. timeout = null;
  1159. if (more) func.apply(context, args);
  1160. whenDone();
  1161. };
  1162. if (!timeout) timeout = setTimeout(later, wait);
  1163. if (throttling) {
  1164. more = true;
  1165. } else {
  1166. result = func.apply(context, args);
  1167. }
  1168. whenDone();
  1169. throttling = true;
  1170. return result;
  1171. };
  1172. }
  1173. function debounce(wait, func, immediate) {
  1174. // Call `func` after `wait` milliseconds elapsed since the last invocation.
  1175. // Unlike `throttle` an invocation will restart the wait period. This is
  1176. // useful if you have a stream of events that you want to wait for to finish
  1177. // and run a subsequent function afterwards. When you pass arguments to the
  1178. // debounced functions then the arguments from the last call will be use for
  1179. // the invocation.
  1180. //
  1181. // With `immediate` set to true, immediately call `func` but when called again during `wait` before
  1182. // wait ms are done nothing happens. E.g. to not exec a user invoked
  1183. // action twice accidentally.
  1184. // Example:
  1185. // var start = Date.now();
  1186. // var f = debounce(200, function(arg1) {
  1187. // alert("running after " + (Date.now()-start) + "ms with arg " + arg1);
  1188. // });
  1189. // f("call1");
  1190. // delay(f.curry("call2"), 0.1);
  1191. // delay(f.curry("call3"), 0.15);
  1192. // // => Will eventually output: "running after 352ms with arg call3"
  1193. var timeout;
  1194. return function () {
  1195. var context = this,
  1196. args = arguments;
  1197. var later = function later() {
  1198. timeout = null;
  1199. if (!immediate) func.apply(context, args);
  1200. };
  1201. if (immediate && !timeout) func.apply(context, args);
  1202. clearTimeout(timeout);
  1203. timeout = setTimeout(later, wait);
  1204. };
  1205. }
  1206. var _throttledByName = {};
  1207. function throttleNamed(name, wait, func) {
  1208. // Like `throttle` but remembers the throttled function once created and
  1209. // repeated calls to `throttleNamed` with the identical name will use the same
  1210. // throttled function. This allows to throttle functions in a central place
  1211. // that might be called various times in different contexts without having to
  1212. // manually store the throttled function.
  1213. var store = _throttledByName;
  1214. if (store[name]) return store[name];
  1215. function throttleNamedWrapper() {
  1216. // ignore-in-doc, cleaning up
  1217. debounceNamed(name, wait, function () {
  1218. delete store[name];
  1219. })();
  1220. func.apply(this, arguments);
  1221. }
  1222. return store[name] = throttle(throttleNamedWrapper, wait);
  1223. }
  1224. var _debouncedByName = {};
  1225. function debounceNamed(name, wait, func, immediate) {
  1226. // Like `debounce` but remembers the debounced function once created and
  1227. // repeated calls to `debounceNamed` with the identical name will use the same
  1228. // debounced function. This allows to debounce functions in a central place
  1229. // that might be called various times in different contexts without having to
  1230. // manually store the debounced function.
  1231. var store = _debouncedByName;
  1232. if (store[name]) return store[name];
  1233. function debounceNamedWrapper() {
  1234. // ignore-in-doc, cleaning up
  1235. delete store[name];
  1236. func.apply(this, arguments);
  1237. }
  1238. return store[name] = debounce(wait, debounceNamedWrapper, immediate);
  1239. }
  1240. var _queues = {};
  1241. function createQueue(id, workerFunc) {
  1242. // A simple queue with an attached asynchronous `workerFunc` to process
  1243. // queued tasks. Calling `createQueue` will return an object with the
  1244. // following interface:
  1245. // ```js
  1246. // {
  1247. // push: function(task) {/**/},
  1248. // pushAll: function(tasks) {/**/},
  1249. // handleError: function(err) {}, // Overwrite to handle errors
  1250. // dran: function() {}, // Overwrite to react when the queue empties
  1251. // }
  1252. // Example:
  1253. // var sum = 0;
  1254. // var q = createQueue("example-queue", function(arg, thenDo) { sum += arg; thenDo(); });
  1255. // q.pushAll([1,2,3]);
  1256. // queues will be remembered by their name
  1257. // createQueue("example-queue").push(4);
  1258. // sum // => 6
  1259. var store = _queues;
  1260. var queue = store[id] || (store[id] = {
  1261. _workerActive: false,
  1262. worker: workerFunc, tasks: [],
  1263. drain: null, // can be overwritten by a function
  1264. push: function push(task) {
  1265. queue.tasks.push(task);
  1266. queue.activateWorker();
  1267. },
  1268. pushAll: function pushAll(tasks) {
  1269. tasks.forEach(function (ea) {
  1270. queue.tasks.push(ea);
  1271. });
  1272. queue.activateWorker();
  1273. },
  1274. pushNoActivate: function pushNoActivate(task) {
  1275. queue.tasks.push(task);
  1276. },
  1277. handleError: function handleError(err) {
  1278. // can be overwritten
  1279. err && console.error('Error in queue: ' + err);
  1280. },
  1281. activateWorker: function activateWorker() {
  1282. function callback(err) {
  1283. queue.handleError(err);queue.activateWorker();
  1284. }
  1285. var tasks = queue.tasks,
  1286. active = queue._workerActive;
  1287. if (tasks.length === 0) {
  1288. if (active) {
  1289. queue._workerActive = false;
  1290. if (typeof queue.drain === 'function') queue.drain();
  1291. }
  1292. delete store[id];
  1293. } else {
  1294. if (!active) queue._workerActive = true;
  1295. try {
  1296. queue.worker(tasks.shift(), callback);
  1297. } catch (err) {
  1298. callback(err);
  1299. }
  1300. }
  1301. }
  1302. });
  1303. return queue;
  1304. }
  1305. var _queueUntilCallbacks = {};
  1306. function workerWithCallbackQueue(id, workerFunc, optTimeout) {
  1307. // This functions helps when you have a long running computation that
  1308. // multiple call sites (independent from each other) depend on. This
  1309. // function does the housekeeping to start the long running computation
  1310. // just once and returns an object that allows to schedule callbacks
  1311. // once the workerFunc is done.
  1312. // Example:
  1313. // var worker = workerWithCallbackQueue("example",
  1314. // function slowFunction(thenDo) {
  1315. // var theAnswer = 42;
  1316. // setTimeout(function() { thenDo(null, theAnswer); });
  1317. // });
  1318. // // all "call sites" depend on `slowFunction` but don't have to know about
  1319. // // each other
  1320. // worker.whenDone(function callsite1(err, theAnswer) { alert("callback1: " + theAnswer); })
  1321. // worker.whenDone(function callsite2(err, theAnswer) { alert("callback2: " + theAnswer); })
  1322. // workerWithCallbackQueue("example").whenDone(function callsite3(err, theAnswer) { alert("callback3: " + theAnswer); })
  1323. // // => Will eventually show: callback1: 42, callback2: 42 and callback3: 42
  1324. // ignore-in-doc
  1325. // This is how it works:
  1326. // If `id` does not exist, workerFunc is called, otherwise ignored.
  1327. // workerFunc is expected to call thenDoFunc with arguments: error, arg1, ..., argN
  1328. // if called subsequently before workerFunc is done, the other thenDoFunc
  1329. // will "pile up" and called with the same arguments as the first
  1330. // thenDoFunc once workerFunc is done
  1331. var store = _queueUntilCallbacks,
  1332. queueCallbacks = store[id],
  1333. isRunning = !!queueCallbacks;
  1334. if (isRunning) return queueCallbacks;
  1335. var callbacksRun = false,
  1336. canceled = false;
  1337. function cleanup() {
  1338. if (timeoutProc) clearTimeout(timeoutProc);
  1339. callbacksRun = true;
  1340. delete store[id];
  1341. }
  1342. function runCallbacks(args) {
  1343. if (callbacksRun) return;
  1344. cleanup();
  1345. queueCallbacks.callbacks.forEach(function (cb) {
  1346. try {
  1347. cb.apply(null, args);
  1348. } catch (e) {
  1349. console.error("Error when invoking callbacks in queueUntil [" + id + "]:\n" + String(e.stack || e));
  1350. }
  1351. });
  1352. }
  1353. // timeout
  1354. if (optTimeout) {
  1355. var timeoutProc = setTimeout(function () {
  1356. if (callbacksRun) return;
  1357. runCallbacks([new Error("timeout")]);
  1358. }, optTimeout);
  1359. }
  1360. // init the store
  1361. queueCallbacks = store[id] = {
  1362. callbacks: [],
  1363. cancel: function cancel() {
  1364. canceled = true;
  1365. cleanup();
  1366. },
  1367. whenDone: function whenDone(cb) {
  1368. queueCallbacks.callbacks.push(cb);
  1369. return queueCallbacks;
  1370. }
  1371. };
  1372. // call worker, but delay so we can immediately return
  1373. setTimeout(function () {
  1374. if (canceled) return;
  1375. try {
  1376. workerFunc(function () /*args*/{
  1377. runCallbacks(arguments);
  1378. });
  1379. } catch (e) {
  1380. runCallbacks([e]);
  1381. }
  1382. }, 0);
  1383. return queueCallbacks;
  1384. }
  1385. function _composeAsyncDefaultEndCallback(err, arg1 /*err + args*/) {
  1386. if (err) console.error("lively.lang.composeAsync error", err);
  1387. }
  1388. function composeAsync() /*functions*/{
  1389. // Composes functions that are asynchronous and expecting continuations to
  1390. // be called in node.js callback style (error is first argument, real
  1391. // arguments follow).
  1392. // A call like `composeAsync(f,g,h)(arg1, arg2)` has a flow of control like:
  1393. // `f(arg1, arg2, thenDo1)` -> `thenDo1(err, fResult)`
  1394. // -> `g(fResult, thenDo2)` -> `thenDo2(err, gResult)` ->
  1395. // -> `h(fResult, thenDo3)` -> `thenDo2(err, hResult)`
  1396. // Example:
  1397. // composeAsync(
  1398. // function(a,b, thenDo) { thenDo(null, a+b); },
  1399. // function(x, thenDo) { thenDo(x*4); }
  1400. // )(3,2, function(err, result) { alert(result); });
  1401. var toArray$$1 = Array.prototype.slice,
  1402. functions = toArray$$1.call(arguments),
  1403. defaultEndCb = _composeAsyncDefaultEndCallback,
  1404. endCallback = defaultEndCb,
  1405. endSuccess,
  1406. endFailure,
  1407. endPromise = new Promise(function (resolve, reject) {
  1408. endSuccess = resolve;endFailure = reject;
  1409. });
  1410. return functions.reverse().reduce(function (prevFunc, funcOrPromise, i) {
  1411. var nextActivated = false;
  1412. return function () {
  1413. var args = toArray$$1.call(arguments);
  1414. // ignore-in-doc
  1415. // the last arg needs to be function, discard all non-args
  1416. // following it. This allows to have an optional callback func that can
  1417. // even be `undefined`, e.g. when calling this func from a callsite
  1418. // using var args;
  1419. if (endCallback === defaultEndCb && i === functions.length - 1 /*first function*/) {
  1420. while (args.length && typeof args[args.length - 1] !== 'function') {
  1421. args.pop();
  1422. }if (typeof args[args.length - 1] === 'function') endCallback = args.pop();
  1423. }
  1424. function next() /*err and args*/{
  1425. nextActivated = true;
  1426. var args = toArray$$1.call(arguments),
  1427. err = args.shift();
  1428. if (err) {
  1429. endCallback(err);endFailure(err);
  1430. } else prevFunc.apply(null, args);
  1431. }
  1432. if (typeof funcOrPromise === "function") {
  1433. try {
  1434. var result = funcOrPromise.apply(this, args.concat([next]));
  1435. if (result && typeof result.then === "function" && typeof result.catch === "function") {
  1436. result.then(function (value) {
  1437. return next(null, value);
  1438. }).catch(function (err) {
  1439. return next(err);
  1440. });
  1441. }
  1442. } catch (e) {
  1443. console.error('composeAsync: ', e.stack || e);
  1444. if (!nextActivated) {
  1445. endCallback(e);endFailure(e);
  1446. }
  1447. }
  1448. } else if (funcOrPromise && typeof funcOrPromise.then === "function" && typeof funcOrPromise.catch === "function") {
  1449. funcOrPromise.then(function (value) {
  1450. next(null, value);
  1451. }).catch(function (err) {
  1452. next(err);
  1453. });
  1454. } else {
  1455. var err = new Error("Invalid argument to composeAsync: " + funcOrPromise);
  1456. endCallback(err);
  1457. endFailure(err);
  1458. }
  1459. return endPromise;
  1460. };
  1461. }, function () {
  1462. var args = toArray$$1.call(arguments);
  1463. endCallback.apply(null, [null].concat(args));
  1464. endSuccess(args[0]);
  1465. });
  1466. }
  1467. function compose() /*functions*/{
  1468. // Composes synchronousefunctions:
  1469. // `compose(f,g,h)(arg1, arg2)` = `h(g(f(arg1, arg2)))`
  1470. // Example:
  1471. // compose(
  1472. // function(a,b) { return a+b; },
  1473. // function(x) {return x*4}
  1474. // )(3,2) // => 20
  1475. var functions = Array.prototype.slice.call(arguments);
  1476. return functions.reverse().reduce(function (prevFunc, func) {
  1477. return function () {
  1478. return prevFunc(func.apply(this, arguments));
  1479. };
  1480. }, function (x) {
  1481. return x;
  1482. });
  1483. }
  1484. function flip(f) {
  1485. // Swaps the first two args
  1486. // Example:
  1487. // flip(function(a, b, c) {
  1488. // return a + b + c; })(' World', 'Hello', '!') // => "Hello World!"
  1489. return function flipped() /*args*/{
  1490. var args = Array.prototype.slice.call(arguments),
  1491. flippedArgs = [args[1], args[0]].concat(args.slice(2));
  1492. return f.apply(null, flippedArgs);
  1493. };
  1494. }
  1495. function withNull(func) {
  1496. // returns a modified version of func that will have `null` always curried
  1497. // as first arg. Usful e.g. to make a nodejs-style callback work with a
  1498. // then-able:
  1499. // Example:
  1500. // promise.then(withNull(cb)).catch(cb);
  1501. func = func || function () {};
  1502. return function () /*args*/{
  1503. var args = lively.lang.arr.from(arguments);
  1504. func.apply(null, [null].concat(args));
  1505. };
  1506. }
  1507. function waitFor(timeoutMs, waitTesterFunc, thenDo) {
  1508. // Wait for waitTesterFunc to return true, then run thenDo, passing
  1509. // failure/timout err as first parameter. A timout occurs after
  1510. // timeoutMs. During the wait period waitTesterFunc might be called
  1511. // multiple times.
  1512. var start = Date.now();
  1513. var timeStep = 50;
  1514. if (!thenDo) {
  1515. thenDo = waitTesterFunc;
  1516. waitTesterFunc = timeoutMs;
  1517. timeoutMs = undefined;
  1518. }
  1519. (function test() {
  1520. if (waitTesterFunc()) return thenDo();
  1521. if (timeoutMs) {
  1522. var duration = Date.now() - start,
  1523. timeLeft = timeoutMs - duration;
  1524. if (timeLeft <= 0) return thenDo(new Error('timeout'));
  1525. if (timeLeft < timeStep) timeStep = timeLeft;
  1526. }
  1527. setTimeout(test, timeStep);
  1528. })();
  1529. }
  1530. function waitForAll(options, funcs, thenDo) {
  1531. // Wait for multiple asynchronous functions. Once all have called the
  1532. // continuation, call `thenDo`.
  1533. // options can be: `{timeout: NUMBER}` (how long to wait in milliseconds).
  1534. if (!thenDo) {
  1535. thenDo = funcs;funcs = options;options = null;
  1536. }
  1537. options = options || {};
  1538. var results = funcs.map(function () {
  1539. return null;
  1540. });
  1541. if (!funcs.length) {
  1542. thenDo(null, results);return;
  1543. }
  1544. var leftFuncs = Array.prototype.slice.call(funcs);
  1545. funcs.forEach(function (f, i) {
  1546. try {
  1547. f(function () /*err and args*/{
  1548. var args = Array.prototype.slice.call(arguments);
  1549. var err = args.shift();
  1550. markAsDone(f, i, err, args);
  1551. });
  1552. } catch (e) {
  1553. markAsDone(f, i, e, null);
  1554. }
  1555. });
  1556. if (options.timeout) {
  1557. setTimeout(function () {
  1558. if (!leftFuncs.length) return;
  1559. var missing = results.map(function (ea, i) {
  1560. return ea === null && i;
  1561. }).filter(function (ea) {
  1562. return typeof ea === 'number';
  1563. }).join(', ');
  1564. var err = new Error("waitForAll timed out, functions at " + missing + " not done");
  1565. markAsDone(null, null, err, null);
  1566. }, options.timeout);
  1567. }
  1568. function markAsDone(f, i, err, result) {
  1569. if (!leftFuncs.length) return;
  1570. var waitForAllErr = null;
  1571. var fidx = leftFuncs.indexOf(f);
  1572. fidx > -1 && leftFuncs.splice(fidx, 1);
  1573. if (err) {
  1574. leftFuncs.length = 0;
  1575. waitForAllErr = new Error("in waitForAll at" + (typeof i === 'number' ? " " + i : "") + ": \n" + (err.stack || String(err)));
  1576. } else if (result) results[i] = result;
  1577. if (!leftFuncs.length) setTimeout(function () {
  1578. thenDo(waitForAllErr, results);
  1579. }, 0);
  1580. }
  1581. }
  1582. // -=-=-=-=-
  1583. // wrapping
  1584. // -=-=-=-=-
  1585. function curry(func, arg1, arg2, argN /*func and curry args*/) {
  1586. // Return a version of `func` with args applied.
  1587. // Example:
  1588. // var add1 = (function(a, b) { return a + b; }).curry(1);
  1589. // add1(3) // => 4
  1590. if (arguments.length <= 1) return arguments[0];
  1591. var args = Array.prototype.slice.call(arguments),
  1592. func = args.shift();
  1593. function wrappedFunc() {
  1594. return func.apply(this, args.concat(Array.prototype.slice.call(arguments)));
  1595. }
  1596. wrappedFunc.isWrapper = true;
  1597. wrappedFunc.originalFunction = func;
  1598. return wrappedFunc;
  1599. }
  1600. function wrap(func, wrapper) {
  1601. // A `wrapper` is another function that is being called with the arguments
  1602. // of `func` and a proceed function that, when called, runs the originally
  1603. // wrapped function.
  1604. // Example:
  1605. // function original(a, b) { return a+b }
  1606. // var wrapped = wrap(original, function logWrapper(proceed, a, b) {
  1607. // alert("original called with " + a + "and " + b);
  1608. // return proceed(a, b);
  1609. // })
  1610. // wrapped(3,4) // => 7 and a message will pop up
  1611. var __method = func;
  1612. var wrappedFunc = function wrapped() {
  1613. var args = Array.prototype.slice.call(arguments);
  1614. var wrapperArgs = wrapper.isWrapper ? args : [__method.bind(this)].concat(args);
  1615. return wrapper.apply(this, wrapperArgs);
  1616. };
  1617. wrappedFunc.isWrapper = true;
  1618. wrappedFunc.originalFunction = __method;
  1619. return wrappedFunc;
  1620. }
  1621. function getOriginal(func) {
  1622. // Get the original function that was augmented by `wrap`. `getOriginal`
  1623. // will traversed as many wrappers as necessary.
  1624. while (func.originalFunction) {
  1625. func = func.originalFunction;
  1626. }return func;
  1627. }
  1628. function wrapperChain(method) {
  1629. // Function wrappers used for wrapping, cop, and other method
  1630. // manipulations attach a property "originalFunction" to the wrapper. By
  1631. // convention this property references the wrapped method like wrapper
  1632. // -> cop wrapper -> real method.
  1633. // tThis method gives access to the linked list starting with the outmost
  1634. // wrapper.
  1635. var result = [];
  1636. do {
  1637. result.push(method);
  1638. method = method.originalFunction;
  1639. } while (method);
  1640. return result;
  1641. }
  1642. function replaceMethodForOneCall(obj, methodName, replacement) {
  1643. // Change an objects method for a single invocation.
  1644. // Example:
  1645. // var obj = {foo: function() { return "foo"}};
  1646. // lively.lang.replaceMethodForOneCall(obj, "foo", function() { return "bar"; });
  1647. // obj.foo(); // => "bar"
  1648. // obj.foo(); // => "foo"
  1649. replacement.originalFunction = obj[methodName];
  1650. var reinstall = obj.hasOwnProperty(methodName);
  1651. obj[methodName] = function () {
  1652. if (reinstall) obj[methodName] = replacement.originalFunction;else delete obj[methodName];
  1653. return replacement.apply(this, arguments);
  1654. };
  1655. return obj;
  1656. }
  1657. function once(func) {
  1658. // Ensure that `func` is only executed once. Multiple calls will not call
  1659. // `func` again but will return the original result.
  1660. if (!func) return undefined;
  1661. if (typeof func !== 'function') throw new Error("once() expecting a function");
  1662. var invoked = false,
  1663. result;
  1664. return function () {
  1665. if (invoked) return result;
  1666. invoked = true;
  1667. return result = func.apply(this, arguments);
  1668. };
  1669. }
  1670. function either() /*funcs*/{
  1671. // Accepts multiple functions and returns an array of wrapped
  1672. // functions. Those wrapped functions ensure that only one of the original
  1673. // function is run (the first on to be invoked).
  1674. //
  1675. // This is useful if you have multiple asynchronous choices of how the
  1676. // control flow might continue but want to ensure that a continuation
  1677. // is only triggered once, like in a timeout situation:
  1678. //
  1679. // ```js
  1680. // function outerFunction(callback) {
  1681. // function timeoutAction() { callback(new Error('timeout!')); }
  1682. // function otherAction() { callback(null, "All OK"); }
  1683. // setTimeout(timeoutAction, 200);
  1684. // doSomethingAsync(otherAction);
  1685. // }
  1686. // ```
  1687. //
  1688. // To ensure that `callback` only runs once you would normally have to write boilerplate like this:
  1689. //
  1690. // ```js
  1691. // var ran = false;
  1692. // function timeoutAction() { if (ran) return; ran = true; callback(new Error('timeout!')); }
  1693. // function otherAction() { if (ran) return; ran = true; callback(null, "All OK"); }
  1694. // ```
  1695. //
  1696. // Since this can get tedious an error prone, especially if more than two choices are involved, `either` can be used like this:
  1697. // Example:
  1698. // function outerFunction(callback) {
  1699. // var actions = either(
  1700. // function() { callback(new Error('timeout!')); },
  1701. // function() { callback(null, "All OK"); });
  1702. // setTimeout(actions[0], 200);
  1703. // doSomethingAsync(actions[1]);
  1704. // }
  1705. var funcs = Array.prototype.slice.call(arguments),
  1706. wasCalled = false;
  1707. return funcs.map(function (func) {
  1708. return function () {
  1709. if (wasCalled) return undefined;
  1710. wasCalled = true;
  1711. return func.apply(this, arguments);
  1712. };
  1713. });
  1714. }
  1715. var _eitherNameRegistry = {};
  1716. function eitherNamed(name, func) {
  1717. // Works like [`either`](#) but usage does not require to wrap all
  1718. // functions at once:
  1719. // Example:
  1720. // var log = "", name = "either-example-" + Date.now();
  1721. // function a() { log += "aRun"; };
  1722. // function b() { log += "bRun"; };
  1723. // function c() { log += "cRun"; };
  1724. // setTimeout(eitherNamed(name, a), 100);
  1725. // setTimeout(eitherNamed(name, b), 40);
  1726. // setTimeout(eitherNamed(name, c), 80);
  1727. // setTimeout(function() { alert(log); /* => "bRun" */ }, 150);
  1728. var funcs = Array.prototype.slice.call(arguments);
  1729. var registry = _eitherNameRegistry;
  1730. var name = funcs.shift();
  1731. var eitherCall = registry[name] || (registry[name] = { wasCalled: false, callsLeft: 0 });
  1732. eitherCall.callsLeft++;
  1733. return function () {
  1734. eitherCall.callsLeft--;
  1735. // cleanup the storage if all registered functions fired
  1736. if (eitherCall.callsLeft <= 0) delete registry[name];
  1737. if (eitherCall.wasCalled) return undefined;
  1738. eitherCall.wasCalled = true;
  1739. return func.apply(this, arguments);
  1740. };
  1741. }
  1742. // -=-=-=-=-
  1743. // creation
  1744. // -=-=-=-=-
  1745. function evalJS(src) {
  1746. return eval(src);
  1747. }
  1748. function fromString(funcOrString) {
  1749. // Example:
  1750. // fromString("function() { return 3; }")() // => 3
  1751. return evalJS('(' + funcOrString.toString() + ');');
  1752. }
  1753. function asScript(func, optVarMapping) {
  1754. // Lifts `func` to become a `Closure`, that is that free variables referenced
  1755. // in `func` will be bound to the values of an object that can be passed in as
  1756. // the second parameter. Keys of this object are mapped to the free variables.
  1757. //
  1758. // Please see [`Closure`](#) for a more detailed explanation and examples.
  1759. return Closure.fromFunction(func, optVarMapping).recreateFunc();
  1760. }
  1761. function asScriptOf(f, obj, optName, optMapping) {
  1762. // Like `asScript` but makes `f` a method of `obj` as `optName` or the name
  1763. // of the function.
  1764. var name = optName || f.name;
  1765. if (!name) {
  1766. throw Error("Function that wants to be a script needs a name: " + this);
  1767. }
  1768. var proto = Object.getPrototypeOf(obj),
  1769. mapping = { "this": obj };
  1770. if (optMapping) mapping = merge([mapping, optMapping]);
  1771. if (proto && proto[name]) {
  1772. var superFunc = function superFunc() {
  1773. try {
  1774. // FIXME super is supposed to be static
  1775. return Object.getPrototypeOf(obj)[name].apply(obj, arguments);
  1776. } catch (e) {
  1777. if (typeof $world !== "undefined") $world.logError(e, 'Error in $super call');else console.error('Error in $super call: ' + e + '\n' + e.stack);
  1778. return null;
  1779. }
  1780. };
  1781. mapping["$super"] = Closure.fromFunction(superFunc, { obj: obj, name: name }).recreateFunc();
  1782. }
  1783. return addToObject(asScript(f, mapping), obj, name);
  1784. }
  1785. // -=-=-=-=-=-=-=-=-
  1786. // closure related
  1787. // -=-=-=-=-=-=-=-=-
  1788. function addToObject(f, obj, name) {
  1789. // ignore-in-doc
  1790. f.displayName = name;
  1791. var methodConnections = obj.attributeConnections ? obj.attributeConnections.filter(function (con) {
  1792. return con.getSourceAttrName() === 'update';
  1793. }) : [];
  1794. if (methodConnections) methodConnections.forEach(function (ea) {
  1795. ea.disconnect();
  1796. });
  1797. obj[name] = f;
  1798. if (typeof obj === "undefined" ? "undefined" : _typeof(obj)) f.declaredObject = safeToString(obj);
  1799. // suppport for tracing
  1800. if (typeof lively !== "undefined" && obj && lively.Tracing && lively.Tracing.stackTracingEnabled) {
  1801. lively.Tracing.instrumentMethod(obj, name, {
  1802. declaredObject: safeToString(obj)
  1803. });
  1804. }
  1805. if (methodConnections) methodConnections.forEach(function (ea) {
  1806. ea.connect();
  1807. });
  1808. return f;
  1809. }
  1810. function binds(f, varMapping) {
  1811. // ignore-in-doc
  1812. // convenience function
  1813. return Closure.fromFunction(f, varMapping || {}).recreateFunc();
  1814. }
  1815. function setLocalVarValue(f, name, value) {
  1816. // ignore-in-doc
  1817. if (f.hasLivelyClosure) f.livelyClosure.funcProperties[name] = value;
  1818. }
  1819. function getVarMapping(f) {
  1820. // ignore-in-doc
  1821. if (f.hasLivelyClosure) return f.livelyClosure.varMapping;
  1822. if (f.isWrapper) return f.originalFunction.varMapping;
  1823. if (f.varMapping) return f.varMapping;
  1824. return {};
  1825. }
  1826. function setProperty(func, name, value) {
  1827. func[name] = value;
  1828. if (func.hasLivelyClosure) func.livelyClosure.funcProperties[name] = value;
  1829. }
  1830. // -=-=-=-=-=-=-=-=-=-=-=-=-
  1831. // class-related functions
  1832. // -=-=-=-=-=-=-=-=-=-=-=-=-
  1833. function functionNames(klass) {
  1834. // Treats passed function as class (constructor).
  1835. // Example:
  1836. // var Klass1 = function() {}
  1837. // Klass1.prototype.foo = function(a, b) { return a + b; };
  1838. // Klass1.prototype.bar = function(a) { return this.foo(a, 3); };
  1839. // Klass1.prototype.baz = 23;
  1840. // functionNames(Klass1); // => ["bar","foo"]
  1841. var result = [],
  1842. lookupObj = klass.prototype;
  1843. while (lookupObj) {
  1844. result = Object.keys(lookupObj).reduce(function (result, name) {
  1845. if (typeof lookupObj[name] === 'function' && result.indexOf(name) === -1) result.push(name);
  1846. return result;
  1847. }, result);
  1848. lookupObj = Object.getPrototypeOf(lookupObj);
  1849. }
  1850. return result;
  1851. }
  1852. function localFunctionNames(func) {
  1853. return Object.keys(func.prototype).filter(function (name) {
  1854. return typeof func.prototype[name] === 'function';
  1855. });
  1856. }
  1857. // -=-=-=-=-=-=-=-=-=-=-
  1858. // tracing and logging
  1859. // -=-=-=-=-=-=-=-=-=-=-
  1860. function logErrors(func, prefix) {
  1861. var advice = function logErrorsAdvice(proceed /*,args*/) {
  1862. var args = Array.prototype.slice.call(arguments);
  1863. args.shift();
  1864. try {
  1865. return proceed.apply(func, args);
  1866. } catch (er) {
  1867. if (typeof lively !== "undefined" && lively.morphic && lively.morphic.World && lively.morphic.World.current()) {
  1868. lively.morphic.World.current().logError(er);
  1869. throw er;
  1870. }
  1871. if (prefix) console.warn("ERROR: %s.%s(%s): err: %s %s", func, prefix, args, er, er.stack || "");else console.warn("ERROR: %s %s", er, er.stack || "");
  1872. throw er;
  1873. }
  1874. };
  1875. advice.methodName = "$logErrorsAdvice";
  1876. var result = wrap(func, advice);
  1877. result.originalFunction = func;
  1878. result.methodName = "$logErrorsWrapper";
  1879. return result;
  1880. }
  1881. function logCompletion(func, module) {
  1882. var advice = function logCompletionAdvice(proceed) {
  1883. var args = Array.prototype.slice.call(arguments);
  1884. args.shift();
  1885. try {
  1886. var result = proceed.apply(func, args);
  1887. } catch (er) {
  1888. console.warn('failed to load ' + module + ': ' + er);
  1889. if (typeof lively !== 'undefined' && lively.lang.Execution) lively.lang.Execution.showStack();
  1890. throw er;
  1891. }
  1892. console.log('completed ' + module);
  1893. return result;
  1894. };
  1895. advice.methodName = "$logCompletionAdvice::" + module;
  1896. var result = wrap(func, advice);
  1897. result.methodName = "$logCompletionWrapper::" + module;
  1898. result.originalFunction = func;
  1899. return result;
  1900. }
  1901. function logCalls(func, isUrgent) {
  1902. var original = func,
  1903. advice = function logCallsAdvice(proceed) {
  1904. var args = Array.prototype.slice.call(arguments);
  1905. args.shift(), result = proceed.apply(func, args);
  1906. if (isUrgent) {
  1907. console.warn('%s(%s) -> %s', qualifiedMethodName(original), args, result);
  1908. } else {
  1909. console.log('%s(%s) -> %s', qualifiedMethodName(original), args, result);
  1910. }
  1911. return result;
  1912. };
  1913. advice.methodName = "$logCallsAdvice::" + qualifiedMethodName(func);
  1914. var result = wrap(func, advice);
  1915. result.originalFunction = func;
  1916. result.methodName = "$logCallsWrapper::" + qualifiedMethodName(func);
  1917. return result;
  1918. }
  1919. function traceCalls(func, stack) {
  1920. var advice = function traceCallsAdvice(proceed) {
  1921. var args = Array.prototype.slice.call(arguments);
  1922. args.shift();
  1923. stack.push(args);
  1924. var result = proceed.apply(func, args);
  1925. stack.pop();
  1926. return result;
  1927. };
  1928. return wrap(func, advice);
  1929. }
  1930. function webkitStack() {
  1931. // this won't work in every browser
  1932. try {
  1933. throw new Error();
  1934. } catch (e) {
  1935. // remove "Error" and this function from stack, rewrite it nicely
  1936. return String(e.stack).split(/\n/).slice(2).map(function (line) {
  1937. return line.replace(/^\s*at\s*([^\s]+).*/, '$1');
  1938. }).join('\n');
  1939. }
  1940. }
  1941. var fun = Object.freeze({
  1942. Empty: Empty,
  1943. K: K,
  1944. Null: Null,
  1945. False: False,
  1946. True: True,
  1947. notYetImplemented: notYetImplemented,
  1948. withNull: withNull,
  1949. all: all,
  1950. own: own,
  1951. argumentNames: argumentNames,
  1952. qualifiedMethodName: qualifiedMethodName,
  1953. extractBody: extractBody,
  1954. timeToRun: timeToRun,
  1955. timeToRunN: timeToRunN$1,
  1956. delay: delay,
  1957. throttle: throttle,
  1958. debounce: debounce,
  1959. throttleNamed: throttleNamed,
  1960. debounceNamed: debounceNamed,
  1961. createQueue: createQueue,
  1962. workerWithCallbackQueue: workerWithCallbackQueue,
  1963. composeAsync: composeAsync,
  1964. compose: compose,
  1965. waitFor: waitFor,
  1966. waitForAll: waitForAll,
  1967. flip: flip,
  1968. curry: curry,
  1969. wrap: wrap,
  1970. binds: binds,
  1971. getOriginal: getOriginal,
  1972. wrapperChain: wrapperChain,
  1973. replaceMethodForOneCall: replaceMethodForOneCall,
  1974. once: once,
  1975. either: either,
  1976. eitherNamed: eitherNamed,
  1977. evalJS: evalJS,
  1978. fromString: fromString,
  1979. asScript: asScript,
  1980. asScriptOf: asScriptOf,
  1981. addToObject: addToObject,
  1982. setLocalVarValue: setLocalVarValue,
  1983. getVarMapping: getVarMapping,
  1984. setProperty: setProperty,
  1985. functionNames: functionNames,
  1986. localFunctionNames: localFunctionNames,
  1987. logErrors: logErrors,
  1988. logCompletion: logCompletion,
  1989. logCalls: logCalls,
  1990. traceCalls: traceCalls,
  1991. webkitStack: webkitStack
  1992. });
  1993. // show-in-doc
  1994. // A Grouping is created by arr.groupBy and maps keys to Arrays.
  1995. var Group = function () {
  1996. function Group() {
  1997. classCallCheck(this, Group);
  1998. }
  1999. createClass(Group, [{
  2000. key: "toArray",
  2001. value: function toArray() {
  2002. // Example:
  2003. // var group = arr.groupBy([1,2,3,4,5], function(n) { return n % 2; })
  2004. // group.toArray(); // => [[2,4],[1,3,5]]
  2005. return this.reduceGroups(function (all$$1, _, group) {
  2006. return all$$1.concat([group]);
  2007. }, []);
  2008. }
  2009. }, {
  2010. key: "forEach",
  2011. value: function forEach(iterator, context) {
  2012. // Iteration for each item in each group, called like `iterator(groupKey, groupItem)`
  2013. var groups = this;
  2014. Object.keys(groups).forEach(function (groupName) {
  2015. groups[groupName].forEach(iterator.bind(context, groupName));
  2016. });
  2017. return groups;
  2018. }
  2019. }, {
  2020. key: "forEachGroup",
  2021. value: function forEachGroup(iterator, context) {
  2022. // Iteration for each group, called like `iterator(groupKey, group)`
  2023. var groups = this;
  2024. Object.keys(groups).forEach(function (groupName) {
  2025. iterator.call(context, groupName, groups[groupName]);
  2026. });
  2027. return groups;
  2028. }
  2029. }, {
  2030. key: "map",
  2031. value: function map(iterator, context) {
  2032. // Map for each item in each group, called like `iterator(groupKey, group)`
  2033. var result = new Group();
  2034. this.forEachGroup(function (groupName, group) {
  2035. result[groupName] = group.map(iterator.bind(context, groupName));
  2036. });
  2037. return result;
  2038. }
  2039. }, {
  2040. key: "mapGroups",
  2041. value: function mapGroups(iterator, context) {
  2042. // Map for each group, called like `iterator(groupKey, group)`
  2043. var result = new Group();
  2044. this.forEachGroup(function (groupName, group) {
  2045. result[groupName] = iterator.call(context, groupName, group);
  2046. });
  2047. return result;
  2048. }
  2049. }, {
  2050. key: "keys",
  2051. value: function keys() {
  2052. // show-in-docs
  2053. return Object.keys(this);
  2054. }
  2055. }, {
  2056. key: "reduceGroups",
  2057. value: function reduceGroups(iterator, carryOver, context) {
  2058. // Reduce/fold for each group, called like `iterator(carryOver, groupKey, group)`
  2059. this.forEachGroup(function (groupName, group) {
  2060. carryOver = iterator.call(context, carryOver, groupName, group);
  2061. });
  2062. return carryOver;
  2063. }
  2064. }, {
  2065. key: "count",
  2066. value: function count() {
  2067. // counts the elements of each group
  2068. return this.reduceGroups(function (groupCount, groupName, group) {
  2069. groupCount[groupName] = group.length;
  2070. return groupCount;
  2071. }, {});
  2072. }
  2073. }], [{
  2074. key: "fromArray",
  2075. value: function fromArray(array, hashFunc, context) {
  2076. // Example:
  2077. // Group.fromArray([1,2,3,4,5,6], function(n) { return n % 2; })
  2078. // // => {"0": [2,4,6], "1": [1,3,5]}
  2079. var grouping = new Group();
  2080. for (var i = 0, len = array.length; i < len; i++) {
  2081. var hash = hashFunc.call(context, array[i], i);
  2082. if (!grouping[hash]) grouping[hash] = [];
  2083. grouping[hash].push(array[i]);
  2084. }
  2085. return grouping;
  2086. }
  2087. }, {
  2088. key: "by",
  2089. get: function get() {
  2090. return groupBy;
  2091. }
  2092. }]);
  2093. return Group;
  2094. }();
  2095. /*global System, global*/
  2096. /*
  2097. * Methods to make working with arrays more convenient and collection-like
  2098. * abstractions for groups, intervals, grids.
  2099. */
  2100. var GLOBAL$1 = typeof System !== "undefined" ? System.global : typeof window !== 'undefined' ? window : global;
  2101. var features$1 = {
  2102. from: !!Array.from,
  2103. filter: !!Array.prototype.filter,
  2104. find: !!Array.prototype.find,
  2105. findIndex: !!Array.prototype.findIndex,
  2106. includes: !!Array.prototype.includes
  2107. };
  2108. // variety of functions for Arrays
  2109. // -=-=-=-=-=-=-=-
  2110. // array creations
  2111. // -=-=-=-=-=-=-=-
  2112. function range(begin, end, step) {
  2113. // Examples:
  2114. // arr.range(0,5) // => [0,1,2,3,4,5]
  2115. // arr.range(0,10,2) // => [0,2,4,6,8,10]
  2116. step = step || 0;
  2117. var result = [];
  2118. if (begin <= end) {
  2119. if (step <= 0) step = -step || 1;
  2120. for (var i = begin; i <= end; i += step) {
  2121. result.push(i);
  2122. }
  2123. } else {
  2124. if (step >= 0) step = -step || -1;
  2125. for (var i = begin; i >= end; i += step) {
  2126. result.push(i);
  2127. }
  2128. }
  2129. return result;
  2130. }
  2131. var from = features$1.from ? Array.from : function (iterable) {
  2132. // Makes JS arrays out of array like objects like `arguments` or DOM `childNodes`
  2133. if (!iterable) return [];
  2134. if (Array.isArray(iterable)) return iterable;
  2135. if (iterable.toArray) return iterable.toArray();
  2136. var length = iterable.length,
  2137. results = new Array(length);
  2138. while (length--) {
  2139. results[length] = iterable[length];
  2140. }return results;
  2141. };
  2142. function withN(n, obj) {
  2143. // Example:
  2144. // arr.withN(3, "Hello") // => ["Hello","Hello","Hello"]
  2145. var result = new Array(n);
  2146. while (n > 0) {
  2147. result[--n] = obj;
  2148. }return result;
  2149. }
  2150. function genN(n, generator) {
  2151. // Number -> Function -> Array
  2152. // Takes a generator function that is called for each `n`.
  2153. // Example:
  2154. // arr.genN(3, num.random) // => [46,77,95]
  2155. var result = new Array(n);
  2156. while (n > 0) {
  2157. result[--n] = generator(n);
  2158. }return result;
  2159. }
  2160. // -=-=-=-=-
  2161. // filtering
  2162. // -=-=-=-=-
  2163. function filter(array, iterator, context) {
  2164. // [a] -> (a -> Boolean) -> c? -> [a]
  2165. // Calls `iterator` for each element in `array` and returns a subset of it
  2166. // including the elements for which `iterator` returned a truthy value.
  2167. // Like `Array.prototype.filter`.
  2168. return array.filter(iterator, context);
  2169. }
  2170. var detect = features$1.find ? function (arr, iterator, context) {
  2171. return arr.find(iterator, context);
  2172. } : function (arr, iterator, context) {
  2173. // [a] -> (a -> Boolean) -> c? -> a
  2174. // returns the first occurrence of an element in `arr` for which iterator
  2175. // returns a truthy value
  2176. for (var value, i = 0, len = arr.length; i < len; i++) {
  2177. value = arr[i];
  2178. if (iterator.call(context, value, i)) return value;
  2179. }
  2180. return undefined;
  2181. };
  2182. var findIndex = features$1.findIndex ? function (arr, iterator, context) {
  2183. return arr.findIndex(iterator, context);
  2184. } : function (arr, iterator, context) {
  2185. var i = -1;
  2186. return arr.find(function (ea, j) {
  2187. i = j;return iterator.call(ea, context);
  2188. }) ? i : -1;
  2189. };
  2190. function findAndGet(arr, iterator) {
  2191. // find the first occurence for which `iterator` returns a truthy value and
  2192. // return *this* value, i.e. unlike find the iterator result and not the
  2193. // element of the list is returned
  2194. var result;
  2195. arr.find(function (ea, i) {
  2196. return result = iterator(ea, i);
  2197. });
  2198. return result;
  2199. }
  2200. function filterByKey(arr, key) {
  2201. // [a] -> String -> [a]
  2202. // Example:
  2203. // var objects = [{x: 3}, {y: 4}, {x:5}]
  2204. // arr.filterByKey(objects, "x") // => [{x: 3},{x: 5}]
  2205. return arr.filter(function (ea) {
  2206. return !!ea[key];
  2207. });
  2208. }
  2209. function grep(arr, filter, context) {
  2210. // [a] -> String|RegExp -> [a]
  2211. // `filter` can be a String or RegExp. Will stringify each element in
  2212. // Example:
  2213. // ["Hello", "World", "Lively", "User"].grep("l") // => ["Hello","World","Lively"]
  2214. if (typeof filter === 'string') filter = new RegExp(filter, 'i');
  2215. return arr.filter(filter.test.bind(filter));
  2216. }
  2217. function mask(array, mask) {
  2218. // select every element in array for which array's element is truthy
  2219. // Example: [1,2,3].mask([false, true, false]) => [2]
  2220. return array.filter(function (_, i) {
  2221. return !!mask[i];
  2222. });
  2223. }
  2224. function reject(array, func, context) {
  2225. // show-in-doc
  2226. function iterator(val, i) {
  2227. return !func.call(context, val, i);
  2228. }
  2229. return array.filter(iterator);
  2230. }
  2231. function rejectByKey(array, key) {
  2232. // show-in-doc
  2233. return array.filter(function (ea) {
  2234. return !ea[key];
  2235. });
  2236. }
  2237. function without(array, elem) {
  2238. // non-mutating
  2239. // Example:
  2240. // arr.without([1,2,3,4,5,6], 3) // => [1,2,4,5,6]
  2241. return array.filter(function (val) {
  2242. return val !== elem;
  2243. });
  2244. }
  2245. function withoutAll(array, otherArr) {
  2246. // non-mutating
  2247. // Example:
  2248. // arr.withoutAll([1,2,3,4,5,6], [3,4]) // => [1,2,5,6]
  2249. return array.filter(function (val) {
  2250. return otherArr.indexOf(val) === -1;
  2251. });
  2252. }
  2253. function uniq(array, sorted) {
  2254. // non-mutating
  2255. // Removes duplicates from array.
  2256. // if sorted == true then assume array is sorted which allows uniq to be more
  2257. // efficient
  2258. // uniq([3,5,6,2,3,4,2,6,4])
  2259. if (!array.length) return array;
  2260. var result = [array[0]];
  2261. if (sorted) {
  2262. for (var i = 1; i < array.length; i++) {
  2263. var val = array[i];
  2264. if (val !== result[result.length]) result.push(val);
  2265. }
  2266. } else {
  2267. for (var _i = 1; _i < array.length; _i++) {
  2268. var _val = array[_i];
  2269. if (result.indexOf(_val) === -1) result.push(_val);
  2270. }
  2271. }
  2272. return result;
  2273. }
  2274. function uniqBy(array, comparator, context) {
  2275. // like `arr.uniq` but with custom equality: `comparator(a,b)` returns
  2276. // BOOL. True if a and be should be regarded equal, false otherwise.
  2277. var result = array.slice();
  2278. for (var i = result.length; i--;) {
  2279. var item = array[i];
  2280. for (var j = i + 1; j < result.length; j++) {
  2281. if (comparator.call(context, item, result[j])) result.splice(j--, 1);
  2282. }
  2283. }
  2284. return result;
  2285. }
  2286. function uniqByKey(array, key) {
  2287. // like `arr.uniq` but with equality based on item[key]
  2288. var seen = {},
  2289. result = [];
  2290. for (var i = 0; i < array.length; i++) {
  2291. var item = array[i];
  2292. if (!seen[item[key]]) {
  2293. seen[item[key]] = true;
  2294. result.push(item);
  2295. }
  2296. }
  2297. return result;
  2298. }
  2299. function compact(array) {
  2300. // removes falsy values
  2301. // Example:
  2302. // arr.compact([1,2,undefined,4,0]) // => [1,2,4]
  2303. return array.filter(Boolean);
  2304. }
  2305. function mutableCompact(array) {
  2306. // fix gaps that were created with 'delete'
  2307. var i = 0,
  2308. j = 0,
  2309. len = array.length;
  2310. while (i < len) {
  2311. if (array.hasOwnProperty(i)) array[j++] = array[i];
  2312. i++;
  2313. }
  2314. while (j++ < len) {
  2315. array.pop();
  2316. }return array;
  2317. }
  2318. // -=-=-=-=-
  2319. // iteration
  2320. // -=-=-=-=-
  2321. function forEach$1(array, iterator, context) {
  2322. // [a] -> (a -> Undefined) -> c? -> Undefined
  2323. // `iterator` is called on each element in `array` for side effects. Like
  2324. // `Array.prototype.forEach`.
  2325. return array.forEach(iterator, context);
  2326. }
  2327. function zip() /*arr, arr2, arr3*/{
  2328. // Takes any number of lists as arguments. Combines them elment-wise.
  2329. // Example:
  2330. // arr.zip([1,2,3], ["a", "b", "c"], ["A", "B"])
  2331. // // => [[1,"a","A"],[2,"b","B"],[3,"c",undefined]]
  2332. var args = Array.from(arguments),
  2333. array = args.shift(),
  2334. iterator = typeof last(args) === 'function' ? args.pop() : function (x) {
  2335. return x;
  2336. },
  2337. collections = [array].concat(args).map(function (ea) {
  2338. return Array.from(ea);
  2339. });
  2340. return array.map(function (value, index) {
  2341. return iterator(pluck(collections, index), index);
  2342. });
  2343. }
  2344. function flatten(array, optDepth) {
  2345. // Turns a nested collection into a flat one.
  2346. // Example:
  2347. // arr.flatten([1, [2, [3,4,5], [6]], 7,8])
  2348. // // => [1,2,3,4,5,6,7,8]
  2349. if (typeof optDepth === "number") {
  2350. if (optDepth <= 0) return array;
  2351. optDepth--;
  2352. }
  2353. return array.reduce(function (flattened, value) {
  2354. return flattened.concat(Array.isArray(value) ? flatten(value, optDepth) : [value]);
  2355. }, []);
  2356. }
  2357. function flatmap(array, it, ctx) {
  2358. // the simple version
  2359. // Array.prototype.concat.apply([], array.map(it, ctx));
  2360. // causes stack overflows with really big arrays
  2361. var results = [];
  2362. for (var i = 0; i < array.length; i++) {
  2363. results.push.apply(results, it.call(ctx, array[i], i));
  2364. }
  2365. return results;
  2366. }
  2367. function interpose(array, delim) {
  2368. // Injects delim between elements of array
  2369. // Example:
  2370. // lively.lang.arr.interpose(["test", "abc", 444], "aha"));
  2371. // // => ["test","aha","abc","aha",444]
  2372. return array.reduce(function (xs, x) {
  2373. if (xs.length > 0) xs.push(delim);
  2374. xs.push(x);return xs;
  2375. }, []);
  2376. }
  2377. function delimWith(array, delim) {
  2378. // ignore-in-doc
  2379. // previously used, use interpose now!
  2380. return interpose(array, delim);
  2381. }
  2382. // -=-=-=-=-
  2383. // mapping
  2384. // -=-=-=-=-
  2385. function map$1(array, iterator, context) {
  2386. // [a] -> (a -> b) -> c? -> [b]
  2387. // Applies `iterator` to each element of `array` and returns a new Array
  2388. // with the results of those calls. Like `Array.prototype.some`.
  2389. return array.map(iterator, context);
  2390. }
  2391. function invoke(array, method, arg1, arg2, arg3, arg4, arg5, arg6) {
  2392. // Calls `method` on each element in `array`, passing all arguments. Often
  2393. // a handy way to avoid verbose `map` calls.
  2394. // Example: arr.invoke(["hello", "world"], "toUpperCase") // => ["HELLO","WORLD"]
  2395. return array.map(function (ea) {
  2396. return ea[method](arg1, arg2, arg3, arg4, arg5, arg6);
  2397. });
  2398. }
  2399. function pluck(array, property) {
  2400. // Returns `property` or undefined from each element of array. For quick
  2401. // `map`s and similar to `invoke`.
  2402. // Example: arr.pluck(["hello", "world"], 0) // => ["h","w"]
  2403. return array.map(function (ea) {
  2404. return ea[property];
  2405. });
  2406. }
  2407. // -=-=-=-=-
  2408. // folding
  2409. // -=-=-=-=-
  2410. function reduce(array, iterator, memo, context) {
  2411. // Array -> Function -> Object? -> Object? -> Object?
  2412. // Applies `iterator` to each element of `array` and returns a new Array
  2413. // with the results of those calls. Like `Array.prototype.some`.
  2414. return array.reduce(iterator, memo, context);
  2415. }
  2416. function reduceRight(array, iterator, memo, context) {
  2417. // show-in-doc
  2418. return array.reduceRight(iterator, memo, context);
  2419. }
  2420. // -=-=-=-=-
  2421. // testing
  2422. // -=-=-=-=-
  2423. var isArray$1 = Array.isArray;
  2424. var includes$1 = features$1.includes ? function (array, object) {
  2425. return array.includes(object);
  2426. } : function (array, object) {
  2427. // Example: arr.include([1,2,3], 2) // => true
  2428. return array.indexOf(object) !== -1;
  2429. };
  2430. var include$1 = includes$1;
  2431. function some(array, iterator, context) {
  2432. // [a] -> (a -> Boolean) -> c? -> Boolean
  2433. // Returns true if there is at least one abject in `array` for which
  2434. // `iterator` returns a truthy result. Like `Array.prototype.some`.
  2435. return array.some(iterator, context);
  2436. }
  2437. function every(array, iterator, context) {
  2438. // [a] -> (a -> Boolean) -> c? -> Boolean
  2439. // Returns true if for all abjects in `array` `iterator` returns a truthy
  2440. // result. Like `Array.prototype.every`.
  2441. return array.every(iterator, context);
  2442. }
  2443. function equals$2(array, otherArray) {
  2444. // Returns true iff each element in `array` is equal (`==`) to its
  2445. // corresponding element in `otherArray`
  2446. var len = array.length;
  2447. if (!otherArray || len !== otherArray.length) return false;
  2448. for (var i = 0; i < len; i++) {
  2449. if (array[i] && otherArray[i] && array[i].equals && otherArray[i].equals) {
  2450. if (!array[i].equals(otherArray[i])) {
  2451. return false;
  2452. } else {
  2453. continue;
  2454. }
  2455. }
  2456. if (array[i] != otherArray[i]) return false;
  2457. }
  2458. return true;
  2459. }
  2460. function deepEquals(array, otherArray) {
  2461. // Returns true iff each element in `array` is structurally equal
  2462. // (`lang.obj.equals`) to its corresponding element in `otherArray`
  2463. var len = array.length;
  2464. if (!otherArray || len !== otherArray.length) return false;
  2465. for (var i = 0; i < len; i++) {
  2466. if (!equals$1(array[i], otherArray[i])) return false;
  2467. }
  2468. return true;
  2469. }
  2470. // -=-=-=-=-
  2471. // sorting
  2472. // -=-=-=-=-
  2473. function isSorted(array, descending) {
  2474. if (descending) {
  2475. for (var i = 1; i < array.length; i++) {
  2476. if (array[i - 1] < array[i]) return false;
  2477. }
  2478. } else {
  2479. for (var i = 1; i < array.length; i++) {
  2480. if (array[i - 1] > array[i]) return false;
  2481. }
  2482. }
  2483. return true;
  2484. }
  2485. function sort(array, sortFunc) {
  2486. // [a] -> (a -> Number)? -> [a]
  2487. // Just `Array.prototype.sort`
  2488. return array.sort(sortFunc);
  2489. }
  2490. function sortBy(array, iterator, context) {
  2491. // Example:
  2492. // arr.sortBy(["Hello", "Lively", "User"], function(ea) {
  2493. // return ea.charCodeAt(ea.length-1); }) // => ["Hello","User","Lively"]
  2494. return pluck(array.map(function (value, index) {
  2495. return { value: value, criteria: iterator.call(context, value, index) };
  2496. }).sort(function (left, right) {
  2497. var a = left.criteria,
  2498. b = right.criteria;
  2499. return a < b ? -1 : a > b ? 1 : 0;
  2500. }), 'value');
  2501. }
  2502. function sortByKey(array, key) {
  2503. // Example:
  2504. // lively.lang.arr.sortByKey([{x: 3}, {x: 2}, {x: 8}], "x")
  2505. // // => [{x: 2},{x: 3},{x: 8}]
  2506. return sortBy(array, function (ea) {
  2507. return ea[key];
  2508. });
  2509. }
  2510. function reverse(array) {
  2511. return array.reverse();
  2512. }
  2513. function reversed(array) {
  2514. return array.slice().reverse();
  2515. }
  2516. // -=-=-=-=-=-=-=-=-=-=-=-=-
  2517. // RegExp / String matching
  2518. // -=-=-=-=-=-=-=-=-=-=-=-=-
  2519. function reMatches$1(arr, re, stringifier) {
  2520. // result might include null items if re did not match (usful for masking)
  2521. // Example:
  2522. // var morphs = $world.withAllSubmorphsDo(function(x) { return x; ;
  2523. // morphs.mask(morphs.reMatches(/code/i))
  2524. stringifier = stringifier || String;
  2525. return arr.map(function (ea) {
  2526. return stringifier(ea).match(re);
  2527. });
  2528. }
  2529. // -=-=-=-=-=-
  2530. // accessors
  2531. // -=-=-=-=-=-
  2532. function first(array) {
  2533. return array[0];
  2534. }
  2535. function last(array) {
  2536. return array[array.length - 1];
  2537. }
  2538. // -=-=-=-=-=-=-=-
  2539. // Set operations
  2540. // -=-=-=-=-=-=-=-
  2541. function intersect(array1, array2) {
  2542. // set-like intersection
  2543. return uniq(array1).filter(function (item) {
  2544. return array2.indexOf(item) > -1;
  2545. });
  2546. }
  2547. function union(array1, array2) {
  2548. // set-like union
  2549. var result = array1.slice();
  2550. for (var i = 0; i < array2.length; i++) {
  2551. var item = array2[i];
  2552. if (result.indexOf(item) === -1) result.push(item);
  2553. }
  2554. return result;
  2555. }
  2556. function pushAt(array, item, index) {
  2557. // inserts `item` at `index`, mutating
  2558. array.splice(index, 0, item);
  2559. }
  2560. function removeAt(array, index) {
  2561. // inserts item at `index`, mutating
  2562. array.splice(index, 1);
  2563. }
  2564. function remove(array, item) {
  2565. // removes first occurrence of item in `array`, mutating
  2566. var index = array.indexOf(item);
  2567. if (index >= 0) removeAt(array, index);
  2568. return item;
  2569. }
  2570. function pushAll$1(array, items) {
  2571. // appends all `items`, mutating
  2572. array.push.apply(array, items);
  2573. return array;
  2574. }
  2575. function pushAllAt(array, items, idx) {
  2576. // inserts all `items` at `idx`, mutating
  2577. array.splice.apply(array, [idx, 0].concat(items));
  2578. }
  2579. function pushIfNotIncluded(array, item) {
  2580. // only appends `item` if its not already in `array`, mutating
  2581. if (!array.includes(item)) array.push(item);
  2582. }
  2583. function replaceAt(array, item, index) {
  2584. // mutating
  2585. array.splice(index, 1, item);
  2586. }
  2587. function clear(array) {
  2588. // removes all items, mutating
  2589. array.length = 0;return array;
  2590. }
  2591. function isSubset(list1, list2) {
  2592. // are all elements in list1 in list2?
  2593. for (var i = 0; i < list1.length; i++) {
  2594. if (!list2.includes(list1[i])) return false;
  2595. }return true;
  2596. }
  2597. // -=-=-=-=-=-=-=-=-=-=-=-
  2598. // asynchronous iteration
  2599. // -=-=-=-=-=-=-=-=-=-=-=-
  2600. function doAndContinue(array, iterator, endFunc, context) {
  2601. // Iterates over array but instead of consecutively calling iterator,
  2602. // iterator gets passed in the invocation for the next iteration step
  2603. // as a function as first parameter. This allows to wait arbitrarily
  2604. // between operation steps, great for managing dependencies between tasks.
  2605. // Related is [`fun.composeAsync`]().
  2606. // Example:
  2607. // arr.doAndContinue([1,2,3,4], function(next, n) {
  2608. // alert("At " + n);
  2609. // setTimeout(next, 100);
  2610. // }, function() { alert("Done"); })
  2611. // // If the elements are functions you can leave out the iterator:
  2612. // arr.doAndContinue([
  2613. // function(next) { alert("At " + 1); next(); },
  2614. // function(next) { alert("At " + 2); next(); }
  2615. // ], null, function() { alert("Done"); });
  2616. endFunc = endFunc || Null;
  2617. context = context || GLOBAL$1;
  2618. iterator = iterator || function (next, ea, idx) {
  2619. ea.call(context, next, idx);
  2620. };
  2621. return array.reduceRight(function (nextFunc, ea, idx) {
  2622. return function () {
  2623. iterator.call(context, nextFunc, ea, idx);
  2624. };
  2625. }, endFunc)();
  2626. }
  2627. function nestedDelay(array, iterator, waitSecs, endFunc, context, optSynchronChunks) {
  2628. // Calls `iterator` for every element in `array` and waits between iterator
  2629. // calls `waitSecs`. Eventually `endFunc` is called. When passing a number n
  2630. // as `optSynchronChunks`, only every nth iteration is delayed.
  2631. endFunc = endFunc || function () {};
  2632. return array.clone().reverse().reduce(function (nextFunc, ea, idx) {
  2633. return function () {
  2634. iterator.call(context || GLOBAL$1, ea, idx);
  2635. // only really delay every n'th call optionally
  2636. if (optSynchronChunks && idx % optSynchronChunks !== 0) {
  2637. nextFunc();
  2638. } else {
  2639. nextFunc.delay(waitSecs);
  2640. }
  2641. };
  2642. }, endFunc)();
  2643. }
  2644. function forEachShowingProgress() /*array, progressBar, iterator, labelFunc, whenDoneFunc, context or spec*/{
  2645. // ignore-in-doc
  2646. var args = Array.from(arguments),
  2647. array = args.shift(),
  2648. steps = array.length,
  2649. progressBar,
  2650. iterator,
  2651. labelFunc,
  2652. whenDoneFunc,
  2653. context,
  2654. progressBarAdded = false;
  2655. // init args
  2656. if (args.length === 1) {
  2657. progressBar = args[0].progressBar;
  2658. iterator = args[0].iterator;
  2659. labelFunc = args[0].labelFunction;
  2660. whenDoneFunc = args[0].whenDone;
  2661. context = args[0].context;
  2662. } else {
  2663. progressBar = args[0];
  2664. iterator = args[1];
  2665. labelFunc = args[2];
  2666. whenDoneFunc = args[3];
  2667. context = args[4];
  2668. }
  2669. if (!context) context = typeof window !== 'undefined' ? window : global;
  2670. if (!labelFunc) labelFunc = function labelFunc(x) {
  2671. return x;
  2672. };
  2673. // init progressbar
  2674. if (!progressBar) {
  2675. progressBarAdded = true;
  2676. var Global = typeof window !== 'undefined' ? window : global;
  2677. var world = Global.lively && lively.morphic && lively.morphic.World.current();
  2678. progressBar = world ? world.addProgressBar() : {
  2679. setValue: function setValue(val) {},
  2680. setLabel: function setLabel() {},
  2681. remove: function remove() {}
  2682. };
  2683. }
  2684. progressBar.setValue(0);
  2685. // nest functions so that the iterator calls the next after a delay
  2686. array.reduceRight(function (nextFunc, item, idx) {
  2687. return function () {
  2688. try {
  2689. progressBar.setValue(idx / steps);
  2690. if (labelFunc) progressBar.setLabel(labelFunc.call(context, item, idx));
  2691. iterator.call(context, item, idx);
  2692. } catch (e) {
  2693. console.error('Error in forEachShowingProgress at %s (%s)\n%s\n%s', idx, item, e, e.stack);
  2694. }
  2695. nextFunc.delay(0);
  2696. };
  2697. }, function () {
  2698. progressBar.setValue(1);
  2699. if (progressBarAdded) (function () {
  2700. progressBar.remove();
  2701. }).delay(0);
  2702. if (whenDoneFunc) whenDoneFunc.call(context);
  2703. })();
  2704. return array;
  2705. }
  2706. function swap(array, index1, index2) {
  2707. // mutating
  2708. // Example:
  2709. // var a = [1,2,3,4];
  2710. // arr.swap(a, 3, 1);
  2711. // a // => [1,4,3,2]
  2712. if (index1 < 0) index1 = array.length + index1;
  2713. if (index2 < 0) index2 = array.length + index2;
  2714. var temp = array[index1];
  2715. array[index1] = array[index2];
  2716. array[index2] = temp;
  2717. return array;
  2718. }
  2719. function rotate(array, times) {
  2720. // non-mutating
  2721. // Example:
  2722. // arr.rotate([1,2,3]) // => [2,3,1]
  2723. times = times || 1;
  2724. return array.slice(times).concat(array.slice(0, times));
  2725. }
  2726. // -=-=-=-=-
  2727. // grouping
  2728. // -=-=-=-=-
  2729. function groupBy(array, iterator, context) {
  2730. // Applies `iterator` to each element in `array`, and puts the return value
  2731. // into a collection (the group) associated to it's stringified representation
  2732. // (the "hash").
  2733. // See [`Group.prototype`] for available operations on groups.
  2734. // Example:
  2735. // Example 1: Groups characters by how often they occur in a string:
  2736. // var chars = arr.from("Hello World");
  2737. // arr.groupBy(arr.uniq(chars), function(c) {
  2738. // return arr.count(chars, c); })
  2739. // // => {
  2740. // // "1": ["H","e"," ","W","r","d"],
  2741. // // "2": ["o"],
  2742. // // "3": ["l"]
  2743. // // }
  2744. // // Example 2: Group numbers by a custom qualifier:
  2745. // arr.groupBy([3,4,1,7,4,3,8,4], function(n) {
  2746. // if (n <= 3) return "small";
  2747. // if (n <= 7) return "medium";
  2748. // return "large";
  2749. // });
  2750. // // => {
  2751. // // large: [8],
  2752. // // medium: [4,7,4,4],
  2753. // // small: [3,1,3]
  2754. // // }
  2755. return Group.fromArray(array, iterator, context);
  2756. }
  2757. function groupByKey(array, key) {
  2758. // var objects = [{x: }]
  2759. // arr.groupBy(arr.uniq(chars), function(c) {
  2760. // return arr.count(chars, c); })
  2761. // // => {
  2762. // // "1": ["H","e"," ","W","r","d"],
  2763. // // "2": ["o"],
  2764. // // "3": ["l"]
  2765. // // }
  2766. return groupBy(array, function (ea) {
  2767. return ea[key];
  2768. });
  2769. }
  2770. function partition(array, iterator, context) {
  2771. // Example:
  2772. // var array = [1,2,3,4,5,6];
  2773. // arr.partition(array, function(ea) { return ea > 3; })
  2774. // // => [[1,2,3,4],[5,6]]
  2775. iterator = iterator || function (x) {
  2776. return x;
  2777. };
  2778. var trues = [],
  2779. falses = [];
  2780. array.forEach(function (value, index) {
  2781. (iterator.call(context, value, index) ? trues : falses).push(value);
  2782. });
  2783. return [trues, falses];
  2784. }
  2785. function batchify(array, constrainedFunc, context) {
  2786. // Takes elements and fits them into subarrays (= batches) so that for
  2787. // each batch constrainedFunc returns true. Note that contrained func
  2788. // should at least produce 1-length batches, otherwise an error is raised
  2789. // Example:
  2790. // // Assume you have list of things that have different sizes and you want to
  2791. // // create sub-arrays of these things, with each sub-array having if possible
  2792. // // less than a `batchMaxSize` of combined things in it:
  2793. // var sizes = [
  2794. // Math.pow(2, 15), // 32KB
  2795. // Math.pow(2, 29), // 512MB
  2796. // Math.pow(2, 29), // 512MB
  2797. // Math.pow(2, 27), // 128MB
  2798. // Math.pow(2, 26), // 64MB
  2799. // Math.pow(2, 26), // 64MB
  2800. // Math.pow(2, 24), // 16MB
  2801. // Math.pow(2, 26)] // 64MB
  2802. // var batchMaxSize = Math.pow(2, 28)/*256MB*/;
  2803. // function batchConstrained(batch) {
  2804. // return batch.length == 1 || batch.sum() < batchMaxSize;
  2805. // }
  2806. // var batches = sizes.batchify(batchConstrained);
  2807. // batches.pluck('length') // => [4,1,1,2]
  2808. // batches.map(arr.sum).map(num.humanReadableByteSize) // => ["208.03MB","512MB","512MB","128MB"]
  2809. return findBatches([], array);
  2810. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  2811. function extractBatch(batch, sizes) {
  2812. // ignore-in-doc
  2813. // Array -> Array -> Array[Array,Array]
  2814. // case 1: no sizes to distribute, we are done
  2815. if (!sizes.length) return [batch, []];
  2816. var first = sizes[0],
  2817. rest = sizes.slice(1);
  2818. // if batch is empty we have to take at least one
  2819. // if batch and first still fits, add first
  2820. var candidate = batch.concat([first]);
  2821. if (constrainedFunc.call(context, candidate)) return extractBatch(candidate, rest);
  2822. // otherwise leave first out for now
  2823. var batchAndSizes = extractBatch(batch, rest);
  2824. return [batchAndSizes[0], [first].concat(batchAndSizes[1])];
  2825. }
  2826. function findBatches(batches, sizes) {
  2827. if (!sizes.length) return batches;
  2828. var extracted = extractBatch([], sizes);
  2829. if (!extracted[0].length) throw new Error('Batchify constrained does not ensure consumption ' + 'of at least one item per batch!');
  2830. return findBatches(batches.concat([extracted[0]]), extracted[1]);
  2831. }
  2832. }
  2833. function toTuples(array, tupleLength) {
  2834. // Creates sub-arrays with length `tupleLength`
  2835. // Example:
  2836. // arr.toTuples(["H","e","l","l","o"," ","W","o","r","l","d"], 4)
  2837. // // => [["H","e","l","l"],["o"," ","W","o"],["r","l","d"]]
  2838. tupleLength = tupleLength || 1;
  2839. return range(0, Math.ceil(array.length / tupleLength) - 1).map(function (n) {
  2840. return array.slice(n * tupleLength, n * tupleLength + tupleLength);
  2841. }, array);
  2842. }
  2843. var permutations = function () {
  2844. function computePermutations(restArray, values$$1) {
  2845. return !restArray.length ? [values$$1] : flatmap(restArray, function (ea, i) {
  2846. return computePermutations(restArray.slice(0, i).concat(restArray.slice(i + 1)), values$$1.concat([ea]));
  2847. });
  2848. }
  2849. return function (array) {
  2850. return computePermutations(array, []);
  2851. };
  2852. }();
  2853. function combinationsPick(listOfListsOfValues, pickIndices) {
  2854. // Given a "listOfListsOfValues" in the form of an array of arrays and
  2855. // `pickIndices` list with the size of the number of arrays which indicates what
  2856. // values to pick from each of the arrays, return a list with two values:
  2857. // 1. values picked from each of the arrays, 2. the next pickIndices or null if at end
  2858. // Example:
  2859. // var searchSpace = [["a", "b", "c"], [1,2]];
  2860. // arr.combinationsPick(searchSpace, [0,1]);
  2861. // // => [["a",2], [1,0]]
  2862. // arr.combinationsPick(searchSpace, [1,0]);
  2863. // // => [["b",1], [1,1]]
  2864. var values$$1 = listOfListsOfValues.map(function (subspace, i) {
  2865. return subspace[pickIndices[i]];
  2866. }),
  2867. nextState = pickIndices.slice();
  2868. for (var i = listOfListsOfValues.length; i--; i >= 0) {
  2869. var subspace = listOfListsOfValues[i],
  2870. nextIndex = nextState[i] + 1;
  2871. if (subspace[nextIndex]) {
  2872. nextState[i] = nextIndex;break;
  2873. } else if (i === 0) {
  2874. nextState = undefined;break;
  2875. } else {
  2876. nextState[i] = 0;
  2877. }
  2878. }
  2879. return [values$$1, nextState];
  2880. }
  2881. function combinations(listOfListsOfValues) {
  2882. // Given a "listOfListsOfValues" in the form of an array of arrays,
  2883. // retrieve all the combinations by picking one item from each array.
  2884. // This basically creates a search tree, traverses it and gathers all node
  2885. // values whenever a leaf node is reached.
  2886. // Example:
  2887. // lively.lang.arr.combinations([['a', 'b', 'c'], [1, 2]])
  2888. // // => [["a", 1], ["a", 2], ["b", 1], ["b", 2], ["c", 1], ["c", 2]]
  2889. var size = listOfListsOfValues.reduce(function (prod, space) {
  2890. return prod * space.length;
  2891. }, 1),
  2892. searchState = listOfListsOfValues.map(function (_) {
  2893. return 0;
  2894. }),
  2895. results = new Array(size);
  2896. for (var i = 0; i < size; i++) {
  2897. var result = combinationsPick(listOfListsOfValues, searchState);
  2898. results[i] = result[0];
  2899. searchState = result[1];
  2900. }
  2901. return results;
  2902. }
  2903. function take(arr, n) {
  2904. return arr.slice(0, n);
  2905. }
  2906. function drop(arr, n) {
  2907. return arr.slice(n);
  2908. }
  2909. function takeWhile(arr, fun, context) {
  2910. var i = 0;
  2911. for (; i < arr.length; i++) {
  2912. if (!fun.call(context, arr[i], i)) break;
  2913. }return arr.slice(0, i);
  2914. }
  2915. function dropWhile(arr, fun, context) {
  2916. var i = 0;
  2917. for (; i < arr.length; i++) {
  2918. if (!fun.call(context, arr[i], i)) break;
  2919. }return arr.slice(i);
  2920. }
  2921. // -=-=-=-=-=-
  2922. // randomness
  2923. // -=-=-=-=-=-
  2924. function shuffle(array) {
  2925. // Ramdomize the order of elements of array. Does not mutate array.
  2926. // Example:
  2927. // shuffle([1,2,3,4,5]) // => [3,1,2,5,4]
  2928. var unusedIndexes = range(0, array.length - 1),
  2929. shuffled = Array(array.length);
  2930. for (var i = 0; i < array.length; i++) {
  2931. var shuffledIndex = unusedIndexes.splice(Math.round(Math.random() * (unusedIndexes.length - 1)), 1);
  2932. shuffled[shuffledIndex] = array[i];
  2933. }
  2934. return shuffled;
  2935. }
  2936. // -=-=-=-=-=-=-=-
  2937. // Number related
  2938. // -=-=-=-=-=-=-=-
  2939. function max(array, iterator, context) {
  2940. // Example:
  2941. // var array = [{x:3,y:2}, {x:5,y:1}, {x:1,y:5}];
  2942. // arr.max(array, function(ea) { return ea.x; }) // => {x: 5, y: 1}
  2943. iterator = iterator || function (x) {
  2944. return x;
  2945. };
  2946. var result;
  2947. array.reduce(function (max, ea, i) {
  2948. var val = iterator.call(context, ea, i);
  2949. if (typeof val !== "number" || val <= max) return max;
  2950. result = ea;return val;
  2951. }, -Infinity);
  2952. return result;
  2953. }
  2954. function min(array, iterator, context) {
  2955. // Similar to `arr.max`.
  2956. iterator = iterator || function (x) {
  2957. return x;
  2958. };
  2959. return max(array, function (ea, i) {
  2960. return -iterator.call(context, ea, i);
  2961. });
  2962. }
  2963. function sum(array) {
  2964. // show-in-doc
  2965. var sum = 0;
  2966. for (var i = 0; i < array.length; i++) {
  2967. sum += array[i];
  2968. }return sum;
  2969. }
  2970. function count$1(array, item) {
  2971. return array.reduce(function (count, ea) {
  2972. return ea === item ? count + 1 : count;
  2973. }, 0);
  2974. }
  2975. function size$1(array) {
  2976. return array.length;
  2977. }
  2978. function histogram(data, binSpec) {
  2979. // ignore-in-doc
  2980. // Without a `binSpec` argument partition the data
  2981. // var numbers = arr.genN(10, num.random);
  2982. // var numbers = arr.withN(10, "a");
  2983. // => [65,73,34,94,92,31,27,55,95,48]
  2984. // => [[65,73],[34,94],[92,31],[27,55],[95,48]]
  2985. // => [[82,50,16],[25,43,77],[40,64,31],[51,39,13],[17,34,87],[51,33,30]]
  2986. if (typeof binSpec === 'undefined' || typeof binSpec === 'number') {
  2987. var binNumber = binSpec || function sturge() {
  2988. return Math.ceil(Math.log(data.length) / Math.log(2) + 1);
  2989. }(data);
  2990. var binSize = Math.ceil(Math.round(data.length / binNumber));
  2991. return range(0, binNumber - 1).map(function (i) {
  2992. return data.slice(i * binSize, (i + 1) * binSize);
  2993. });
  2994. } else if (binSpec instanceof Array) {
  2995. // ignore-in-doc
  2996. // bins specifies n threshold values that will create n-1 bins.
  2997. // Each data value d is placed inside a bin i if:
  2998. // threshold[i] >= d && threshold[i+1] < d
  2999. var thresholds = binSpec;
  3000. return data.reduce(function (bins, d) {
  3001. if (d < thresholds[1]) {
  3002. bins[0].push(d);return bins;
  3003. }
  3004. for (var i = 1; i < thresholds.length; i++) {
  3005. if (d >= thresholds[i] && (!thresholds[i + 1] || d <= thresholds[i + 1])) {
  3006. bins[i].push(d);return bins;
  3007. }
  3008. }
  3009. throw new Error("Histogram creation: Cannot group data " + d + " into thresholds " + thresholds);
  3010. }, range(1, thresholds.length).map(function () {
  3011. return [];
  3012. }));
  3013. }
  3014. }
  3015. // -=-=-=-=-
  3016. // Copying
  3017. // -=-=-=-=-
  3018. function clone$1(array) {
  3019. // shallow copy
  3020. return [].concat(array);
  3021. }
  3022. // -=-=-=-=-=-
  3023. // conversion
  3024. // -=-=-=-=-=-
  3025. function toArray$3(array) {
  3026. return from(array);
  3027. }
  3028. // -=-=-=-=-=-
  3029. // DEPRECATED
  3030. // -=-=-=-=-=-
  3031. function each(arr, iterator, context) {
  3032. return arr.forEach(iterator, context);
  3033. }
  3034. function all$1(arr, iterator, context) {
  3035. return arr.every(iterator, context);
  3036. }
  3037. function any(arr, iterator, context) {
  3038. return arr.some(iterator, context);
  3039. }
  3040. function collect(arr, iterator, context) {
  3041. return arr.map(iterator, context);
  3042. }
  3043. function findAll(arr, iterator, context) {
  3044. return arr.filter(iterator, context);
  3045. }
  3046. function inject(array, memo, iterator, context) {
  3047. if (context) iterator = iterator.bind(context);
  3048. return array.reduce(iterator, memo);
  3049. }
  3050. // asynch methods
  3051. function mapAsyncSeries(array, iterator, callback) {
  3052. // Apply `iterator` over `array`. Unlike `mapAsync` the invocation of
  3053. // the iterator happens step by step in the order of the items of the array
  3054. // and not concurrently.
  3055. // ignore-in-doc
  3056. // Could simply be:
  3057. // return exports.arr.mapAsync(array, {parallel: 1}, iterator, callback);
  3058. // but the version below is 2x faster
  3059. var result = [],
  3060. callbackTriggered = false;
  3061. return array.reduceRight(function (nextFunc, ea, idx) {
  3062. if (callbackTriggered) return;
  3063. return function (err, eaResult) {
  3064. if (err) return maybeDone(err);
  3065. if (idx > 0) result.push(eaResult);
  3066. try {
  3067. iterator(ea, idx, once(nextFunc));
  3068. } catch (e) {
  3069. maybeDone(e);
  3070. }
  3071. };
  3072. }, function (err, eaResult) {
  3073. result.push(eaResult);
  3074. maybeDone(err, true);
  3075. })();
  3076. function maybeDone(err, finalCall) {
  3077. if (callbackTriggered || !err && !finalCall) return;
  3078. callbackTriggered = true;
  3079. try {
  3080. callback(err, result);
  3081. } catch (e) {
  3082. console.error("Error in mapAsyncSeries - callback invocation error:\n" + (e.stack || e));
  3083. }
  3084. }
  3085. }
  3086. function mapAsync(array, options, iterator, callback) {
  3087. // Apply `iterator` over `array`. In each iterator gets a callback as third
  3088. // argument that should be called when the iteration is done. After all
  3089. // iterators have called their callbacks, the main `callback` function is
  3090. // invoked with the result array.
  3091. // Example:
  3092. // lively.lang.arr.mapAsync([1,2,3,4],
  3093. // function(n, i, next) { setTimeout(function() { next(null, n + i); }, 20); },
  3094. // function(err, result) { /* result => [1,3,5,7] */ });
  3095. if (typeof options === "function") {
  3096. callback = iterator;
  3097. iterator = options;
  3098. options = null;
  3099. }
  3100. options = options || {};
  3101. if (!array.length) return callback && callback(null, []);
  3102. if (!options.parallel) options.parallel = Infinity;
  3103. var results = [],
  3104. completed = [],
  3105. callbackTriggered = false,
  3106. lastIteratorIndex = 0,
  3107. nActive = 0;
  3108. var iterators = array.map(function (item, i) {
  3109. return function () {
  3110. nActive++;
  3111. try {
  3112. iterator(item, i, once(function (err, result) {
  3113. results[i] = err || result;
  3114. maybeDone(i, err);
  3115. }));
  3116. } catch (e) {
  3117. maybeDone(i, e);
  3118. }
  3119. };
  3120. });
  3121. return activate();
  3122. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  3123. function activate() {
  3124. while (nActive < options.parallel && lastIteratorIndex < array.length) {
  3125. iterators[lastIteratorIndex++]();
  3126. }
  3127. }
  3128. function maybeDone(idx, err) {
  3129. if (completed.indexOf(idx) > -1) return;
  3130. completed.push(idx);
  3131. nActive--;
  3132. if (callbackTriggered) return;
  3133. if (!err && completed.length < array.length) {
  3134. activate();return;
  3135. }
  3136. callbackTriggered = true;
  3137. try {
  3138. callback && callback(err, results);
  3139. } catch (e) {
  3140. console.error("Error in mapAsync - main callback invocation error:\n" + (e.stack || e));
  3141. }
  3142. }
  3143. }
  3144. // poly-filling...
  3145. if (!features$1.from) Array.from = from;
  3146. if (!features$1.filter) Array.prototype.filter = function (it, ctx) {
  3147. return filter(this, it, ctx);
  3148. };
  3149. if (!features$1.find) Array.prototype.find = function (it, ctx) {
  3150. return detect(this, it, ctx);
  3151. };
  3152. if (!features$1.findIndex) Array.prototype.findIndex = function (it, ctx) {
  3153. return findIndex(this, it, ctx);
  3154. };
  3155. if (!features$1.includes) Array.prototype.includes = function (x) {
  3156. return includes$1(this, x);
  3157. };
  3158. var arr = Object.freeze({
  3159. range: range,
  3160. from: from,
  3161. withN: withN,
  3162. genN: genN,
  3163. filter: filter,
  3164. detect: detect,
  3165. findIndex: findIndex,
  3166. findAndGet: findAndGet,
  3167. filterByKey: filterByKey,
  3168. grep: grep,
  3169. mask: mask,
  3170. reject: reject,
  3171. rejectByKey: rejectByKey,
  3172. without: without,
  3173. withoutAll: withoutAll,
  3174. uniq: uniq,
  3175. uniqBy: uniqBy,
  3176. uniqByKey: uniqByKey,
  3177. compact: compact,
  3178. mutableCompact: mutableCompact,
  3179. forEach: forEach$1,
  3180. zip: zip,
  3181. flatten: flatten,
  3182. flatmap: flatmap,
  3183. interpose: interpose,
  3184. delimWith: delimWith,
  3185. map: map$1,
  3186. invoke: invoke,
  3187. pluck: pluck,
  3188. reduce: reduce,
  3189. reduceRight: reduceRight,
  3190. isArray: isArray$1,
  3191. includes: includes$1,
  3192. include: include$1,
  3193. some: some,
  3194. every: every,
  3195. equals: equals$2,
  3196. deepEquals: deepEquals,
  3197. isSorted: isSorted,
  3198. sort: sort,
  3199. sortBy: sortBy,
  3200. sortByKey: sortByKey,
  3201. reverse: reverse,
  3202. reversed: reversed,
  3203. reMatches: reMatches$1,
  3204. first: first,
  3205. last: last,
  3206. intersect: intersect,
  3207. union: union,
  3208. pushAt: pushAt,
  3209. removeAt: removeAt,
  3210. remove: remove,
  3211. pushAll: pushAll$1,
  3212. pushAllAt: pushAllAt,
  3213. pushIfNotIncluded: pushIfNotIncluded,
  3214. replaceAt: replaceAt,
  3215. clear: clear,
  3216. isSubset: isSubset,
  3217. doAndContinue: doAndContinue,
  3218. nestedDelay: nestedDelay,
  3219. forEachShowingProgress: forEachShowingProgress,
  3220. swap: swap,
  3221. rotate: rotate,
  3222. groupBy: groupBy,
  3223. groupByKey: groupByKey,
  3224. partition: partition,
  3225. batchify: batchify,
  3226. toTuples: toTuples,
  3227. permutations: permutations,
  3228. combinationsPick: combinationsPick,
  3229. combinations: combinations,
  3230. take: take,
  3231. drop: drop,
  3232. takeWhile: takeWhile,
  3233. dropWhile: dropWhile,
  3234. shuffle: shuffle,
  3235. max: max,
  3236. min: min,
  3237. sum: sum,
  3238. count: count$1,
  3239. size: size$1,
  3240. histogram: histogram,
  3241. clone: clone$1,
  3242. toArray: toArray$3,
  3243. each: each,
  3244. all: all$1,
  3245. any: any,
  3246. collect: collect,
  3247. findAll: findAll,
  3248. inject: inject,
  3249. mapAsyncSeries: mapAsyncSeries,
  3250. mapAsync: mapAsync
  3251. });
  3252. /*
  3253. * Utility functions that help to inspect, enumerate, and create JS objects
  3254. */
  3255. // -=-=-=-=-=-=-=-=-
  3256. // internal helper
  3257. // -=-=-=-=-=-=-=-=-
  3258. // serveral methods in lib/object.js are inspired or derived from
  3259. // Prototype JavaScript framework, version 1.6.0_rc1
  3260. // (c) 2005-2007 Sam Stephenson
  3261. // Prototype is freely distributable under the terms of an MIT-style license.
  3262. // For details, see the Prototype web site: http://www.prototypejs.org/
  3263. function print$1(object) {
  3264. if (object && Array.isArray(object)) {
  3265. return '[' + object.map(print$1) + ']';
  3266. }
  3267. if (typeof object !== "string") {
  3268. return String(object);
  3269. }
  3270. var result = String(object);
  3271. result = result.replace(/\n/g, '\\n\\\n');
  3272. result = result.replace(/(")/g, '\\$1');
  3273. result = '\"' + result + '\"';
  3274. return result;
  3275. }
  3276. function indent$1(str, indentString, depth) {
  3277. if (!depth || depth <= 0) return str;
  3278. while (depth > 0) {
  3279. depth--;str = indentString + str;
  3280. }
  3281. return str;
  3282. }
  3283. var getOwnPropertyDescriptors = typeof Object.prototype.getOwnPropertyDescriptors === "function" ? Object.prototype.getOwnPropertyDescriptors : function getOwnPropertyDescriptors(object) {
  3284. var descriptors = {};
  3285. for (var name in object) {
  3286. if (!Object.prototype.hasOwnProperty.call(object, name)) continue;
  3287. Object.defineProperty(descriptors, name, {
  3288. configurable: true,
  3289. enumerable: true,
  3290. writable: true,
  3291. value: Object.getOwnPropertyDescriptor(object, name)
  3292. });
  3293. }
  3294. return descriptors;
  3295. };
  3296. // show-in-doc
  3297. // -=-=-=-=-
  3298. // testing
  3299. // -=-=-=-=-
  3300. function isArray$$1(obj) {
  3301. /*show-in-doc*/return Array.isArray(obj);
  3302. }
  3303. function isElement(object) {
  3304. /*show-in-doc*/return object && object.nodeType == 1;
  3305. }
  3306. function isFunction(object) {
  3307. /*show-in-doc*/return object instanceof Function;
  3308. }
  3309. function isBoolean(object) {
  3310. /*show-in-doc*/return typeof object == "boolean";
  3311. }
  3312. function isString(object) {
  3313. /*show-in-doc*/return typeof object == "string";
  3314. }
  3315. function isNumber(object) {
  3316. /*show-in-doc*/return typeof object == "number";
  3317. }
  3318. function isUndefined(object) {
  3319. /*show-in-doc*/return typeof object == "undefined";
  3320. }
  3321. function isRegExp(object) {
  3322. /*show-in-doc*/return object instanceof RegExp;
  3323. }
  3324. function isObject(object) {
  3325. /*show-in-doc*/return (typeof object === "undefined" ? "undefined" : _typeof(object)) == "object";
  3326. }
  3327. function isPrimitive(obj) {
  3328. // show-in-doc
  3329. if (!obj) return true;
  3330. switch (typeof obj === "undefined" ? "undefined" : _typeof(obj)) {
  3331. case "string":
  3332. case "number":
  3333. case "boolean":
  3334. return true;
  3335. }
  3336. return false;
  3337. }
  3338. function isEmpty(object) {
  3339. /*show-in-doc*/
  3340. for (var key in object) {
  3341. if (object.hasOwnProperty(key)) return false;
  3342. }return true;
  3343. }
  3344. function equals$1(a, b) {
  3345. // Is object `a` structurally equivalent to object `b`? Deep comparison.
  3346. if (a === b) return true;
  3347. if (!a || !b) return a == b;
  3348. if (Array.isArray(a)) return deepEquals(a, b);
  3349. switch (a.constructor) {
  3350. case String:
  3351. case Date:
  3352. case Boolean:
  3353. case Number:
  3354. return a == b;
  3355. }
  3356. if (typeof a.isEqualNode === "function") return a.isEqualNode(b);
  3357. if (typeof a.equals === "function") return a.equals(b);
  3358. var seenInA = [];
  3359. for (var name in a) {
  3360. seenInA.push(name);
  3361. if (typeof a[name] === "function") continue;
  3362. if (!equals$1(a[name], b[name])) return false;
  3363. }
  3364. for (var name in b) {
  3365. if (seenInA.indexOf(name) !== -1) continue;
  3366. if (typeof b[name] === "function") continue;
  3367. if (!equals$1(b[name], a[name])) return false;
  3368. }
  3369. return true;
  3370. }
  3371. // -=-=-=-=-=-
  3372. // accessing
  3373. // -=-=-=-=-=-
  3374. var keys$1 = Object.keys;
  3375. function values(object) {
  3376. // Example:
  3377. // var obj1 = {x: 22}, obj2 = {x: 23, y: {z: 3}};
  3378. // obj2.__proto__ = obj1;
  3379. // obj.values(obj1) // => [22]
  3380. // obj.values(obj2) // => [23,{z: 3}]
  3381. return object ? Object.keys(object).map(function (k) {
  3382. return object[k];
  3383. }) : [];
  3384. }
  3385. function select(obj, keys) {
  3386. // return a new object that copies all properties with `keys` from `obj`
  3387. var selected = {};
  3388. for (var i = 0; i < keys.length; i++) {
  3389. selected[keys[i]] = obj[keys[i]];
  3390. }return selected;
  3391. }
  3392. function dissoc(object, keys) {
  3393. object = object || {};
  3394. var descriptors = getOwnPropertyDescriptors(object);
  3395. for (var i = 0; i < keys.length; i++) {
  3396. if (keys[i] in descriptors) delete descriptors[keys[i]];
  3397. }
  3398. return Object.defineProperties({}, descriptors);
  3399. }
  3400. function addScript(object, funcOrString, optName, optMapping) {
  3401. var func = fromString(funcOrString);
  3402. return asScriptOf(func, object, optName, optMapping);
  3403. }
  3404. // -=-=-=-=-
  3405. // mutation
  3406. // -=-=-=-=-
  3407. function extend(destination, source) {
  3408. // Add all properties of `source` to `destination`.
  3409. // Example:
  3410. // var dest = {x: 22}, src = {x: 23, y: 24}
  3411. // obj.extend(dest, src);
  3412. // dest // => {x: 23,y: 24}
  3413. var currentCategoryNames = null;
  3414. for (var i = 1; i < arguments.length; i++) {
  3415. if (typeof arguments[i] == "string") {
  3416. var catName = arguments[i];
  3417. if (!destination.categories) destination.categories = {};
  3418. if (!destination.categories[catName]) destination.categories[catName] = [];
  3419. currentCategoryNames = destination.categories[catName];
  3420. continue;
  3421. }
  3422. var source = arguments[i];
  3423. for (var property in source) {
  3424. var getter = source.__lookupGetter__(property),
  3425. setter = source.__lookupSetter__(property);
  3426. if (getter) destination.__defineGetter__(property, getter);
  3427. if (setter) destination.__defineSetter__(property, setter);
  3428. if (getter || setter) continue;
  3429. var sourceObj = source[property];
  3430. destination[property] = sourceObj;
  3431. if (currentCategoryNames) currentCategoryNames.push(property);
  3432. if (typeof sourceObj === "function") {
  3433. if (!sourceObj.displayName) sourceObj.displayName = property;
  3434. // remember the module that contains the definition
  3435. if (typeof lively !== "undefined" && lively.Module && lively.Module.current) sourceObj.sourceModule = lively.Module.current();
  3436. }
  3437. }
  3438. }
  3439. return destination;
  3440. }
  3441. // -=-=-=-=-
  3442. // clone
  3443. // -=-=-=-=-
  3444. function clone$$1(object) {
  3445. // Shallow copy
  3446. if (isPrimitive(object)) return object;
  3447. if (Array.isArray(object)) return Array.prototype.slice.call(object);
  3448. var clone$$1 = {};
  3449. for (var key in object) {
  3450. if (object.hasOwnProperty(key)) clone$$1[key] = object[key];
  3451. }
  3452. return clone$$1;
  3453. }
  3454. function extract(object, properties, mapFunc) {
  3455. // Takes a list of properties and returns a new object with those
  3456. // properties shallow-copied from object
  3457. var copied = {};
  3458. for (var i = 0; i < properties.length; i++) {
  3459. if (properties[i] in object) copied[properties[i]] = mapFunc ? mapFunc(properties[i], object[properties[i]]) : object[properties[i]];
  3460. }
  3461. return copied;
  3462. }
  3463. // -=-=-=-=-=-
  3464. // inspection
  3465. // -=-=-=-=-=-
  3466. function inspect(object, options, depth) {
  3467. // Prints a human-readable representation of `obj`. The printed
  3468. // representation will be syntactically correct JavaScript but will not
  3469. // necessarily evaluate to a structurally identical object. `inspect` is
  3470. // meant to be used while interactivively exploring JavaScript programs and
  3471. // state.
  3472. //
  3473. // `options` can be {
  3474. // printFunctionSource: BOOLEAN,
  3475. // escapeKeys: BOOLEAN,
  3476. // maxDepth: NUMBER,
  3477. // customPrinter: FUNCTION,
  3478. // maxNumberOfKeys: NUMBER
  3479. // }
  3480. options = options || {};
  3481. depth = depth || 0;
  3482. if (options.customPrinter) {
  3483. var ignoreSignal = options._ignoreSignal || (options._ignoreSignal = {}),
  3484. continueInspectFn = function continueInspectFn(obj) {
  3485. return inspect(obj, options, depth + 1);
  3486. },
  3487. customInspected = options.customPrinter(object, ignoreSignal, continueInspectFn);
  3488. if (customInspected !== ignoreSignal) return customInspected;
  3489. }
  3490. if (!object) return print$1(object);
  3491. // print function
  3492. if (typeof object === 'function') {
  3493. return options.printFunctionSource ? String(object) : 'function' + (object.name ? ' ' + object.name : '') + '(' + argumentNames(object).join(',') + ') {/*...*/}';
  3494. }
  3495. // print "primitive"
  3496. switch (object.constructor) {
  3497. case String:
  3498. case Boolean:
  3499. case RegExp:
  3500. case Number:
  3501. return print$1(object);
  3502. }
  3503. if (typeof object.serializeExpr === 'function') return object.serializeExpr();
  3504. var isArray$$1 = object && Array.isArray(object),
  3505. openBr = isArray$$1 ? '[' : '{',
  3506. closeBr = isArray$$1 ? ']' : '}';
  3507. if (options.maxDepth && depth >= options.maxDepth) return openBr + '/*...*/' + closeBr;
  3508. var printedProps = [];
  3509. if (isArray$$1) {
  3510. printedProps = object.map(function (ea) {
  3511. return inspect(ea, options, depth + 1);
  3512. });
  3513. } else {
  3514. var propsToPrint = Object.keys(object).sort(function (a, b) {
  3515. var aIsFunc = typeof object[a] === 'function',
  3516. bIsFunc = typeof object[b] === 'function';
  3517. if (aIsFunc === bIsFunc) {
  3518. if (a < b) return -1;
  3519. if (a > b) return 1;
  3520. return 0;
  3521. }
  3522. return aIsFunc ? 1 : -1;
  3523. });
  3524. for (var i = 0; i < propsToPrint.length; i++) {
  3525. if (i > (options.maxNumberOfKeys || Infinity)) {
  3526. var hiddenEntryCount = propsToPrint.length - i;
  3527. printedProps.push("..." + hiddenEntryCount + " hidden " + (hiddenEntryCount > 1 ? 'entries' : 'entry') + "...");
  3528. break;
  3529. }
  3530. var key = propsToPrint[i];
  3531. if (isArray$$1) inspect(object[key], options, depth + 1);
  3532. var printedVal = inspect(object[key], options, depth + 1);
  3533. printedProps.push((options.escapeKeys ? JSON.stringify(key) : key) + ": " + printedVal);
  3534. }
  3535. }
  3536. if (printedProps.length === 0) {
  3537. return openBr + closeBr;
  3538. }
  3539. var printedPropsJoined = printedProps.join(', '),
  3540. useNewLines = (!isArray$$1 || options.newLineInArrays) && (!options.minLengthForNewLine || printedPropsJoined.length >= options.minLengthForNewLine),
  3541. ind = indent$1('', options.indent || ' ', depth),
  3542. propIndent = indent$1('', options.indent || ' ', depth + 1),
  3543. startBreak = useNewLines && !isArray$$1 ? '\n' + propIndent : '',
  3544. eachBreak = useNewLines ? '\n' + propIndent : '',
  3545. endBreak = useNewLines && !isArray$$1 ? '\n' + ind : '';
  3546. if (useNewLines) printedPropsJoined = printedProps.join(',' + eachBreak);
  3547. return openBr + startBreak + printedPropsJoined + endBreak + closeBr;
  3548. }
  3549. // -=-=-=-=-
  3550. // merging
  3551. // -=-=-=-=-
  3552. function merge(objs) {
  3553. // `objs` can be a list of objects. The return value will be a new object,
  3554. // containing all properties of all objects. If the same property exist in
  3555. // multiple objects, the right-most property takes precedence.
  3556. //
  3557. // Like `extend` but will not mutate objects in `objs`.
  3558. // if objs are arrays just concat them
  3559. // if objs are real objs then merge propertdies
  3560. if (arguments.length > 1) {
  3561. return merge(Array.prototype.slice.call(arguments));
  3562. }
  3563. if (Array.isArray(objs[0])) {
  3564. // test for all?
  3565. return Array.prototype.concat.apply([], objs);
  3566. }
  3567. return objs.reduce(function (merged, ea) {
  3568. for (var name in ea) {
  3569. if (ea.hasOwnProperty(name)) merged[name] = ea[name];
  3570. }return merged;
  3571. }, {});
  3572. }
  3573. function deepMerge(objA, objB) {
  3574. // `objs` can be a list of objects. The return value will be a new object,
  3575. // containing all properties of all objects. If the same property exist in
  3576. // multiple objects, the right-most property takes precedence.
  3577. //
  3578. // Like `extend` but will not mutate objects in `objs`.
  3579. // if objs are arrays just concat them
  3580. // if objs are real objs then merge propertdies
  3581. if (!objA) return objB;
  3582. if (!objB) return objA;
  3583. if (Array.isArray(objA)) {
  3584. if (!Array.isArray(objB)) return objB;
  3585. var merged = objA.map(function (ea, i) {
  3586. return deepMerge(ea, objB[i]);
  3587. });
  3588. if (objB.length > objA.length) merged = merged.concat(objB.slice(objA.length));
  3589. return merged;
  3590. }
  3591. if ((typeof objA === "undefined" ? "undefined" : _typeof(objA)) !== "object" || (typeof objB === "undefined" ? "undefined" : _typeof(objB)) !== "object") return objB;
  3592. return Object.keys(objA).concat(Object.keys(objB)).reduce(function (merged, name) {
  3593. if (!objA[name]) merged[name] = objB[name];else if (!objB[name]) merged[name] = objA[name];else if (_typeof(objA[name]) !== "object" || _typeof(objB[name]) !== "object") merged[name] = objB[name];else merged[name] = deepMerge(objA[name], objB[name]);
  3594. return merged;
  3595. }, {});
  3596. }
  3597. function sortKeysWithBeforeAndAfterConstraints(properties) {
  3598. var throwErrorOnMissing = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  3599. // Expects `properties` to be a map of keys to objects having optional
  3600. // before/after attributes that, if present, should be lists of other property
  3601. // keys. `sortProperties` will return an ordered list of property keys so
  3602. // that the before / after requirements are fullfilled. If a cyclic
  3603. // dependency is encountered an error will be thrown.
  3604. // Example:
  3605. // ```
  3606. // sortProperties({foo: {}, bar: {after: ["foo"], before: ["baz"]}, "baz": {after: ["foo"]}})
  3607. // // => ["foo","bar","baz"]
  3608. // ```
  3609. // ignore-in-doc
  3610. // 1. convert "before" requirement into "after" and check if all properties
  3611. // mentioned in after/before are actually there
  3612. var keys = [],
  3613. props = [],
  3614. remaining = [];
  3615. for (var key in properties) {
  3616. var prop = properties[key],
  3617. before = prop.hasOwnProperty("before") ? prop.before : prop.before = [],
  3618. after = prop.hasOwnProperty("after") ? prop.after : prop.after = [];
  3619. keys.push(key);
  3620. props.push(prop);
  3621. for (var i = before.length; i--;) {
  3622. var beforePropName = before[i];
  3623. var beforeProp = properties[beforePropName];
  3624. if (!beforeProp) {
  3625. console.warn("[initializeProperties] " + this + " sortProperties: " + ("Property " + key + " requires to be initialized before " + beforePropName + " ") + "but that property cannot be found.");
  3626. before.splice(i, 1);
  3627. continue;
  3628. }
  3629. if (!beforeProp.hasOwnProperty("after")) beforeProp.after = [];
  3630. beforeProp.after.push(key);
  3631. }
  3632. for (var _i = after.length; _i--;) {
  3633. var afterPropName = after[_i];
  3634. var afterProp = properties[afterPropName];
  3635. if (!afterProp) {
  3636. console.warn("[initializeProperties] " + this + " sortProperties: " + ("Property " + key + " requires to be initialized after " + afterPropName + " ") + "but that property cannot be found.");
  3637. after.splice(_i, 1);
  3638. }
  3639. }
  3640. remaining.push(key);
  3641. }
  3642. // ignore-in-doc
  3643. // compute order
  3644. var resolvedGroups = [],
  3645. resolvedKeys = [],
  3646. lastLength = remaining.length + 1;
  3647. while (remaining.length) {
  3648. if (lastLength === remaining.length) throw new Error("Circular dependencies in handler order, could not resolve properties " + remaining.map(function (key) {
  3649. var before = properties[key].before,
  3650. after = properties[key].after;
  3651. if ((!before || !before.length) && (!after || !after.length)) return "";
  3652. var report = key + "\n";
  3653. if (before && before.length) report += " - before " + before.join(",") + "\n";
  3654. if (after && after.length) report += " - after " + after.join(",") + "\n";
  3655. return report;
  3656. }).join(""));
  3657. lastLength = remaining.length;
  3658. var resolvedGroup = [];
  3659. for (var _i2 = remaining.length; _i2--;) {
  3660. var _key = remaining[_i2];
  3661. if (isSubset(properties[_key].after, resolvedKeys)) {
  3662. remaining.splice(_i2, 1);
  3663. resolvedKeys.push(_key);
  3664. resolvedGroup.push(_key);
  3665. }
  3666. }
  3667. resolvedGroups.push(resolvedGroup);
  3668. }
  3669. return flatten(resolvedGroups, 1);
  3670. }
  3671. // -=-=-=-=-=-=-
  3672. // inheritance
  3673. // -=-=-=-=-=-=-
  3674. function inherit(obj) {
  3675. return Object.create(obj);
  3676. }
  3677. function valuesInPropertyHierarchy(obj, name) {
  3678. // Lookup all properties named name in the proto hierarchy of obj.
  3679. // Example:
  3680. // var a = {foo: 3}, b = Object.create(a), c = Object.create(b);
  3681. // c.foo = 4;
  3682. // obj.valuesInPropertyHierarchy(c, "foo") // => [3,4]
  3683. var result = [],
  3684. lookupObj = obj;
  3685. while (lookupObj) {
  3686. if (lookupObj.hasOwnProperty(name)) result.unshift(lookupObj[name]);
  3687. lookupObj = Object.getPrototypeOf(lookupObj);
  3688. }
  3689. return result;
  3690. }
  3691. function mergePropertyInHierarchy(obj, propName) {
  3692. // like `merge` but automatically gets all definitions of the value in the
  3693. // prototype chain and merges those.
  3694. // Example:
  3695. // var o1 = {x: {foo: 23}}, o2 = {x: {foo: 24, bar: 15}}, o3 = {x: {baz: "zork"}};
  3696. // o2.__proto__ = o1; o3.__proto__ = o2;
  3697. // obj.mergePropertyInHierarchy(o3, "x");
  3698. // // => {bar: 15, baz: "zork",foo: 24}
  3699. return merge(valuesInPropertyHierarchy(obj, propName));
  3700. }
  3701. function deepCopy(object) {
  3702. // Recursively traverses `object` and its properties to create a copy.
  3703. if (!object || (typeof object === "undefined" ? "undefined" : _typeof(object)) !== "object" || object instanceof RegExp) return object;
  3704. var result = Array.isArray(object) ? Array(object.length) : {};
  3705. for (var key in object) {
  3706. if (object.hasOwnProperty(key)) result[key] = deepCopy(object[key]);
  3707. }
  3708. return result;
  3709. }
  3710. // -=-=-=-=-=-=-=-=-
  3711. // stringification
  3712. // -=-=-=-=-=-=-=-=-
  3713. function typeStringOf(obj) {
  3714. // ignore-in-doc
  3715. if (obj === null) return "null";
  3716. if (typeof obj === "undefined") return "undefined";
  3717. return obj.constructor.name;
  3718. }
  3719. function shortPrintStringOf(obj) {
  3720. // ignore-in-doc
  3721. // primitive values
  3722. if (!isMutableType(obj)) return safeToString(obj);
  3723. // constructed objects
  3724. if (obj.constructor.name !== 'Object' && !Array.isArray(obj)) {
  3725. if (obj.constructor.name) return obj.constructor.name ? obj.constructor.name : Object.prototype.toString.call(obj).split(" ")[1].split("]")[0];
  3726. }
  3727. // arrays or plain objects
  3728. var typeString = "";
  3729. function displayTypeAndLength(obj, collectionType, firstBracket, secondBracket) {
  3730. if (obj.constructor.name === collectionType) {
  3731. typeString += firstBracket;
  3732. if (obj.length || Object.keys(obj).length) typeString += "...";
  3733. typeString += secondBracket;
  3734. }
  3735. }
  3736. displayTypeAndLength(obj, "Object", "{", "}");
  3737. displayTypeAndLength(obj, "Array", "[", "]");
  3738. return typeString;
  3739. }
  3740. function isMutableType(obj) {
  3741. // Is `obj` a value or mutable type?
  3742. var immutableTypes = ["null", "undefined", "Boolean", "Number", "String"];
  3743. return immutableTypes.indexOf(typeStringOf(obj)) === -1;
  3744. }
  3745. function safeToString(obj) {
  3746. // Like `toString` but catches errors.
  3747. try {
  3748. return (obj ? obj.toString() : String(obj)).replace('\n', '');
  3749. } catch (e) {
  3750. return '<error printing object>';
  3751. }
  3752. }
  3753. function asObject(obj) {
  3754. switch (typeof obj === "undefined" ? "undefined" : _typeof(obj)) {
  3755. case 'string':
  3756. return new String(obj);
  3757. case 'boolean':
  3758. return new Boolean(obj);
  3759. case 'number':
  3760. return new Number(obj);
  3761. default:
  3762. return obj;
  3763. }
  3764. }
  3765. function newKeyIn(obj) {
  3766. var base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "_";
  3767. var i = 1,
  3768. key;
  3769. do {
  3770. key = base + "-" + i++;
  3771. } while (key in obj);
  3772. return key;
  3773. }
  3774. var obj = Object.freeze({
  3775. isArray: isArray$$1,
  3776. isElement: isElement,
  3777. isFunction: isFunction,
  3778. isBoolean: isBoolean,
  3779. isString: isString,
  3780. isNumber: isNumber,
  3781. isUndefined: isUndefined,
  3782. isRegExp: isRegExp,
  3783. isObject: isObject,
  3784. isPrimitive: isPrimitive,
  3785. isEmpty: isEmpty,
  3786. equals: equals$1,
  3787. keys: keys$1,
  3788. values: values,
  3789. select: select,
  3790. dissoc: dissoc,
  3791. addScript: addScript,
  3792. extend: extend,
  3793. clone: clone$$1,
  3794. extract: extract,
  3795. inspect: inspect,
  3796. merge: merge,
  3797. deepMerge: deepMerge,
  3798. inherit: inherit,
  3799. valuesInPropertyHierarchy: valuesInPropertyHierarchy,
  3800. mergePropertyInHierarchy: mergePropertyInHierarchy,
  3801. sortKeysWithBeforeAndAfterConstraints: sortKeysWithBeforeAndAfterConstraints,
  3802. deepCopy: deepCopy,
  3803. typeStringOf: typeStringOf,
  3804. shortPrintStringOf: shortPrintStringOf,
  3805. isMutableType: isMutableType,
  3806. safeToString: safeToString,
  3807. asObject: asObject,
  3808. newKeyIn: newKeyIn
  3809. });
  3810. /*global btoa,JsDiff*/
  3811. /*lively.vm dontTransform: ["btoa"]*/
  3812. // String utility methods for printing, parsing, and converting strings.
  3813. var features = {
  3814. repeat: !!String.prototype.repeat,
  3815. includes: !!String.prototype.includes,
  3816. startsWith: !!String.prototype.startsWith,
  3817. endsWith: !!String.prototype.endsWith
  3818. };
  3819. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  3820. // printing and formatting strings
  3821. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  3822. function format() {
  3823. // String+ -> String
  3824. // Takes a variable number of arguments. The first argument is the format
  3825. // string. Placeholders in the format string are marked with `"%s"`.
  3826. // Example:
  3827. // lively.lang.string.format("Hello %s!", "Lively User"); // => "Hello Lively User!"
  3828. return formatFromArray(Array.prototype.slice.call(arguments));
  3829. }
  3830. function formatFromArray(objects) {
  3831. var self = objects.shift();
  3832. if (!self) {
  3833. console.log("Error in Strings>>formatFromArray, first arg is undefined");
  3834. }
  3835. function appendText(object, string) {
  3836. return "" + object;
  3837. }
  3838. function appendInteger(value, string) {
  3839. return value.toString();
  3840. }
  3841. function appendFloat(value, string, precision) {
  3842. if (precision > -1) return value.toFixed(precision);else return value.toString();
  3843. }
  3844. function appendObject(value, string) {
  3845. return inspect(value);
  3846. }
  3847. var appenderMap = { s: appendText, d: appendInteger, i: appendInteger, f: appendFloat, o: appendObject };
  3848. var reg = /((^%|[^\\]%)(\d+)?(\.)([a-zA-Z]))|((^%|[^\\]%)([a-zA-Z]))/;
  3849. function parseFormat(fmt) {
  3850. var oldFmt = fmt;
  3851. var parts = [];
  3852. for (var m = reg.exec(fmt); m; m = reg.exec(fmt)) {
  3853. var type = m[8] || m[5],
  3854. appender = type in appenderMap ? appenderMap[type] : appendObject,
  3855. precision = m[3] ? parseInt(m[3]) : m[4] == "." ? -1 : 0;
  3856. parts.push(fmt.substr(0, m[0][0] == "%" ? m.index : m.index + 1));
  3857. parts.push({ appender: appender, precision: precision });
  3858. fmt = fmt.substr(m.index + m[0].length);
  3859. }
  3860. if (fmt) parts.push(fmt.toString());
  3861. return parts;
  3862. }
  3863. var parts = parseFormat(self),
  3864. str = "",
  3865. objIndex = 0;
  3866. for (var i = 0; i < parts.length; ++i) {
  3867. var part = parts[i];
  3868. if (part && (typeof part === "undefined" ? "undefined" : _typeof(part)) == "object") {
  3869. var object = objects[objIndex++];
  3870. str += (part.appender || appendText)(object, str, part.precision);
  3871. } else {
  3872. str += appendText(part, str);
  3873. }
  3874. }
  3875. return str;
  3876. }
  3877. function indent(str, indentString, depth) {
  3878. // String -> String -> String? -> String
  3879. // Example:
  3880. // string.indent("Hello", " ", 2) // => " Hello"
  3881. if (!depth || depth <= 0) return str;
  3882. var indent = "";while (depth > 0) {
  3883. depth--;indent += indentString;
  3884. }
  3885. return lines(str).map(function (line) {
  3886. return indent + line;
  3887. }).join("\n");
  3888. }
  3889. function minIndent(str, indentString) {
  3890. // Find out what the minum indentation of the text in str is
  3891. // Example:
  3892. // minIndent(" Hello", " ") // => 2
  3893. if (!indentString) indentString = " ";
  3894. var indentRe = new RegExp("^(" + indentString + ")*", "gm");
  3895. return min(str.match(indentRe).map(function (ea) {
  3896. return Math.floor(ea.length / indentString.length);
  3897. }));
  3898. }
  3899. function changeIndent(str, indentString, depth) {
  3900. // Add or remove indent from lines in str to match depth
  3901. // Example:
  3902. // string.changeIndent(" Hello", " ", 1) // => " Hello"
  3903. if (!indentString) indentString = " ";
  3904. if (!depth) depth = 0;
  3905. var existingIndent = minIndent(str, indentString);
  3906. if (existingIndent === depth) return str;
  3907. if (existingIndent < depth) return indent(str, indentString, depth - existingIndent);
  3908. var prefixToRemove = indentString.repeat(existingIndent - depth);
  3909. return lines(str).map(function (line) {
  3910. return line.slice(prefixToRemove.length);
  3911. }).join("\n");
  3912. }
  3913. function quote(str) {
  3914. // Example:
  3915. // string.print("fo\"o") // => "\"fo\\\"o\""
  3916. return '"' + str.replace(/"/g, '\\"') + '"';
  3917. }
  3918. function print(obj) {
  3919. // Prints Arrays and escapes quotations. See `obj.inspect` for how to
  3920. // completely print / inspect JavaScript data strcutures
  3921. // Example:
  3922. // string.print([[1,2,3], "string", {foo: 23}])
  3923. // // => [[1,2,3],"string",[object Object]]
  3924. if (obj && Array.isArray(obj)) return '[' + obj.map(print) + ']';
  3925. if (typeof obj !== "string") return String(obj);
  3926. var result = String(obj);
  3927. result = result.replace(/\n/g, '\\n\\\n');
  3928. result = result.replace(/(")/g, '\\$1');
  3929. result = '\"' + result + '\"';
  3930. return result;
  3931. }
  3932. function printNested(list, depth) {
  3933. // Example:
  3934. // string.printNested([1,2,[3,4,5]]) // => "1\n2\n 3\n 4\n 5\n"
  3935. depth = depth || 0;
  3936. return list.reduce(function (s, ea) {
  3937. return s += Array.isArray(ea) ? printNested(ea, depth + 1) : indent(ea + "\n", ' ', depth);
  3938. }, "");
  3939. }
  3940. function pad(string, n, left) {
  3941. // Examples:
  3942. // pad("Foo", 2) // => "Foo "
  3943. // pad("Foo", 2, true) // => " Foo"
  3944. return left ? ' '.repeat(n) + string : string + ' '.repeat(n);
  3945. }
  3946. function printTable(tableArray, options) {
  3947. // Array -> Object? -> String
  3948. // Takes a 2D Array and prints a table string. Kind of the reverse
  3949. // operation to `tableize`
  3950. // Example:
  3951. // string.printTable([["aaa", "b", "c"], ["d", "e","f"]])
  3952. // // =>
  3953. // // aaa b c
  3954. // // d e f
  3955. var columnWidths = [],
  3956. separator = options && options.separator || ' ',
  3957. alignLeftAll = !options || !options.align || options.align === 'left',
  3958. alignRightAll = options && options.align === 'right';
  3959. function alignRight(columnIndex) {
  3960. if (alignLeftAll) return false;
  3961. if (alignRightAll) return true;
  3962. return options && Array.isArray(options.align) && options.align[columnIndex] === 'right';
  3963. }
  3964. tableArray.forEach(function (row) {
  3965. row.forEach(function (cellVal, i) {
  3966. if (columnWidths[i] === undefined) columnWidths[i] = 0;
  3967. columnWidths[i] = Math.max(columnWidths[i], String(cellVal).length);
  3968. });
  3969. });
  3970. return tableArray.map(function (row) {
  3971. return row.map(function (cellVal, i) {
  3972. var cellString = String(cellVal);
  3973. return pad(cellString, columnWidths[i] - cellString.length, alignRight(i));
  3974. }).join(separator);
  3975. }).join('\n');
  3976. }
  3977. function printTree(rootNode, nodePrinter, childGetter, indent) {
  3978. // Object -> Function -> Function -> Number? -> String
  3979. // A generic function to print a tree representation from a nested data structure.
  3980. // Receives three arguments:
  3981. // - `rootNode` an object representing the root node of the tree
  3982. // - `nodePrinter` is a function that gets a tree node and should return stringified version of it
  3983. // - `childGetter` is a function that gets a tree node and should return a list of child nodes
  3984. // Example:
  3985. // var root = {name: "a", subs: [{name: "b", subs: [{name: "c"}]}, {name: "d"}]};
  3986. // string.printTree(root, function(n) { return n.name; }, function(n) { return n.subs; });
  3987. // // =>
  3988. // // a
  3989. // // |-b
  3990. // // | \-c
  3991. // // \-d
  3992. var nodeList = [];
  3993. indent = indent || ' ';
  3994. iterator(0, 0, rootNode);
  3995. return nodeList.join('\n');
  3996. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  3997. function iterator(depth, index, node) {
  3998. // ignore-in-doc
  3999. // 1. Create stringified representation of node
  4000. nodeList[index] = indent.repeat(depth) + nodePrinter(node, depth);
  4001. var children = childGetter(node, depth),
  4002. childIndex = index + 1;
  4003. if (!children || !children.length) return childIndex;
  4004. // 2. If there are children then assemble those linear inside nodeList
  4005. // The childIndex is the pointer of the current items of childList into
  4006. // nodeList.
  4007. var lastIndex = childIndex,
  4008. lastI = children.length - 1;
  4009. children.forEach(function (ea, i) {
  4010. childIndex = iterator(depth + 1, childIndex, ea);
  4011. // 3. When we have printed the recursive version then augment the
  4012. // printed version of the direct children with horizontal slashes
  4013. // directly in front of the represented representation
  4014. var isLast = lastI === i,
  4015. cs = nodeList[lastIndex].split(''),
  4016. fromSlash = depth * indent.length + 1,
  4017. toSlash = depth * indent.length + indent.length;
  4018. for (var i = fromSlash; i < toSlash; i++) {
  4019. cs[i] = '-';
  4020. }if (isLast) cs[depth * indent.length] = '\\';
  4021. nodeList[lastIndex] = cs.join('');
  4022. // 4. For all children (direct and indirect) except for the
  4023. // last one (itself and all its children) add vertical bars in
  4024. // front of each at position of the current nodes depth. This
  4025. // makes is much easier to see which child node belongs to which
  4026. // parent
  4027. if (!isLast) nodeList.slice(lastIndex, childIndex).forEach(function (ea, i) {
  4028. var cs2 = ea.split('');
  4029. cs2[depth * indent.length] = '|';
  4030. nodeList[lastIndex + i] = cs2.join('');
  4031. });
  4032. lastIndex = childIndex;
  4033. });
  4034. return childIndex;
  4035. }
  4036. }
  4037. function toArray$1(s) {
  4038. // Example:
  4039. // string.toArray("fooo") // => ["f","o","o","o"]
  4040. return s.split('');
  4041. }
  4042. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  4043. // parsing strings into other entities
  4044. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  4045. function lines(str) {
  4046. // Example: string.lines("foo\nbar\n\rbaz") // => ["foo","bar","baz"]
  4047. return str.split(/\n\r?/);
  4048. }
  4049. function paragraphs(string, options) {
  4050. // Examples:
  4051. // var text = "Hello, this is a pretty long sentence\nthat even includes new lines."
  4052. // + "\n\n\nThis is a sentence in a new paragraph.";
  4053. // string.paragraphs(text) // => [
  4054. // // "Hello, this is a pretty long sentence\nthat even includes new lines.",
  4055. // // "This is a sentence in a new paragraph."]
  4056. // string.paragraphs(text, {keepEmptyLines: true}) // => [
  4057. // // "Hello, this is a pretty long sentence\n that even includes new lines.",
  4058. // // "\n ",
  4059. // // "This is a sentence in a new paragraph."]
  4060. var sep = options ? options.sep : '\n\n';
  4061. if (!options || !options.keepEmptyLines) return string.split(new RegExp(sep + '+'));
  4062. function isWhiteSpace(s) {
  4063. return (/^\s*$/.test(s)
  4064. );
  4065. }
  4066. return string.split('\n').concat('').reduce(function (parasAndLast, line) {
  4067. var paras = parasAndLast[0],
  4068. last$$1 = parasAndLast[1];
  4069. if (isWhiteSpace(last$$1) === isWhiteSpace(line)) {
  4070. last$$1 += '\n' + line;
  4071. } else {
  4072. last$$1.length && paras.push(last$$1);last$$1 = line;
  4073. }
  4074. return [paras, last$$1];
  4075. }, [[], ''])[0];
  4076. }
  4077. function nonEmptyLines(str) {
  4078. // Example: string.nonEmptyLines("foo\n\nbar\n") // => ["foo","bar"]
  4079. return lines(str).compact();
  4080. }
  4081. function tokens(str, regex) {
  4082. // Example:
  4083. // string.tokens(' a b c') => ['a', 'b', 'c']
  4084. return str.split(regex || /\s+/).filter(function (tok) {
  4085. return !/^\s*$/.test(tok);
  4086. });
  4087. }
  4088. function tableize(s, options) {
  4089. // String -> Object? -> Array
  4090. // Takes a String representing a "table" and parses it into a 2D-Array (as
  4091. // accepted by the `collection.Grid` methods or `string.printTable`)
  4092. // ```js
  4093. // options = {
  4094. // convertTypes: BOOLEAN, // automatically convert to Numbers, Dates, ...?
  4095. // cellSplitter: REGEXP // how to recognize "cells", by default just spaces
  4096. // }
  4097. // ```
  4098. // Examples:
  4099. // string.tableize('a b c\nd e f')
  4100. // // => [["a","b","c"],["d","e","f"]]
  4101. // // can also parse csv like
  4102. // var csv = '"Symbol","Name","LastSale",\n'
  4103. // + '"FLWS","1-800 FLOWERS.COM, Inc.","5.65",\n'
  4104. // + '"FCTY","1st Century Bancshares, Inc","5.65",'
  4105. // string.tableize(csv, {cellSplitter: /^\s*"|","|",?\s*$/g})
  4106. // // => [["Symbol","Name","LastSale"],
  4107. // // ["FLWS","1-800 FLOWERS.COM, Inc.",5.65],
  4108. // // ["FCTY","1st Century Bancshares, Inc",5.65]]
  4109. options = options || {};
  4110. var splitter = options.cellSplitter || /\s+/,
  4111. emptyStringRe = /^\s*$/,
  4112. convertTypes = options.hasOwnProperty('convertTypes') ? !!options.convertTypes : true,
  4113. _lines = lines(s),
  4114. table = [];
  4115. for (var i = 0; i < _lines.length; i++) {
  4116. var _tokens = tokens(_lines[i], splitter);
  4117. if (convertTypes) {
  4118. _tokens = _tokens.map(function (tok) {
  4119. if (tok.match(emptyStringRe)) return tok;
  4120. var num = Number(tok);
  4121. if (!isNaN(num)) return num;
  4122. var date = new Date(tok);
  4123. if (!isNaN(+date)) return date;
  4124. return tok.trim();
  4125. });
  4126. }
  4127. if (_tokens.length > 0) table.push(_tokens);
  4128. }
  4129. return table;
  4130. }
  4131. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  4132. // (un)escape / encoding / decoding
  4133. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  4134. function unescapeCharacterEntities(s) {
  4135. // Converts [character entities](http://dev.w3.org/html5/html-author/charref)
  4136. // into utf-8 strings
  4137. // Example:
  4138. // string.unescapeCharacterEntities("foo &amp;&amp; bar") // => "foo && bar"
  4139. if (typeof document === 'undefined') throw new Error("Cannot unescapeCharacterEntities");
  4140. var div = document.createElement('div');
  4141. div.innerHTML = s;
  4142. return div.textContent;
  4143. }
  4144. function toQueryParams(s, separator) {
  4145. // Example:
  4146. // string.toQueryParams("http://example.com?foo=23&bar=test")
  4147. // // => {bar: "test", foo: "23"}
  4148. var match = s.trim().match(/([^?#]*)(#.*)?$/);
  4149. if (!match) return {};
  4150. var hash = match[1].split(separator || '&').inject({}, function (hash, pair) {
  4151. if ((pair = pair.split('='))[0]) {
  4152. var key = decodeURIComponent(pair.shift());
  4153. var value = pair.length > 1 ? pair.join('=') : pair[0];
  4154. if (value != undefined) value = decodeURIComponent(value);
  4155. if (key in hash) {
  4156. if (!Array.isArray(hash[key])) hash[key] = [hash[key]];
  4157. hash[key].push(value);
  4158. } else hash[key] = value;
  4159. }
  4160. return hash;
  4161. });
  4162. return hash;
  4163. }
  4164. // -=-=-=-=-=-=-=-=-=-=-=-=-
  4165. // file system path support
  4166. // -=-=-=-=-=-=-=-=-=-=-=-=-
  4167. var pathDotRe = /\/\.\//g;
  4168. var pathDoubleDotRe = /\/[^\/]+\/\.\./;
  4169. var pathDoubleSlashRe = /(^|[^:])[\/]+/g;
  4170. var urlStartRe = /^[a-z0-9-_\.]+:\/\//;
  4171. function normalizePath$1(pathString) {
  4172. var urlStartMatch = pathString.match(urlStartRe),
  4173. urlStart = urlStartMatch ? urlStartMatch[0] : null,
  4174. result = urlStart ? pathString.slice(urlStart.length) : pathString;
  4175. // /foo/../bar --> /bar
  4176. do {
  4177. pathString = result;
  4178. result = pathString.replace(pathDoubleDotRe, '');
  4179. } while (result != pathString);
  4180. // foo//bar --> foo/bar
  4181. result = result.replace(pathDoubleSlashRe, '$1/');
  4182. // foo/./bar --> foo/bar
  4183. result = result.replace(pathDotRe, '/');
  4184. if (urlStart) result = urlStart + result;
  4185. return result;
  4186. }
  4187. function joinPath() /*paths*/{
  4188. // Joins the strings passed as paramters together so that ea string is
  4189. // connected via a single "/".
  4190. // Example:
  4191. // string.joinPath("foo", "bar") // => "foo/bar";
  4192. return normalizePath$1(Array.prototype.slice.call(arguments).reduce(function (path, ea) {
  4193. return typeof ea === "string" ? path.replace(/\/*$/, "") + "/" + ea.replace(/^\/*/, "") : path;
  4194. }));
  4195. }
  4196. // -=-=-=-=-=-=-=-=-
  4197. // ids and hashing
  4198. // -=-=-=-=-=-=-=-=-
  4199. var newUUIDTemplate = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
  4200. var newUUIDRe = /[xy]/g;
  4201. var newUUIDReplacer = function newUUIDReplacer(c) {
  4202. var r = Math.random() * 16 | 0,
  4203. v = c == 'x' ? r : r & 0x3 | 0x8;
  4204. return v.toString(16);
  4205. };
  4206. function newUUID() {
  4207. // Example:
  4208. // newUUID() // => "3B3E74D0-85EA-45F2-901C-23ECF3EAB9FB"
  4209. return newUUIDTemplate.replace(newUUIDRe, newUUIDReplacer).toUpperCase();
  4210. }
  4211. function createDataURI(content, mimeType) {
  4212. // String -> String -> String
  4213. // Takes some string representing content and a mime type.
  4214. // For a list of mime types see: [http://www.iana.org/assignments/media-types/media-types.xhtml]()
  4215. // More about data URIs: [https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs]()
  4216. // Example:
  4217. // window.open(string.createDataURI('<h1>test</h1>', 'text/html'));
  4218. mimeType = mimeType || "text/plain";
  4219. return "data:" + mimeType + ";base64," + btoa(content);
  4220. }
  4221. function hashCode(s) {
  4222. // [http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/]()
  4223. // Example: string.hashCode("foo") // => 101574
  4224. var hash = 0,
  4225. len = s.length;
  4226. if (len == 0) return hash;
  4227. for (var i = 0; i < len; i++) {
  4228. var c = s.charCodeAt(i);
  4229. hash = (hash << 5) - hash + c;
  4230. hash = hash & hash; // Convert to 32bit integer
  4231. }
  4232. return hash;
  4233. }
  4234. function md5(string) {
  4235. // © Joseph Myers [http://www.myersdaily.org/joseph/javascript/md5-text.html]()
  4236. // Example:
  4237. // string.md5("foo") // => "acbd18db4cc2f85cedef654fccc4a4d8"
  4238. /* ignore-in-doc
  4239. this function is much faster,
  4240. so if possible we use it. Some IEs
  4241. are the only ones I know of that
  4242. need the idiotic second function,
  4243. generated by an if clause. */
  4244. // var add32 = hex(md51("hello")) === "5d41402abc4b2a76b9719d911017c592" ?
  4245. // function add32(a, b) { return (a + b) & 0xFFFFFFFF; } :
  4246. var add32 = function add32(x, y) {
  4247. var lsw = (x & 0xFFFF) + (y & 0xFFFF),
  4248. msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  4249. return msw << 16 | lsw & 0xFFFF;
  4250. };
  4251. function cmn(q, a, b, x, s, t) {
  4252. a = add32(add32(a, q), add32(x, t));
  4253. return add32(a << s | a >>> 32 - s, b);
  4254. }
  4255. function ff(a, b, c, d, x, s, t) {
  4256. return cmn(b & c | ~b & d, a, b, x, s, t);
  4257. }
  4258. function gg(a, b, c, d, x, s, t) {
  4259. return cmn(b & d | c & ~d, a, b, x, s, t);
  4260. }
  4261. function hh(a, b, c, d, x, s, t) {
  4262. return cmn(b ^ c ^ d, a, b, x, s, t);
  4263. }
  4264. function ii(a, b, c, d, x, s, t) {
  4265. return cmn(c ^ (b | ~d), a, b, x, s, t);
  4266. }
  4267. function md5cycle(x, k) {
  4268. var a = x[0],
  4269. b = x[1],
  4270. c = x[2],
  4271. d = x[3];
  4272. a = ff(a, b, c, d, k[0], 7, -680876936);
  4273. d = ff(d, a, b, c, k[1], 12, -389564586);
  4274. c = ff(c, d, a, b, k[2], 17, 606105819);
  4275. b = ff(b, c, d, a, k[3], 22, -1044525330);
  4276. a = ff(a, b, c, d, k[4], 7, -176418897);
  4277. d = ff(d, a, b, c, k[5], 12, 1200080426);
  4278. c = ff(c, d, a, b, k[6], 17, -1473231341);
  4279. b = ff(b, c, d, a, k[7], 22, -45705983);
  4280. a = ff(a, b, c, d, k[8], 7, 1770035416);
  4281. d = ff(d, a, b, c, k[9], 12, -1958414417);
  4282. c = ff(c, d, a, b, k[10], 17, -42063);
  4283. b = ff(b, c, d, a, k[11], 22, -1990404162);
  4284. a = ff(a, b, c, d, k[12], 7, 1804603682);
  4285. d = ff(d, a, b, c, k[13], 12, -40341101);
  4286. c = ff(c, d, a, b, k[14], 17, -1502002290);
  4287. b = ff(b, c, d, a, k[15], 22, 1236535329);
  4288. a = gg(a, b, c, d, k[1], 5, -165796510);
  4289. d = gg(d, a, b, c, k[6], 9, -1069501632);
  4290. c = gg(c, d, a, b, k[11], 14, 643717713);
  4291. b = gg(b, c, d, a, k[0], 20, -373897302);
  4292. a = gg(a, b, c, d, k[5], 5, -701558691);
  4293. d = gg(d, a, b, c, k[10], 9, 38016083);
  4294. c = gg(c, d, a, b, k[15], 14, -660478335);
  4295. b = gg(b, c, d, a, k[4], 20, -405537848);
  4296. a = gg(a, b, c, d, k[9], 5, 568446438);
  4297. d = gg(d, a, b, c, k[14], 9, -1019803690);
  4298. c = gg(c, d, a, b, k[3], 14, -187363961);
  4299. b = gg(b, c, d, a, k[8], 20, 1163531501);
  4300. a = gg(a, b, c, d, k[13], 5, -1444681467);
  4301. d = gg(d, a, b, c, k[2], 9, -51403784);
  4302. c = gg(c, d, a, b, k[7], 14, 1735328473);
  4303. b = gg(b, c, d, a, k[12], 20, -1926607734);
  4304. a = hh(a, b, c, d, k[5], 4, -378558);
  4305. d = hh(d, a, b, c, k[8], 11, -2022574463);
  4306. c = hh(c, d, a, b, k[11], 16, 1839030562);
  4307. b = hh(b, c, d, a, k[14], 23, -35309556);
  4308. a = hh(a, b, c, d, k[1], 4, -1530992060);
  4309. d = hh(d, a, b, c, k[4], 11, 1272893353);
  4310. c = hh(c, d, a, b, k[7], 16, -155497632);
  4311. b = hh(b, c, d, a, k[10], 23, -1094730640);
  4312. a = hh(a, b, c, d, k[13], 4, 681279174);
  4313. d = hh(d, a, b, c, k[0], 11, -358537222);
  4314. c = hh(c, d, a, b, k[3], 16, -722521979);
  4315. b = hh(b, c, d, a, k[6], 23, 76029189);
  4316. a = hh(a, b, c, d, k[9], 4, -640364487);
  4317. d = hh(d, a, b, c, k[12], 11, -421815835);
  4318. c = hh(c, d, a, b, k[15], 16, 530742520);
  4319. b = hh(b, c, d, a, k[2], 23, -995338651);
  4320. a = ii(a, b, c, d, k[0], 6, -198630844);
  4321. d = ii(d, a, b, c, k[7], 10, 1126891415);
  4322. c = ii(c, d, a, b, k[14], 15, -1416354905);
  4323. b = ii(b, c, d, a, k[5], 21, -57434055);
  4324. a = ii(a, b, c, d, k[12], 6, 1700485571);
  4325. d = ii(d, a, b, c, k[3], 10, -1894986606);
  4326. c = ii(c, d, a, b, k[10], 15, -1051523);
  4327. b = ii(b, c, d, a, k[1], 21, -2054922799);
  4328. a = ii(a, b, c, d, k[8], 6, 1873313359);
  4329. d = ii(d, a, b, c, k[15], 10, -30611744);
  4330. c = ii(c, d, a, b, k[6], 15, -1560198380);
  4331. b = ii(b, c, d, a, k[13], 21, 1309151649);
  4332. a = ii(a, b, c, d, k[4], 6, -145523070);
  4333. d = ii(d, a, b, c, k[11], 10, -1120210379);
  4334. c = ii(c, d, a, b, k[2], 15, 718787259);
  4335. b = ii(b, c, d, a, k[9], 21, -343485551);
  4336. x[0] = add32(a, x[0]);
  4337. x[1] = add32(b, x[1]);
  4338. x[2] = add32(c, x[2]);
  4339. x[3] = add32(d, x[3]);
  4340. }
  4341. function md51(s) {
  4342. var n = s.length,
  4343. state = [1732584193, -271733879, -1732584194, 271733878],
  4344. i;
  4345. for (i = 64; i <= n; i += 64) {
  4346. md5cycle(state, md5blk(s.substring(i - 64, i)));
  4347. }
  4348. s = s.substring(i - 64);
  4349. var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  4350. sl = s.length;
  4351. for (i = 0; i < sl; i++) {
  4352. tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);
  4353. }tail[i >> 2] |= 0x80 << (i % 4 << 3);
  4354. if (i > 55) {
  4355. md5cycle(state, tail);
  4356. i = 16;
  4357. while (i--) {
  4358. tail[i] = 0;
  4359. }
  4360. // for (i=0; i<16; i++) tail[i] = 0;
  4361. }
  4362. tail[14] = n * 8;
  4363. md5cycle(state, tail);
  4364. return state;
  4365. }
  4366. /* ignore-in-doc
  4367. * there needs to be support for Unicode here,
  4368. * unless we pretend that we can redefine the MD-5
  4369. * algorithm for multi-byte characters (perhaps
  4370. * by adding every four 16-bit characters and
  4371. * shortening the sum to 32 bits). Otherwise
  4372. * I suggest performing MD-5 as if every character
  4373. * was two bytes--e.g., 0040 0025 = @%--but then
  4374. * how will an ordinary MD-5 sum be matched?
  4375. * There is no way to standardize text to something
  4376. * like UTF-8 before transformation; speed cost is
  4377. * utterly prohibitive. The JavaScript standard
  4378. * itself needs to look at this: it should start
  4379. * providing access to strings as preformed UTF-8
  4380. * 8-bit unsigned value arrays.
  4381. */
  4382. function md5blk(s) {
  4383. // ignore-in-doc
  4384. /* I figured global was faster. */
  4385. var md5blks = [],
  4386. i; /* Andy King said do it this way. */
  4387. for (i = 0; i < 64; i += 4) {
  4388. md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
  4389. }
  4390. return md5blks;
  4391. }
  4392. var hex_chr = '0123456789abcdef'.split('');
  4393. function rhex(n) {
  4394. var s = '',
  4395. j = 0;
  4396. for (; j < 4; j++) {
  4397. s += hex_chr[n >> j * 8 + 4 & 0x0F] + hex_chr[n >> j * 8 & 0x0F];
  4398. }return s;
  4399. }
  4400. function hex(x) {
  4401. var l = x.length;
  4402. for (var i = 0; i < l; i++) {
  4403. x[i] = rhex(x[i]);
  4404. }return x.join('');
  4405. }
  4406. return hex(md51(string));
  4407. }
  4408. // -=-=-=-=-=-=-=-=-=-=-=-=-=-
  4409. // matching strings / regexps
  4410. // -=-=-=-=-=-=-=-=-=-=-=-=-=-
  4411. function reMatches$$1(string, re) {
  4412. // Different to the native `match` function this method returns an object
  4413. // with `start`, `end`, and `match` fields
  4414. // Example:
  4415. // string.reMatches("Hello World", /o/g)
  4416. // // => [{start: 4, end: 5, match: "o"},{start: 7, end: 8, match: "o"}]
  4417. var matches = [];
  4418. string.replace(re, function (match, idx) {
  4419. matches.push({ match: match, start: idx, end: idx + match.length });
  4420. });
  4421. return matches;
  4422. }
  4423. function stringMatch(s, patternString, options) {
  4424. // returns `{matched: true}` if success otherwise
  4425. // `{matched: false, error: EXPLANATION, pattern: STRING|RE, pos: NUMBER}`
  4426. // Example:
  4427. // string.stringMatch("foo 123 bar", "foo __/[0-9]+/__ bar") // => {matched: true}
  4428. // string.stringMatch("foo aaa bar", "foo __/[0-9]+/__ bar")
  4429. // // => {
  4430. // // error: "foo <--UNMATCHED-->aaa bar",
  4431. // // matched: false,
  4432. // // pattern: /[0-9]+/,
  4433. // // pos: 4
  4434. // // }
  4435. options = options || {};
  4436. if (!!options.normalizeWhiteSpace) s = s.replace(/\s+/g, ' ');
  4437. if (!!options.ignoreIndent) {
  4438. s = s.replace(/^\s+/gm, '');
  4439. patternString = patternString.replace(/^\s+/gm, '');
  4440. }
  4441. return s == patternString ? { matched: true } : embeddedReMatch(s, patternString);
  4442. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  4443. function splitInThree(string, start, end, startGap, endGap) {
  4444. // ignore-in-doc
  4445. // split string at start and end
  4446. // return (0, start), (start, end), (end, ...)
  4447. startGap = startGap || 0;endGap = endGap || 0;
  4448. return [string.slice(0, start), string.slice(start + startGap, end - endGap), string.slice(end)];
  4449. }
  4450. function matchStringForward(s, pattern) {
  4451. // ignore-in-doc
  4452. // try to match pattern at beginning of string. if matched, return
  4453. // result object with {
  4454. // match: STRING,
  4455. // REST: STRING -- remaining string after pattern was consumed
  4456. // }
  4457. if (pattern.constructor !== RegExp) {
  4458. var idx = s.indexOf(pattern);
  4459. if (idx === 0) return { match: pattern, rest: s.slice(pattern.length) };
  4460. // no match
  4461. for (var i = 0; i < pattern.length; i++) {
  4462. // figure out where we failed
  4463. if (pattern[i] != s[i]) return { match: null, pos: i };
  4464. }return { match: null };
  4465. }
  4466. var matches = reMatches$$1(s, pattern);
  4467. // show(matches)
  4468. // show(string.slice(matches[0].end));
  4469. return !matches || !matches.length || matches[0].start !== 0 ? { match: null } : { match: matches[0].match, rest: s.slice(matches[0].end) };
  4470. }
  4471. function matchStringForwardWithAllPatterns(s, patterns) {
  4472. // ignore-in-doc
  4473. // like matchStringForward, just apply list of patterns
  4474. var pos = 0;
  4475. for (var i = 0; i < patterns.length; i++) {
  4476. var p = patterns[i],
  4477. result = matchStringForward(s, p);
  4478. if (!result.match) return { matched: false, pos: pos + (result.pos || 0), pattern: p };
  4479. pos += result.match.length;
  4480. s = result.rest;
  4481. }
  4482. return s.length ? { matched: false, pos: pos } : { matched: true };
  4483. }
  4484. function splitIntoPatterns(matcher) {
  4485. var starts = reMatches$$1(matcher, /__\//g),
  4486. ends = reMatches$$1(matcher, /\/__/g);
  4487. if (starts.length !== ends.length) {
  4488. throw new Error("pattern invalid: " + matcher + " cannot be split into __/.../__ embedded RegExps" + "\nstarts: " + JSON.stringify(starts) + '\nvs ends:\n' + JSON.stringify(ends));
  4489. }
  4490. var consumed = 0;
  4491. return starts.reduce(function (patterns, start, i) {
  4492. var end = ends[i];
  4493. var matcher = patterns.pop();
  4494. var splitted = splitInThree(matcher, start.start - consumed, end.end - consumed, 3, 3);
  4495. if (splitted[0].length) {
  4496. patterns.push(splitted[0]);
  4497. consumed += splitted[0].length;
  4498. }
  4499. try {
  4500. if (splitted[1].length) {
  4501. patterns.push(new RegExp(splitted[1]));
  4502. consumed += splitted[1].length + 3 + 3;
  4503. }
  4504. } catch (e) {
  4505. throw new Error("Cannot create pattern re from: " + inspect(splitted));
  4506. }
  4507. if (splitted[2].length) {
  4508. patterns.push(splitted[2]);
  4509. }
  4510. return patterns;
  4511. }, [matcher]);
  4512. }
  4513. function embeddedReMatch(s, patternString) {
  4514. // ignore-in-doc
  4515. // the main match func
  4516. var patterns = splitIntoPatterns(patternString);
  4517. var result = matchStringForwardWithAllPatterns(s, patterns);
  4518. if (result.matched) return result;
  4519. result.error = s.slice(0, result.pos) + '<--UNMATCHED-->' + s.slice(result.pos);
  4520. return result;
  4521. }
  4522. }
  4523. function peekRight(s, start, needle) {
  4524. // Finds the next occurence of `needle` (String or RegExp). Returns delta
  4525. // index.
  4526. // Example:
  4527. // peekRight("Hello World", 0, /o/g) // => 4
  4528. // peekRight("Hello World", 5, /o/) // => 2
  4529. s = s.slice(start);
  4530. if (typeof needle === 'string') {
  4531. var idx = s.indexOf(needle);
  4532. return idx === -1 ? null : idx + start;
  4533. } else if (needle.constructor === RegExp) {
  4534. var matches = reMatches$$1(s, needle);
  4535. return matches[0] ? matches[0].start : null;
  4536. }
  4537. return null;
  4538. }
  4539. function peekLeft(s, start, needle) {
  4540. // Similar to `peekRight`
  4541. s = s.slice(0, start);
  4542. if (typeof needle === 'string') {
  4543. var idx = s.lastIndexOf(needle);
  4544. return idx === -1 ? null : idx;
  4545. } else if (needle.constructor === RegExp) {
  4546. var matches = reMatches$$1(s, needle);
  4547. return last(matches) ? last(matches).start : null;
  4548. }
  4549. return null;
  4550. }
  4551. function lineIndexComputer(s) {
  4552. // String -> Function
  4553. // For converting character positions to line numbers.
  4554. // Returns a function accepting char positions. If the char pos is outside
  4555. // of the line ranges -1 is returned.
  4556. // Example:
  4557. // var idxComp = lineIndexComputer("Hello\nWorld\n\nfoo");
  4558. // idxComp(3) // => 0 (index 3 is "l")
  4559. // idxComp(6) // => 1 (index 6 is "W")
  4560. // idxComp(12) // => 2 (index 12 is "\n")
  4561. // ignore-in-doc
  4562. // line ranges: list of numbers, each line has two entries:
  4563. // i -> start of line, i+1 -> end of line
  4564. var _lineRanges = lineRanges(s);
  4565. // ignore-in-doc
  4566. // FIXME, this is O(n). Make cumputation more efficient, binary lookup?
  4567. return function (pos) {
  4568. for (var line = 0; line < _lineRanges.length; line++) {
  4569. var lineRange = _lineRanges[line];
  4570. if (pos >= lineRange[0] && pos < lineRange[1]) return line;
  4571. }
  4572. return -1;
  4573. };
  4574. }
  4575. function lineNumberToIndexesComputer(s) {
  4576. // String -> Function
  4577. // For converting line numbers to [startIndex, endIndex]
  4578. // Example:
  4579. // var idxComp = lineNumberToIndexesComputer("Hello\nWorld\n\nfoo");
  4580. // idxComp(1) // => [6,12]
  4581. return function (lineNo) {
  4582. return lineRanges(s)[lineNo];
  4583. };
  4584. }
  4585. function lineRanges(s) {
  4586. var from$$1 = 0,
  4587. to = 0,
  4588. linesOfS = lines(s),
  4589. result = [];
  4590. for (var i = 0; i < linesOfS.length; i++) {
  4591. var line = linesOfS[i];
  4592. to = from$$1 + line.length + 1;
  4593. result.push([from$$1, to]);
  4594. from$$1 = to;
  4595. }
  4596. return result;
  4597. }
  4598. function findLineWithIndexInLineRanges(lineRanges, idx) {
  4599. // given a list of `lineRanges` (produced by
  4600. // `livley.lang.string.lineRanges(string)`) like lineRanges = [[0, 12], [12, 33]]
  4601. // and an string index `idx` into `string`, find the line no (the index into
  4602. // `lineRanges`) that includes idx. The index intervals include start and exclude end:
  4603. // Example:
  4604. // findLineWithIndex2(lineRanges, 2); // => 0
  4605. // findLineWithIndex2(lineRanges, 12); // => 1
  4606. // findLineWithIndex2(lineRanges, 33); // => 1
  4607. // findLineWithIndex2(lineRanges, 34); // => -1
  4608. // findLineWithIndex2(lineRanges, -4); // => -1
  4609. var nRows = lineRanges.length;
  4610. if (nRows === 0) return -1;
  4611. // let currentRow = Math.floor(nRows/2), lastRow = nRows;
  4612. var startRow = 0,
  4613. endRow = nRows;
  4614. while (true) {
  4615. var middle = startRow + Math.floor((endRow - startRow) / 2),
  4616. _lineRanges$middle = slicedToArray(lineRanges[middle], 2),
  4617. from$$1 = _lineRanges$middle[0],
  4618. to = _lineRanges$middle[1];
  4619. if (idx < from$$1) {
  4620. if (middle === 0) return -1;
  4621. endRow = middle;
  4622. continue;
  4623. }
  4624. if (idx > to) {
  4625. startRow = middle;continue;
  4626. }
  4627. return middle;
  4628. }
  4629. return -1;
  4630. }
  4631. function regexIndexOf(string, regex) {
  4632. var startpos = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  4633. var indexOf = this.substring(startpos || 0).search(regex);
  4634. return indexOf >= 0 ? indexOf + (startpos || 0) : indexOf;
  4635. }
  4636. function regexLastIndexOf(string, regex) {
  4637. var startpos = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : string.length;
  4638. regex = regex.global ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
  4639. var stringToWorkWith = this.substring(0, startpos + 1),
  4640. lastIndexOf = -1,
  4641. nextStop = 0,
  4642. result;
  4643. while ((result = regex.exec(stringToWorkWith)) != null) {
  4644. lastIndexOf = result.index;
  4645. regex.lastIndex = ++nextStop;
  4646. }
  4647. return lastIndexOf;
  4648. }
  4649. // -=-=-=-=-
  4650. // diffing
  4651. // -=-=-=-=-
  4652. function diff(s1, s2) {
  4653. if (typeof JsDiff === "undefined") return 'diff not supported';
  4654. return JsDiff.convertChangesToXML(JsDiff.diffWordsWithSpace(s1, s2));
  4655. }
  4656. // -=-=-=-=-
  4657. // testing
  4658. // -=-=-=-=-
  4659. function empty(s) {
  4660. // show-in-doc
  4661. return s == '';
  4662. }
  4663. var includes$$1 = features.includes ? function (s, pattern) {
  4664. return s.includes(pattern);
  4665. } : function (s, pattern) {
  4666. // Example:
  4667. // include("fooo!", "oo") // => true
  4668. return s.indexOf(pattern) > -1;
  4669. };
  4670. var include$$1 = includes$$1;
  4671. var startsWith = features.startsWith ? function (s, pattern) {
  4672. return s.startsWith(pattern);
  4673. } : function (s, pattern) {
  4674. // Example:
  4675. // startsWith("fooo!", "foo") // => true
  4676. return s.indexOf(pattern) === 0;
  4677. };
  4678. function startsWithVowel(s) {
  4679. // show-in-doc
  4680. var c = s[0];
  4681. return c === 'A' || c === 'E' || c === 'I' || c === 'O' || c === 'U' || c === 'a' || c === 'e' || c === 'i' || c === 'o' || c === 'u' || false;
  4682. }
  4683. var endsWith = features.endsWith ? function (s, pattern) {
  4684. return s.endsWith(pattern);
  4685. } : function (s, pattern) {
  4686. // Example:
  4687. // endsWith("fooo!", "o!") // => true
  4688. var d = s.length - pattern.length;
  4689. return d >= 0 && s.lastIndexOf(pattern) === d;
  4690. };
  4691. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  4692. // string conversion and manipulation
  4693. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  4694. function withDecimalPrecision(str, precision) {
  4695. // String -> Number -> String
  4696. // Example: withDecimalPrecision("1.12345678", 3) // => "1.123"
  4697. var floatValue = parseFloat(str);
  4698. return isNaN(floatValue) ? str : floatValue.toFixed(precision);
  4699. }
  4700. function capitalize(s) {
  4701. // Example:
  4702. // capitalize("foo bar") // => "Foo bar"
  4703. return s.length ? s.charAt(0).toUpperCase() + s.slice(1) : s;
  4704. }
  4705. function camelCaseString(s) {
  4706. // Spaces to camels, including first char
  4707. // Example: camelCaseString("foo bar baz") // => "FooBarBaz"
  4708. return s.split(" ").map(capitalize).join("");
  4709. }
  4710. function camelize(s) {
  4711. // Dashes to camels, excluding first char
  4712. // Example: camelize("foo-bar-baz") // => "fooBarBaz"
  4713. var parts = s.split('-'),
  4714. len = parts.length;
  4715. if (len == 1) return parts[0];
  4716. var camelized = s.charAt(0) == '-' ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) : parts[0];
  4717. for (var i = 1; i < len; i++) {
  4718. camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
  4719. }return camelized;
  4720. }
  4721. function truncate(s, length, truncation) {
  4722. // Enforces that s is not more then `length` characters long.
  4723. // Example:
  4724. // truncate("123456789", 5) // => "12..."
  4725. length = length || 30;
  4726. truncation = truncation === undefined ? '...' : truncation;
  4727. return s.length > length ? s.slice(0, length - truncation.length) + truncation : String(s);
  4728. }
  4729. function truncateLeft(s, length, truncation) {
  4730. // Enforces that s is not more then `length` characters long.
  4731. // Example:
  4732. // truncate("123456789", 5) // => "12..."
  4733. length = length || 30;
  4734. truncation = truncation === undefined ? '...' : truncation;
  4735. return s.length > length ? truncation + s.slice(-length) : String(s);
  4736. }
  4737. function regExpEscape(s) {
  4738. // For creating RegExps from strings and not worrying about proper escaping
  4739. // of RegExp special characters to literally match those.
  4740. // Example:
  4741. // var re = new RegExp(regExpEscape("fooo{20}"));
  4742. // re.test("fooo") // => false
  4743. // re.test("fooo{20}") // => true
  4744. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').replace(/\x08/g, '\\x08');
  4745. }
  4746. function succ(s) {
  4747. // Uses char code.
  4748. // Example:
  4749. // succ("a") // => "b"
  4750. // succ("Z") // => "["
  4751. return s.slice(0, s.length - 1) + String.fromCharCode(s.charCodeAt(s.length - 1) + 1);
  4752. }
  4753. function digitValue(s) {
  4754. // ignore-in-doc
  4755. return s.charCodeAt(0) - "0".charCodeAt(0);
  4756. }
  4757. var times = features.repeat ? function (s, count$$1) {
  4758. return s.repeat(count$$1);
  4759. } : function (s, count$$1) {
  4760. // Example:
  4761. // string.times("test", 3) // => "testtesttest"
  4762. return count$$1 < 1 ? '' : new Array(count$$1 + 1).join(s);
  4763. };
  4764. function longestCommonSubstring(a, b) {
  4765. // Example:
  4766. // longestCommonSubstring("bar foo barrr", "hello fooo world");
  4767. // => {indexA: 3, indexB: 5, length: 4, string: " foo"}
  4768. var lcs = [];
  4769. for (var i = 0; i < a.length; i++) {
  4770. lcs[i] = [];
  4771. for (var j = 0; j < b.length; j++) {
  4772. lcs[i][j] = 0;
  4773. }
  4774. }
  4775. // if B is null then LCS of A, B =0
  4776. for (var _i = 0; _i < a.length; _i++) {
  4777. lcs[_i][0] = 0;
  4778. } // fill the rest of the matrix
  4779. for (var _i2 = 1; _i2 < a.length; _i2++) {
  4780. for (var _j = 1; _j < b.length; _j++) {
  4781. lcs[_i2][_j] = a[_i2 - 1] == b[_j - 1] ? lcs[_i2 - 1][_j - 1] + 1 : 0;
  4782. }
  4783. }
  4784. var maxLength = -1,
  4785. indexA = -1,
  4786. indexB = -1;
  4787. for (var _i3 = 0; _i3 < a.length; _i3++) {
  4788. for (var _j2 = 0; _j2 < b.length; _j2++) {
  4789. var length = lcs[_i3][_j2];
  4790. if (maxLength < length) {
  4791. maxLength = length;
  4792. indexA = _i3 - length;
  4793. indexB = _j2 - length;
  4794. }
  4795. }
  4796. }
  4797. return {
  4798. length: maxLength, indexA: indexA, indexB: indexB,
  4799. string: maxLength > 0 ? a.slice(indexA, indexA + maxLength) : ""
  4800. };
  4801. }
  4802. function applyChange(string, change) {
  4803. // change is of the form
  4804. // `{start: Number, end: Number, lines: [String], action: "insert"|"remove"}`
  4805. if (change.action === "insert") {
  4806. return string.slice(0, change.start) + change.lines.join("\n") + string.slice(change.start);
  4807. } else if (change.action === "remove") {
  4808. return string.slice(0, change.start) + string.slice(change.end);
  4809. }
  4810. return string;
  4811. }
  4812. function applyChanges(s, changes) {
  4813. return changes.reduce(function (result, change) {
  4814. return applyChange(s, change);
  4815. }, s);
  4816. }
  4817. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  4818. // diffing / comparing
  4819. function levenshtein(a, b) {
  4820. // How many edit operations separate string a from b?
  4821. // MIT licensed, https://gist.github.com/andrei-
  4822. // Copyright (c) 2011 Andrei Mackenzie and https://github.com/kigiri
  4823. if (a.length === 0) return b.length;
  4824. if (b.length === 0) return a.length;
  4825. var tmp, i, j, prev, val, row;
  4826. // swap to save some memory O(min(a,b)) instead of O(a)
  4827. if (a.length > b.length) {
  4828. tmp = a;a = b;b = tmp;
  4829. }
  4830. row = Array(a.length + 1);
  4831. // init the row
  4832. for (i = 0; i <= a.length; i++) {
  4833. row[i] = i;
  4834. } // fill in the rest
  4835. for (i = 1; i <= b.length; i++) {
  4836. prev = i;
  4837. for (j = 1; j <= a.length; j++) {
  4838. if (b[i - 1] === a[j - 1]) {
  4839. val = row[j - 1]; // match
  4840. } else {
  4841. val = Math.min(row[j - 1] + 1, // substitution
  4842. Math.min(prev + 1, // insertion
  4843. row[j] + 1)); // deletion
  4844. }
  4845. row[j - 1] = prev;
  4846. prev = val;
  4847. }
  4848. row[a.length] = prev;
  4849. }
  4850. return row[a.length];
  4851. }
  4852. var string = Object.freeze({
  4853. format: format,
  4854. formatFromArray: formatFromArray,
  4855. indent: indent,
  4856. minIndent: minIndent,
  4857. changeIndent: changeIndent,
  4858. quote: quote,
  4859. print: print,
  4860. printNested: printNested,
  4861. pad: pad,
  4862. printTable: printTable,
  4863. printTree: printTree,
  4864. toArray: toArray$1,
  4865. lines: lines,
  4866. paragraphs: paragraphs,
  4867. nonEmptyLines: nonEmptyLines,
  4868. tokens: tokens,
  4869. tableize: tableize,
  4870. unescapeCharacterEntities: unescapeCharacterEntities,
  4871. toQueryParams: toQueryParams,
  4872. normalizePath: normalizePath$1,
  4873. joinPath: joinPath,
  4874. newUUID: newUUID,
  4875. createDataURI: createDataURI,
  4876. hashCode: hashCode,
  4877. md5: md5,
  4878. reMatches: reMatches$$1,
  4879. stringMatch: stringMatch,
  4880. peekRight: peekRight,
  4881. peekLeft: peekLeft,
  4882. lineIndexComputer: lineIndexComputer,
  4883. lineNumberToIndexesComputer: lineNumberToIndexesComputer,
  4884. findLineWithIndexInLineRanges: findLineWithIndexInLineRanges,
  4885. regexIndexOf: regexIndexOf,
  4886. regexLastIndexOf: regexLastIndexOf,
  4887. lineRanges: lineRanges,
  4888. diff: diff,
  4889. empty: empty,
  4890. includes: includes$$1,
  4891. include: include$$1,
  4892. startsWith: startsWith,
  4893. startsWithVowel: startsWithVowel,
  4894. endsWith: endsWith,
  4895. withDecimalPrecision: withDecimalPrecision,
  4896. capitalize: capitalize,
  4897. camelCaseString: camelCaseString,
  4898. camelize: camelize,
  4899. truncate: truncate,
  4900. truncateLeft: truncateLeft,
  4901. regExpEscape: regExpEscape,
  4902. succ: succ,
  4903. digitValue: digitValue,
  4904. times: times,
  4905. longestCommonSubstring: longestCommonSubstring,
  4906. applyChange: applyChange,
  4907. applyChanges: applyChanges,
  4908. levenshtein: levenshtein
  4909. });
  4910. /*
  4911. * Utility functions for JS Numbers.
  4912. */
  4913. function random(min, max) {
  4914. // random number between (and including) `min` and `max`
  4915. min = min || 0;
  4916. max = max || 100;
  4917. return Math.round(Math.random() * (max - min) + min);
  4918. }
  4919. var normalRandom = function (mean, stdDev) {
  4920. // returns randomized numbers in a normal distribution that can be
  4921. // controlled ising the `mean` and `stdDev` parameters
  4922. var spare,
  4923. isSpareReady = false;
  4924. return function (mean, stdDev) {
  4925. if (isSpareReady) {
  4926. isSpareReady = false;
  4927. return spare * stdDev + mean;
  4928. } else {
  4929. var u, v, s;
  4930. do {
  4931. u = Math.random() * 2 - 1;
  4932. v = Math.random() * 2 - 1;
  4933. s = u * u + v * v;
  4934. } while (s >= 1 || s == 0);
  4935. var mul = Math.sqrt(-2.0 * Math.log(s) / s);
  4936. spare = v * mul;
  4937. isSpareReady = true;
  4938. return mean + stdDev * u * mul;
  4939. }
  4940. };
  4941. }();
  4942. function randomSmallerInteger(n) {
  4943. return Math.floor(Math.random() * n);
  4944. }
  4945. function humanReadableByteSize(n) {
  4946. // interpret `n` as byte size and print a more readable version
  4947. // Example:
  4948. // num.humanReadableByteSize(Math.pow(2,32)) // => "4096MB"
  4949. function round(n) {
  4950. return Math.round(n * 100) / 100;
  4951. }
  4952. if (n < 1000) return String(round(n)) + 'B';
  4953. n = n / 1024;
  4954. if (n < 1000) return String(round(n)) + 'KB';
  4955. n = n / 1024;
  4956. return String(round(n)) + 'MB';
  4957. }
  4958. function average(numbers) {
  4959. // show-in-doc
  4960. return numbers.reduce(function (sum, n) {
  4961. return sum + n;
  4962. }, 0) / numbers.length;
  4963. }
  4964. function averageInc(newVal, oldAvg, n) {
  4965. // show-in-doc
  4966. // Example:
  4967. // let nums = range(0, 10).map(() => random(0, 10))
  4968. // nums.reduce((avg, ea, i) => avgInc(ea, avg, i+1), 0);
  4969. return (newVal - oldAvg) / n + oldAvg;
  4970. }
  4971. function median(numbers) {
  4972. // show-in-doc
  4973. var sorted = numbers.sort(function (a, b) {
  4974. return b - a;
  4975. }),
  4976. len = numbers.length;
  4977. return len % 2 === 0 ? 0.5 * (sorted[len / 2 - 1] + sorted[len / 2]) : sorted[(len - 1) / 2];
  4978. }
  4979. function between(x, a, b, eps) {
  4980. // is `a` <= `x` <= `y`?
  4981. eps = eps || 0;
  4982. var min, max;
  4983. if (a < b) {
  4984. min = a, max = b;
  4985. } else {
  4986. max = a, min = b;
  4987. }
  4988. return max - x + eps >= 0 && min - x - eps <= 0;
  4989. }
  4990. function sort$1(arr) {
  4991. // numerical sort, JavaScript native `sort` function is lexical by default.
  4992. return arr.sort(function (a, b) {
  4993. return a - b;
  4994. });
  4995. }
  4996. function parseLength(string, toUnit) {
  4997. // This converts the length value to pixels or the specified `toUnit`.
  4998. // length converstion, supported units are: mm, cm, in, px, pt, pc
  4999. // Examples:
  5000. // num.parseLength('3cm') // => 113.38582677165354
  5001. // num.parseLength('3cm', "in") // => 1.1811023622047243
  5002. toUnit = toUnit || 'px';
  5003. var match = string.match(/([0-9\.]+)\s*(.*)/);
  5004. if (!match || !match[1]) return undefined;
  5005. var length = parseFloat(match[1]),
  5006. fromUnit = match[2];
  5007. return convertLength(length, fromUnit, toUnit);
  5008. }
  5009. var convertLength = function () {
  5010. // ignore-in-doc
  5011. // num.convertLength(20, 'px', 'pt').roundTo(0.01)
  5012. function toCm(n, unit) {
  5013. // as defined in http://www.w3.org/TR/css3-values/#absolute-lengths
  5014. if (unit === 'cm') return n;else if (unit === 'mm') return n * 0.1;else if (unit === 'in') return n * 2.54;else if (unit === 'px') return n * toCm(1 / 96, 'in');else if (unit === 'pt') return n * toCm(1 / 72, 'in');else if (unit === 'pc') return n * toCm(12, 'pt');
  5015. }
  5016. return function to(length, fromUnit, toUnit) {
  5017. if (fromUnit === toUnit) return length;else if (toUnit === "cm") return toCm(length, fromUnit);else if (fromUnit === "cm") return length / toCm(1, toUnit);else return to(to(length, fromUnit, 'cm'), 'cm', toUnit);
  5018. };
  5019. }();
  5020. function roundTo(n, quantum) {
  5021. // `quantum` is something like 0.01,
  5022. // for JS rounding to work we need the reciprocal
  5023. quantum = 1 / quantum;
  5024. return Math.round(n * quantum) / quantum;
  5025. }
  5026. function detent(n, detent, grid, snap) {
  5027. // This function is useful to implement smooth transitions and snapping.
  5028. // Map all values that are within detent/2 of any multiple of grid to
  5029. // that multiple. Otherwise, if snap is true, return self, meaning that
  5030. // the values in the dead zone will never be returned. If snap is
  5031. // false, then expand the range between dead zone so that it covers the
  5032. // range between multiples of the grid, and scale the value by that
  5033. // factor.
  5034. // Examples:
  5035. // // With snapping:
  5036. // num.detent(0.11, 0.2, 0.5, true) // => 0.11
  5037. // num.detent(0.39, 0.2, 0.5, true) // => 0.39
  5038. // num.detent(0.55, 0.2, 0.5, true) // => 0.5
  5039. // num.detent(0.61, 0.2, 0.5, true) // => 0.61
  5040. // // Smooth transitions without snapping:
  5041. // num.detent(0.1, 0.2, 0.5) // => 0
  5042. // num.detent(0.11, 0.2, 0.5) // => 0.0166666
  5043. // num.detent(0.34, 0.2, 0.5) // => 0.4
  5044. // num.detent(0.39, 0.2, 0.5) // => 0.4833334
  5045. // num.detent(0.4, 0.2, 0.5) // => 0.5
  5046. // num.detent(0.6, 0.2, 0.5) // => 0.5
  5047. var r1 = roundTo(n, grid); // Nearest multiple of grid
  5048. if (Math.abs(n - r1) < detent / 2) return r1; // Snap to that multiple...
  5049. if (snap) return n; // ...and return n
  5050. // or compute nearest end of dead zone
  5051. var r2 = n < r1 ? r1 - detent / 2 : r1 + detent / 2;
  5052. // and scale values between dead zones to fill range between multiples
  5053. return r1 + (n - r2) * grid / (grid - detent);
  5054. }
  5055. function toDegrees(n) {
  5056. // Example:
  5057. // num.toDegrees(Math.PI/2) // => 90
  5058. return n * 180 / Math.PI % 360;
  5059. }
  5060. function toRadians(n) {
  5061. // Example:
  5062. // num.toRadians(180) // => 3.141592653589793
  5063. return n / 180 * Math.PI;
  5064. }
  5065. function backoff(attempt) /*ms*/{
  5066. var base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 5;
  5067. var cap = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 30000;
  5068. // exponential backoff function
  5069. // https://www.awsarchitectureblog.com/2015/03/backoff.html
  5070. var temp = Math.min(cap, base * Math.pow(2, attempt)),
  5071. sleep = temp / 2 + Math.round(Math.random() * (temp / 2));
  5072. return Math.min(cap, base + Math.random() * (sleep * 3 - base));
  5073. }
  5074. function interpolate(i, a, b) {
  5075. return a + i * (b - a);
  5076. }
  5077. var num = Object.freeze({
  5078. random: random,
  5079. normalRandom: normalRandom,
  5080. randomSmallerInteger: randomSmallerInteger,
  5081. humanReadableByteSize: humanReadableByteSize,
  5082. average: average,
  5083. averageInc: averageInc,
  5084. median: median,
  5085. between: between,
  5086. sort: sort$1,
  5087. parseLength: parseLength,
  5088. convertLength: convertLength,
  5089. roundTo: roundTo,
  5090. detent: detent,
  5091. toDegrees: toDegrees,
  5092. toRadians: toRadians,
  5093. backoff: backoff,
  5094. interpolate: interpolate
  5095. });
  5096. function all$2(object, predicate) {
  5097. // ignore-in-doc
  5098. var a = [];
  5099. for (var name in object) {
  5100. if ((object.__lookupGetter__(name) || typeof object[name] !== 'function') && (predicate ? predicate(name, object) : true)) a.push(name);
  5101. }
  5102. return a;
  5103. }
  5104. function allOwnPropertiesOrFunctions(obj, predicate) {
  5105. // ignore-in-doc
  5106. return Object.getOwnPropertyNames(obj).reduce(function (result, name) {
  5107. if (predicate ? predicate(obj, name) : true) result.push(name);
  5108. return result;
  5109. }, []);
  5110. }
  5111. function own$1(object) {
  5112. // ignore-in-doc
  5113. var a = [];
  5114. for (var name in object) {
  5115. if (object.hasOwnProperty(name) && (object.__lookupGetter__(name) || object[name] !== 'function')) a.push(name);
  5116. }
  5117. return a;
  5118. }
  5119. function forEachOwn(object, func, context) {
  5120. // ignore-in-doc
  5121. var result = [];
  5122. for (var name in object) {
  5123. if (!object.hasOwnProperty(name)) continue;
  5124. var value = object[name];
  5125. if (value !== 'function') {
  5126. result.push(func.call(context || this, name, value));
  5127. }
  5128. }
  5129. return result;
  5130. }
  5131. function nameFor(object, value) {
  5132. // ignore-in-doc
  5133. for (var name in object) {
  5134. if (object[name] === value) return name;
  5135. }return undefined;
  5136. }
  5137. function values$1(obj) {
  5138. // ignore-in-doc
  5139. var values = [];
  5140. for (var name in obj) {
  5141. values.push(obj[name]);
  5142. }return values;
  5143. }
  5144. function ownValues(obj) {
  5145. // ignore-in-doc
  5146. var values = [];
  5147. for (var name in obj) {
  5148. if (obj.hasOwnProperty(name)) values.push(obj[name]);
  5149. }return values;
  5150. }
  5151. function any$1(obj, predicate) {
  5152. // ignore-in-doc
  5153. for (var name in obj) {
  5154. if (predicate(obj, name)) return true;
  5155. }return false;
  5156. }
  5157. function allProperties(obj, predicate) {
  5158. // ignore-in-doc
  5159. var result = [];
  5160. for (var name in obj) {
  5161. if (predicate ? predicate(obj, name) : true) result.push(name);
  5162. }return result;
  5163. }
  5164. function hash(obj) {
  5165. // ignore-in-doc
  5166. // Using the property names of `obj` to generate a hash value.
  5167. return Object.keys(obj).sort().join('').hashCode();
  5168. }
  5169. var properties = Object.freeze({
  5170. all: all$2,
  5171. allOwnPropertiesOrFunctions: allOwnPropertiesOrFunctions,
  5172. own: own$1,
  5173. forEachOwn: forEachOwn,
  5174. nameFor: nameFor,
  5175. values: values$1,
  5176. ownValues: ownValues,
  5177. any: any$1,
  5178. allProperties: allProperties,
  5179. hash: hash
  5180. });
  5181. /*
  5182. * Util functions to print and work with JS date objects.
  5183. */
  5184. var dateFormat = function setupDateFormat() {
  5185. /*
  5186. * Date Format 1.2.3
  5187. * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
  5188. * MIT license
  5189. *
  5190. * Includes enhancements by Scott Trenda <scott.trenda.net>
  5191. * and Kris Kowal <cixar.com/~kris.kowal/>
  5192. *
  5193. * Accepts a date, a mask, or a date and a mask.
  5194. * Returns a formatted version of the given date.
  5195. * The date defaults to the current date/time.
  5196. * The mask defaults to dateFormat.masks.default.
  5197. */
  5198. // http://blog.stevenlevithan.com/archives/date-time-format
  5199. var dateFormat = function () {
  5200. var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
  5201. timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
  5202. timezoneClip = /[^-+\dA-Z]/g,
  5203. pad = function pad(val, len) {
  5204. val = String(val);
  5205. len = len || 2;
  5206. while (val.length < len) {
  5207. val = "0" + val;
  5208. }return val;
  5209. };
  5210. // Regexes and supporting functions are cached through closure
  5211. return function (date, mask, utc) {
  5212. var dF = dateFormat;
  5213. // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
  5214. if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
  5215. mask = date;
  5216. date = undefined;
  5217. }
  5218. // Passing date through Date applies Date.parse, if necessary
  5219. date = date ? new Date(date) : new Date();
  5220. if (isNaN(date)) throw SyntaxError("invalid date");
  5221. mask = String(dF.masks[mask] || mask || dF.masks["default"]);
  5222. // Allow setting the utc argument via the mask
  5223. if (mask.slice(0, 4) == "UTC:") {
  5224. mask = mask.slice(4);
  5225. utc = true;
  5226. }
  5227. var _ = utc ? "getUTC" : "get",
  5228. d = date[_ + "Date"](),
  5229. D = date[_ + "Day"](),
  5230. m = date[_ + "Month"](),
  5231. y = date[_ + "FullYear"](),
  5232. H = date[_ + "Hours"](),
  5233. M = date[_ + "Minutes"](),
  5234. s = date[_ + "Seconds"](),
  5235. L = date[_ + "Milliseconds"](),
  5236. o = utc ? 0 : date.getTimezoneOffset(),
  5237. flags = {
  5238. d: d,
  5239. dd: pad(d),
  5240. ddd: dF.i18n.dayNames[D],
  5241. dddd: dF.i18n.dayNames[D + 7],
  5242. m: m + 1,
  5243. mm: pad(m + 1),
  5244. mmm: dF.i18n.monthNames[m],
  5245. mmmm: dF.i18n.monthNames[m + 12],
  5246. yy: String(y).slice(2),
  5247. yyyy: y,
  5248. h: H % 12 || 12,
  5249. hh: pad(H % 12 || 12),
  5250. H: H,
  5251. HH: pad(H),
  5252. M: M,
  5253. MM: pad(M),
  5254. s: s,
  5255. ss: pad(s),
  5256. l: pad(L, 3),
  5257. L: pad(L > 99 ? Math.round(L / 10) : L),
  5258. t: H < 12 ? "a" : "p",
  5259. tt: H < 12 ? "am" : "pm",
  5260. T: H < 12 ? "A" : "P",
  5261. TT: H < 12 ? "AM" : "PM",
  5262. Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
  5263. o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
  5264. S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
  5265. };
  5266. return mask.replace(token, function ($0) {
  5267. return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
  5268. });
  5269. };
  5270. }();
  5271. // Some common format strings
  5272. dateFormat.masks = {
  5273. "default": "ddd mmm dd yyyy HH:MM:ss",
  5274. shortDate: "m/d/yy",
  5275. mediumDate: "mmm d, yyyy",
  5276. longDate: "mmmm d, yyyy",
  5277. fullDate: "dddd, mmmm d, yyyy",
  5278. shortTime: "h:MM TT",
  5279. mediumTime: "h:MM:ss TT",
  5280. longTime: "h:MM:ss TT Z",
  5281. isoDate: "yyyy-mm-dd",
  5282. isoTime: "HH:MM:ss",
  5283. isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
  5284. isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
  5285. };
  5286. // Internationalization strings
  5287. dateFormat.i18n = {
  5288. dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  5289. monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
  5290. };
  5291. return dateFormat;
  5292. }(); // end of setupDateFormat
  5293. function format$1(date, mask, utc) {
  5294. // Custom date / time stringifier. Provides default masks:
  5295. //
  5296. // Mask | Pattern
  5297. // ---------------|--------------------------------
  5298. // default | `"ddd mmm dd yyyy HH:MM:ss"`
  5299. // shortDate | `"m/d/yy"`
  5300. // mediumDate | `"mmm d, yyyy"`
  5301. // longDate | `"mmmm d, yyyy"`
  5302. // fullDate | `"dddd, mmmm d, yyyy"`
  5303. // shortTime | `"h:MM TT"`
  5304. // mediumTime | `"h:MM:ss TT"`
  5305. // longTime | `"h:MM:ss TT Z"`
  5306. // isoDate | `"yyyy-mm-dd"`
  5307. // isoTime | `"HH:MM:ss"`
  5308. // isoDateTime | `"yyyy-mm-dd'T'HH:MM:ss"`
  5309. // isoUtcDateTime | `"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"`
  5310. //
  5311. // and internationalized strings via `date.format.i18n.dayNames`
  5312. // and `date.format.i18n.dayNames`
  5313. // Examples:
  5314. // date.format(new Date(), date.format.masks.longTime) // => "7:13:31 PM PDT"
  5315. // date.format(new Date(), "yyyy/mm/dd") // => "2014/10/09"
  5316. return dateFormat(date, mask, utc);
  5317. }
  5318. function equals$3(date, otherDate) {
  5319. // show-in-doc
  5320. return otherDate && otherDate instanceof Date && otherDate.getTime() === date.getTime();
  5321. }
  5322. function relativeTo(date, otherDate) {
  5323. // Prints a human readable difference of two Date objects. The older date
  5324. // goes first.
  5325. // Examples:
  5326. // var now = new Date();
  5327. // date.relativeTo(new Date(now-2000), now) // => "2 secs"
  5328. // date.relativeTo(new Date("10/11/2014"), new Date("10/12/2014")) // => "1 day"
  5329. if (!(otherDate instanceof Date)) return '';
  5330. if (otherDate < date) return '';
  5331. if (otherDate === date) return 'now';
  5332. var minuteString = 'min',
  5333. secondString = 'sec',
  5334. hourString = 'hour',
  5335. dayString = 'day',
  5336. diff = otherDate - date,
  5337. totalSecs = Math.round(diff / 1000),
  5338. secs = totalSecs % 60,
  5339. mins = Math.floor(totalSecs / 60) % 60,
  5340. hours = Math.floor(totalSecs / 60 / 60) % 24,
  5341. days = Math.floor(totalSecs / 60 / 60 / 24),
  5342. parts = [];
  5343. if (days > 0) {
  5344. parts.push(days);
  5345. if (days > 1) dayString += 's';
  5346. parts.push(dayString);
  5347. }
  5348. if (hours > 0 && days < 2) {
  5349. parts.push(hours);
  5350. if (hours > 1) hourString += 's';
  5351. parts.push(hourString);
  5352. }
  5353. if (mins > 0 && hours < 3 && days === 0) {
  5354. parts.push(mins);
  5355. if (mins > 1) minuteString += 's';
  5356. parts.push(minuteString);
  5357. }
  5358. if (secs > 0 && mins < 3 && hours === 0 && days === 0) {
  5359. parts.push(secs);
  5360. if (secs > 1) secondString += 's';
  5361. parts.push(secondString);
  5362. }
  5363. return parts.join(' ');
  5364. }
  5365. var date = Object.freeze({
  5366. format: format$1,
  5367. equals: equals$3,
  5368. relativeTo: relativeTo
  5369. });
  5370. /*global require, process, Promise, System*/
  5371. /*
  5372. * Methods helping with promises (Promise/A+ model). Not a promise shim.
  5373. */
  5374. function promise(obj) {
  5375. // Promise object / function converter
  5376. // Example:
  5377. // promise("foo");
  5378. // // => Promise({state: "fullfilled", value: "foo"})
  5379. // lively.lang.promise({then: (resolve, reject) => resolve(23)})
  5380. // // => Promise({state: "fullfilled", value: 23})
  5381. // lively.lang.promise(function(val, thenDo) { thenDo(null, val + 1) })(3)
  5382. // // => Promise({state: "fullfilled", value: 4})
  5383. return typeof obj === "function" ? promise.convertCallbackFun(obj) : Promise.resolve(obj);
  5384. }
  5385. function delay$1(ms, resolveVal) {
  5386. // Like `Promise.resolve(resolveVal)` but waits for `ms` milliseconds
  5387. // before resolving
  5388. return new Promise(function (resolve) {
  5389. return setTimeout(resolve, ms, resolveVal);
  5390. });
  5391. }
  5392. function delayReject(ms, rejectVal) {
  5393. // like `promise.delay` but rejects
  5394. return new Promise(function (_, reject$$1) {
  5395. return setTimeout(reject$$1, ms, rejectVal);
  5396. });
  5397. }
  5398. function timeout(ms, promise) {
  5399. // Takes a promise and either resolves to the value of the original promise
  5400. // when it succeeds before `ms` milliseconds passed or fails with a timeout
  5401. // error
  5402. return new Promise(function (resolve, reject$$1) {
  5403. var done = false;
  5404. setTimeout(function () {
  5405. return !done && (done = true) && reject$$1(new Error('Promise timed out'));
  5406. }, ms);
  5407. promise.then(function (val) {
  5408. return !done && (done = true) && resolve(val);
  5409. }, function (err) {
  5410. return !done && (done = true) && reject$$1(err);
  5411. });
  5412. });
  5413. }
  5414. function waitFor$1(ms, tester, timeoutObj) {
  5415. // Tests for a condition calling function `tester` until the result is
  5416. // truthy. Resolves with last return value of `tester`. If `ms` is defined
  5417. // and `ms` milliseconds passed, reject with timeout error
  5418. // if timeoutObj is passed will resolve(!) with this object instead of raise
  5419. // an error
  5420. if (typeof ms === "function") {
  5421. tester = ms;ms = undefined;
  5422. }
  5423. return new Promise(function (resolve, reject$$1) {
  5424. var stopped = false,
  5425. timedout = false,
  5426. timeoutValue = undefined,
  5427. error = undefined,
  5428. value = undefined,
  5429. i = setInterval(function () {
  5430. if (stopped) return clearInterval(i);
  5431. try {
  5432. value = tester();
  5433. } catch (e) {
  5434. error = e;
  5435. }
  5436. if (!value && !error && !timedout) return;
  5437. stopped = true;
  5438. clearInterval(i);
  5439. if (error) return reject$$1(error);
  5440. if (timedout) return typeof timeoutObj === "undefined" ? reject$$1(new Error("timeout")) : resolve(timeoutObj);
  5441. return resolve(value);
  5442. }, 10);
  5443. if (typeof ms === "number") setTimeout(function () {
  5444. return timedout = true;
  5445. }, ms);
  5446. });
  5447. }
  5448. function deferred() {
  5449. // returns an object
  5450. // `{resolve: FUNCTION, reject: FUNCTION, promise: PROMISE}`
  5451. // that separates the resolve/reject handling from the promise itself
  5452. // Similar to the deprecated `Promise.defer()`
  5453. var resolve,
  5454. reject$$1,
  5455. promise = new Promise(function (_resolve, _reject) {
  5456. resolve = _resolve;reject$$1 = _reject;
  5457. });
  5458. return { resolve: resolve, reject: reject$$1, promise: promise };
  5459. }
  5460. function convertCallbackFun(func) {
  5461. // Takes a function that accepts a nodejs-style callback function as a last
  5462. // parameter and converts it to a function *not* taking the callback but
  5463. // producing a promise instead. The promise will be resolved with the
  5464. // *first* non-error argument.
  5465. // nodejs callback convention: a function that takes as first parameter an
  5466. // error arg and second+ parameters are the result(s).
  5467. // Example:
  5468. // var fs = require("fs"),
  5469. // readFile = promise.convertCallbackFun(fs.readFile);
  5470. // readFile("./some-file.txt")
  5471. // .then(content => console.log(String(content)))
  5472. // .catch(err => console.error("Could not read file!", err));
  5473. return function promiseGenerator() /*args*/{
  5474. var args = Array.from(arguments),
  5475. self = this;
  5476. return new Promise(function (resolve, reject$$1) {
  5477. args.push(function (err, result) {
  5478. return err ? reject$$1(err) : resolve(result);
  5479. });
  5480. func.apply(self, args);
  5481. });
  5482. };
  5483. }
  5484. function convertCallbackFunWithManyArgs(func) {
  5485. // like convertCallbackFun but the promise will be resolved with the
  5486. // all non-error arguments wrapped in an array.
  5487. return function promiseGenerator() /*args*/{
  5488. var args = Array.from(arguments),
  5489. self = this;
  5490. return new Promise(function (resolve, reject$$1) {
  5491. args.push(function () /*err + args*/{
  5492. var args = Array.from(arguments),
  5493. err = args.shift();
  5494. return err ? reject$$1(err) : resolve(args);
  5495. });
  5496. func.apply(self, args);
  5497. });
  5498. };
  5499. }
  5500. function _chainResolveNext(promiseFuncs, prevResult, akku, resolve, reject$$1) {
  5501. var next = promiseFuncs.shift();
  5502. if (!next) resolve(prevResult);else {
  5503. try {
  5504. Promise.resolve(next(prevResult, akku)).then(function (result) {
  5505. return _chainResolveNext(promiseFuncs, result, akku, resolve, reject$$1);
  5506. }).catch(function (err) {
  5507. reject$$1(err);
  5508. });
  5509. } catch (err) {
  5510. reject$$1(err);
  5511. }
  5512. }
  5513. }
  5514. function chain$1(promiseFuncs) {
  5515. // Similar to Promise.all but takes a list of promise-producing functions
  5516. // (instead of Promises directly) that are run sequentially. Each function
  5517. // gets the result of the previous promise and a shared "state" object passed
  5518. // in. The function should return either a value or a promise. The result of
  5519. // the entire chain call is a promise itself that either resolves to the last
  5520. // returned value or rejects with an error that appeared somewhere in the
  5521. // promise chain. In case of an error the chain stops at that point.
  5522. // Example:
  5523. // lively.lang.promise.chain([
  5524. // () => Promise.resolve(23),
  5525. // (prevVal, state) => { state.first = prevVal; return prevVal + 2 },
  5526. // (prevVal, state) => { state.second = prevVal; return state }
  5527. // ]).then(result => console.log(result));
  5528. // // => prints {first: 23,second: 25}
  5529. return new Promise(function (resolve, reject$$1) {
  5530. return _chainResolveNext(promiseFuncs.slice(), undefined, {}, resolve, reject$$1);
  5531. });
  5532. }
  5533. function promise_finally(promise, finallyFn) {
  5534. return Promise.resolve(promise).then(function (result) {
  5535. try {
  5536. finallyFn();
  5537. } catch (err) {
  5538. console.error("Error in promise finally: " + err.stack || err);
  5539. }return result;
  5540. }).catch(function (err) {
  5541. try {
  5542. finallyFn();
  5543. } catch (err) {
  5544. console.error("Error in promise finally: " + err.stack || err);
  5545. }throw err;
  5546. });
  5547. }
  5548. function parallel(promiseGenFns) {
  5549. var parallelLimit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Infinity;
  5550. // Starts functions from promiseGenFns that are expected to return a promise
  5551. // Once `parallelLimit` promises are unresolved at the same time, stops
  5552. // spawning further promises until a running promise resolves
  5553. if (!promiseGenFns.length) return Promise.resolve([]);
  5554. var results = [],
  5555. error = null,
  5556. index = 0,
  5557. left = promiseGenFns.length,
  5558. resolve = void 0,
  5559. reject$$1 = void 0;
  5560. return new Promise(function (res, rej) {
  5561. resolve = function resolve() {
  5562. return res(results);
  5563. };
  5564. reject$$1 = function reject$$1(err) {
  5565. return rej(error = err);
  5566. };
  5567. spawnMore();
  5568. });
  5569. function spawn() {
  5570. parallelLimit--;
  5571. try {
  5572. (function () {
  5573. var i = index++,
  5574. prom = promiseGenFns[i]();
  5575. prom.then(function (result) {
  5576. parallelLimit++;
  5577. results[i] = result;
  5578. if (--left === 0) resolve();else spawnMore();
  5579. }).catch(function (err) {
  5580. return reject$$1(err);
  5581. });
  5582. })();
  5583. } catch (err) {
  5584. reject$$1(err);
  5585. }
  5586. }
  5587. function spawnMore() {
  5588. while (!error && left > 0 && index < promiseGenFns.length && parallelLimit > 0) {
  5589. spawn();
  5590. }
  5591. }
  5592. }
  5593. // FIXME!
  5594. Object.assign(promise, {
  5595. delay: delay$1,
  5596. delayReject: delayReject,
  5597. timeout: timeout,
  5598. waitFor: waitFor$1,
  5599. deferred: deferred,
  5600. convertCallbackFun: convertCallbackFun,
  5601. convertCallbackFunWithManyArgs: convertCallbackFunWithManyArgs,
  5602. chain: chain$1,
  5603. "finally": promise_finally,
  5604. parallel: parallel
  5605. });
  5606. // -=-=-=-=-=-=-=-=-=-=-=-=-=-
  5607. // js object path accessor
  5608. // -=-=-=-=-=-=-=-=-=-=-=-=-=-
  5609. // show-in-doc
  5610. // A `Path` is an objectified chain of property names (kind of a "complex"
  5611. // getter and setter). Path objects can make access and writes into deeply nested
  5612. // structures more convenient. `Path` provide "safe" get and set operations and
  5613. // can be used for debugging by providing a hook that allows users to find out
  5614. // when get/set operations happen.
  5615. function Path(p, splitter) {
  5616. if (p instanceof Path) return p;
  5617. if (!(this instanceof Path)) return new Path(p, splitter);
  5618. this.setSplitter(splitter || '.');
  5619. this.fromPath(p);
  5620. }
  5621. Object.assign(Path.prototype, {
  5622. get isPathAccessor() {
  5623. return true;
  5624. },
  5625. fromPath: function fromPath(path) {
  5626. // ignore-in-doc
  5627. if (typeof path === "string" && path !== '' && path !== this.splitter) {
  5628. this._parts = path.split(this.splitter);
  5629. this._path = path;
  5630. } else if (Array.isArray(path)) {
  5631. this._parts = [].concat(path);
  5632. this._path = path.join(this.splitter);
  5633. } else {
  5634. this._parts = [];
  5635. this._path = '';
  5636. }
  5637. return this;
  5638. },
  5639. setSplitter: function setSplitter(splitter) {
  5640. // ignore-in-doc
  5641. if (splitter) this.splitter = splitter;
  5642. return this;
  5643. },
  5644. parts: function parts() {
  5645. /*key names as array*/return this._parts;
  5646. },
  5647. size: function size() {
  5648. /*show-in-doc*/return this._parts.length;
  5649. },
  5650. slice: function slice(n, m) {
  5651. /*show-in-doc*/return Path(this.parts().slice(n, m));
  5652. },
  5653. normalizePath: function normalizePath() {
  5654. // ignore-in-doc
  5655. // FIXME: define normalization
  5656. return this._path;
  5657. },
  5658. isRoot: function isRoot(obj) {
  5659. return this._parts.length === 0;
  5660. },
  5661. isIn: function isIn(obj) {
  5662. // Does the Path resolve to a value when applied to `obj`?
  5663. if (this.isRoot()) return true;
  5664. var parent = this.get(obj, -1);
  5665. return parent && parent.hasOwnProperty(this._parts[this._parts.length - 1]);
  5666. },
  5667. equals: function equals(obj) {
  5668. // Example:
  5669. // var p1 = Path("foo.1.bar.baz"), p2 = Path(["foo", 1, "bar", "baz"]);
  5670. // // Path's can be both created via strings or pre-parsed with keys in a list.
  5671. // p1.equals(p2) // => true
  5672. return obj && obj.isPathAccessor && this.parts().equals(obj.parts());
  5673. },
  5674. isParentPathOf: function isParentPathOf(otherPath) {
  5675. // Example:
  5676. // var p1 = Path("foo.1.bar.baz"), p2 = Path("foo.1.bar");
  5677. // p2.isParentPathOf(p1) // => true
  5678. // p1.isParentPathOf(p2) // => false
  5679. otherPath = otherPath && otherPath.isPathAccessor ? otherPath : Path(otherPath);
  5680. var parts = this.parts(),
  5681. otherParts = otherPath.parts();
  5682. for (var i = 0; i < parts.length; i++) {
  5683. if (parts[i] != otherParts[i]) return false;
  5684. }
  5685. return true;
  5686. },
  5687. relativePathTo: function relativePathTo(otherPath) {
  5688. // Example:
  5689. // var p1 = Path("foo.1.bar.baz"), p2 = Path("foo.1");
  5690. // p2.relativePathTo(p1) // => Path(["bar","baz"])
  5691. // p1.relativePathTo(p2) // => undefined
  5692. otherPath = Path(otherPath);
  5693. return this.isParentPathOf(otherPath) ? otherPath.slice(this.size(), otherPath.size()) : undefined;
  5694. },
  5695. del: function del(obj) {
  5696. if (this.isRoot()) return false;
  5697. var parent = obj;
  5698. for (var i = 0; i < this._parts.length - 1; i++) {
  5699. var part = this._parts[i];
  5700. if (parent.hasOwnProperty(part)) {
  5701. parent = parent[part];
  5702. } else return false;
  5703. }
  5704. return delete parent[this._parts[this._parts.length - 1]];
  5705. },
  5706. withParentAndKeyDo: function withParentAndKeyDo(obj, ensure, doFunc) {
  5707. // Deeply resolve path in `obj`, not fully, however, only to the parent
  5708. // element of the last part of path. Take the parent, the key (the last
  5709. // part of path) and pass it to `doFunc`. When `ensure` is true, create
  5710. // objects along path it path does not resolve
  5711. if (this.isRoot()) return doFunc(null, null);
  5712. var parent = obj;
  5713. for (var i = 0; i < this._parts.length - 1; i++) {
  5714. var part = this._parts[i];
  5715. if (parent.hasOwnProperty(part) && (_typeof(parent[part]) === "object" || typeof parent[part] === "function")) {
  5716. parent = parent[part];
  5717. } else if (ensure) {
  5718. parent = parent[part] = {};
  5719. } else {
  5720. return doFunc(null, part);
  5721. }
  5722. }
  5723. return doFunc(parent, this._parts[this._parts.length - 1]);
  5724. },
  5725. set: function set(obj, val, ensure) {
  5726. // Deeply resolve path in `obj` and set the resulting property to `val`. If
  5727. // `ensure` is true, create nested structure in between as necessary.
  5728. // Example:
  5729. // var o1 = {foo: {bar: {baz: 42}}};
  5730. // var path = Path("foo.bar.baz");
  5731. // path.set(o1, 43)
  5732. // o1 // => {foo: {bar: {baz: 43}}}
  5733. // var o2 = {foo: {}};
  5734. // path.set(o2, 43, true)
  5735. // o2 // => {foo: {bar: {baz: 43}}}
  5736. return this.withParentAndKeyDo(obj, ensure, function (parent, key) {
  5737. return parent ? parent[key] = val : undefined;
  5738. });
  5739. },
  5740. defineProperty: function defineProperty(obj, propertySpec, ensure) {
  5741. // like `Path>>set`, however uses Objeect.defineProperty
  5742. return this.withParentAndKeyDo(obj, ensure, function (parent, key) {
  5743. return parent ? Object.defineProperty(parent, key, propertySpec) : undefined;
  5744. });
  5745. },
  5746. get: function get(obj, n) {
  5747. // show-in-doc
  5748. var parts = n ? this._parts.slice(0, n) : this._parts;
  5749. return parts.reduce(function (current, pathPart) {
  5750. return current ? current[pathPart] : current;
  5751. }, obj);
  5752. },
  5753. concat: function concat(p, splitter) {
  5754. // show-in-doc
  5755. return Path(this.parts().concat(Path(p, splitter).parts()));
  5756. },
  5757. toString: function toString() {
  5758. return this.normalizePath();
  5759. },
  5760. serializeExpr: function serializeExpr() {
  5761. // ignore-in-doc
  5762. return 'lively.lang.Path(' + inspect(this.parts()) + ')';
  5763. },
  5764. watch: function watch(options) {
  5765. // React or be notified on reads or writes to a path in a `target`. Options:
  5766. // ```js
  5767. // {
  5768. // target: OBJECT,
  5769. // uninstall: BOOLEAN,
  5770. // onGet: FUNCTION,
  5771. // onSet: FUNCTION,
  5772. // haltWhenChanged: BOOLEAN,
  5773. // verbose: BOOLEAN
  5774. // }
  5775. // ```
  5776. // Example:
  5777. // // Quite useful for debugging to find out what call-sites change an object.
  5778. // var o = {foo: {bar: 23}};
  5779. // Path("foo.bar").watch({target: o, verbose: true});
  5780. // o.foo.bar = 24; // => You should see: "[object Object].bar changed: 23 -> 24"
  5781. if (!options || this.isRoot()) return;
  5782. var target = options.target,
  5783. parent = this.get(target, -1),
  5784. propName = this.parts().slice(-1)[0],
  5785. newPropName = 'propertyWatcher$' + propName,
  5786. watcherIsInstalled = parent && parent.hasOwnProperty(newPropName),
  5787. uninstall = options.uninstall,
  5788. haltWhenChanged = options.haltWhenChanged,
  5789. showStack = options.showStack,
  5790. getter = parent.__lookupGetter__(propName),
  5791. setter = parent.__lookupSetter__(propName);
  5792. if (!target || !propName || !parent) return;
  5793. if (uninstall) {
  5794. if (!watcherIsInstalled) return;
  5795. delete parent[propName];
  5796. parent[propName] = parent[newPropName];
  5797. delete parent[newPropName];
  5798. var msg = 'Watcher for ' + parent + '.' + propName + ' uninstalled';
  5799. show(msg);
  5800. return;
  5801. }
  5802. if (watcherIsInstalled) {
  5803. var msg = 'Watcher for ' + parent + '.' + propName + ' already installed';
  5804. show(msg);
  5805. return;
  5806. }
  5807. if (getter || setter) {
  5808. var msg = parent + '["' + propName + '"] is a getter/setter, watching not support';
  5809. console.log(msg);
  5810. if (typeof show === "undefined") show(msg);
  5811. return;
  5812. }
  5813. // observe slots, for debugging
  5814. parent[newPropName] = parent[propName];
  5815. parent.__defineSetter__(propName, function (v) {
  5816. var oldValue = parent[newPropName];
  5817. if (options.onSet) options.onSet(v, oldValue);
  5818. var msg = parent + "." + propName + " changed: " + oldValue + " -> " + v;
  5819. if (showStack) msg += '\n' + (typeof lively !== "undefined" ? lively.printStack() : console.trace());
  5820. if (options.verbose) {
  5821. console.log(msg);
  5822. if (typeof show !== 'undefined') show(msg);
  5823. }
  5824. if (haltWhenChanged) debugger;
  5825. return parent[newPropName] = v;
  5826. });
  5827. parent.__defineGetter__(propName, function () {
  5828. if (options.onGet) options.onGet(parent[newPropName]);
  5829. return parent[newPropName];
  5830. });
  5831. var msg = 'Watcher for ' + parent + '.' + propName + ' installed';
  5832. console.log(msg);
  5833. if (typeof show !== 'undefined') show(msg);
  5834. },
  5835. debugFunctionWrapper: function debugFunctionWrapper(options) {
  5836. // ignore-in-doc
  5837. // options = {target, [haltWhenChanged, showStack, verbose, uninstall]}
  5838. var target = options.target,
  5839. parent = this.get(target, -1),
  5840. funcName = this.parts().slice(-1)[0],
  5841. uninstall = options.uninstall,
  5842. haltWhenChanged = options.haltWhenChanged === undefined ? true : options.haltWhenChanged,
  5843. showStack = options.showStack,
  5844. func = parent && funcName && parent[funcName],
  5845. debuggerInstalled = func && func.isDebugFunctionWrapper;
  5846. if (!target || !funcName || !func || !parent) return;
  5847. if (uninstall) {
  5848. if (!debuggerInstalled) return;
  5849. parent[funcName] = parent[funcName].debugTargetFunction;
  5850. var msg = 'Uninstalled debugFunctionWrapper for ' + parent + '.' + funcName;
  5851. console.log(msg);
  5852. if (typeof show !== 'undefined') show(msg);
  5853. show(msg);
  5854. return;
  5855. }
  5856. if (debuggerInstalled) {
  5857. var msg = 'debugFunctionWrapper for ' + parent + '.' + funcName + ' already installed';
  5858. console.log(msg);
  5859. if (typeof show !== 'undefined') show(msg);
  5860. return;
  5861. }
  5862. var debugFunc = parent[funcName] = func.wrap(function (proceed) {
  5863. var args = Array.from(arguments);
  5864. if (haltWhenChanged) debugger;
  5865. if (showStack) show(lively.printStack());
  5866. if (options.verbose) show(funcName + ' called');
  5867. return args.shift().apply(parent, args);
  5868. });
  5869. debugFunc.isDebugFunctionWrapper = true;
  5870. debugFunc.debugTargetFunction = func;
  5871. var msg = 'debugFunctionWrapper for ' + parent + '.' + funcName + ' installed';
  5872. console.log(msg);
  5873. if (typeof show !== 'undefined') show(msg);
  5874. }
  5875. });
  5876. /*
  5877. Computation over graphs. Unless otherwise specified a graph is a simple JS
  5878. object whose properties are interpreted as nodes that refer to arrays whose
  5879. elements describe edges. Example:
  5880. ```js
  5881. var testGraph = {
  5882. "a": ["b", "c"],
  5883. "b": ["c", "d", "e", "f"],
  5884. "d": ["c", "f"],
  5885. "e": ["a", "f"],
  5886. "f": []
  5887. }
  5888. ```
  5889. */
  5890. // show-in-doc
  5891. function clone$2(graph) {
  5892. // return a copy of graph map
  5893. var cloned = {};
  5894. for (var id in graph) {
  5895. cloned[id] = graph[id].slice();
  5896. }return cloned;
  5897. }
  5898. function without$1(graph, ids) {
  5899. // return a copy of graph map with ids removed
  5900. var cloned = {};
  5901. for (var id in graph) {
  5902. if (ids.includes(id)) continue;
  5903. cloned[id] = [];
  5904. var refs = graph[id];
  5905. for (var i = 0; i < refs.length; i++) {
  5906. var ref = refs[i];
  5907. if (!ids.includes(ref)) cloned[id].push(ref);
  5908. }
  5909. }
  5910. return cloned;
  5911. }
  5912. function hull(g, id) {
  5913. var ignoredKeyList = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  5914. var maxDepth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : Infinity;
  5915. // Takes a graph in object format and a start id and then traverses the
  5916. // graph and gathers all nodes that can be reached from that start id.
  5917. // Returns a list of those nodes.
  5918. // Optionally use `ignore` list to filter out certain nodes that shouldn't
  5919. // be considered and maxDepth to stop early. By default a maxDepth of 20 is
  5920. // used.
  5921. // Example:
  5922. // var testGraph = {
  5923. // "a": ["b", "c"],
  5924. // "b": ["c", "d", "e", "f"],
  5925. // "d": ["c", "f"],
  5926. // "e": ["a", "f"],
  5927. // "f": []
  5928. // }
  5929. // hull(testGraph, "d") // => ["c", "f"]
  5930. // hull(testGraph, "e") // => ['a', 'f', 'b', 'c', 'd', 'e']
  5931. // hull(testGraph, "e", ["b"]) // => ["a", "f", "c"]
  5932. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  5933. // below is an optimized variant, the functional but slow version:
  5934. // return uniq(
  5935. // flatten(
  5936. // values(
  5937. // subgraphReachableBy(
  5938. // graphMap, id, ignore, maxDepth))));
  5939. if (!Array.isArray(g[id])) return [];
  5940. var hull = [],
  5941. visited = {};
  5942. var ignoredKeys = {};
  5943. for (var i = 0; i < ignoredKeyList.length; i++) {
  5944. ignoredKeys[ignoredKeyList[i]] = true;
  5945. }var toVisitList = g[id].slice(),
  5946. toVisitMapAndDistFromRoot = {};
  5947. for (var _i = toVisitList.length; _i--;) {
  5948. var key = toVisitList[_i];
  5949. if (key in ignoredKeys) toVisitList.splice(_i, 1);else toVisitMapAndDistFromRoot[key] = 1;
  5950. }
  5951. if (ignoredKeyList) while (true) {
  5952. if (toVisitList.length === 0) break;
  5953. for (var _i2 = 0; _i2 < toVisitList.length; _i2++) {
  5954. var _key = toVisitList.shift();
  5955. if (_key in visited || _key in ignoredKeys) continue;
  5956. var dist = toVisitMapAndDistFromRoot[_key] || 0;
  5957. if (dist > maxDepth) continue;
  5958. hull.push(_key);
  5959. visited[_key] = true;
  5960. var refs = g[_key];
  5961. if (!refs) continue;
  5962. for (var j = 0; j < refs.length; j++) {
  5963. var refKey = refs[j];
  5964. if (refKey in visited || refKey in toVisitMapAndDistFromRoot) continue;
  5965. toVisitMapAndDistFromRoot[refKey] = dist + 1;
  5966. toVisitList.push(refKey);
  5967. }
  5968. }
  5969. }
  5970. return hull;
  5971. }
  5972. function subgraphReachableBy(graphMap, startId, ignore) {
  5973. var maxDepth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : Infinity;
  5974. // show-in-doc
  5975. // Like hull but returns subgraph map of `graphMap`
  5976. // Example:
  5977. // subgraphReachableBy(testGraph, "e", [], 2);
  5978. // // => {e: [ 'a', 'f' ], a: [ 'b', 'c' ], f: []}
  5979. if (ignore) graphMap = without$1(graphMap, ignore);
  5980. var ids = [startId],
  5981. step = 0,
  5982. subgraph = {};
  5983. while (ids.length && step++ < maxDepth) {
  5984. var id = ids.shift();
  5985. if (subgraph[id]) continue;
  5986. var newIds = graphMap[id] || [];
  5987. subgraph[id] = newIds;
  5988. ids.push.apply(ids, toConsumableArray(newIds));
  5989. }
  5990. return subgraph;
  5991. }
  5992. function invert(g) {
  5993. // inverts the references of graph object `g`.
  5994. // Example:
  5995. // invert({a: ["b"], b: ["a", "c"]})
  5996. // // => {a: ["b"], b: ["a"], c: ["b"]}
  5997. var inverted = {};
  5998. for (var key in g) {
  5999. var refs = g[key];
  6000. for (var i = 0; i < refs.length; i++) {
  6001. var key2 = refs[i];
  6002. if (!inverted[key2]) inverted[key2] = [key];else inverted[key2].push(key);
  6003. }
  6004. }
  6005. return inverted;
  6006. }
  6007. function sortByReference(depGraph, startNode) {
  6008. // Sorts graph into an array of arrays. Each "bucket" contains the graph
  6009. // nodes that have no other incoming nodes than those already visited. This
  6010. // means, we start with the leaf nodes and then walk our way up.
  6011. // This is useful for computing how to traverse a dependency graph: You get
  6012. // a sorted list of dependencies that also allows circular references.
  6013. // Example:
  6014. // var depGraph = {a: ["b", "c"], b: ["c"], c: ["b"]};
  6015. // sortByReference(depGraph, "a");
  6016. // // => [["c"], ["b"], ["a"]]
  6017. // establish unique list of keys
  6018. var remaining = [],
  6019. remainingSeen = {},
  6020. uniqDepGraph = {},
  6021. inverseDepGraph = {};
  6022. for (var _key2 in depGraph) {
  6023. if (!remainingSeen.hasOwnProperty(_key2)) {
  6024. remainingSeen[_key2] = true;
  6025. remaining.push(_key2);
  6026. }
  6027. var deps = depGraph[_key2],
  6028. uniqDeps = {};
  6029. if (deps) {
  6030. uniqDepGraph[_key2] = [];
  6031. var _iteratorNormalCompletion = true;
  6032. var _didIteratorError = false;
  6033. var _iteratorError = undefined;
  6034. try {
  6035. for (var _iterator = deps[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  6036. var dep = _step.value;
  6037. if (uniqDeps.hasOwnProperty(dep) || _key2 === dep) continue;
  6038. var inverse = inverseDepGraph[dep] || (inverseDepGraph[dep] = []);
  6039. if (!inverse.includes(_key2)) inverse.push(_key2);
  6040. uniqDeps[dep] = true;
  6041. uniqDepGraph[_key2].push(dep);
  6042. if (!remainingSeen.hasOwnProperty(dep)) {
  6043. remainingSeen[dep] = true;
  6044. remaining.push(dep);
  6045. }
  6046. }
  6047. } catch (err) {
  6048. _didIteratorError = true;
  6049. _iteratorError = err;
  6050. } finally {
  6051. try {
  6052. if (!_iteratorNormalCompletion && _iterator.return) {
  6053. _iterator.return();
  6054. }
  6055. } finally {
  6056. if (_didIteratorError) {
  6057. throw _iteratorError;
  6058. }
  6059. }
  6060. }
  6061. }
  6062. }
  6063. // for each iteration find the keys with the minimum number of dependencies
  6064. // and add them to the result group list
  6065. var groups = [];
  6066. while (remaining.length) {
  6067. var minDepCount = Infinity,
  6068. minKeys = [],
  6069. minKeyIndexes = [],
  6070. affectedKeys = [];
  6071. for (var i = 0; i < remaining.length; i++) {
  6072. var key = remaining[i];
  6073. var _deps = uniqDepGraph[key] || [];
  6074. if (_deps.length > minDepCount) continue;
  6075. // if (deps.length === minDepCount && !minKeys.some(ea => deps.includes(ea))) {
  6076. if (_deps.length === minDepCount && !_deps.some(function (ea) {
  6077. return minKeys.includes(ea);
  6078. })) {
  6079. var _affectedKeys;
  6080. minKeys.push(key);
  6081. minKeyIndexes.push(i);
  6082. (_affectedKeys = affectedKeys).push.apply(_affectedKeys, toConsumableArray(inverseDepGraph[key] || []));
  6083. continue;
  6084. }
  6085. minDepCount = _deps.length;
  6086. minKeys = [key];
  6087. minKeyIndexes = [i];
  6088. affectedKeys = (inverseDepGraph[key] || []).slice();
  6089. }
  6090. for (var i = minKeyIndexes.length; i--;) {
  6091. var key = remaining[minKeyIndexes[i]];
  6092. inverseDepGraph[key] = [];
  6093. remaining.splice(minKeyIndexes[i], 1);
  6094. }
  6095. var _iteratorNormalCompletion2 = true;
  6096. var _didIteratorError2 = false;
  6097. var _iteratorError2 = undefined;
  6098. try {
  6099. for (var _iterator2 = affectedKeys[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  6100. var key = _step2.value;
  6101. uniqDepGraph[key] = uniqDepGraph[key].filter(function (ea) {
  6102. return !minKeys.includes(ea);
  6103. });
  6104. }
  6105. } catch (err) {
  6106. _didIteratorError2 = true;
  6107. _iteratorError2 = err;
  6108. } finally {
  6109. try {
  6110. if (!_iteratorNormalCompletion2 && _iterator2.return) {
  6111. _iterator2.return();
  6112. }
  6113. } finally {
  6114. if (_didIteratorError2) {
  6115. throw _iteratorError2;
  6116. }
  6117. }
  6118. }
  6119. groups.push(minKeys);
  6120. }
  6121. return groups;
  6122. }
  6123. function reduce$1(doFunc, graph, rootNode, carryOver, ignore, context) {
  6124. // Starts with `rootNode` and visits all (in)directly related nodes, calling
  6125. // `doFunc` at each node. The result of `doFunc` is passed as first
  6126. // argument to the next iterator call. For the first call the value
  6127. // `carryOver` is used.
  6128. // Example:
  6129. // var depGraph = {a: ["b", "c"],b: ["c"]}
  6130. // graphReduce((_, ea, i) => console.log("%s %s", ea, i), depGraph, "a")
  6131. var visitedNodes = ignore || [],
  6132. index = 0;
  6133. iterator(rootNode);
  6134. return carryOver;
  6135. function iterator(currentNode) {
  6136. if (visitedNodes.indexOf(currentNode) > -1) return;
  6137. carryOver = doFunc.call(context, carryOver, currentNode, index++);
  6138. visitedNodes = visitedNodes.concat([currentNode]);
  6139. var next = withoutAll(graph[currentNode] || [], visitedNodes);
  6140. next.forEach(function (ea) {
  6141. return iterator(ea);
  6142. });
  6143. }
  6144. }
  6145. function random$1() {
  6146. var nKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10;
  6147. var g = {},
  6148. keys$$1 = range(1, nKeys).map(String);
  6149. for (var i = 0; i < keys$$1.length; i++) {
  6150. var r = Math.floor(Math.random() * nKeys);
  6151. g[keys$$1[i]] = shuffle(keys$$1).slice(0, r);
  6152. }
  6153. return g;
  6154. }
  6155. var graph = Object.freeze({
  6156. clone: clone$2,
  6157. without: without$1,
  6158. hull: hull,
  6159. subgraphReachableBy: subgraphReachableBy,
  6160. invert: invert,
  6161. sortByReference: sortByReference,
  6162. reduce: reduce$1,
  6163. random: random$1
  6164. });
  6165. /*global System, global*/
  6166. // show-in-doc
  6167. // Intervals are arrays whose first two elements are numbers and the
  6168. // first element should be less or equal the second element, see
  6169. // [`interval.isInterval`](). This abstraction is useful when working with text
  6170. // ranges in rich text, for example.
  6171. var GLOBAL$2 = typeof System !== "undefined" ? System.global : typeof window !== 'undefined' ? window : global;
  6172. function isInterval(object) {
  6173. // Example:
  6174. // interval.isInterval([1,12]) // => true
  6175. // interval.isInterval([1,12, {property: 23}]) // => true
  6176. // interval.isInterval([1]) // => false
  6177. // interval.isInterval([12, 1]) // => false
  6178. return Array.isArray(object) && object.length >= 2 && object[0] <= object[1];
  6179. }
  6180. function sort$2(intervals) {
  6181. // Sorts intervals according to rules defined in [`interval.compare`]().
  6182. return intervals.sort(compare);
  6183. }
  6184. function compare(a, b) {
  6185. // How [`interval.sort`]() compares.
  6186. // We assume that `a[0] <= a[1] and b[0] <= b[1]` according to `isInterval`
  6187. // ```
  6188. // -3: a < b and non-overlapping, e.g [1,2] and [3,4]
  6189. // -2: a < b and intervals border at each other, e.g [1,3] and [3,4]
  6190. // -1: a < b and overlapping, e.g, [1,3] and [2,4] or [1,3] and [1,4]
  6191. // 0: a = b, e.g. [1,2] and [1,2]
  6192. // 1: a > b and overlapping, e.g. [2,4] and [1,3]
  6193. // 2: a > b and share border, e.g [1,4] and [0,1]
  6194. // 3: a > b and non-overlapping, e.g [2,4] and [0,1]
  6195. // ```
  6196. if (a[0] < b[0]) {
  6197. // -3 || -2 || -1
  6198. if (a[1] < b[0]) return -3;
  6199. if (a[1] === b[0]) return -2;
  6200. return -1;
  6201. }
  6202. if (a[0] === b[0]) {
  6203. // -1 || 0 || 1
  6204. if (a[1] === b[1]) return 0;
  6205. return a[1] < b[1] ? -1 : 1;
  6206. }
  6207. // we know a[0] > b[0], 1 || 2 || 3
  6208. return -1 * compare(b, a);
  6209. }
  6210. function coalesce(interval1, interval2, optMergeCallback) {
  6211. // Turns two interval into one iff compare(interval1, interval2) ∈ [-2,
  6212. // -1,0,1, 2] (see [`inerval.compare`]()).
  6213. // Otherwise returns null. Optionally uses merge function.
  6214. // Examples:
  6215. // interval.coalesce([1,4], [5,7]) // => null
  6216. // interval.coalesce([1,2], [1,2]) // => [1,2]
  6217. // interval.coalesce([1,4], [3,6]) // => [1,6]
  6218. // interval.coalesce([3,6], [4,5]) // => [3,6]
  6219. var cmpResult = this.compare(interval1, interval2);
  6220. switch (cmpResult) {
  6221. case -3:
  6222. case 3:
  6223. return null;
  6224. case 0:
  6225. optMergeCallback && optMergeCallback(interval1, interval2, interval1);
  6226. return interval1;
  6227. case 2:
  6228. case 1:
  6229. var temp = interval1;interval1 = interval2;interval2 = temp; // swap
  6230. case -2:
  6231. case -1:
  6232. var coalesced = [interval1[0], Math.max(interval1[1], interval2[1])];
  6233. optMergeCallback && optMergeCallback(interval1, interval2, coalesced);
  6234. return coalesced;
  6235. default:
  6236. throw new Error("Interval compare failed");
  6237. }
  6238. }
  6239. function coalesceOverlapping(intervals, mergeFunc) {
  6240. // Like `coalesce` but accepts an array of intervals.
  6241. // Example:
  6242. // interval.coalesceOverlapping([[9,10], [1,8], [3, 7], [15, 20], [14, 21]])
  6243. // // => [[1,8],[9,10],[14,21]]
  6244. var condensed = [],
  6245. len = intervals.length;
  6246. while (len > 0) {
  6247. var ival = intervals.shift();len--;
  6248. for (var i = 0; i < len; i++) {
  6249. var otherInterval = intervals[i],
  6250. coalesced = coalesce(ival, otherInterval, mergeFunc);
  6251. if (coalesced) {
  6252. ival = coalesced;
  6253. intervals.splice(i, 1);
  6254. len--;i--;
  6255. }
  6256. }
  6257. condensed.push(ival);
  6258. }
  6259. return this.sort(condensed);
  6260. }
  6261. function mergeOverlapping(intervalsA, intervalsB, mergeFunc) {
  6262. var result = [];
  6263. while (intervalsA.length > 0) {
  6264. var intervalA = intervalsA.shift();
  6265. var toMerge = intervalsB.map(function (intervalB) {
  6266. var cmp = compare(intervalA, intervalB);
  6267. return cmp === -1 || cmp === 0 || cmp === 1;
  6268. });
  6269. result.push(mergeFunc(intervalA, toMerge[0]));
  6270. result.push(intervalA);
  6271. }
  6272. return result;
  6273. }
  6274. function intervalsInRangeDo(start, end, intervals, iterator, mergeFunc, context) {
  6275. // Merges and iterates through sorted intervals. Will "fill up"
  6276. // intervals. This is currently used for computing text chunks in
  6277. // lively.morphic.TextCore.
  6278. // Example:
  6279. // interval.intervalsInRangeDo(
  6280. // 2, 10, [[0, 1], [5,8], [2,4]],
  6281. // function(i, isNew) { i.push(isNew); return i; })
  6282. // // => [[2,4,false],[4,5,true],[5,8,false],[8,10,true]]
  6283. context = context || GLOBAL$2;
  6284. // need to be sorted for the algorithm below
  6285. intervals = this.sort(intervals);
  6286. var free = [],
  6287. nextInterval,
  6288. collected = [];
  6289. // merged intervals are already sorted, simply "negate" the interval array;
  6290. while (nextInterval = intervals.shift()) {
  6291. if (nextInterval[1] < start) continue;
  6292. if (nextInterval[0] < start) {
  6293. nextInterval = Array.prototype.slice.call(nextInterval);
  6294. nextInterval[0] = start;
  6295. }
  6296. var nextStart = end < nextInterval[0] ? end : nextInterval[0];
  6297. if (start < nextStart) {
  6298. collected.push(iterator.call(context, [start, nextStart], true));
  6299. }
  6300. if (end < nextInterval[1]) {
  6301. nextInterval = Array.prototype.slice.call(nextInterval);
  6302. nextInterval[1] = end;
  6303. }
  6304. // special case, the newly constructed interval has length 0,
  6305. // happens when intervals contains doubles at the start
  6306. if (nextInterval[0] === nextInterval[1]) {
  6307. var prevInterval;
  6308. if (mergeFunc && (prevInterval = collected.slice(-1)[0])) {
  6309. // arguments: a, b, merged, like in the callback of #merge
  6310. mergeFunc.call(context, prevInterval, nextInterval, prevInterval);
  6311. }
  6312. } else {
  6313. collected.push(iterator.call(context, nextInterval, false));
  6314. }
  6315. start = nextInterval[1];
  6316. if (start >= end) break;
  6317. }
  6318. if (start < end) collected.push(iterator.call(context, [start, end], true));
  6319. return collected;
  6320. }
  6321. function intervalsInbetween(start, end, intervals) {
  6322. // Computes "free" intervals between the intervals given in range start - end
  6323. // currently used for computing text chunks in lively.morphic.TextCore
  6324. // Example:
  6325. // interval.intervalsInbetween(0, 10,[[1,4], [5,8]])
  6326. // // => [[0,1],[4,5],[8,10]]
  6327. return intervalsInRangeDo(start, end, coalesceOverlapping(Array.prototype.slice.call(intervals)), function (interval, isNew) {
  6328. return isNew ? interval : null;
  6329. }).filter(Boolean);
  6330. }
  6331. function mapToMatchingIndexes(intervals, intervalsToFind) {
  6332. // Returns an array of indexes of the items in intervals that match
  6333. // items in `intervalsToFind`.
  6334. // Note: We expect intervals and intervals to be sorted according to [`interval.compare`]()!
  6335. // This is the optimized version of:
  6336. // ```
  6337. // return intervalsToFind.collect(function findOne(toFind) {
  6338. // var startIdx, endIdx;
  6339. // var start = intervals.detect(function(ea, i) {
  6340. // startIdx = i; return ea[0] === toFind[0]; });
  6341. // if (start === undefined) return [];
  6342. // var end = intervals.detect(function(ea, i) {
  6343. // endIdx = i; return ea[1] === toFind[1]; });
  6344. // if (end === undefined) return [];
  6345. // return Array.range(startIdx, endIdx);
  6346. // });
  6347. // ```
  6348. var startIntervalIndex = 0,
  6349. endIntervalIndex,
  6350. currentInterval;
  6351. return intervalsToFind.map(function (toFind) {
  6352. while (currentInterval = intervals[startIntervalIndex]) {
  6353. if (currentInterval[0] < toFind[0]) {
  6354. startIntervalIndex++;continue;
  6355. }
  6356. break;
  6357. }
  6358. if (currentInterval && currentInterval[0] === toFind[0]) {
  6359. endIntervalIndex = startIntervalIndex;
  6360. while (currentInterval = intervals[endIntervalIndex]) {
  6361. if (currentInterval[1] < toFind[1]) {
  6362. endIntervalIndex++;continue;
  6363. }
  6364. break;
  6365. }
  6366. if (currentInterval && currentInterval[1] === toFind[1]) {
  6367. return range(startIntervalIndex, endIntervalIndex);
  6368. }
  6369. }
  6370. return [];
  6371. });
  6372. }
  6373. var interval = Object.freeze({
  6374. isInterval: isInterval,
  6375. sort: sort$2,
  6376. compare: compare,
  6377. coalesce: coalesce,
  6378. coalesceOverlapping: coalesceOverlapping,
  6379. mergeOverlapping: mergeOverlapping,
  6380. intervalsInRangeDo: intervalsInRangeDo,
  6381. intervalsInbetween: intervalsInbetween,
  6382. mapToMatchingIndexes: mapToMatchingIndexes
  6383. });
  6384. // show-in-doc
  6385. // Accessor to sub-ranges of arrays. This is used, for example, for rendering
  6386. // large lists or tables in which only a part of the items should be used for
  6387. // processing or rendering. An array projection provides convenient access and
  6388. // can apply operations to sub-ranges.
  6389. function create(array, length, optStartIndex) {
  6390. // Example:
  6391. // arrayProjection.create([1,2,3,4,5,6,7,8,9], 4, 1)
  6392. // // => { array: [/*...*/], from: 1, to: 5 }
  6393. var startIndex = optStartIndex || 0;
  6394. if (startIndex + length > array.length) startIndex -= startIndex + length - array.length;
  6395. return { array: array, from: startIndex, to: startIndex + length };
  6396. }
  6397. function toArray$4(projection) {
  6398. // show-in-doc
  6399. return projection.array.slice(projection.from, projection.to);
  6400. }
  6401. function originalToProjectedIndex(projection, index) {
  6402. // Maps index from original Array to projection.
  6403. // Example:
  6404. // var proj = arrayProjection.create([1,2,3,4,5,6,7,8,9], 4, 3);
  6405. // arrayProjection.originalToProjectedIndex(proj, 1) // => null
  6406. // arrayProjection.originalToProjectedIndex(proj, 3) // => 0
  6407. // arrayProjection.originalToProjectedIndex(proj, 5) // => 2
  6408. return index < projection.from || index >= projection.to ? null : index - projection.from;
  6409. }
  6410. function projectedToOriginalIndex(projection, index) {
  6411. // Inverse to `originalToProjectedIndex`.
  6412. // Example:
  6413. // var proj = arrayProjection.create([1,2,3,4,5,6,7,8,9], 4, 3);
  6414. // arrayProjection.projectedToOriginalIndex(proj, 1) // => 4
  6415. if (index < 0 || index > projection.to - projection.from) return null;
  6416. return projection.from + index;
  6417. }
  6418. function transformToIncludeIndex(projection, index) {
  6419. // Computes how the projection needs to shift minimally (think "scroll"
  6420. // down or up) so that index becomes "visible" in projection.
  6421. // Example:
  6422. // var proj = arrayProjection.create([1,2,3,4,5,6,7,8,9], 4, 3);
  6423. // arrayProjection.transformToIncludeIndex(proj, 1)
  6424. // // => { array: [/*...*/], from: 1, to: 5 }
  6425. if (!(index in projection.array)) return null;
  6426. var delta = 0;
  6427. if (index < projection.from) delta = -projection.from + index;
  6428. if (index >= projection.to) delta = index - projection.to + 1;
  6429. if (delta === 0) return projection;
  6430. return create(projection.array, projection.to - projection.from, projection.from + delta);
  6431. }
  6432. var arrayProjection = Object.freeze({
  6433. create: create,
  6434. toArray: toArray$4,
  6435. originalToProjectedIndex: originalToProjectedIndex,
  6436. projectedToOriginalIndex: projectedToOriginalIndex,
  6437. transformToIncludeIndex: transformToIncludeIndex
  6438. });
  6439. // show-in-doc
  6440. // A grid is a two-dimaensional array, representing a table-like data
  6441. function get$2(grid, nRow, nCol) {
  6442. var row = grid[nRow];
  6443. return row ? row[nCol] : undefined;
  6444. }
  6445. function set$2(grid, nRow, nCol, obj) {
  6446. var row = grid[nRow];
  6447. if (row) row[nCol] = obj;
  6448. return obj;
  6449. }
  6450. function getRow(grid, nRow) {
  6451. return grid[nRow];
  6452. }
  6453. function setRow(grid, nRow, newRow) {
  6454. return grid[nRow] = newRow;
  6455. }
  6456. function getCol(grid, nCol) {
  6457. return grid.reduce(function (col, row) {
  6458. col.push(row[nCol]);return col;
  6459. }, []);
  6460. }
  6461. function setCol(grid, nCol, newCol) {
  6462. return grid.map(function (row, i) {
  6463. return row[nCol] ? row[nCol] = newCol[i] : undefined;
  6464. });
  6465. }
  6466. function create$1(rows, columns, initialObj) {
  6467. // Example:
  6468. // grid.create(3, 2, "empty")
  6469. // // => [["empty","empty"],
  6470. // // ["empty","empty"],
  6471. // // ["empty","empty"]]
  6472. var result = new Array(rows);
  6473. while (rows > 0) {
  6474. result[--rows] = withN(columns, initialObj);
  6475. }return result;
  6476. }
  6477. function mapCreate(rows, cols, func, context) {
  6478. // like `grid.create` but takes generator function for cells
  6479. var result = new Array(rows);
  6480. for (var i = 0; i < rows; i++) {
  6481. result[i] = new Array(cols);
  6482. for (var j = 0; j < cols; j++) {
  6483. result[i][j] = func.call(context || this, i, j);
  6484. }
  6485. }
  6486. return result;
  6487. }
  6488. function forEach$2(grid, func, context) {
  6489. // iterate, `func` is called as `func(cellValue, i, j)`
  6490. grid.forEach(function (row, i) {
  6491. row.forEach(function (val, j) {
  6492. func.call(context || this, val, i, j);
  6493. });
  6494. });
  6495. }
  6496. function map$2(grid, func, context) {
  6497. // map, `func` is called as `func(cellValue, i, j)`
  6498. var result = new Array(grid.length);
  6499. grid.forEach(function (row, i) {
  6500. result[i] = new Array(row.length);
  6501. row.forEach(function (val, j) {
  6502. result[i][j] = func.call(context || this, val, i, j);
  6503. });
  6504. });
  6505. return result;
  6506. }
  6507. function toObjects(grid) {
  6508. // The first row of the grid defines the propNames
  6509. // for each following row create a new object with those porperties
  6510. // mapped to the cells of the row as values
  6511. // Example:
  6512. // grid.toObjects([['a', 'b'],[1,2],[3,4]])
  6513. // // => [{a:1,b:2},{a:3,b:4}]
  6514. var props = grid[0],
  6515. objects = new Array(grid.length - 1);
  6516. for (var i = 1; i < grid.length; i++) {
  6517. var obj = objects[i - 1] = {};
  6518. for (var j = 0; j < props.length; j++) {
  6519. obj[props[j]] = grid[i][j];
  6520. }
  6521. }
  6522. return objects;
  6523. }
  6524. function tableFromObjects(objects, valueForUndefined) {
  6525. // Reverse operation to `grid.toObjects`. Useful for example to convert objectified
  6526. // SQL result sets into tables that can be printed via Strings.printTable.
  6527. // Objects are key/values like [{x:1,y:2},{x:3},{z:4}]. Keys are interpreted as
  6528. // column names and objects as rows.
  6529. // Example:
  6530. // grid.tableFromObjects([{x:1,y:2},{x:3},{z:4}])
  6531. // // => [["x","y","z"],
  6532. // // [1,2,null],
  6533. // // [3,null,null],
  6534. // // [null,null,4]]
  6535. if (!Array.isArray(objects)) objects = [objects];
  6536. var table = [[]],
  6537. columns = table[0],
  6538. rows = objects.reduce(function (rows, ea) {
  6539. return rows.concat([Object.keys(ea).reduce(function (row, col) {
  6540. var colIdx = columns.indexOf(col);
  6541. if (colIdx === -1) {
  6542. colIdx = columns.length;columns.push(col);
  6543. }
  6544. row[colIdx] = ea[col];
  6545. return row;
  6546. }, [])]);
  6547. }, []);
  6548. valueForUndefined = arguments.length === 1 ? null : valueForUndefined;
  6549. rows.forEach(function (row) {
  6550. // fill cells with no value with null
  6551. for (var i = 0; i < columns.length; i++) {
  6552. if (!row[i]) row[i] = valueForUndefined;
  6553. }
  6554. });
  6555. return table.concat(rows);
  6556. }
  6557. var grid = Object.freeze({
  6558. get: get$2,
  6559. set: set$2,
  6560. getRow: getRow,
  6561. setRow: setRow,
  6562. getCol: getCol,
  6563. setCol: setCol,
  6564. create: create$1,
  6565. mapCreate: mapCreate,
  6566. forEach: forEach$2,
  6567. map: map$2,
  6568. toObjects: toObjects,
  6569. tableFromObjects: tableFromObjects
  6570. });
  6571. /*
  6572. * Methods for traversing and transforming tree structures.
  6573. */
  6574. function prewalk(treeNode, iterator, childGetter) {
  6575. var counter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { i: 0 };
  6576. var depth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  6577. var i = counter.i++;
  6578. iterator(treeNode, i, depth);
  6579. (childGetter(treeNode, i, depth) || []).forEach(function (ea) {
  6580. return prewalk(ea, iterator, childGetter, counter, depth + 1);
  6581. });
  6582. }
  6583. function postwalk(treeNode, iterator, childGetter) {
  6584. var counter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { i: 0 };
  6585. var depth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  6586. var i = counter.i++;
  6587. (childGetter(treeNode, i, depth) || []).forEach(function (ea) {
  6588. return postwalk(ea, iterator, childGetter, counter, depth);
  6589. });
  6590. iterator(treeNode, i, depth);
  6591. }
  6592. function find(treeNode, testFunc, childGetter) {
  6593. // Traverses a `treeNode` recursively and returns the first node for which
  6594. // `testFunc` returns true. `childGetter` is a function to retrieve the
  6595. // children from a node.
  6596. if (testFunc(treeNode)) return treeNode;
  6597. var children = childGetter(treeNode);
  6598. if (!children || !children.length) return undefined;
  6599. for (var i = 0; i < children.length; i++) {
  6600. var found = find(children[i], testFunc, childGetter);
  6601. if (found) return found;
  6602. }
  6603. return undefined;
  6604. }
  6605. var detect$1 = find;
  6606. function filter$1(treeNode, testFunc, childGetter) {
  6607. // Traverses a `treeNode` recursively and returns all nodes for which
  6608. // `testFunc` returns true. `childGetter` is a function to retrieve the
  6609. // children from a node.
  6610. var result = [];
  6611. if (testFunc(treeNode)) result.push(treeNode);
  6612. return result.concat(flatten((childGetter(treeNode) || []).map(function (n) {
  6613. return filter$1(n, testFunc, childGetter);
  6614. })));
  6615. }
  6616. function map$3(treeNode, mapFunc, childGetter) {
  6617. var depth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  6618. // Traverses a `treeNode` recursively and call `mapFunc` on each node. The
  6619. // return values of all mapFunc calls is the result. `childGetter` is a
  6620. // function to retrieve the children from a node.
  6621. return [mapFunc(treeNode, depth)].concat(flatten((childGetter(treeNode) || []).map(function (n) {
  6622. return map$3(n, mapFunc, childGetter, depth + 1);
  6623. })));
  6624. }
  6625. function mapTree(treeNode, mapFunc, childGetter) {
  6626. var depth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  6627. // Traverses the tree and creates a structurally identical tree but with
  6628. // mapped nodes
  6629. var mappedNodes = (childGetter(treeNode) || []).map(function (n) {
  6630. return mapTree(n, mapFunc, childGetter, depth + 1);
  6631. });
  6632. return mapFunc(treeNode, mappedNodes, depth);
  6633. }
  6634. var tree = Object.freeze({
  6635. prewalk: prewalk,
  6636. postwalk: postwalk,
  6637. find: find,
  6638. detect: detect$1,
  6639. filter: filter$1,
  6640. map: map$3,
  6641. mapTree: mapTree
  6642. });
  6643. /*global process, require*/
  6644. /*
  6645. * A simple node.js-like cross-platform event emitter implementation that can
  6646. * be used as a mixin. Emitters support the methods: `on(eventName, handlerFunc)`,
  6647. * `once(eventName, handlerFunc)`, `emit(eventName, eventData)`,
  6648. * `removeListener(eventName, handlerFunc)`, `removeAllListeners(eventName)`
  6649. * Example:
  6650. * var emitter = events.makeEmitter({});
  6651. * var log = [];
  6652. * emitter.on("test", function() { log.push("listener1"); });
  6653. * emitter.once("test", function() { log.push("listener2"); });
  6654. * emitter.emit("test");
  6655. * emitter.emit("test");
  6656. * log // => ["listener1","listener2","listener1"]
  6657. * emitter.removeAllListeners("test");
  6658. * emitter.emit("test");
  6659. * log // => is still ["listener1","listener2","listener1"]
  6660. */
  6661. var isNode$1 = typeof process !== 'undefined' && process.versions && process.versions.node;
  6662. var makeEmitter = isNode$1 ? function (obj, options) {
  6663. if (obj.on && obj.removeListener) return obj;
  6664. var events = typeof System !== "undefined" ? System._nodeRequire("events") : require("events");
  6665. Object.assign(obj, events.EventEmitter.prototype);
  6666. events.EventEmitter.call(obj);
  6667. if (options && options.maxListenerLimit) obj.setMaxListeners(options.maxListenerLimit);
  6668. return obj;
  6669. } : function (obj) {
  6670. if (obj.on && obj.removeListener) return obj;
  6671. obj.listeners = {};
  6672. obj.on = function (type, handler) {
  6673. if (!handler) return;
  6674. if (!obj.listeners[type]) obj.listeners[type] = [];
  6675. obj.listeners[type].push(handler);
  6676. };
  6677. obj.once = function (type, handler) {
  6678. if (!handler) return;
  6679. function onceHandler /*ignore-in-docs args*/() {
  6680. obj.removeListener(type, onceHandler);
  6681. handler.apply(this, arguments);
  6682. }
  6683. obj.on(type, onceHandler);
  6684. };
  6685. obj.removeListener = function (type, handler) {
  6686. if (!obj.listeners[type]) return;
  6687. obj.listeners[type] = obj.listeners[type].filter(function (h) {
  6688. return h !== handler;
  6689. });
  6690. };
  6691. obj.removeAllListeners = function (type) {
  6692. if (!obj.listeners[type]) return;
  6693. obj.listeners[type] = [];
  6694. };
  6695. obj.emit = function () /*type and args*/{
  6696. var args = Array.prototype.slice.call(arguments),
  6697. type = args.shift(),
  6698. handlers = obj.listeners[type];
  6699. if (!handlers || !handlers.length) return;
  6700. handlers.forEach(function (handler) {
  6701. try {
  6702. handler.apply(null, args);
  6703. } catch (e) {
  6704. console.error("Error in event handler: %s", e.stack || String(e));
  6705. }
  6706. });
  6707. };
  6708. return obj;
  6709. };
  6710. var events = Object.freeze({
  6711. makeEmitter: makeEmitter
  6712. });
  6713. /*global clearTimeout, setTimeout, clearInterval, setInterval*/
  6714. /*
  6715. * A pluggable interface to provide asynchronous, actor-like message
  6716. * communication between JavaScript systems. Provides a unified message protocol
  6717. * and send / receive methods.
  6718. */
  6719. var OFFLINE = 'offline';
  6720. var ONLINE = 'online';
  6721. /*
  6722. TODO: move to promises! include broadcast API
  6723. renames:
  6724. listen() => open()
  6725. id() => id
  6726. */
  6727. /*
  6728. A messenger is an object that provides a common, message-based interface. Messengers expect you to provide an implementation of a small number of methods: `send`, `listen`, `close`, and `isOnline`. A messenger will then provide a unified interface for sending and receiving messages. Common boilerplate functionality such as queuing messages, error handling, dealing with instable connections, heartbeats, etc. is handled by the messenger object automatically (and can be parameterized).
  6729. This allows to use a single interface across a range of heterogeneous objects without having to implement every detail of the abstraction repeatedly. This is especially valuable when dealing with asynchronous or remote communication (web workers, XHR requests, WebSockets, node.js processes, ...).
  6730. To see a minimal example of how to use messengers for the local communication between JavaScript objects [see this example](#messenger-example).
  6731. A more sophisticated example of messengers is [the worker implementation](worker.js) which provides an actor-like worker interface that uses web workers in web browsers and child_process.fork in node.js.
  6732. ```js
  6733. var msger = lively.lang.messenger.create({
  6734. send: function(msg, onSendDone) { console.log(msg); onSendDone(); },
  6735. listen: function(thenDo) { thenDo(); },
  6736. close: function(thenDo) { thenDo(); },
  6737. isOnline: function() { return true }
  6738. });
  6739. ```
  6740. #### Messenger interface
  6741. The interface methods are build to enable an user to send and receive
  6742. messages. Each messenger provides the following methods:
  6743. ##### msger.id()
  6744. Each msger has an id that can either be defined by the user when the
  6745. msger is created or is automatically assigned. The id should be unique for each
  6746. messenger in a messenger network. It is used as the `target` attribute to
  6747. address messages and internally in the messaging implementation for routing.
  6748. See the [message protocol](#messenger-message-protocol) description for more info.
  6749. ##### msger.isOnline()
  6750. Can the msger send and receive messages right now?
  6751. ##### msger.heartbeatEnabled()
  6752. Does the msger send automated heartbeat messages?
  6753. ##### msger.listen(optionalCallback)
  6754. Brings the messenger "online": Starts listening for messages and brings it
  6755. into a state to send messages. `optionalCallback` is a function that is called
  6756. when listening begins. It should accept one argument `error` that is null if no
  6757. error occured when listening was started, an Error object otherwise.
  6758. ##### msger.send(msg, onReceiveFunc)
  6759. Sends a message. The message should be structured according to the [message
  6760. protocol](#messenger-message-protocol). `onReceiveFunc` is triggered when the `msg` is being
  6761. answered. `onReceiveFunc` should take two arguments: `error` and `answer`.
  6762. `answer` is itself a message object.
  6763. ##### msger.sendTo(target, action, data, onReceiveFunc)
  6764. A simpler `send`, the `msg` object is automatically assembled. `target`
  6765. should be an id of the receiver and `action` a string naming the service that
  6766. should be triggered on the receiver.
  6767. ##### msger.answer(msg, data, expectMore, whenSend)
  6768. Assembles an answer message for `msg` that includes `data`. `expectMore`
  6769. should be truthy when multiple answers should be send (a streaming response,
  6770. see the [messaging protocol](#messenger-message-protocol)).
  6771. ##### msger.close(thenDo)
  6772. Stops listening.
  6773. ##### msger.whenOnline(thenDo)
  6774. Registers a callback that is triggered as soon as a listen attempt succeeds
  6775. (or when the messenger is listening already then it succeeds immediately).
  6776. ##### msger.outgoingMessages()
  6777. Returns the messages that are currently inflight or not yet send.
  6778. ##### msger.addServices(serviceSpec)
  6779. Add services to the messenger. `serviceSpec` should be JS object whose keys
  6780. correspond to message actions:
  6781. ```js
  6782. msg.addServices({
  6783. helloWorld: function(msg, messenger) {
  6784. messenger.answer(msg, "received a message!");
  6785. }
  6786. });
  6787. ```
  6788. See the examples below for more information.
  6789. ##### *[event]* msger.on("message")
  6790. To allow users to receive messages that were not initiated by a send,
  6791. messengers are [event emitters](events.js) that emit `"message"` events
  6792. whenever they receive a new message.
  6793. The messenger object is used to create new messenger interfaces and ties
  6794. them to a specific implementation. Please see [worker.js]() for examples of
  6795. how web workers and node.js processes are wrapped to provide a cross-platform
  6796. interface to a worker abstraction.
  6797. #### <a name="messenger-message-protocol"></a>Message protocol
  6798. A message is a JSON object with the following fields:
  6799. ```js
  6800. var messageSchema = {
  6801. // REQUIRED selector for service lookup. By convention action gets
  6802. // postfixed with "Result" for response messages
  6803. action: STRING,
  6804. // REQUIRED target of the message, the id of the receiver
  6805. target: UUID,
  6806. // OPTIONAL arguments
  6807. data: OBJECT,
  6808. // OPTIONAL identifier of the message, will be provided if not set by user
  6809. messageId: UUID,
  6810. // OPTIONAL sender of the message, will be provided if not set by user
  6811. sender: UUID,
  6812. // OPTIONAL identifier of a message that this message answers, will be provided
  6813. inResponseTo: UUID,
  6814. // OPTIONAL if message is an answer. Can be interpreted by the receiver as
  6815. // a streaming response. Lively participants (tracker and clients) will
  6816. // trigger data bindings and fire callbacks for a message for every streaming
  6817. // response
  6818. expectMoreResponses: BOOL,
  6819. // EXPERIMENTAL UUIDs of trackers/sessions handlers that forwarded this
  6820. // message
  6821. route: ARRAY
  6822. }
  6823. ```
  6824. The `sendTo` and `answer` methods of messengers will automatically create these
  6825. messages. If the user invokes the `send` method then a JS object according to
  6826. the schema above should be passed as the first argument.
  6827. #### <a name="messenger-example"></a>Messenger examples
  6828. The following code implements what is needed to use a messenger to communicate
  6829. between any number of local JavaScript objects. Instead of dispatching methods using
  6830. a local list of messengers you will most likely use an existing networking /
  6831. messaging mechanism.
  6832. See the [worker](#) and [its implementation](worker.js) for a real use case in
  6833. which forking processes in the browser using Web Workers and in node.js using
  6834. child_process.fork is unified.
  6835. ```js
  6836. // spec that defines message sending in terms of receivers in the messengers list
  6837. var messengers = [];
  6838. var messengerSpec = {
  6839. send: function(msg, onSendDone) {
  6840. var err = null, recv = arr.detect(messengers, function(ea) {
  6841. return ea.id() === msg.target; });
  6842. if (recv) recv.onMessage(msg);
  6843. else err = new Error("Could not find receiver " + msg.target);
  6844. onSendDone(err);
  6845. },
  6846. listen: function(thenDo) { arr.pushIfNotIncluded(messengers, this); },
  6847. close: function(thenDo) { arr.remove(messengers, this); },
  6848. isOnline: function() { return arr.include(messengers, this); }
  6849. };
  6850. // Create the messengers and add a simple "service"
  6851. var msger1 = messenger.create(messengerSpec);
  6852. var msger2 = messenger.create(messengerSpec);
  6853. msger2.addServices({
  6854. add: function(msg, msger) { msger.answer(msg, {result: msg.data.a + msg.data.b}); }
  6855. });
  6856. // turn'em on...
  6857. msger1.listen();
  6858. msger2.listen();
  6859. // ...and action!
  6860. msger1.sendTo(msger2.id(), 'add', {a: 3, b: 4},
  6861. function(err, answer) { alert(answer.data.result); });
  6862. ```
  6863. */
  6864. function create$2(spec) {
  6865. var expectedMethods = [{ name: "send", args: ['msg', 'callback'] }, { name: "listen", args: ['messenger', 'callback'] }, { name: "close", args: ['messenger', 'callback'] }, { name: "isOnline", args: [] }];
  6866. var ignoredAttributes = expectedMethods.map(function (ea) {
  6867. return ea.name;
  6868. }).concat(["id", "sendHeartbeat", "heartbeatInterval", "ignoreUnknownMessages", "allowConcurrentSends", "sendTimeout", "services"]);
  6869. expectedMethods.forEach(function (exp) {
  6870. if (spec[exp.name]) return;
  6871. var msg = "message implementation needs function " + exp.name + "(" + exp.args.join(',') + ")";
  6872. throw new Error(msg);
  6873. });
  6874. var heartbeatInterval = spec.sendHeartbeat && (spec.heartbeatInterval || 1000);
  6875. var ignoreUnknownMessages = spec.hasOwnProperty("ignoreUnknownMessages") ? spec.ignoreUnknownMessages : false;
  6876. var messenger = {
  6877. _outgoing: [],
  6878. _inflight: [],
  6879. _id: spec.id || newUUID(),
  6880. _ignoreUnknownMessages: ignoreUnknownMessages,
  6881. _services: {},
  6882. _messageCounter: 0,
  6883. _messageResponseCallbacks: {},
  6884. _whenOnlineCallbacks: [],
  6885. _statusWatcherProc: null,
  6886. _startHeartbeatProcessProc: null,
  6887. _listenInProgress: null,
  6888. _heartbeatInterval: heartbeatInterval,
  6889. _status: OFFLINE,
  6890. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  6891. _runWhenOnlineCallbacks: function _runWhenOnlineCallbacks() {
  6892. var cbs = messenger._whenOnlineCallbacks.slice();
  6893. messenger._whenOnlineCallbacks = [];
  6894. cbs.forEach(function (ea) {
  6895. try {
  6896. ea.call(null, null, messenger);
  6897. } catch (e) {
  6898. console.error("error in _runWhenOnlineCallbacks: %s", e);
  6899. }
  6900. });
  6901. },
  6902. _ensureStatusWatcher: function _ensureStatusWatcher() {
  6903. if (messenger._statusWatcherProc) return;
  6904. messenger._statusWatcherProc = setInterval(function () {
  6905. if (messenger.isOnline() && messenger._whenOnlineCallbacks.length) messenger._runWhenOnlineCallbacks();
  6906. var prevStatus = messenger._status;
  6907. messenger._status = messenger.isOnline() ? ONLINE : OFFLINE;
  6908. if (messenger._status !== ONLINE && messenger._statusWatcherProc) {
  6909. messenger.reconnect();
  6910. }
  6911. if (messenger._status !== prevStatus && messenger.onStatusChange) {
  6912. messenger.onStatusChange();
  6913. }
  6914. }, 20);
  6915. },
  6916. _addMissingData: function _addMissingData(msg) {
  6917. if (!msg.target) throw new Error("Message needs target!");
  6918. if (!msg.action) throw new Error("Message needs action!");
  6919. if (!msg.data) msg.data = null;
  6920. if (!msg.messageId) msg.messageId = newUUID();
  6921. msg.sender = messenger.id();
  6922. msg.messageIndex = messenger._messageCounter++;
  6923. return msg;
  6924. },
  6925. _queueSend: function _queueSend(msg, onReceiveFunc) {
  6926. if (onReceiveFunc && typeof onReceiveFunc !== 'function') throw new Error("Expecing a when send callback, got: " + onReceiveFunc);
  6927. messenger._outgoing.push([msg, onReceiveFunc]);
  6928. },
  6929. _deliverMessageQueue: function _deliverMessageQueue() {
  6930. if (!spec.allowConcurrentSends && messenger._inflight.length) return;
  6931. var queued = messenger._outgoing.shift();
  6932. if (!queued) return;
  6933. messenger._inflight.push(queued);
  6934. if (messenger.isOnline()) deliver(queued);else messenger.whenOnline(function () {
  6935. deliver(queued);
  6936. });
  6937. startTimeoutProc(queued);
  6938. if (spec.allowConcurrentSends && messenger._outgoing.length) messenger._deliverMessageQueue();
  6939. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  6940. function deliver(queued) {
  6941. // ignore-in-doc
  6942. if (messenger._inflight.indexOf(queued) === -1) return; // timed out
  6943. var msg = queued[0],
  6944. callback = queued[1];
  6945. if (callback) messenger._messageResponseCallbacks[msg.messageId] = callback;
  6946. spec.send.call(messenger, msg, function (err) {
  6947. remove(messenger._inflight, queued);
  6948. if (err) onSendError(err, queued);
  6949. messenger._deliverMessageQueue();
  6950. });
  6951. }
  6952. function startTimeoutProc(queued) {
  6953. if (typeof spec.sendTimeout !== 'number') return;
  6954. setTimeout(function () {
  6955. if (messenger._inflight.indexOf(queued) === -1) return; // delivered
  6956. remove(messenger._inflight, queued);
  6957. onSendError(new Error('Timeout sending message'), queued);
  6958. messenger._deliverMessageQueue();
  6959. }, spec.sendTimeout);
  6960. }
  6961. function onSendError(err, queued) {
  6962. var msg = queued[0],
  6963. callback = queued[1];
  6964. delete messenger._messageResponseCallbacks[msg.messageId];
  6965. console.error(err);
  6966. callback && callback(err);
  6967. }
  6968. },
  6969. _startHeartbeatProcess: function _startHeartbeatProcess() {
  6970. if (messenger._startHeartbeatProcessProc) return;
  6971. messenger._startHeartbeatProcessProc = setTimeout(function () {
  6972. spec.sendHeartbeat.call(messenger, function (err, result) {
  6973. messenger._startHeartbeatProcessProc = null;
  6974. messenger._startHeartbeatProcess();
  6975. });
  6976. }, messenger._heartbeatInterval);
  6977. },
  6978. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  6979. id: function id() {
  6980. return messenger._id;
  6981. },
  6982. isOnline: function isOnline() {
  6983. return spec.isOnline.call(messenger);
  6984. },
  6985. heartbeatEnabled: function heartbeatEnabled() {
  6986. return typeof messenger._heartbeatInterval === 'number';
  6987. },
  6988. listen: function listen(thenDo) {
  6989. if (messenger._listenInProgress) return;
  6990. messenger._listenInProgress = true;
  6991. messenger._ensureStatusWatcher();
  6992. return spec.listen.call(messenger, function (err) {
  6993. messenger._listenInProgress = null;
  6994. thenDo && thenDo(err);
  6995. if (messenger.heartbeatEnabled()) messenger._startHeartbeatProcess();
  6996. });
  6997. return messenger;
  6998. },
  6999. reconnect: function reconnect() {
  7000. if (messenger._status === ONLINE) return;
  7001. messenger.listen();
  7002. return messenger;
  7003. },
  7004. send: function send(msg, onReceiveFunc) {
  7005. messenger._addMissingData(msg);
  7006. messenger._queueSend(msg, onReceiveFunc);
  7007. messenger._deliverMessageQueue();
  7008. return msg;
  7009. },
  7010. sendTo: function sendTo(target, action, data, onReceiveFunc) {
  7011. var msg = { target: target, action: action, data: data };
  7012. return messenger.send(msg, onReceiveFunc);
  7013. },
  7014. onMessage: function onMessage(msg) {
  7015. messenger.emit("message", msg);
  7016. if (msg.inResponseTo) {
  7017. var cb = messenger._messageResponseCallbacks[msg.inResponseTo];
  7018. if (cb && !msg.expectMoreResponses) delete messenger._messageResponseCallbacks[msg.inResponseTo];
  7019. if (cb) cb(null, msg);
  7020. } else {
  7021. var action = messenger._services[msg.action];
  7022. if (action) {
  7023. try {
  7024. action.call(null, msg, messenger);
  7025. } catch (e) {
  7026. var errmMsg = String(e.stack || e);
  7027. console.error("Error invoking service: " + errmMsg);
  7028. messenger.answer(msg, { error: errmMsg });
  7029. }
  7030. } else if (!messenger._ignoreUnknownMessages) {
  7031. var err = new Error("messageNotUnderstood: " + msg.action);
  7032. messenger.answer(msg, { error: String(err) });
  7033. }
  7034. }
  7035. },
  7036. answer: function answer(msg, data, expectMore, whenSend) {
  7037. if (typeof expectMore === 'function') {
  7038. whenSend = expectMore;expectMore = false;
  7039. }
  7040. var answer = {
  7041. target: msg.sender,
  7042. action: msg.action + 'Result',
  7043. inResponseTo: msg.messageId,
  7044. data: data };
  7045. if (expectMore) answer.expectMoreResponses = true;
  7046. return messenger.send(answer, whenSend);
  7047. },
  7048. close: function close(thenDo) {
  7049. clearInterval(messenger._statusWatcherProc);
  7050. messenger._statusWatcherProc = null;
  7051. spec.close.call(messenger, function (err) {
  7052. messenger._status = OFFLINE;
  7053. thenDo && thenDo(err);
  7054. });
  7055. return messenger;
  7056. },
  7057. whenOnline: function whenOnline(thenDo) {
  7058. messenger._whenOnlineCallbacks.push(thenDo);
  7059. if (messenger.isOnline()) messenger._runWhenOnlineCallbacks();
  7060. return messenger;
  7061. },
  7062. outgoingMessages: function outgoingMessages() {
  7063. return pluck(messenger._inflight.concat(messenger._outgoing), 0);
  7064. },
  7065. addServices: function addServices(serviceSpec) {
  7066. Object.assign(messenger._services, serviceSpec);
  7067. return messenger;
  7068. }
  7069. };
  7070. if (spec.services) messenger.addServices(spec.services);
  7071. makeEmitter(messenger);
  7072. for (var name in spec) {
  7073. if (ignoredAttributes.indexOf(name) === -1 && spec.hasOwnProperty(name)) {
  7074. messenger[name] = spec[name];
  7075. }
  7076. }
  7077. return messenger;
  7078. }
  7079. var messenger = Object.freeze({
  7080. create: create$2
  7081. });
  7082. /*global, require, Worker, URL, webkitURL, Blob, BlobBuilder, process, require,self,global,remoteWorker,postMessage,XMLHttpRequest,__FUNCTIONDECLARATIONS__,initBrowserGlobals,loadDependenciesBrowser,initOnMessageHandler,initWorkerInterface,initWorkerMessenger,loadDependenciesNodejs,importScripts*/
  7083. /*
  7084. * A platform-independent worker interface that will spawn new processes per
  7085. * worker (if the platform you use it on supports it).
  7086. */
  7087. var isNodejs = typeof require !== 'undefined' && typeof process !== 'undefined';
  7088. // ignore-in-doc
  7089. // Code in worker setup is evaluated in the context of workers, it will get to
  7090. // workers in a stringified form(!).
  7091. var WorkerSetup = {
  7092. loadDependenciesBrowser: function loadDependenciesBrowser(options) {
  7093. var me = typeof self !== "undefined" ? self : this;
  7094. importScripts.apply(me, options.scriptsToLoad || []);
  7095. },
  7096. loadDependenciesNodejs: function loadDependenciesNodejs(options) {
  7097. var lv = global.lively || (global.lively = {});
  7098. lv.lang = require(require("path").join(options.libLocation, "index"));
  7099. },
  7100. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  7101. // yoshiki and robert, 05/08/13: Inserted code that sets up the lively context
  7102. // and globals of Lively and other required objects:
  7103. initBrowserGlobals: function initBrowserGlobals(options) {
  7104. remoteWorker.send = function (msg) {
  7105. postMessage(msg);
  7106. };
  7107. var me = typeof self !== "undefined" ? self : this;
  7108. var Global = me.Global = me;
  7109. Global.window = Global;
  7110. Global.console = Global.console || function () {
  7111. var c = {};
  7112. ['log', 'error', 'warn'].forEach(function (name) {
  7113. c[name] = function () /*args*/{
  7114. var string = arguments[0];
  7115. for (var i = 1; i < arguments.length; i++) {
  7116. string = string.replace('%s', arguments[i]);
  7117. }remoteWorker.send({
  7118. type: name,
  7119. message: ['[', name.toUpperCase(), '] ', string].join('')
  7120. });
  7121. };
  7122. });
  7123. return c;
  7124. }();
  7125. },
  7126. initOnMessageHandler: function initOnMessageHandler(options) {
  7127. if (remoteWorker.on) remoteWorker.on('message', onMessage);else remoteWorker.onmessage = onMessage;
  7128. function onMessage(msg) {
  7129. msg = msg.data.data ? msg.data : msg;
  7130. if (remoteWorker.messenger) remoteWorker.messenger.onMessage(msg);else if (msg.action == "close") {
  7131. remoteWorker.send({ type: "closed", workerReady: false });
  7132. remoteWorker.close();
  7133. return;
  7134. }
  7135. }
  7136. },
  7137. initWorkerInterface: function initWorkerInterface(options) {
  7138. remoteWorker.callStringifiedFunction = function (stringifiedFunc, args, thenDo) {
  7139. // ignore-in-doc
  7140. // runs stringified function and passing args. stringifiedFunc might
  7141. // be asynchronous if it takes an addaitional argument. In this case a
  7142. // callback to call when the work is done is passed, otherwise thenDo
  7143. // will be called immediatelly after creating and calling the function
  7144. var func;
  7145. try {
  7146. func = eval('(' + stringifiedFunc + ')');
  7147. } catch (e) {
  7148. thenDo(new Error("Cannot create function from string: " + e.stack || e));
  7149. return;
  7150. }
  7151. // ignore-in-doc
  7152. // when it takes one more arg then we assume that this is the callback
  7153. // to be called by the run func when it considers to be done
  7154. var usesCallback = func.length === args.length + 1;
  7155. var whenDone = lively.lang.fun.once(function (err, result) {
  7156. remoteWorker.isBusy = false;thenDo(err, result);
  7157. });
  7158. remoteWorker.isBusy = true;
  7159. if (usesCallback) args.push(whenDone);
  7160. try {
  7161. var result = func.apply(remoteWorker, args.concat([whenDone]));
  7162. } catch (e) {
  7163. whenDone(e, null);return;
  7164. }
  7165. if (!usesCallback) whenDone(null, result);
  7166. };
  7167. remoteWorker.httpRequest = function (options) {
  7168. if (!options.url) {
  7169. console.log("Error, httpRequest needs url");
  7170. return;
  7171. }
  7172. var req = new XMLHttpRequest(),
  7173. method = options.method || 'GET';
  7174. function handleStateChange() {
  7175. if (req.readyState === 4) {
  7176. // req.status
  7177. options.done && options.done(req);
  7178. }
  7179. }
  7180. req.onreadystatechange = handleStateChange;
  7181. req.open(method, options.url);
  7182. req.send();
  7183. };
  7184. remoteWorker.terminateIfNotBusyIn = function (ms) {
  7185. setTimeout(function () {
  7186. if (remoteWorker.isBusy) {
  7187. remoteWorker.terminateIfNotBusyIn(ms);return;
  7188. }
  7189. remoteWorker.send({ type: "closed", workerReady: false });
  7190. remoteWorker.close();
  7191. }, ms);
  7192. };
  7193. },
  7194. // ignore-in-doc
  7195. // setting up the worker messenger interface, this is how the worker
  7196. // should be communicated with
  7197. initWorkerMessenger: function initWorkerMessenger(options) {
  7198. if (!options.useMessenger) return null;
  7199. if (!lively.lang.messenger) throw new Error("worker.create requires messenger.js to be loaded!");
  7200. if (!lively.lang.events) throw new Error("worker.create requires events.js to be loaded!");
  7201. return remoteWorker.messenger = lively.lang.messenger.create({
  7202. services: {
  7203. remoteEval: function remoteEval(msg, messenger) {
  7204. var result;
  7205. try {
  7206. result = eval(msg.data.expr);
  7207. } catch (e) {
  7208. result = e.stack || e;
  7209. }
  7210. messenger.answer(msg, { result: String(result) });
  7211. },
  7212. run: function run(msg, messenger) {
  7213. var funcString = msg.data.func,
  7214. args = msg.data.args;
  7215. if (!funcString) {
  7216. messenger.answer(msg, { error: 'no funcString' });return;
  7217. }
  7218. remoteWorker.callStringifiedFunction(funcString, args, function (err, result) {
  7219. messenger.answer(msg, { error: err ? String(err) : null, result: result });
  7220. });
  7221. },
  7222. close: function close(msg, messenger) {
  7223. messenger.answer(msg, { status: "OK" });
  7224. remoteWorker.send({ type: "closed", workerReady: false });
  7225. remoteWorker.close();
  7226. }
  7227. },
  7228. isOnline: function isOnline() {
  7229. return true;
  7230. },
  7231. send: function send(msg, whenSend) {
  7232. remoteWorker.send(msg);whenSend();
  7233. },
  7234. listen: function listen(whenListening) {
  7235. whenListening();
  7236. },
  7237. close: function close(whenClosed) {
  7238. remoteWorker.send({ type: "closed", workerReady: false });remoteWorker.close();
  7239. }
  7240. });
  7241. }
  7242. };
  7243. var BrowserWorker = {
  7244. create: function create$3(options) {
  7245. // ignore-in-doc
  7246. // this function instantiates a browser worker object. We provide a
  7247. // messenger-based interface to the pure Worker. Please use create to get an
  7248. // improved interface to a worker
  7249. options = options || {};
  7250. // ignore-in-doc
  7251. // figure out where the other lang libs can be loaded from
  7252. if (!options.libLocation && !options.scriptsToLoad) {
  7253. var workerScript = document.querySelector("script[src$=\"worker.js\"]");
  7254. if (!workerScript) throw new Error("Cannot find library path to start worker. Use worker.create({libLocation: \"...\"}) to explicitly define the path!");
  7255. options.libLocation = workerScript.src.replace(/worker.js$/, '');
  7256. }
  7257. var workerSetupCode = String(workerSetupFunction).replace("__FUNCTIONDECLARATIONS__", [WorkerSetup.initBrowserGlobals, WorkerSetup.loadDependenciesBrowser, WorkerSetup.initOnMessageHandler, WorkerSetup.initWorkerInterface, WorkerSetup.initWorkerMessenger].join('\n'));
  7258. var workerCode = '(' + lively_sourceTransform.stringifyFunctionWithoutToplevelRecorder(workerSetupCode) + ')();';
  7259. var worker = new Worker(makeDataURI(workerCode));
  7260. init(options, worker);
  7261. return worker;
  7262. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  7263. // ignore-in-doc
  7264. // This code is triggered in the UI process directly after the
  7265. // creation of the worker and sends the setup message to the worker
  7266. // for initializing it.
  7267. function init(options, worker) {
  7268. makeEmitter(worker);
  7269. if (!options.scriptsToLoad) {
  7270. options.scriptsToLoad = ['base.js', 'events.js', 'object.js', 'collection.js', 'function.js', 'string.js', 'number.js', 'date.js', 'messenger.js', 'worker.js'].map(function (ea) {
  7271. return options.libLocation + ea;
  7272. });
  7273. }
  7274. var workerOptions = Object.keys(options).reduce(function (opts, key) {
  7275. if (typeof options[key] !== 'function') opts[key] = options[key];
  7276. return opts;
  7277. }, {});
  7278. worker.onmessage = function (evt) {
  7279. if (evt.data.workerReady !== undefined) {
  7280. worker.ready = !!evt.data.workerReady;
  7281. if (worker.ready) worker.emit("ready");else worker.emit("close");
  7282. } else worker.emit('message', evt.data);
  7283. };
  7284. worker.errors = [];
  7285. worker.onerror = function (evt) {
  7286. console.error(evt);
  7287. worker.errors.push(evt);
  7288. worker.emit("error", evt);
  7289. };
  7290. worker.postMessage({ action: 'setup', options: workerOptions });
  7291. }
  7292. // ignore-in-doc
  7293. // This code is run inside the worker and bootstraps the messenger
  7294. // interface. It also installs a console.log method since since this is not
  7295. // available by default.
  7296. function workerSetupFunction() {
  7297. var remoteWorker = self;
  7298. remoteWorker.onmessage = function (evt) {
  7299. if (evt.data.action !== "setup") {
  7300. throw new Error("expected setup to be first message but got " + JSON.stringify(evt.data));
  7301. }
  7302. var options = evt.data.options || {};
  7303. initBrowserGlobals(options);
  7304. loadDependenciesBrowser(options);
  7305. initOnMessageHandler(options);
  7306. initWorkerInterface(options);
  7307. initWorkerMessenger(options);
  7308. postMessage({ workerReady: true });
  7309. };
  7310. __FUNCTIONDECLARATIONS__;
  7311. }
  7312. function makeDataURI(codeToInclude) {
  7313. // ignore-in-doc
  7314. // see http://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string
  7315. var blob;
  7316. try {
  7317. blob = new Blob([codeToInclude], { type: "text/javascript" });
  7318. } catch (e) {
  7319. /* ignore-in-doc Backwards-compatibility*/
  7320. window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
  7321. blob = new BlobBuilder();
  7322. blob.append(codeToInclude);
  7323. blob = blob.getBlob();
  7324. }
  7325. var urlInterface = typeof webkitURL !== 'undefined' ? webkitURL : URL;
  7326. return urlInterface.createObjectURL(blob);
  7327. }
  7328. }
  7329. };
  7330. var NodejsWorker = {
  7331. debug: false,
  7332. initCodeFileCreated: false,
  7333. create: function create$3(options) {
  7334. options = options || {};
  7335. // ignore-in-doc
  7336. // figure out where the other lang libs can be loaded from
  7337. // if (!options.libLocation && !options.scriptsToLoad) {
  7338. // var workerScript = document.querySelector("script[src$=\"worker.js\"]");
  7339. // if (!workerScript) throw new Error("Cannot find library path to start worker. Use worker.create({libLocation: \"...\"}) to explicitly define the path!");
  7340. // options.libLocation = workerScript.src.replace(/worker.js$/, '');
  7341. // }
  7342. var workerProc;
  7343. var worker = makeEmitter({
  7344. ready: false,
  7345. errors: [],
  7346. postMessage: function postMessage(msg) {
  7347. if (!workerProc) {
  7348. worker.emit("error", new Error('nodejs worker process not yet created'));
  7349. return;
  7350. }
  7351. if (!worker.ready) {
  7352. worker.emit("error", new Error('nodejs worker process not ready or already closed'));
  7353. return;
  7354. }
  7355. workerProc.send(msg);
  7356. }
  7357. });
  7358. NodejsWorker.startWorker(options, function (err, _workerProc) {
  7359. if (err) {
  7360. worker.ready = false;worker.emit("error", err);return;
  7361. }
  7362. workerProc = _workerProc;
  7363. workerProc.on('message', function (m) {
  7364. NodejsWorker.debug && console.log('[WORKER PARENT] got message:', m);
  7365. worker.emit("message", m);
  7366. });
  7367. workerProc.on('close', function () {
  7368. console.log("[WORKER PARENT] worker closed");
  7369. worker.emit("close");
  7370. });
  7371. workerProc.on('error', function (err) {
  7372. console.log("[WORKER PARENT] error ", err);
  7373. worker.errors.push(err);
  7374. worker.emit("error", err);
  7375. });
  7376. worker.ready = true;
  7377. worker.emit("ready");
  7378. });
  7379. return worker;
  7380. },
  7381. // this code is run in the context of the worker process
  7382. workerSetupFunction: function workerSetupFunction() {
  7383. var remoteWorker = process;
  7384. var debug = true;
  7385. var close = false;
  7386. debug && console.log("[WORKER] Starting init");
  7387. // ignore-in-doc
  7388. // process.on('message', function(m) {
  7389. // debug && console.log('[WORKER] got message:', m);
  7390. // if (m.action === 'ping') process.send({action: 'pong', data: m});
  7391. // else if (m.action === 'close') close = true;
  7392. // else if (m.action === 'setup') setup(m.data);
  7393. // else console.error('[WORKER] unknown message: ', m);
  7394. // });
  7395. remoteWorker.on("message", function (msg) {
  7396. if (msg.action !== "setup") {
  7397. throw new Error("expected setup to be first message but got " + JSON.stringify(msg.data));
  7398. }
  7399. remoteWorker.removeAllListeners("message");
  7400. var options = msg.data.options || {};
  7401. debug && console.log("[WORKER] running setup with options", options);
  7402. loadDependenciesNodejs(options);
  7403. initOnMessageHandler(options);
  7404. initWorkerInterface(options);
  7405. initWorkerMessenger(options);
  7406. remoteWorker.send({ workerReady: true });
  7407. });
  7408. __FUNCTIONDECLARATIONS__;
  7409. },
  7410. ensureInitCodeFile: function ensureInitCodeFile(options, initCode, thenDo) {
  7411. var path = require("path");
  7412. var os = require("os");
  7413. var fs = require("fs");
  7414. var workerTmpDir = path.join(os.tmpDir(), 'lively-nodejs-workers/');
  7415. var fn = path.join(workerTmpDir, 'nodejs-worker-init.js');
  7416. if (!NodejsWorker.initCodeFileCreated) NodejsWorker.createWorkerCodeFile(options, fn, initCode, thenDo);else fs.exists(fn, function (exists) {
  7417. if (exists) thenDo(null, fn);else NodejsWorker.createWorkerCodeFile(options, fn, initCode, thenDo);
  7418. });
  7419. },
  7420. createWorkerCodeFile: function createWorkerCodeFile(options, fileName, initCode, thenDo) {
  7421. var path = require("path");
  7422. var fs = require("fs");
  7423. var exec = require("child_process").exec;
  7424. exec("mkdir -p " + path.dirname(fileName), function (code, out, err) {
  7425. if (code) {
  7426. thenDo(new Error(["[WORKER PARENT] Could not create worker temp dir:", out, err].join('\n')));
  7427. return;
  7428. }
  7429. fs.writeFile(fileName, initCode, function (err) {
  7430. NodejsWorker.debug && console.log('worker code file %s created', fileName);
  7431. NodejsWorker.initCodeFileCreated = true;
  7432. thenDo(err, fileName);
  7433. });
  7434. });
  7435. },
  7436. startWorker: function startWorker(options, thenDo) {
  7437. var util = require("util");
  7438. var fork = require("child_process").fork;
  7439. var workerSetupCode = String(NodejsWorker.workerSetupFunction).replace("__FUNCTIONDECLARATIONS__", [WorkerSetup.loadDependenciesNodejs, WorkerSetup.initOnMessageHandler, WorkerSetup.initWorkerInterface, WorkerSetup.initWorkerMessenger].join('\n'));
  7440. var initCode = util.format("(%s)();\n", workerSetupCode);
  7441. NodejsWorker.ensureInitCodeFile(options, initCode, function (err, codeFileName) {
  7442. if (err) return thenDo(err);
  7443. var worker = fork(codeFileName, {});
  7444. NodejsWorker.debug && console.log('worker forked');
  7445. worker.on('message', function (m) {
  7446. if (m.action === 'pong') console.log("[WORKER pong] ", m);else if (m.action === 'log') console.log("[Message from WORKER] ", m.data);
  7447. });
  7448. worker.once('message', function (m) {
  7449. NodejsWorker.debug && console.log('worker setup done');
  7450. thenDo(null, worker, m);
  7451. });
  7452. worker.on('close', function () {
  7453. NodejsWorker.debug && console.log("[WORKER PARENT] worker closed");
  7454. });
  7455. worker.send({ action: "setup", data: { options: options } });
  7456. global.WORKER = worker;
  7457. });
  7458. }
  7459. };
  7460. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  7461. // the worker interface, usable both in browser and node.js contexts
  7462. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  7463. /*
  7464. Worker objects allow to fork processes in both Web and node.js JavaScript
  7465. environments. They provide this mechanism using web workers in the browser and
  7466. node.js child processes in node.js. The interface is unified for all platforms.
  7467. */
  7468. function fork(options, workerFunc, thenDo) {
  7469. // Fork automatically starts a worker and calls `workerFunc`. `workerFunc`
  7470. // gets as a last paramter a callback, that, when invoked with an error and
  7471. // result object, ends the worker execution.
  7472. //
  7473. // Options are the same as in `create` except for an `args` property that
  7474. // can be an array of objects. These objects will be passed to `workerFunc`
  7475. // as arguments.
  7476. //
  7477. // Note: `workerFunc` will not be able to capture outside variables (create a
  7478. // closure).
  7479. //
  7480. // Example:
  7481. // // When running this inside a browser: Note how the UI does not block.
  7482. // worker.fork({args: [40]},
  7483. // function(n, thenDo) {
  7484. // function fib(n) { return n <= 1 ? n : fib(n-1) + fib(n-2); }
  7485. // thenDo(null, fib(n));
  7486. // },
  7487. // function(err, result) { show(err ? err.stack : result); })
  7488. if (!thenDo) {
  7489. thenDo = workerFunc;workerFunc = options;options = null;
  7490. }
  7491. options = options || {};
  7492. var args = options.args || [];
  7493. var w = create$3(options);
  7494. w.run.apply(w, [workerFunc].concat(args).concat(thenDo));
  7495. return w;
  7496. }
  7497. function create$3(options) {
  7498. // Explicitly creates a first-class worker. Options:
  7499. // ```js
  7500. // {
  7501. // workerId: STRING, // optional, id for worker, will be auto assigned if not provided
  7502. // libLocation: STRING, // optional, path to where the lively.lang lib is located. Worker will try to find it automatically if not provided.
  7503. // scriptsToLoad: ARRAY // optional, list of path/urls to load. Overwrites `libLocation`
  7504. // }
  7505. // ```
  7506. //
  7507. // Example:
  7508. // // this is just a helper function
  7509. // function resultHandler(err, result) { alert(err ? String(err) : result); }
  7510. //
  7511. // // 1. Create the worker
  7512. // var worker = lively.lang.worker.create({libLocation: baseURL});
  7513. //
  7514. // // 2. You can evaluate arbitrary JS code
  7515. // worker.eval("1+2", function(err, result) { show(err ? String(err) : result); });
  7516. //
  7517. // // 3. Arbitrary functions can be called inside the worker context.
  7518. // // Note: functions shouldn't be closures / capture local state!) and passing
  7519. // // in arguments!
  7520. // worker.run(
  7521. // function(a, b, thenDo) { setTimeout(function() { thenDo(null, a+b); }, 300); },
  7522. // 19, 4, resultHandler);
  7523. //
  7524. // // 4. You can also install your own messenger services...
  7525. // worker.run(
  7526. // function(thenDo) {
  7527. // self.messenger.addServices({
  7528. // foo: function(msg, messenger) { messenger.answer(msg, "bar!"); }
  7529. // });
  7530. // thenDo(null, "Service installed!");
  7531. // }, resultHandler);
  7532. //
  7533. // // ... and call them via the messenger interface
  7534. // worker.sendTo("worker", "foo", {}, resultHandler);
  7535. //
  7536. // // 5. afterwards: shut it down
  7537. // worker.close(function(err) { err && show(String(err)); alertOK("worker shutdown"); })
  7538. options = options || {};
  7539. options.useMessenger = true;
  7540. // if (!exports.messenger)
  7541. // throw new Error("worker.create requires messenger.js to be loaded!")
  7542. // if (!exports.events)
  7543. // throw new Error("worker.create requires events.js to be loaded!")
  7544. // if (!exports.obj)
  7545. // throw new Error("worker.create requires object.js to be loaded!")
  7546. var workerId = options.workerId || newUUID();
  7547. var messenger = create$2({
  7548. sendTimeout: 5000,
  7549. send: function send(msg, whenSend) {
  7550. messenger.worker.postMessage(msg);
  7551. whenSend();
  7552. },
  7553. listen: function listen(whenListening) {
  7554. var w = messenger.worker = isNodejs ? NodejsWorker.create(options) : BrowserWorker.create(options);
  7555. w.on("message", function (msg) {
  7556. messenger.onMessage(msg);
  7557. });
  7558. w.on('ready', function () {
  7559. NodejsWorker.debug && console.log("WORKER READY!!!");
  7560. });
  7561. w.on('close', function () {
  7562. NodejsWorker.debug && console.log("WORKER CLOSED...!!!");
  7563. });
  7564. w.once('ready', whenListening);
  7565. },
  7566. close: function close(whenClosed) {
  7567. if (!messenger.worker.ready) return whenClosed(null);
  7568. return messenger.sendTo(workerId, 'close', {}, function (err, answer) {
  7569. err = err || answer.data.error;
  7570. err && console.error("Error in worker messenger close: " + err.stack || err);
  7571. if (err) whenClosed(err);else {
  7572. var closed = false;
  7573. messenger.worker.once('close', function () {
  7574. closed = true;
  7575. });
  7576. waitFor(1000, function () {
  7577. return !!closed;
  7578. }, whenClosed);
  7579. }
  7580. });
  7581. },
  7582. isOnline: function isOnline() {
  7583. return messenger.worker && messenger.worker.ready;
  7584. }
  7585. });
  7586. Object.assign(messenger, {
  7587. eval: function _eval(code, thenDo) {
  7588. messenger.sendTo(workerId, "remoteEval", { expr: code }, function (err, answer) {
  7589. thenDo(err, answer ? answer.data.result : null);
  7590. });
  7591. },
  7592. run: function run() /*runFunc, arg1, ... argN, thenDo*/{
  7593. var args = Array.prototype.slice.call(arguments),
  7594. workerFunc = args.shift(),
  7595. thenDo = args.pop();
  7596. if (typeof workerFunc !== "function") throw new Error("run: no function that should run in worker passed");
  7597. if (typeof thenDo !== "function") throw new Error("run: no callback passed");
  7598. return messenger.sendTo(workerId, 'run', { func: String(workerFunc), args: args }, function (err, answer) {
  7599. thenDo(err || answer.data.error, answer ? answer.data.result : null);
  7600. });
  7601. }
  7602. });
  7603. messenger.listen();
  7604. return messenger;
  7605. }
  7606. var worker = Object.freeze({
  7607. fork: fork,
  7608. create: create$3
  7609. });
  7610. var GLOBAL = typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : undefined;
  7611. var isNode = typeof process !== "undefined" && process.env && typeof process.exit === "function";
  7612. var globalInterfaceSpec = [{ action: "installMethods", target: "Array", sources: ["arr"], methods: ["from", "genN", "range", "withN"] }, { action: "installMethods", target: "Array.prototype", sources: ["arr"], methods: ["all", "any", "batchify", "clear", "clone", "collect", "compact", "delimWith", "detect", "doAndContinue", "each", "equals", "filterByKey", "findAll", "first", "flatten", "forEachShowingProgress", "grep", "groupBy", "groupByKey", "histogram", "include", "inject", "intersect", "invoke", "last", "mapAsync", "mapAsyncSeries", "mask", "max", "min", "mutableCompact", "nestedDelay", "partition", "pluck", "pushAll", "pushAllAt", "pushAt", "pushIfNotIncluded", "reMatches", "reject", "rejectByKey", "remove", "removeAt", "replaceAt", "rotate", "shuffle", "size", "sortBy", "sortByKey", "sum", "swap", "toArray", "toTuples", "union", "uniq", "uniqBy", "without", "withoutAll", "zip"], alias: [["select", "filter"]] }, { action: "installMethods", target: "Date", sources: ["date"], methods: [/*"parse"*/] }, { action: "installMethods", target: "Date.prototype", sources: ["date"], methods: ["equals", "format", "relativeTo"] }, { action: "installMethods", target: "Function", sources: ["fun"], methods: ["fromString"] }, { action: "installMethods", target: "Function.prototype", sources: ["fun"], methods: [/*"addProperties",*/"addToObject", "argumentNames", "asScript", "asScriptOf", "binds", "curry", "delay", "functionNames", "localFunctionNames", "getOriginal", "getVarMapping", "logCalls", "logCompletion", "logErrors", "qualifiedMethodName", "setProperty", "traceCalls", "wrap"] }, { action: "installMethods", target: "Number", sources: ["num"], methods: [] }, { action: "installMethods", target: "Number.prototype", sources: ["num"], methods: ["detent", "randomSmallerInteger", "roundTo", "toDegrees", "toRadians"] }, { action: "installMethods", target: "Object", sources: ["obj"], methods: ["addScript", "clone", "deepCopy", "extend", "inherit", "isArray", "isBoolean", "isElement", "isEmpty", "isFunction", "isNumber", "isObject", "isRegExp", "isString", "isUndefined", "merge", "mergePropertyInHierarchy", "values", "valuesInPropertyHierarchy"] }, { action: "installMethods", target: "Object.prototype", sources: ["obj"], methods: [] }, { action: "installMethods", target: "String.prototype", sources: ["string"], methods: ["camelize", "capitalize", "digitValue", "empty", "hashCode", "include", "pad", "regExpEscape", "startsWithVowel", "succ", "times", "toArray", "toQueryParams", "truncate"] }, { action: "installObject", target: "Numbers", source: "num", methods: ["average", "between", "convertLength", "humanReadableByteSize", "median", "normalRandom", "parseLength", "random", "sort"] }, { action: "installObject", target: "Properties", source: "properties", methods: ["all", "allOwnPropertiesOrFunctions", "allProperties", "any", "forEachOwn", "hash", "nameFor", "own", "ownValues", "values"] }, { action: "installObject", target: "Strings", source: "string", methods: ["camelCaseString", "createDataURI", "diff", "format", "formatFromArray", "indent", "lineIndexComputer", "lines", "md5", "newUUID", "nonEmptyLines", "pad", "paragraphs", "peekLeft", "peekRight", "print", "printNested", "printTable", "printTree", "quote", "reMatches", "stringMatch", "tableize", "tokens", "unescapeCharacterEntities", "withDecimalPrecision"] }, { action: "installObject", target: "Objects", source: "obj", methods: ["asObject", "equals", "inspect", "isMutableType", "safeToString", "shortPrintStringOf", "typeStringOf"] }, { action: "installObject", target: "Functions", source: "fun", methods: ["all", "compose", "composeAsync", "createQueue", "debounce", "debounceNamed", "either", "extractBody", "flip", "notYetImplemented", "once", "own", "throttle", "throttleNamed", "timeToRun", "timeToRunN", "waitFor", "workerWithCallbackQueue", "wrapperChain"] }, { action: "installObject", target: "Grid", source: "grid" }, { action: "installObject", target: "Interval", source: "interval" }, { action: "installObject", target: "lively.ArrayProjection", source: "arrayProjection" }, { action: "installObject", target: "lively.Closure", source: "Closure" }, { action: "installObject", target: "lively.Grouping", source: "Group" }, { action: "installObject", target: "lively.PropertyPath", source: "Path" }, { action: "installObject", target: "lively.Worker", source: "worker" }, { action: "installObject", target: "lively.Class", source: "classHelper" }];
  7613. function createLivelyLangObject() {
  7614. return {
  7615. chain: chain$$1,
  7616. noConflict: noConflict,
  7617. installGlobals: installGlobals,
  7618. uninstallGlobals: uninstallGlobals,
  7619. globalInterfaceSpec: globalInterfaceSpec,
  7620. toString: function toString() {
  7621. return "[object lively.lang]";
  7622. }
  7623. };
  7624. }
  7625. var livelyLang = createLivelyLangObject();
  7626. function chain$$1(object) {
  7627. if (!object) return object;
  7628. var chained;
  7629. if (Array.isArray(object)) return createChain(arr, object);
  7630. if (object.constructor.name === "Date") return createChain(date, object);
  7631. switch (typeof object === "undefined" ? "undefined" : _typeof(object)) {
  7632. case 'string':
  7633. return createChain(string, object);
  7634. case 'object':
  7635. return createChain(obj, object);
  7636. case 'function':
  7637. return createChain(fun, object);
  7638. case 'number':
  7639. return createChain(num, object);
  7640. }
  7641. throw new Error("Chain for object " + object + " (" + object.constructor.name + ") no supported");
  7642. }
  7643. function createChain(interfaceObj, obj) {
  7644. return Object.keys(interfaceObj).reduce(function (chained, methodName) {
  7645. chained[methodName] = function () /*args*/{
  7646. var args = Array.prototype.slice.call(arguments),
  7647. result = interfaceObj[methodName].apply(null, [obj].concat(args));
  7648. return chain$$1(result);
  7649. };
  7650. return chained;
  7651. }, { value: function value() {
  7652. return obj;
  7653. } });
  7654. }
  7655. function noConflict() {
  7656. if (!isNode) {
  7657. var keepLivelyNS = livelyLang._prevLivelyGlobal;
  7658. if (!keepLivelyNS) delete GLOBAL.lively;else delete GLOBAL.lively.lang;
  7659. }
  7660. return livelyLang;
  7661. }
  7662. function installGlobals() {
  7663. Object.assign(livelyLang, {
  7664. worker: worker,
  7665. messenger: messenger,
  7666. events: events,
  7667. tree: tree,
  7668. grid: grid,
  7669. arrayProjection: arrayProjection,
  7670. interval: interval,
  7671. graph: graph,
  7672. date: date,
  7673. properties: properties,
  7674. obj: obj,
  7675. arr: arr,
  7676. fun: fun,
  7677. num: num,
  7678. string: string,
  7679. Closure: Closure,
  7680. promise: promise,
  7681. Path: Path,
  7682. Group: Group
  7683. });
  7684. globalInterfaceSpec.forEach(function (ea) {
  7685. if (ea.action === "installMethods") {
  7686. var targetPath = Path(ea.target);
  7687. if (!targetPath.isIn(GLOBAL)) targetPath.set(GLOBAL, {}, true);
  7688. var sourcePath = Path(ea.sources[0]);
  7689. ea.methods.forEach(function (name) {
  7690. installProperty(sourcePath.concat([name]), targetPath.concat([name]));
  7691. });
  7692. if (ea.alias) ea.alias.forEach(function (mapping) {
  7693. installProperty(sourcePath.concat([mapping[1]]), targetPath.concat([mapping[0]]));
  7694. });
  7695. } else if (ea.action === "installObject") {
  7696. var targetPath = Path(ea.target);
  7697. var source = Path(ea.source).get(livelyLang);
  7698. targetPath.set(GLOBAL, source, true);
  7699. } else throw new Error("Cannot deal with global setup action: " + ea.action);
  7700. });
  7701. }
  7702. function installProperty(sourcePath, targetPath) {
  7703. if (!sourcePath.isIn(livelyLang)) {
  7704. var err = new Error("property not provided by lively.lang: " + sourcePath);
  7705. console.error(err.stack || err);
  7706. throw err;
  7707. }
  7708. var prop = sourcePath.get(livelyLang);
  7709. if (typeof prop === "function" && targetPath.slice(-2, -1).toString() === "prototype") {
  7710. var origFunc = prop;
  7711. prop = function prop() /*this and args*/{
  7712. var args = Array.prototype.slice.call(arguments);
  7713. args.unshift(this);
  7714. return origFunc.apply(null, args);
  7715. };
  7716. prop.toString = function () {
  7717. return origFunc.toString();
  7718. };
  7719. }
  7720. targetPath.set(GLOBAL, prop, true);
  7721. }
  7722. function uninstallGlobals() {
  7723. globalInterfaceSpec.forEach(function (ea) {
  7724. if (ea.action === "installMethods") {
  7725. var p = Path(ea.target);
  7726. var source = Path(ea.source).get(livelyLang);
  7727. var target = p.get(GLOBAL);
  7728. if (!target) return;
  7729. ea.methods.filter(function (name) {
  7730. return source === target[name];
  7731. }).forEach(function (name) {
  7732. delete target[name];
  7733. });
  7734. if (ea.alias) ea.alias.filter(function (name) {
  7735. return source === target[name];
  7736. }).forEach(function (mapping) {
  7737. delete target[mapping[0]];
  7738. });
  7739. } else if (ea.action === "installObject") {
  7740. var p = Path(ea.target);
  7741. p.del(GLOBAL);
  7742. } else throw new Error("Cannot deal with global setup action: " + ea.action);
  7743. });
  7744. }
  7745. exports.worker = worker;
  7746. exports.messenger = messenger;
  7747. exports.events = events;
  7748. exports.tree = tree;
  7749. exports.grid = grid;
  7750. exports.arrayProjection = arrayProjection;
  7751. exports.interval = interval;
  7752. exports.graph = graph;
  7753. exports.date = date;
  7754. exports.properties = properties;
  7755. exports.obj = obj;
  7756. exports.arr = arr;
  7757. exports.fun = fun;
  7758. exports.num = num;
  7759. exports.string = string;
  7760. exports.Closure = Closure;
  7761. exports.promise = promise;
  7762. exports.Path = Path;
  7763. exports.Group = Group;
  7764. exports.livelyLang = livelyLang;
  7765. exports.chain = chain$$1;
  7766. exports.noConflict = noConflict;
  7767. exports.installGlobals = installGlobals;
  7768. exports.uninstallGlobals = uninstallGlobals;
  7769. }((this.lively.lang = this.lively.lang || {}),lively.sourceTransform));
  7770. }).call(GLOBAL);
  7771. if (typeof module !== "undefined" && module.exports) module.exports = GLOBAL.lively.lang;
  7772. })();
  7773. // INLINED END /Users/user/git/lively.vm/node_modules/lively.lang/dist/lively.lang.js
  7774. // INLINED /Users/user/git/lively.vm/node_modules/lively.notifications/dist/lively.notifications.js
  7775. (function() {
  7776. var GLOBAL = typeof window !== "undefined" ? window :
  7777. typeof global!=="undefined" ? global :
  7778. typeof self!=="undefined" ? self : this;
  7779. this.lively = this.lively || {};
  7780. (function (exports,lively_lang) {
  7781. 'use strict';
  7782. /*global System*/
  7783. // type EventType = string
  7784. // type EventTime = number
  7785. // type Notification = {type: EventType, time: EventTime, ...};
  7786. // type Handler = Notification -> ()
  7787. // type Notifications = { [number]: Notification, limit: number }
  7788. // type Emitter = {isRecording: boolean, isLogging: boolean, ... }
  7789. // type Env = {emitter: Emitter, notifications: Notifications}
  7790. var env = void 0;
  7791. function getEnv(_System) {
  7792. // System? -> Env
  7793. if (_System === undefined) {
  7794. if (typeof System === "undefined") {
  7795. // fallback if not System is available
  7796. if (env !== undefined) return env;
  7797. return env || (env = {
  7798. emitter: lively_lang.events.makeEmitter({}, { maxListenerLimit: 10000 }),
  7799. notifications: []
  7800. });
  7801. }
  7802. _System = System;
  7803. }
  7804. var livelyEnv = _System.get("@lively-env");
  7805. if (!livelyEnv) _System.set("@lively-env", _System.newModule({ options: {} }));
  7806. var options = livelyEnv.options;
  7807. if (!options) throw new Error("@lively-env registered read-only");
  7808. if (!options.emitter) {
  7809. Object.assign(options, {
  7810. emitter: _System["__lively.notifications_emitter"] || (_System["__lively.notifications_emitter"] = lively_lang.events.makeEmitter({}, { maxListenerLimit: 10000 })),
  7811. notifications: _System["__lively.notifications_notifications"] || (_System["__lively.notifications_notifications"] = [])
  7812. });
  7813. }
  7814. var emitter = options.emitter,
  7815. notifications = options.notifications;
  7816. return { emitter: emitter, notifications: notifications };
  7817. }
  7818. function subscribe(type, handler, system) {
  7819. // EventType, Handler, System? -> Handler
  7820. getEnv(system).emitter.on(type, handler);
  7821. return handler;
  7822. }
  7823. function subscribeOnce(type, handler, system) {
  7824. // EventType, Handler, System? -> Handler
  7825. getEnv(system).emitter.once(type, handler);
  7826. return handler;
  7827. }
  7828. function emit(type) {
  7829. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  7830. var time = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Date.now();
  7831. var system = arguments[3];
  7832. // EventType, Notification?, EventTime?, System? -> Notification
  7833. var notification = Object.assign({ type: type, time: time }, data),
  7834. _getEnv = getEnv(system),
  7835. emitter = _getEnv.emitter,
  7836. notifications = _getEnv.notifications;
  7837. emitter.emit(type, notification);
  7838. if (emitter.isLogging) log(notification);
  7839. if (emitter.isRecording) record(notifications, notification);
  7840. return notification;
  7841. }
  7842. function unsubscribe(type, handler, system) {
  7843. // EventType, Handler, System? -> Handler
  7844. getEnv(system).emitter.removeListener(type, handler);
  7845. return handler;
  7846. }
  7847. function unsubscribeAll(type, system) {
  7848. // EventType, System? -> ()
  7849. getEnv(system).emitter.removeAllListeners(type);
  7850. }
  7851. function record(notifications, notification) {
  7852. // Array<Notification>, Notification -> ()
  7853. notifications.push(notification);
  7854. if (notifications.limit) {
  7855. notifications.splice(0, notifications.length - notifications.limit);
  7856. }
  7857. }
  7858. function startRecording(system) {
  7859. // System? -> ()
  7860. getEnv(system).emitter.isRecording = true;
  7861. }
  7862. function stopRecording(system) {
  7863. // System? -> ()
  7864. getEnv(system).emitter.isRecording = false;
  7865. }
  7866. function clearRecord(system) {
  7867. // System? -> ()
  7868. var _getEnv2 = getEnv(system),
  7869. notifications = _getEnv2.notifications;
  7870. notifications.splice(0, notifications.length);
  7871. }
  7872. function getRecord(system) {
  7873. // System? -> Notifications
  7874. return getEnv(system).notifications;
  7875. }
  7876. function log(notification) {
  7877. // Notification -> ()
  7878. var padded = notification.type + " ".repeat(Math.max(0, 32 - notification.type.length));
  7879. console.log(padded + " " + lively_lang.obj.inspect(notification, { maxDepth: 2 }));
  7880. }
  7881. function startLogging(system) {
  7882. // System? -> ()
  7883. getEnv(system).emitter.isLogging = true;
  7884. }
  7885. function stopLogging(system) {
  7886. // System? -> ()
  7887. getEnv(system).emitter.isLogging = false;
  7888. }
  7889. exports.subscribe = subscribe;
  7890. exports.subscribeOnce = subscribeOnce;
  7891. exports.emit = emit;
  7892. exports.unsubscribe = unsubscribe;
  7893. exports.unsubscribeAll = unsubscribeAll;
  7894. exports.startRecording = startRecording;
  7895. exports.stopRecording = stopRecording;
  7896. exports.clearRecord = clearRecord;
  7897. exports.getRecord = getRecord;
  7898. exports.startLogging = startLogging;
  7899. exports.stopLogging = stopLogging;
  7900. }((this.lively.notifications = this.lively.notifications || {}),lively.lang));
  7901. if (typeof module !== "undefined" && module.exports) module.exports = GLOBAL.lively.classes;
  7902. })();
  7903. // INLINED END /Users/user/git/lively.vm/node_modules/lively.notifications/dist/lively.notifications.js
  7904. // INLINED /Users/user/git/lively.vm/node_modules/lively.ast/dist/lively.ast.js
  7905. ;(function() {
  7906. var GLOBAL = typeof window !== "undefined" ? window :
  7907. typeof global!=="undefined" ? global :
  7908. typeof self!=="undefined" ? self : this;
  7909. if (GLOBAL.define) { var __define_suckz__ = GLOBAL; delete GLOBAL.define; }
  7910. (function() {
  7911. var module = undefined, require = undefined, define = undefined;
  7912. (function() {
  7913. var module = undefined, require = undefined, define = undefined;
  7914. (function (global, factory) {
  7915. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  7916. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  7917. (factory((global.acorn = global.acorn || {})));
  7918. }(this, (function (exports) { 'use strict';
  7919. // Reserved word lists for various dialects of the language
  7920. var reservedWords = {
  7921. 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  7922. 5: "class enum extends super const export import",
  7923. 6: "enum",
  7924. strict: "implements interface let package private protected public static yield",
  7925. strictBind: "eval arguments"
  7926. };
  7927. // And the keywords
  7928. var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
  7929. var keywords = {
  7930. 5: ecma5AndLessKeywords,
  7931. 6: ecma5AndLessKeywords + " const class extends export import super"
  7932. };
  7933. // ## Character categories
  7934. // Big ugly regular expressions that match characters in the
  7935. // whitespace, identifier, and identifier-start categories. These
  7936. // are only applied when a character is found to actually have a
  7937. // code point above 128.
  7938. // Generated by `bin/generate-identifier-regex.js`.
  7939. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fd5\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  7940. var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  7941. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  7942. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  7943. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  7944. // These are a run-length and offset encoded representation of the
  7945. // >0xffff code points that are a valid part of identifiers. The
  7946. // offset starts at 0x10000, and each pair of numbers represents an
  7947. // offset to the next range, and then a size of the range. They were
  7948. // generated by bin/generate-identifier-regex.js
  7949. // eslint-disable-next-line comma-spacing
  7950. var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541];
  7951. // eslint-disable-next-line comma-spacing
  7952. var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239];
  7953. // This has a complexity linear to the value of the code. The
  7954. // assumption is that looking up astral identifier characters is
  7955. // rare.
  7956. function isInAstralSet(code, set) {
  7957. var pos = 0x10000;
  7958. for (var i = 0; i < set.length; i += 2) {
  7959. pos += set[i];
  7960. if (pos > code) { return false }
  7961. pos += set[i + 1];
  7962. if (pos >= code) { return true }
  7963. }
  7964. }
  7965. // Test whether a given character code starts an identifier.
  7966. function isIdentifierStart(code, astral) {
  7967. if (code < 65) { return code === 36 }
  7968. if (code < 91) { return true }
  7969. if (code < 97) { return code === 95 }
  7970. if (code < 123) { return true }
  7971. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  7972. if (astral === false) { return false }
  7973. return isInAstralSet(code, astralIdentifierStartCodes)
  7974. }
  7975. // Test whether a given character is part of an identifier.
  7976. function isIdentifierChar(code, astral) {
  7977. if (code < 48) { return code === 36 }
  7978. if (code < 58) { return true }
  7979. if (code < 65) { return false }
  7980. if (code < 91) { return true }
  7981. if (code < 97) { return code === 95 }
  7982. if (code < 123) { return true }
  7983. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  7984. if (astral === false) { return false }
  7985. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  7986. }
  7987. // ## Token types
  7988. // The assignment of fine-grained, information-carrying type objects
  7989. // allows the tokenizer to store the information it has about a
  7990. // token in a way that is very cheap for the parser to look up.
  7991. // All token type variables start with an underscore, to make them
  7992. // easy to recognize.
  7993. // The `beforeExpr` property is used to disambiguate between regular
  7994. // expressions and divisions. It is set on all token types that can
  7995. // be followed by an expression (thus, a slash after them would be a
  7996. // regular expression).
  7997. //
  7998. // The `startsExpr` property is used to check if the token ends a
  7999. // `yield` expression. It is set on all token types that either can
  8000. // directly start an expression (like a quotation mark) or can
  8001. // continue an expression (like the body of a string).
  8002. //
  8003. // `isLoop` marks a keyword as starting a loop, which is important
  8004. // to know when parsing a label, in order to allow or disallow
  8005. // continue jumps to that label.
  8006. var TokenType = function TokenType(label, conf) {
  8007. if ( conf === void 0 ) conf = {};
  8008. this.label = label;
  8009. this.keyword = conf.keyword;
  8010. this.beforeExpr = !!conf.beforeExpr;
  8011. this.startsExpr = !!conf.startsExpr;
  8012. this.isLoop = !!conf.isLoop;
  8013. this.isAssign = !!conf.isAssign;
  8014. this.prefix = !!conf.prefix;
  8015. this.postfix = !!conf.postfix;
  8016. this.binop = conf.binop || null;
  8017. this.updateContext = null;
  8018. };
  8019. function binop(name, prec) {
  8020. return new TokenType(name, {beforeExpr: true, binop: prec})
  8021. }
  8022. var beforeExpr = {beforeExpr: true};
  8023. var startsExpr = {startsExpr: true};
  8024. // Map keyword names to token types.
  8025. var keywords$1 = {};
  8026. // Succinct definitions of keyword token types
  8027. function kw(name, options) {
  8028. if ( options === void 0 ) options = {};
  8029. options.keyword = name;
  8030. return keywords$1[name] = new TokenType(name, options)
  8031. }
  8032. var types = {
  8033. num: new TokenType("num", startsExpr),
  8034. regexp: new TokenType("regexp", startsExpr),
  8035. string: new TokenType("string", startsExpr),
  8036. name: new TokenType("name", startsExpr),
  8037. eof: new TokenType("eof"),
  8038. // Punctuation token types.
  8039. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  8040. bracketR: new TokenType("]"),
  8041. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  8042. braceR: new TokenType("}"),
  8043. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  8044. parenR: new TokenType(")"),
  8045. comma: new TokenType(",", beforeExpr),
  8046. semi: new TokenType(";", beforeExpr),
  8047. colon: new TokenType(":", beforeExpr),
  8048. dot: new TokenType("."),
  8049. question: new TokenType("?", beforeExpr),
  8050. arrow: new TokenType("=>", beforeExpr),
  8051. template: new TokenType("template"),
  8052. invalidTemplate: new TokenType("invalidTemplate"),
  8053. ellipsis: new TokenType("...", beforeExpr),
  8054. backQuote: new TokenType("`", startsExpr),
  8055. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  8056. // Operators. These carry several kinds of properties to help the
  8057. // parser use them properly (the presence of these properties is
  8058. // what categorizes them as operators).
  8059. //
  8060. // `binop`, when present, specifies that this operator is a binary
  8061. // operator, and will refer to its precedence.
  8062. //
  8063. // `prefix` and `postfix` mark the operator as a prefix or postfix
  8064. // unary operator.
  8065. //
  8066. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  8067. // binary operators with a very low precedence, that should result
  8068. // in AssignmentExpression nodes.
  8069. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  8070. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  8071. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  8072. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  8073. logicalOR: binop("||", 1),
  8074. logicalAND: binop("&&", 2),
  8075. bitwiseOR: binop("|", 3),
  8076. bitwiseXOR: binop("^", 4),
  8077. bitwiseAND: binop("&", 5),
  8078. equality: binop("==/!=/===/!==", 6),
  8079. relational: binop("</>/<=/>=", 7),
  8080. bitShift: binop("<</>>/>>>", 8),
  8081. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  8082. modulo: binop("%", 10),
  8083. star: binop("*", 10),
  8084. slash: binop("/", 10),
  8085. starstar: new TokenType("**", {beforeExpr: true}),
  8086. // Keyword token types.
  8087. _break: kw("break"),
  8088. _case: kw("case", beforeExpr),
  8089. _catch: kw("catch"),
  8090. _continue: kw("continue"),
  8091. _debugger: kw("debugger"),
  8092. _default: kw("default", beforeExpr),
  8093. _do: kw("do", {isLoop: true, beforeExpr: true}),
  8094. _else: kw("else", beforeExpr),
  8095. _finally: kw("finally"),
  8096. _for: kw("for", {isLoop: true}),
  8097. _function: kw("function", startsExpr),
  8098. _if: kw("if"),
  8099. _return: kw("return", beforeExpr),
  8100. _switch: kw("switch"),
  8101. _throw: kw("throw", beforeExpr),
  8102. _try: kw("try"),
  8103. _var: kw("var"),
  8104. _const: kw("const"),
  8105. _while: kw("while", {isLoop: true}),
  8106. _with: kw("with"),
  8107. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  8108. _this: kw("this", startsExpr),
  8109. _super: kw("super", startsExpr),
  8110. _class: kw("class", startsExpr),
  8111. _extends: kw("extends", beforeExpr),
  8112. _export: kw("export"),
  8113. _import: kw("import"),
  8114. _null: kw("null", startsExpr),
  8115. _true: kw("true", startsExpr),
  8116. _false: kw("false", startsExpr),
  8117. _in: kw("in", {beforeExpr: true, binop: 7}),
  8118. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  8119. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  8120. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  8121. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  8122. };
  8123. // Matches a whole line break (where CRLF is considered a single
  8124. // line break). Used to count lines.
  8125. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  8126. var lineBreakG = new RegExp(lineBreak.source, "g");
  8127. function isNewLine(code) {
  8128. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  8129. }
  8130. var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  8131. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  8132. var ref = Object.prototype;
  8133. var hasOwnProperty = ref.hasOwnProperty;
  8134. var toString = ref.toString;
  8135. // Checks if an object has a property.
  8136. function has(obj, propName) {
  8137. return hasOwnProperty.call(obj, propName)
  8138. }
  8139. var isArray = Array.isArray || (function (obj) { return (
  8140. toString.call(obj) === "[object Array]"
  8141. ); });
  8142. // These are used when `options.locations` is on, for the
  8143. // `startLoc` and `endLoc` properties.
  8144. var Position = function Position(line, col) {
  8145. this.line = line;
  8146. this.column = col;
  8147. };
  8148. Position.prototype.offset = function offset (n) {
  8149. return new Position(this.line, this.column + n)
  8150. };
  8151. var SourceLocation = function SourceLocation(p, start, end) {
  8152. this.start = start;
  8153. this.end = end;
  8154. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  8155. };
  8156. // The `getLineInfo` function is mostly useful when the
  8157. // `locations` option is off (for performance reasons) and you
  8158. // want to find the line/column position for a given character
  8159. // offset. `input` should be the code string that the offset refers
  8160. // into.
  8161. function getLineInfo(input, offset) {
  8162. for (var line = 1, cur = 0;;) {
  8163. lineBreakG.lastIndex = cur;
  8164. var match = lineBreakG.exec(input);
  8165. if (match && match.index < offset) {
  8166. ++line;
  8167. cur = match.index + match[0].length;
  8168. } else {
  8169. return new Position(line, offset - cur)
  8170. }
  8171. }
  8172. }
  8173. // A second optional argument can be given to further configure
  8174. // the parser process. These options are recognized:
  8175. var defaultOptions = {
  8176. // `ecmaVersion` indicates the ECMAScript version to parse. Must
  8177. // be either 3, 5, 6 (2015), 7 (2016), or 8 (2017). This influences support
  8178. // for strict mode, the set of reserved words, and support for
  8179. // new syntax features. The default is 7.
  8180. ecmaVersion: 7,
  8181. // `sourceType` indicates the mode the code should be parsed in.
  8182. // Can be either `"script"` or `"module"`. This influences global
  8183. // strict mode and parsing of `import` and `export` declarations.
  8184. sourceType: "script",
  8185. // `onInsertedSemicolon` can be a callback that will be called
  8186. // when a semicolon is automatically inserted. It will be passed
  8187. // th position of the comma as an offset, and if `locations` is
  8188. // enabled, it is given the location as a `{line, column}` object
  8189. // as second argument.
  8190. onInsertedSemicolon: null,
  8191. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  8192. // trailing commas.
  8193. onTrailingComma: null,
  8194. // By default, reserved words are only enforced if ecmaVersion >= 5.
  8195. // Set `allowReserved` to a boolean value to explicitly turn this on
  8196. // an off. When this option has the value "never", reserved words
  8197. // and keywords can also not be used as property names.
  8198. allowReserved: null,
  8199. // When enabled, a return at the top level is not considered an
  8200. // error.
  8201. allowReturnOutsideFunction: false,
  8202. // When enabled, import/export statements are not constrained to
  8203. // appearing at the top of the program.
  8204. allowImportExportEverywhere: false,
  8205. // When enabled, hashbang directive in the beginning of file
  8206. // is allowed and treated as a line comment.
  8207. allowHashBang: false,
  8208. // When `locations` is on, `loc` properties holding objects with
  8209. // `start` and `end` properties in `{line, column}` form (with
  8210. // line being 1-based and column 0-based) will be attached to the
  8211. // nodes.
  8212. locations: false,
  8213. // A function can be passed as `onToken` option, which will
  8214. // cause Acorn to call that function with object in the same
  8215. // format as tokens returned from `tokenizer().getToken()`. Note
  8216. // that you are not allowed to call the parser from the
  8217. // callback—that will corrupt its internal state.
  8218. onToken: null,
  8219. // A function can be passed as `onComment` option, which will
  8220. // cause Acorn to call that function with `(block, text, start,
  8221. // end)` parameters whenever a comment is skipped. `block` is a
  8222. // boolean indicating whether this is a block (`/* */`) comment,
  8223. // `text` is the content of the comment, and `start` and `end` are
  8224. // character offsets that denote the start and end of the comment.
  8225. // When the `locations` option is on, two more parameters are
  8226. // passed, the full `{line, column}` locations of the start and
  8227. // end of the comments. Note that you are not allowed to call the
  8228. // parser from the callback—that will corrupt its internal state.
  8229. onComment: null,
  8230. // Nodes have their start and end characters offsets recorded in
  8231. // `start` and `end` properties (directly on the node, rather than
  8232. // the `loc` object, which holds line/column data. To also add a
  8233. // [semi-standardized][range] `range` property holding a `[start,
  8234. // end]` array with the same numbers, set the `ranges` option to
  8235. // `true`.
  8236. //
  8237. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  8238. ranges: false,
  8239. // It is possible to parse multiple files into a single AST by
  8240. // passing the tree produced by parsing the first file as
  8241. // `program` option in subsequent parses. This will add the
  8242. // toplevel forms of the parsed file to the `Program` (top) node
  8243. // of an existing parse tree.
  8244. program: null,
  8245. // When `locations` is on, you can pass this to record the source
  8246. // file in every node's `loc` object.
  8247. sourceFile: null,
  8248. // This value, if given, is stored in every node, whether
  8249. // `locations` is on or off.
  8250. directSourceFile: null,
  8251. // When enabled, parenthesized expressions are represented by
  8252. // (non-standard) ParenthesizedExpression nodes
  8253. preserveParens: false,
  8254. plugins: {}
  8255. };
  8256. // Interpret and default an options object
  8257. function getOptions(opts) {
  8258. var options = {};
  8259. for (var opt in defaultOptions)
  8260. { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  8261. if (options.ecmaVersion >= 2015)
  8262. { options.ecmaVersion -= 2009; }
  8263. if (options.allowReserved == null)
  8264. { options.allowReserved = options.ecmaVersion < 5; }
  8265. if (isArray(options.onToken)) {
  8266. var tokens = options.onToken;
  8267. options.onToken = function (token) { return tokens.push(token); };
  8268. }
  8269. if (isArray(options.onComment))
  8270. { options.onComment = pushComment(options, options.onComment); }
  8271. return options
  8272. }
  8273. function pushComment(options, array) {
  8274. return function(block, text, start, end, startLoc, endLoc) {
  8275. var comment = {
  8276. type: block ? "Block" : "Line",
  8277. value: text,
  8278. start: start,
  8279. end: end
  8280. };
  8281. if (options.locations)
  8282. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  8283. if (options.ranges)
  8284. { comment.range = [start, end]; }
  8285. array.push(comment);
  8286. }
  8287. }
  8288. // Registered plugins
  8289. var plugins = {};
  8290. function keywordRegexp(words) {
  8291. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  8292. }
  8293. var Parser = function Parser(options, input, startPos) {
  8294. this.options = options = getOptions(options);
  8295. this.sourceFile = options.sourceFile;
  8296. this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]);
  8297. var reserved = "";
  8298. if (!options.allowReserved) {
  8299. for (var v = options.ecmaVersion;; v--)
  8300. { if (reserved = reservedWords[v]) { break } }
  8301. if (options.sourceType == "module") { reserved += " await"; }
  8302. }
  8303. this.reservedWords = keywordRegexp(reserved);
  8304. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  8305. this.reservedWordsStrict = keywordRegexp(reservedStrict);
  8306. this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind);
  8307. this.input = String(input);
  8308. // Used to signal to callers of `readWord1` whether the word
  8309. // contained any escape sequences. This is needed because words with
  8310. // escape sequences must not be interpreted as keywords.
  8311. this.containsEsc = false;
  8312. // Load plugins
  8313. this.loadPlugins(options.plugins);
  8314. // Set up token state
  8315. // The current position of the tokenizer in the input.
  8316. if (startPos) {
  8317. this.pos = startPos;
  8318. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  8319. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  8320. } else {
  8321. this.pos = this.lineStart = 0;
  8322. this.curLine = 1;
  8323. }
  8324. // Properties of the current token:
  8325. // Its type
  8326. this.type = types.eof;
  8327. // For tokens that include more information than their type, the value
  8328. this.value = null;
  8329. // Its start and end offset
  8330. this.start = this.end = this.pos;
  8331. // And, if locations are used, the {line, column} object
  8332. // corresponding to those offsets
  8333. this.startLoc = this.endLoc = this.curPosition();
  8334. // Position information for the previous token
  8335. this.lastTokEndLoc = this.lastTokStartLoc = null;
  8336. this.lastTokStart = this.lastTokEnd = this.pos;
  8337. // The context stack is used to superficially track syntactic
  8338. // context to predict whether a regular expression is allowed in a
  8339. // given position.
  8340. this.context = this.initialContext();
  8341. this.exprAllowed = true;
  8342. // Figure out if it's a module code.
  8343. this.inModule = options.sourceType === "module";
  8344. this.strict = this.inModule || this.strictDirective(this.pos);
  8345. // Used to signify the start of a potential arrow function
  8346. this.potentialArrowAt = -1;
  8347. // Flags to track whether we are in a function, a generator, an async function.
  8348. this.inFunction = this.inGenerator = this.inAsync = false;
  8349. // Positions to delayed-check that yield/await does not exist in default parameters.
  8350. this.yieldPos = this.awaitPos = 0;
  8351. // Labels in scope.
  8352. this.labels = [];
  8353. // If enabled, skip leading hashbang line.
  8354. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  8355. { this.skipLineComment(2); }
  8356. // Scope tracking for duplicate variable names (see scope.js)
  8357. this.scopeStack = [];
  8358. this.enterFunctionScope();
  8359. };
  8360. // DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
  8361. Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) };
  8362. Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) };
  8363. Parser.prototype.extend = function extend (name, f) {
  8364. this[name] = f(this[name]);
  8365. };
  8366. Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) {
  8367. var this$1 = this;
  8368. for (var name in pluginConfigs) {
  8369. var plugin = plugins[name];
  8370. if (!plugin) { throw new Error("Plugin '" + name + "' not found") }
  8371. plugin(this$1, pluginConfigs[name]);
  8372. }
  8373. };
  8374. Parser.prototype.parse = function parse () {
  8375. var node = this.options.program || this.startNode();
  8376. this.nextToken();
  8377. return this.parseTopLevel(node)
  8378. };
  8379. var pp = Parser.prototype;
  8380. // ## Parser utilities
  8381. var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)"|;)/;
  8382. pp.strictDirective = function(start) {
  8383. var this$1 = this;
  8384. for (;;) {
  8385. skipWhiteSpace.lastIndex = start;
  8386. start += skipWhiteSpace.exec(this$1.input)[0].length;
  8387. var match = literal.exec(this$1.input.slice(start));
  8388. if (!match) { return false }
  8389. if ((match[1] || match[2]) == "use strict") { return true }
  8390. start += match[0].length;
  8391. }
  8392. };
  8393. // Predicate that tests whether the next token is of the given
  8394. // type, and if yes, consumes it as a side effect.
  8395. pp.eat = function(type) {
  8396. if (this.type === type) {
  8397. this.next();
  8398. return true
  8399. } else {
  8400. return false
  8401. }
  8402. };
  8403. // Tests whether parsed token is a contextual keyword.
  8404. pp.isContextual = function(name) {
  8405. return this.type === types.name && this.value === name
  8406. };
  8407. // Consumes contextual keyword if possible.
  8408. pp.eatContextual = function(name) {
  8409. return this.value === name && this.eat(types.name)
  8410. };
  8411. // Asserts that following token is given contextual keyword.
  8412. pp.expectContextual = function(name) {
  8413. if (!this.eatContextual(name)) { this.unexpected(); }
  8414. };
  8415. // Test whether a semicolon can be inserted at the current position.
  8416. pp.canInsertSemicolon = function() {
  8417. return this.type === types.eof ||
  8418. this.type === types.braceR ||
  8419. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  8420. };
  8421. pp.insertSemicolon = function() {
  8422. if (this.canInsertSemicolon()) {
  8423. if (this.options.onInsertedSemicolon)
  8424. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  8425. return true
  8426. }
  8427. };
  8428. // Consume a semicolon, or, failing that, see if we are allowed to
  8429. // pretend that there is a semicolon at this position.
  8430. pp.semicolon = function() {
  8431. if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
  8432. };
  8433. pp.afterTrailingComma = function(tokType, notNext) {
  8434. if (this.type == tokType) {
  8435. if (this.options.onTrailingComma)
  8436. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  8437. if (!notNext)
  8438. { this.next(); }
  8439. return true
  8440. }
  8441. };
  8442. // Expect a token of a given type. If found, consume it, otherwise,
  8443. // raise an unexpected token error.
  8444. pp.expect = function(type) {
  8445. this.eat(type) || this.unexpected();
  8446. };
  8447. // Raise an unexpected token error.
  8448. pp.unexpected = function(pos) {
  8449. this.raise(pos != null ? pos : this.start, "Unexpected token");
  8450. };
  8451. function DestructuringErrors() {
  8452. this.shorthandAssign =
  8453. this.trailingComma =
  8454. this.parenthesizedAssign =
  8455. this.parenthesizedBind =
  8456. -1;
  8457. }
  8458. pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  8459. if (!refDestructuringErrors) { return }
  8460. if (refDestructuringErrors.trailingComma > -1)
  8461. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  8462. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  8463. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  8464. };
  8465. pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  8466. var pos = refDestructuringErrors ? refDestructuringErrors.shorthandAssign : -1;
  8467. if (!andThrow) { return pos >= 0 }
  8468. if (pos > -1) { this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns"); }
  8469. };
  8470. pp.checkYieldAwaitInDefaultParams = function() {
  8471. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  8472. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  8473. if (this.awaitPos)
  8474. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  8475. };
  8476. pp.isSimpleAssignTarget = function(expr) {
  8477. if (expr.type === "ParenthesizedExpression")
  8478. { return this.isSimpleAssignTarget(expr.expression) }
  8479. return expr.type === "Identifier" || expr.type === "MemberExpression"
  8480. };
  8481. var pp$1 = Parser.prototype;
  8482. // ### Statement parsing
  8483. // Parse a program. Initializes the parser, reads any number of
  8484. // statements, and wraps them in a Program node. Optionally takes a
  8485. // `program` argument. If present, the statements will be appended
  8486. // to its body instead of creating a new node.
  8487. pp$1.parseTopLevel = function(node) {
  8488. var this$1 = this;
  8489. var exports = {};
  8490. if (!node.body) { node.body = []; }
  8491. while (this.type !== types.eof) {
  8492. var stmt = this$1.parseStatement(true, true, exports);
  8493. node.body.push(stmt);
  8494. }
  8495. this.adaptDirectivePrologue(node.body);
  8496. this.next();
  8497. if (this.options.ecmaVersion >= 6) {
  8498. node.sourceType = this.options.sourceType;
  8499. }
  8500. return this.finishNode(node, "Program")
  8501. };
  8502. var loopLabel = {kind: "loop"};
  8503. var switchLabel = {kind: "switch"};
  8504. pp$1.isLet = function() {
  8505. if (this.type !== types.name || this.options.ecmaVersion < 6 || this.value != "let") { return false }
  8506. skipWhiteSpace.lastIndex = this.pos;
  8507. var skip = skipWhiteSpace.exec(this.input);
  8508. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  8509. if (nextCh === 91 || nextCh == 123) { return true } // '{' and '['
  8510. if (isIdentifierStart(nextCh, true)) {
  8511. var pos = next + 1;
  8512. while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
  8513. var ident = this.input.slice(next, pos);
  8514. if (!this.isKeyword(ident)) { return true }
  8515. }
  8516. return false
  8517. };
  8518. // check 'async [no LineTerminator here] function'
  8519. // - 'async /*foo*/ function' is OK.
  8520. // - 'async /*\n*/ function' is invalid.
  8521. pp$1.isAsyncFunction = function() {
  8522. if (this.type !== types.name || this.options.ecmaVersion < 8 || this.value != "async")
  8523. { return false }
  8524. skipWhiteSpace.lastIndex = this.pos;
  8525. var skip = skipWhiteSpace.exec(this.input);
  8526. var next = this.pos + skip[0].length;
  8527. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  8528. this.input.slice(next, next + 8) === "function" &&
  8529. (next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
  8530. };
  8531. // Parse a single statement.
  8532. //
  8533. // If expecting a statement and finding a slash operator, parse a
  8534. // regular expression literal. This is to handle cases like
  8535. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  8536. // does not help.
  8537. pp$1.parseStatement = function(declaration, topLevel, exports) {
  8538. var starttype = this.type, node = this.startNode(), kind;
  8539. if (this.isLet()) {
  8540. starttype = types._var;
  8541. kind = "let";
  8542. }
  8543. // Most types of statements are recognized by the keyword they
  8544. // start with. Many are trivial to parse, some require a bit of
  8545. // complexity.
  8546. switch (starttype) {
  8547. case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  8548. case types._debugger: return this.parseDebuggerStatement(node)
  8549. case types._do: return this.parseDoStatement(node)
  8550. case types._for: return this.parseForStatement(node)
  8551. case types._function:
  8552. if (!declaration && this.options.ecmaVersion >= 6) { this.unexpected(); }
  8553. return this.parseFunctionStatement(node, false)
  8554. case types._class:
  8555. if (!declaration) { this.unexpected(); }
  8556. return this.parseClass(node, true)
  8557. case types._if: return this.parseIfStatement(node)
  8558. case types._return: return this.parseReturnStatement(node)
  8559. case types._switch: return this.parseSwitchStatement(node)
  8560. case types._throw: return this.parseThrowStatement(node)
  8561. case types._try: return this.parseTryStatement(node)
  8562. case types._const: case types._var:
  8563. kind = kind || this.value;
  8564. if (!declaration && kind != "var") { this.unexpected(); }
  8565. return this.parseVarStatement(node, kind)
  8566. case types._while: return this.parseWhileStatement(node)
  8567. case types._with: return this.parseWithStatement(node)
  8568. case types.braceL: return this.parseBlock()
  8569. case types.semi: return this.parseEmptyStatement(node)
  8570. case types._export:
  8571. case types._import:
  8572. if (!this.options.allowImportExportEverywhere) {
  8573. if (!topLevel)
  8574. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  8575. if (!this.inModule)
  8576. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  8577. }
  8578. return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
  8579. // If the statement does not start with a statement keyword or a
  8580. // brace, it's an ExpressionStatement or LabeledStatement. We
  8581. // simply start parsing an expression, and afterwards, if the
  8582. // next token is a colon and the expression was a simple
  8583. // Identifier node, we switch to interpreting it as a label.
  8584. default:
  8585. if (this.isAsyncFunction() && declaration) {
  8586. this.next();
  8587. return this.parseFunctionStatement(node, true)
  8588. }
  8589. var maybeName = this.value, expr = this.parseExpression();
  8590. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
  8591. { return this.parseLabeledStatement(node, maybeName, expr) }
  8592. else { return this.parseExpressionStatement(node, expr) }
  8593. }
  8594. };
  8595. pp$1.parseBreakContinueStatement = function(node, keyword) {
  8596. var this$1 = this;
  8597. var isBreak = keyword == "break";
  8598. this.next();
  8599. if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
  8600. else if (this.type !== types.name) { this.unexpected(); }
  8601. else {
  8602. node.label = this.parseIdent();
  8603. this.semicolon();
  8604. }
  8605. // Verify that there is an actual destination to break or
  8606. // continue to.
  8607. var i = 0;
  8608. for (; i < this.labels.length; ++i) {
  8609. var lab = this$1.labels[i];
  8610. if (node.label == null || lab.name === node.label.name) {
  8611. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  8612. if (node.label && isBreak) { break }
  8613. }
  8614. }
  8615. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  8616. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  8617. };
  8618. pp$1.parseDebuggerStatement = function(node) {
  8619. this.next();
  8620. this.semicolon();
  8621. return this.finishNode(node, "DebuggerStatement")
  8622. };
  8623. pp$1.parseDoStatement = function(node) {
  8624. this.next();
  8625. this.labels.push(loopLabel);
  8626. node.body = this.parseStatement(false);
  8627. this.labels.pop();
  8628. this.expect(types._while);
  8629. node.test = this.parseParenExpression();
  8630. if (this.options.ecmaVersion >= 6)
  8631. { this.eat(types.semi); }
  8632. else
  8633. { this.semicolon(); }
  8634. return this.finishNode(node, "DoWhileStatement")
  8635. };
  8636. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  8637. // loop is non-trivial. Basically, we have to parse the init `var`
  8638. // statement or expression, disallowing the `in` operator (see
  8639. // the second parameter to `parseExpression`), and then check
  8640. // whether the next token is `in` or `of`. When there is no init
  8641. // part (semicolon immediately after the opening parenthesis), it
  8642. // is a regular `for` loop.
  8643. pp$1.parseForStatement = function(node) {
  8644. this.next();
  8645. this.labels.push(loopLabel);
  8646. this.enterLexicalScope();
  8647. this.expect(types.parenL);
  8648. if (this.type === types.semi) { return this.parseFor(node, null) }
  8649. var isLet = this.isLet();
  8650. if (this.type === types._var || this.type === types._const || isLet) {
  8651. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  8652. this.next();
  8653. this.parseVar(init$1, true, kind);
  8654. this.finishNode(init$1, "VariableDeclaration");
  8655. if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 &&
  8656. !(kind !== "var" && init$1.declarations[0].init))
  8657. { return this.parseForIn(node, init$1) }
  8658. return this.parseFor(node, init$1)
  8659. }
  8660. var refDestructuringErrors = new DestructuringErrors;
  8661. var init = this.parseExpression(true, refDestructuringErrors);
  8662. if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  8663. this.toAssignable(init);
  8664. this.checkLVal(init);
  8665. this.checkPatternErrors(refDestructuringErrors, true);
  8666. return this.parseForIn(node, init)
  8667. } else {
  8668. this.checkExpressionErrors(refDestructuringErrors, true);
  8669. }
  8670. return this.parseFor(node, init)
  8671. };
  8672. pp$1.parseFunctionStatement = function(node, isAsync) {
  8673. this.next();
  8674. return this.parseFunction(node, true, false, isAsync)
  8675. };
  8676. pp$1.isFunction = function() {
  8677. return this.type === types._function || this.isAsyncFunction()
  8678. };
  8679. pp$1.parseIfStatement = function(node) {
  8680. this.next();
  8681. node.test = this.parseParenExpression();
  8682. // allow function declarations in branches, but only in non-strict mode
  8683. node.consequent = this.parseStatement(!this.strict && this.isFunction());
  8684. node.alternate = this.eat(types._else) ? this.parseStatement(!this.strict && this.isFunction()) : null;
  8685. return this.finishNode(node, "IfStatement")
  8686. };
  8687. pp$1.parseReturnStatement = function(node) {
  8688. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  8689. { this.raise(this.start, "'return' outside of function"); }
  8690. this.next();
  8691. // In `return` (and `break`/`continue`), the keywords with
  8692. // optional arguments, we eagerly look for a semicolon or the
  8693. // possibility to insert one.
  8694. if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
  8695. else { node.argument = this.parseExpression(); this.semicolon(); }
  8696. return this.finishNode(node, "ReturnStatement")
  8697. };
  8698. pp$1.parseSwitchStatement = function(node) {
  8699. var this$1 = this;
  8700. this.next();
  8701. node.discriminant = this.parseParenExpression();
  8702. node.cases = [];
  8703. this.expect(types.braceL);
  8704. this.labels.push(switchLabel);
  8705. this.enterLexicalScope();
  8706. // Statements under must be grouped (by label) in SwitchCase
  8707. // nodes. `cur` is used to keep the node that we are currently
  8708. // adding statements to.
  8709. var cur;
  8710. for (var sawDefault = false; this.type != types.braceR;) {
  8711. if (this$1.type === types._case || this$1.type === types._default) {
  8712. var isCase = this$1.type === types._case;
  8713. if (cur) { this$1.finishNode(cur, "SwitchCase"); }
  8714. node.cases.push(cur = this$1.startNode());
  8715. cur.consequent = [];
  8716. this$1.next();
  8717. if (isCase) {
  8718. cur.test = this$1.parseExpression();
  8719. } else {
  8720. if (sawDefault) { this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses"); }
  8721. sawDefault = true;
  8722. cur.test = null;
  8723. }
  8724. this$1.expect(types.colon);
  8725. } else {
  8726. if (!cur) { this$1.unexpected(); }
  8727. cur.consequent.push(this$1.parseStatement(true));
  8728. }
  8729. }
  8730. this.exitLexicalScope();
  8731. if (cur) { this.finishNode(cur, "SwitchCase"); }
  8732. this.next(); // Closing brace
  8733. this.labels.pop();
  8734. return this.finishNode(node, "SwitchStatement")
  8735. };
  8736. pp$1.parseThrowStatement = function(node) {
  8737. this.next();
  8738. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  8739. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  8740. node.argument = this.parseExpression();
  8741. this.semicolon();
  8742. return this.finishNode(node, "ThrowStatement")
  8743. };
  8744. // Reused empty array added for node fields that are always empty.
  8745. var empty = [];
  8746. pp$1.parseTryStatement = function(node) {
  8747. this.next();
  8748. node.block = this.parseBlock();
  8749. node.handler = null;
  8750. if (this.type === types._catch) {
  8751. var clause = this.startNode();
  8752. this.next();
  8753. this.expect(types.parenL);
  8754. clause.param = this.parseBindingAtom();
  8755. this.enterLexicalScope();
  8756. this.checkLVal(clause.param, "let");
  8757. this.expect(types.parenR);
  8758. clause.body = this.parseBlock(false);
  8759. this.exitLexicalScope();
  8760. node.handler = this.finishNode(clause, "CatchClause");
  8761. }
  8762. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  8763. if (!node.handler && !node.finalizer)
  8764. { this.raise(node.start, "Missing catch or finally clause"); }
  8765. return this.finishNode(node, "TryStatement")
  8766. };
  8767. pp$1.parseVarStatement = function(node, kind) {
  8768. this.next();
  8769. this.parseVar(node, false, kind);
  8770. this.semicolon();
  8771. return this.finishNode(node, "VariableDeclaration")
  8772. };
  8773. pp$1.parseWhileStatement = function(node) {
  8774. this.next();
  8775. node.test = this.parseParenExpression();
  8776. this.labels.push(loopLabel);
  8777. node.body = this.parseStatement(false);
  8778. this.labels.pop();
  8779. return this.finishNode(node, "WhileStatement")
  8780. };
  8781. pp$1.parseWithStatement = function(node) {
  8782. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  8783. this.next();
  8784. node.object = this.parseParenExpression();
  8785. node.body = this.parseStatement(false);
  8786. return this.finishNode(node, "WithStatement")
  8787. };
  8788. pp$1.parseEmptyStatement = function(node) {
  8789. this.next();
  8790. return this.finishNode(node, "EmptyStatement")
  8791. };
  8792. pp$1.parseLabeledStatement = function(node, maybeName, expr) {
  8793. var this$1 = this;
  8794. for (var i$1 = 0, list = this$1.labels; i$1 < list.length; i$1 += 1)
  8795. {
  8796. var label = list[i$1];
  8797. if (label.name === maybeName)
  8798. { this$1.raise(expr.start, "Label '" + maybeName + "' is already declared");
  8799. } }
  8800. var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
  8801. for (var i = this.labels.length - 1; i >= 0; i--) {
  8802. var label$1 = this$1.labels[i];
  8803. if (label$1.statementStart == node.start) {
  8804. label$1.statementStart = this$1.start;
  8805. label$1.kind = kind;
  8806. } else { break }
  8807. }
  8808. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  8809. node.body = this.parseStatement(true);
  8810. if (node.body.type == "ClassDeclaration" ||
  8811. node.body.type == "VariableDeclaration" && node.body.kind != "var" ||
  8812. node.body.type == "FunctionDeclaration" && (this.strict || node.body.generator))
  8813. { this.raiseRecoverable(node.body.start, "Invalid labeled declaration"); }
  8814. this.labels.pop();
  8815. node.label = expr;
  8816. return this.finishNode(node, "LabeledStatement")
  8817. };
  8818. pp$1.parseExpressionStatement = function(node, expr) {
  8819. node.expression = expr;
  8820. this.semicolon();
  8821. return this.finishNode(node, "ExpressionStatement")
  8822. };
  8823. // Parse a semicolon-enclosed block of statements, handling `"use
  8824. // strict"` declarations when `allowStrict` is true (used for
  8825. // function bodies).
  8826. pp$1.parseBlock = function(createNewLexicalScope) {
  8827. var this$1 = this;
  8828. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  8829. var node = this.startNode();
  8830. node.body = [];
  8831. this.expect(types.braceL);
  8832. if (createNewLexicalScope) {
  8833. this.enterLexicalScope();
  8834. }
  8835. while (!this.eat(types.braceR)) {
  8836. var stmt = this$1.parseStatement(true);
  8837. node.body.push(stmt);
  8838. }
  8839. if (createNewLexicalScope) {
  8840. this.exitLexicalScope();
  8841. }
  8842. return this.finishNode(node, "BlockStatement")
  8843. };
  8844. // Parse a regular `for` loop. The disambiguation code in
  8845. // `parseStatement` will already have parsed the init statement or
  8846. // expression.
  8847. pp$1.parseFor = function(node, init) {
  8848. node.init = init;
  8849. this.expect(types.semi);
  8850. node.test = this.type === types.semi ? null : this.parseExpression();
  8851. this.expect(types.semi);
  8852. node.update = this.type === types.parenR ? null : this.parseExpression();
  8853. this.expect(types.parenR);
  8854. this.exitLexicalScope();
  8855. node.body = this.parseStatement(false);
  8856. this.labels.pop();
  8857. return this.finishNode(node, "ForStatement")
  8858. };
  8859. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  8860. // same from parser's perspective.
  8861. pp$1.parseForIn = function(node, init) {
  8862. var type = this.type === types._in ? "ForInStatement" : "ForOfStatement";
  8863. this.next();
  8864. node.left = init;
  8865. node.right = this.parseExpression();
  8866. this.expect(types.parenR);
  8867. this.exitLexicalScope();
  8868. node.body = this.parseStatement(false);
  8869. this.labels.pop();
  8870. return this.finishNode(node, type)
  8871. };
  8872. // Parse a list of variable declarations.
  8873. pp$1.parseVar = function(node, isFor, kind) {
  8874. var this$1 = this;
  8875. node.declarations = [];
  8876. node.kind = kind;
  8877. for (;;) {
  8878. var decl = this$1.startNode();
  8879. this$1.parseVarId(decl, kind);
  8880. if (this$1.eat(types.eq)) {
  8881. decl.init = this$1.parseMaybeAssign(isFor);
  8882. } else if (kind === "const" && !(this$1.type === types._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) {
  8883. this$1.unexpected();
  8884. } else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === types._in || this$1.isContextual("of")))) {
  8885. this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value");
  8886. } else {
  8887. decl.init = null;
  8888. }
  8889. node.declarations.push(this$1.finishNode(decl, "VariableDeclarator"));
  8890. if (!this$1.eat(types.comma)) { break }
  8891. }
  8892. return node
  8893. };
  8894. pp$1.parseVarId = function(decl, kind) {
  8895. decl.id = this.parseBindingAtom(kind);
  8896. this.checkLVal(decl.id, kind, false);
  8897. };
  8898. // Parse a function declaration or literal (depending on the
  8899. // `isStatement` parameter).
  8900. pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) {
  8901. this.initFunction(node);
  8902. if (this.options.ecmaVersion >= 6 && !isAsync)
  8903. { node.generator = this.eat(types.star); }
  8904. if (this.options.ecmaVersion >= 8)
  8905. { node.async = !!isAsync; }
  8906. if (isStatement) {
  8907. node.id = isStatement === "nullableID" && this.type != types.name ? null : this.parseIdent();
  8908. if (node.id) {
  8909. this.checkLVal(node.id, "var");
  8910. }
  8911. }
  8912. var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
  8913. oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
  8914. this.inGenerator = node.generator;
  8915. this.inAsync = node.async;
  8916. this.yieldPos = 0;
  8917. this.awaitPos = 0;
  8918. this.inFunction = true;
  8919. this.enterFunctionScope();
  8920. if (!isStatement)
  8921. { node.id = this.type == types.name ? this.parseIdent() : null; }
  8922. this.parseFunctionParams(node);
  8923. this.parseFunctionBody(node, allowExpressionBody);
  8924. this.inGenerator = oldInGen;
  8925. this.inAsync = oldInAsync;
  8926. this.yieldPos = oldYieldPos;
  8927. this.awaitPos = oldAwaitPos;
  8928. this.inFunction = oldInFunc;
  8929. return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression")
  8930. };
  8931. pp$1.parseFunctionParams = function(node) {
  8932. this.expect(types.parenL);
  8933. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  8934. this.checkYieldAwaitInDefaultParams();
  8935. };
  8936. // Parse a class declaration or literal (depending on the
  8937. // `isStatement` parameter).
  8938. pp$1.parseClass = function(node, isStatement) {
  8939. var this$1 = this;
  8940. this.next();
  8941. this.parseClassId(node, isStatement);
  8942. this.parseClassSuper(node);
  8943. var classBody = this.startNode();
  8944. var hadConstructor = false;
  8945. classBody.body = [];
  8946. this.expect(types.braceL);
  8947. while (!this.eat(types.braceR)) {
  8948. if (this$1.eat(types.semi)) { continue }
  8949. var method = this$1.startNode();
  8950. var isGenerator = this$1.eat(types.star);
  8951. var isAsync = false;
  8952. var isMaybeStatic = this$1.type === types.name && this$1.value === "static";
  8953. this$1.parsePropertyName(method);
  8954. method.static = isMaybeStatic && this$1.type !== types.parenL;
  8955. if (method.static) {
  8956. if (isGenerator) { this$1.unexpected(); }
  8957. isGenerator = this$1.eat(types.star);
  8958. this$1.parsePropertyName(method);
  8959. }
  8960. if (this$1.options.ecmaVersion >= 8 && !isGenerator && !method.computed &&
  8961. method.key.type === "Identifier" && method.key.name === "async" && this$1.type !== types.parenL &&
  8962. !this$1.canInsertSemicolon()) {
  8963. isAsync = true;
  8964. this$1.parsePropertyName(method);
  8965. }
  8966. method.kind = "method";
  8967. var isGetSet = false;
  8968. if (!method.computed) {
  8969. var key = method.key;
  8970. if (!isGenerator && !isAsync && key.type === "Identifier" && this$1.type !== types.parenL && (key.name === "get" || key.name === "set")) {
  8971. isGetSet = true;
  8972. method.kind = key.name;
  8973. key = this$1.parsePropertyName(method);
  8974. }
  8975. if (!method.static && (key.type === "Identifier" && key.name === "constructor" ||
  8976. key.type === "Literal" && key.value === "constructor")) {
  8977. if (hadConstructor) { this$1.raise(key.start, "Duplicate constructor in the same class"); }
  8978. if (isGetSet) { this$1.raise(key.start, "Constructor can't have get/set modifier"); }
  8979. if (isGenerator) { this$1.raise(key.start, "Constructor can't be a generator"); }
  8980. if (isAsync) { this$1.raise(key.start, "Constructor can't be an async method"); }
  8981. method.kind = "constructor";
  8982. hadConstructor = true;
  8983. }
  8984. }
  8985. this$1.parseClassMethod(classBody, method, isGenerator, isAsync);
  8986. if (isGetSet) {
  8987. var paramCount = method.kind === "get" ? 0 : 1;
  8988. if (method.value.params.length !== paramCount) {
  8989. var start = method.value.start;
  8990. if (method.kind === "get")
  8991. { this$1.raiseRecoverable(start, "getter should have no params"); }
  8992. else
  8993. { this$1.raiseRecoverable(start, "setter should have exactly one param"); }
  8994. } else {
  8995. if (method.kind === "set" && method.value.params[0].type === "RestElement")
  8996. { this$1.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
  8997. }
  8998. }
  8999. }
  9000. node.body = this.finishNode(classBody, "ClassBody");
  9001. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  9002. };
  9003. pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) {
  9004. method.value = this.parseMethod(isGenerator, isAsync);
  9005. classBody.body.push(this.finishNode(method, "MethodDefinition"));
  9006. };
  9007. pp$1.parseClassId = function(node, isStatement) {
  9008. node.id = this.type === types.name ? this.parseIdent() : isStatement === true ? this.unexpected() : null;
  9009. };
  9010. pp$1.parseClassSuper = function(node) {
  9011. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  9012. };
  9013. // Parses module export declaration.
  9014. pp$1.parseExport = function(node, exports) {
  9015. var this$1 = this;
  9016. this.next();
  9017. // export * from '...'
  9018. if (this.eat(types.star)) {
  9019. this.expectContextual("from");
  9020. node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
  9021. this.semicolon();
  9022. return this.finishNode(node, "ExportAllDeclaration")
  9023. }
  9024. if (this.eat(types._default)) { // export default ...
  9025. this.checkExport(exports, "default", this.lastTokStart);
  9026. var isAsync;
  9027. if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
  9028. var fNode = this.startNode();
  9029. this.next();
  9030. if (isAsync) { this.next(); }
  9031. node.declaration = this.parseFunction(fNode, "nullableID", false, isAsync);
  9032. } else if (this.type === types._class) {
  9033. var cNode = this.startNode();
  9034. node.declaration = this.parseClass(cNode, "nullableID");
  9035. } else {
  9036. node.declaration = this.parseMaybeAssign();
  9037. this.semicolon();
  9038. }
  9039. return this.finishNode(node, "ExportDefaultDeclaration")
  9040. }
  9041. // export var|const|let|function|class ...
  9042. if (this.shouldParseExportStatement()) {
  9043. node.declaration = this.parseStatement(true);
  9044. if (node.declaration.type === "VariableDeclaration")
  9045. { this.checkVariableExport(exports, node.declaration.declarations); }
  9046. else
  9047. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  9048. node.specifiers = [];
  9049. node.source = null;
  9050. } else { // export { x, y as z } [from '...']
  9051. node.declaration = null;
  9052. node.specifiers = this.parseExportSpecifiers(exports);
  9053. if (this.eatContextual("from")) {
  9054. node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
  9055. } else {
  9056. // check for keywords used as local names
  9057. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  9058. var spec = list[i];
  9059. this$1.checkUnreserved(spec.local);
  9060. }
  9061. node.source = null;
  9062. }
  9063. this.semicolon();
  9064. }
  9065. return this.finishNode(node, "ExportNamedDeclaration")
  9066. };
  9067. pp$1.checkExport = function(exports, name, pos) {
  9068. if (!exports) { return }
  9069. if (has(exports, name))
  9070. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  9071. exports[name] = true;
  9072. };
  9073. pp$1.checkPatternExport = function(exports, pat) {
  9074. var this$1 = this;
  9075. var type = pat.type;
  9076. if (type == "Identifier")
  9077. { this.checkExport(exports, pat.name, pat.start); }
  9078. else if (type == "ObjectPattern")
  9079. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  9080. {
  9081. var prop = list[i];
  9082. this$1.checkPatternExport(exports, prop.value);
  9083. } }
  9084. else if (type == "ArrayPattern")
  9085. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  9086. var elt = list$1[i$1];
  9087. if (elt) { this$1.checkPatternExport(exports, elt); }
  9088. } }
  9089. else if (type == "AssignmentPattern")
  9090. { this.checkPatternExport(exports, pat.left); }
  9091. else if (type == "ParenthesizedExpression")
  9092. { this.checkPatternExport(exports, pat.expression); }
  9093. };
  9094. pp$1.checkVariableExport = function(exports, decls) {
  9095. var this$1 = this;
  9096. if (!exports) { return }
  9097. for (var i = 0, list = decls; i < list.length; i += 1)
  9098. {
  9099. var decl = list[i];
  9100. this$1.checkPatternExport(exports, decl.id);
  9101. }
  9102. };
  9103. pp$1.shouldParseExportStatement = function() {
  9104. return this.type.keyword === "var" ||
  9105. this.type.keyword === "const" ||
  9106. this.type.keyword === "class" ||
  9107. this.type.keyword === "function" ||
  9108. this.isLet() ||
  9109. this.isAsyncFunction()
  9110. };
  9111. // Parses a comma-separated list of module exports.
  9112. pp$1.parseExportSpecifiers = function(exports) {
  9113. var this$1 = this;
  9114. var nodes = [], first = true;
  9115. // export { x, y as z } [from '...']
  9116. this.expect(types.braceL);
  9117. while (!this.eat(types.braceR)) {
  9118. if (!first) {
  9119. this$1.expect(types.comma);
  9120. if (this$1.afterTrailingComma(types.braceR)) { break }
  9121. } else { first = false; }
  9122. var node = this$1.startNode();
  9123. node.local = this$1.parseIdent(true);
  9124. node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local;
  9125. this$1.checkExport(exports, node.exported.name, node.exported.start);
  9126. nodes.push(this$1.finishNode(node, "ExportSpecifier"));
  9127. }
  9128. return nodes
  9129. };
  9130. // Parses import declaration.
  9131. pp$1.parseImport = function(node) {
  9132. this.next();
  9133. // import '...'
  9134. if (this.type === types.string) {
  9135. node.specifiers = empty;
  9136. node.source = this.parseExprAtom();
  9137. } else {
  9138. node.specifiers = this.parseImportSpecifiers();
  9139. this.expectContextual("from");
  9140. node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
  9141. }
  9142. this.semicolon();
  9143. return this.finishNode(node, "ImportDeclaration")
  9144. };
  9145. // Parses a comma-separated list of module imports.
  9146. pp$1.parseImportSpecifiers = function() {
  9147. var this$1 = this;
  9148. var nodes = [], first = true;
  9149. if (this.type === types.name) {
  9150. // import defaultObj, { x, y as z } from '...'
  9151. var node = this.startNode();
  9152. node.local = this.parseIdent();
  9153. this.checkLVal(node.local, "let");
  9154. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  9155. if (!this.eat(types.comma)) { return nodes }
  9156. }
  9157. if (this.type === types.star) {
  9158. var node$1 = this.startNode();
  9159. this.next();
  9160. this.expectContextual("as");
  9161. node$1.local = this.parseIdent();
  9162. this.checkLVal(node$1.local, "let");
  9163. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  9164. return nodes
  9165. }
  9166. this.expect(types.braceL);
  9167. while (!this.eat(types.braceR)) {
  9168. if (!first) {
  9169. this$1.expect(types.comma);
  9170. if (this$1.afterTrailingComma(types.braceR)) { break }
  9171. } else { first = false; }
  9172. var node$2 = this$1.startNode();
  9173. node$2.imported = this$1.parseIdent(true);
  9174. if (this$1.eatContextual("as")) {
  9175. node$2.local = this$1.parseIdent();
  9176. } else {
  9177. this$1.checkUnreserved(node$2.imported);
  9178. node$2.local = node$2.imported;
  9179. }
  9180. this$1.checkLVal(node$2.local, "let");
  9181. nodes.push(this$1.finishNode(node$2, "ImportSpecifier"));
  9182. }
  9183. return nodes
  9184. };
  9185. // Set `ExpressionStatement#directive` property for directive prologues.
  9186. pp$1.adaptDirectivePrologue = function(statements) {
  9187. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  9188. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  9189. }
  9190. };
  9191. pp$1.isDirectiveCandidate = function(statement) {
  9192. return (
  9193. statement.type === "ExpressionStatement" &&
  9194. statement.expression.type === "Literal" &&
  9195. typeof statement.expression.value === "string" &&
  9196. // Reject parenthesized strings.
  9197. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  9198. )
  9199. };
  9200. var pp$2 = Parser.prototype;
  9201. // Convert existing expression atom to assignable pattern
  9202. // if possible.
  9203. pp$2.toAssignable = function(node, isBinding) {
  9204. var this$1 = this;
  9205. if (this.options.ecmaVersion >= 6 && node) {
  9206. switch (node.type) {
  9207. case "Identifier":
  9208. if (this.inAsync && node.name === "await")
  9209. { this.raise(node.start, "Can not use 'await' as identifier inside an async function"); }
  9210. break
  9211. case "ObjectPattern":
  9212. case "ArrayPattern":
  9213. break
  9214. case "ObjectExpression":
  9215. node.type = "ObjectPattern";
  9216. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  9217. var prop = list[i];
  9218. if (prop.kind !== "init") { this$1.raise(prop.key.start, "Object pattern can't contain getter or setter"); }
  9219. this$1.toAssignable(prop.value, isBinding);
  9220. }
  9221. break
  9222. case "ArrayExpression":
  9223. node.type = "ArrayPattern";
  9224. this.toAssignableList(node.elements, isBinding);
  9225. break
  9226. case "AssignmentExpression":
  9227. if (node.operator === "=") {
  9228. node.type = "AssignmentPattern";
  9229. delete node.operator;
  9230. this.toAssignable(node.left, isBinding);
  9231. // falls through to AssignmentPattern
  9232. } else {
  9233. this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
  9234. break
  9235. }
  9236. case "AssignmentPattern":
  9237. break
  9238. case "ParenthesizedExpression":
  9239. this.toAssignable(node.expression, isBinding);
  9240. break
  9241. case "MemberExpression":
  9242. if (!isBinding) { break }
  9243. default:
  9244. this.raise(node.start, "Assigning to rvalue");
  9245. }
  9246. }
  9247. return node
  9248. };
  9249. // Convert list of expression atoms to binding list.
  9250. pp$2.toAssignableList = function(exprList, isBinding) {
  9251. var this$1 = this;
  9252. var end = exprList.length;
  9253. if (end) {
  9254. var last = exprList[end - 1];
  9255. if (last && last.type == "RestElement") {
  9256. --end;
  9257. } else if (last && last.type == "SpreadElement") {
  9258. last.type = "RestElement";
  9259. var arg = last.argument;
  9260. this.toAssignable(arg, isBinding);
  9261. --end;
  9262. }
  9263. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  9264. { this.unexpected(last.argument.start); }
  9265. }
  9266. for (var i = 0; i < end; i++) {
  9267. var elt = exprList[i];
  9268. if (elt) { this$1.toAssignable(elt, isBinding); }
  9269. }
  9270. return exprList
  9271. };
  9272. // Parses spread element.
  9273. pp$2.parseSpread = function(refDestructuringErrors) {
  9274. var node = this.startNode();
  9275. this.next();
  9276. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  9277. return this.finishNode(node, "SpreadElement")
  9278. };
  9279. pp$2.parseRestBinding = function() {
  9280. var node = this.startNode();
  9281. this.next();
  9282. // RestElement inside of a function parameter must be an identifier
  9283. if (this.options.ecmaVersion === 6 && this.type !== types.name)
  9284. { this.unexpected(); }
  9285. node.argument = this.parseBindingAtom();
  9286. return this.finishNode(node, "RestElement")
  9287. };
  9288. // Parses lvalue (assignable) atom.
  9289. pp$2.parseBindingAtom = function() {
  9290. if (this.options.ecmaVersion >= 6) {
  9291. switch (this.type) {
  9292. case types.bracketL:
  9293. var node = this.startNode();
  9294. this.next();
  9295. node.elements = this.parseBindingList(types.bracketR, true, true);
  9296. return this.finishNode(node, "ArrayPattern")
  9297. case types.braceL:
  9298. return this.parseObj(true)
  9299. }
  9300. }
  9301. return this.parseIdent()
  9302. };
  9303. pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  9304. var this$1 = this;
  9305. var elts = [], first = true;
  9306. while (!this.eat(close)) {
  9307. if (first) { first = false; }
  9308. else { this$1.expect(types.comma); }
  9309. if (allowEmpty && this$1.type === types.comma) {
  9310. elts.push(null);
  9311. } else if (allowTrailingComma && this$1.afterTrailingComma(close)) {
  9312. break
  9313. } else if (this$1.type === types.ellipsis) {
  9314. var rest = this$1.parseRestBinding();
  9315. this$1.parseBindingListItem(rest);
  9316. elts.push(rest);
  9317. if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); }
  9318. this$1.expect(close);
  9319. break
  9320. } else {
  9321. var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc);
  9322. this$1.parseBindingListItem(elem);
  9323. elts.push(elem);
  9324. }
  9325. }
  9326. return elts
  9327. };
  9328. pp$2.parseBindingListItem = function(param) {
  9329. return param
  9330. };
  9331. // Parses assignment pattern around given atom if possible.
  9332. pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
  9333. left = left || this.parseBindingAtom();
  9334. if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
  9335. var node = this.startNodeAt(startPos, startLoc);
  9336. node.left = left;
  9337. node.right = this.parseMaybeAssign();
  9338. return this.finishNode(node, "AssignmentPattern")
  9339. };
  9340. // Verify that a node is an lval — something that can be assigned
  9341. // to.
  9342. // bindingType can be either:
  9343. // 'var' indicating that the lval creates a 'var' binding
  9344. // 'let' indicating that the lval creates a lexical ('let' or 'const') binding
  9345. // 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references
  9346. pp$2.checkLVal = function(expr, bindingType, checkClashes) {
  9347. var this$1 = this;
  9348. switch (expr.type) {
  9349. case "Identifier":
  9350. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  9351. { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  9352. if (checkClashes) {
  9353. if (has(checkClashes, expr.name))
  9354. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  9355. checkClashes[expr.name] = true;
  9356. }
  9357. if (bindingType && bindingType !== "none") {
  9358. if (
  9359. bindingType === "var" && !this.canDeclareVarName(expr.name) ||
  9360. bindingType !== "var" && !this.canDeclareLexicalName(expr.name)
  9361. ) {
  9362. this.raiseRecoverable(expr.start, ("Identifier '" + (expr.name) + "' has already been declared"));
  9363. }
  9364. if (bindingType === "var") {
  9365. this.declareVarName(expr.name);
  9366. } else {
  9367. this.declareLexicalName(expr.name);
  9368. }
  9369. }
  9370. break
  9371. case "MemberExpression":
  9372. if (bindingType) { this.raiseRecoverable(expr.start, (bindingType ? "Binding" : "Assigning to") + " member expression"); }
  9373. break
  9374. case "ObjectPattern":
  9375. for (var i = 0, list = expr.properties; i < list.length; i += 1)
  9376. {
  9377. var prop = list[i];
  9378. this$1.checkLVal(prop.value, bindingType, checkClashes);
  9379. }
  9380. break
  9381. case "ArrayPattern":
  9382. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  9383. var elem = list$1[i$1];
  9384. if (elem) { this$1.checkLVal(elem, bindingType, checkClashes); }
  9385. }
  9386. break
  9387. case "AssignmentPattern":
  9388. this.checkLVal(expr.left, bindingType, checkClashes);
  9389. break
  9390. case "RestElement":
  9391. this.checkLVal(expr.argument, bindingType, checkClashes);
  9392. break
  9393. case "ParenthesizedExpression":
  9394. this.checkLVal(expr.expression, bindingType, checkClashes);
  9395. break
  9396. default:
  9397. this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue");
  9398. }
  9399. };
  9400. // A recursive descent parser operates by defining functions for all
  9401. // syntactic elements, and recursively calling those, each function
  9402. // advancing the input stream and returning an AST node. Precedence
  9403. // of constructs (for example, the fact that `!x[1]` means `!(x[1])`
  9404. // instead of `(!x)[1]` is handled by the fact that the parser
  9405. // function that parses unary prefix operators is called first, and
  9406. // in turn calls the function that parses `[]` subscripts — that
  9407. // way, it'll receive the node for `x[1]` already parsed, and wraps
  9408. // *that* in the unary operator node.
  9409. //
  9410. // Acorn uses an [operator precedence parser][opp] to handle binary
  9411. // operator precedence, because it is much more compact than using
  9412. // the technique outlined above, which uses different, nesting
  9413. // functions to specify precedence, for all of the ten binary
  9414. // precedence levels that JavaScript defines.
  9415. //
  9416. // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
  9417. var pp$3 = Parser.prototype;
  9418. // Check if property name clashes with already added.
  9419. // Object/class getters and setters are not allowed to clash —
  9420. // either with each other or with an init property — and in
  9421. // strict mode, init properties are also not allowed to be repeated.
  9422. pp$3.checkPropClash = function(prop, propHash) {
  9423. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  9424. { return }
  9425. var key = prop.key;
  9426. var name;
  9427. switch (key.type) {
  9428. case "Identifier": name = key.name; break
  9429. case "Literal": name = String(key.value); break
  9430. default: return
  9431. }
  9432. var kind = prop.kind;
  9433. if (this.options.ecmaVersion >= 6) {
  9434. if (name === "__proto__" && kind === "init") {
  9435. if (propHash.proto) { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
  9436. propHash.proto = true;
  9437. }
  9438. return
  9439. }
  9440. name = "$" + name;
  9441. var other = propHash[name];
  9442. if (other) {
  9443. var redefinition;
  9444. if (kind === "init") {
  9445. redefinition = this.strict && other.init || other.get || other.set;
  9446. } else {
  9447. redefinition = other.init || other[kind];
  9448. }
  9449. if (redefinition)
  9450. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  9451. } else {
  9452. other = propHash[name] = {
  9453. init: false,
  9454. get: false,
  9455. set: false
  9456. };
  9457. }
  9458. other[kind] = true;
  9459. };
  9460. // ### Expression parsing
  9461. // These nest, from the most general expression type at the top to
  9462. // 'atomic', nondivisible expression types at the bottom. Most of
  9463. // the functions will simply let the function(s) below them parse,
  9464. // and, *if* the syntactic construct they handle is present, wrap
  9465. // the AST node that the inner parser gave them in another node.
  9466. // Parse a full expression. The optional arguments are used to
  9467. // forbid the `in` operator (in for loops initalization expressions)
  9468. // and provide reference for storing '=' operator inside shorthand
  9469. // property assignment in contexts where both object expression
  9470. // and object pattern might appear (so it's possible to raise
  9471. // delayed syntax error at correct position).
  9472. pp$3.parseExpression = function(noIn, refDestructuringErrors) {
  9473. var this$1 = this;
  9474. var startPos = this.start, startLoc = this.startLoc;
  9475. var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
  9476. if (this.type === types.comma) {
  9477. var node = this.startNodeAt(startPos, startLoc);
  9478. node.expressions = [expr];
  9479. while (this.eat(types.comma)) { node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)); }
  9480. return this.finishNode(node, "SequenceExpression")
  9481. }
  9482. return expr
  9483. };
  9484. // Parse an assignment expression. This includes applications of
  9485. // operators like `+=`.
  9486. pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
  9487. if (this.inGenerator && this.isContextual("yield")) { return this.parseYield() }
  9488. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
  9489. if (refDestructuringErrors) {
  9490. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  9491. oldTrailingComma = refDestructuringErrors.trailingComma;
  9492. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  9493. } else {
  9494. refDestructuringErrors = new DestructuringErrors;
  9495. ownDestructuringErrors = true;
  9496. }
  9497. var startPos = this.start, startLoc = this.startLoc;
  9498. if (this.type == types.parenL || this.type == types.name)
  9499. { this.potentialArrowAt = this.start; }
  9500. var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
  9501. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  9502. if (this.type.isAssign) {
  9503. this.checkPatternErrors(refDestructuringErrors, true);
  9504. if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); }
  9505. var node = this.startNodeAt(startPos, startLoc);
  9506. node.operator = this.value;
  9507. node.left = this.type === types.eq ? this.toAssignable(left) : left;
  9508. refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly
  9509. this.checkLVal(left);
  9510. this.next();
  9511. node.right = this.parseMaybeAssign(noIn);
  9512. return this.finishNode(node, "AssignmentExpression")
  9513. } else {
  9514. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  9515. }
  9516. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  9517. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  9518. return left
  9519. };
  9520. // Parse a ternary conditional (`?:`) operator.
  9521. pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
  9522. var startPos = this.start, startLoc = this.startLoc;
  9523. var expr = this.parseExprOps(noIn, refDestructuringErrors);
  9524. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  9525. if (this.eat(types.question)) {
  9526. var node = this.startNodeAt(startPos, startLoc);
  9527. node.test = expr;
  9528. node.consequent = this.parseMaybeAssign();
  9529. this.expect(types.colon);
  9530. node.alternate = this.parseMaybeAssign(noIn);
  9531. return this.finishNode(node, "ConditionalExpression")
  9532. }
  9533. return expr
  9534. };
  9535. // Start the precedence parser.
  9536. pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
  9537. var startPos = this.start, startLoc = this.startLoc;
  9538. var expr = this.parseMaybeUnary(refDestructuringErrors, false);
  9539. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  9540. return expr.start == startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
  9541. };
  9542. // Parse binary operators with the operator precedence parsing
  9543. // algorithm. `left` is the left-hand side of the operator.
  9544. // `minPrec` provides context that allows the function to stop and
  9545. // defer further parser to one of its callers when it encounters an
  9546. // operator that has a lower precedence than the set it is parsing.
  9547. pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  9548. var prec = this.type.binop;
  9549. if (prec != null && (!noIn || this.type !== types._in)) {
  9550. if (prec > minPrec) {
  9551. var logical = this.type === types.logicalOR || this.type === types.logicalAND;
  9552. var op = this.value;
  9553. this.next();
  9554. var startPos = this.start, startLoc = this.startLoc;
  9555. var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
  9556. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical);
  9557. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
  9558. }
  9559. }
  9560. return left
  9561. };
  9562. pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  9563. var node = this.startNodeAt(startPos, startLoc);
  9564. node.left = left;
  9565. node.operator = op;
  9566. node.right = right;
  9567. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  9568. };
  9569. // Parse unary operators, both prefix and postfix.
  9570. pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
  9571. var this$1 = this;
  9572. var startPos = this.start, startLoc = this.startLoc, expr;
  9573. if (this.inAsync && this.isContextual("await")) {
  9574. expr = this.parseAwait();
  9575. sawUnary = true;
  9576. } else if (this.type.prefix) {
  9577. var node = this.startNode(), update = this.type === types.incDec;
  9578. node.operator = this.value;
  9579. node.prefix = true;
  9580. this.next();
  9581. node.argument = this.parseMaybeUnary(null, true);
  9582. this.checkExpressionErrors(refDestructuringErrors, true);
  9583. if (update) { this.checkLVal(node.argument); }
  9584. else if (this.strict && node.operator === "delete" &&
  9585. node.argument.type === "Identifier")
  9586. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  9587. else { sawUnary = true; }
  9588. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  9589. } else {
  9590. expr = this.parseExprSubscripts(refDestructuringErrors);
  9591. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  9592. while (this.type.postfix && !this.canInsertSemicolon()) {
  9593. var node$1 = this$1.startNodeAt(startPos, startLoc);
  9594. node$1.operator = this$1.value;
  9595. node$1.prefix = false;
  9596. node$1.argument = expr;
  9597. this$1.checkLVal(expr);
  9598. this$1.next();
  9599. expr = this$1.finishNode(node$1, "UpdateExpression");
  9600. }
  9601. }
  9602. if (!sawUnary && this.eat(types.starstar))
  9603. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
  9604. else
  9605. { return expr }
  9606. };
  9607. // Parse call, dot, and `[]`-subscript expressions.
  9608. pp$3.parseExprSubscripts = function(refDestructuringErrors) {
  9609. var startPos = this.start, startLoc = this.startLoc;
  9610. var expr = this.parseExprAtom(refDestructuringErrors);
  9611. var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")";
  9612. if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr }
  9613. var result = this.parseSubscripts(expr, startPos, startLoc);
  9614. if (refDestructuringErrors && result.type === "MemberExpression") {
  9615. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  9616. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  9617. }
  9618. return result
  9619. };
  9620. pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
  9621. var this$1 = this;
  9622. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  9623. this.lastTokEnd == base.end && !this.canInsertSemicolon();
  9624. for (var computed = (void 0);;) {
  9625. if ((computed = this$1.eat(types.bracketL)) || this$1.eat(types.dot)) {
  9626. var node = this$1.startNodeAt(startPos, startLoc);
  9627. node.object = base;
  9628. node.property = computed ? this$1.parseExpression() : this$1.parseIdent(true);
  9629. node.computed = !!computed;
  9630. if (computed) { this$1.expect(types.bracketR); }
  9631. base = this$1.finishNode(node, "MemberExpression");
  9632. } else if (!noCalls && this$1.eat(types.parenL)) {
  9633. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos;
  9634. this$1.yieldPos = 0;
  9635. this$1.awaitPos = 0;
  9636. var exprList = this$1.parseExprList(types.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors);
  9637. if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(types.arrow)) {
  9638. this$1.checkPatternErrors(refDestructuringErrors, false);
  9639. this$1.checkYieldAwaitInDefaultParams();
  9640. this$1.yieldPos = oldYieldPos;
  9641. this$1.awaitPos = oldAwaitPos;
  9642. return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true)
  9643. }
  9644. this$1.checkExpressionErrors(refDestructuringErrors, true);
  9645. this$1.yieldPos = oldYieldPos || this$1.yieldPos;
  9646. this$1.awaitPos = oldAwaitPos || this$1.awaitPos;
  9647. var node$1 = this$1.startNodeAt(startPos, startLoc);
  9648. node$1.callee = base;
  9649. node$1.arguments = exprList;
  9650. base = this$1.finishNode(node$1, "CallExpression");
  9651. } else if (this$1.type === types.backQuote) {
  9652. var node$2 = this$1.startNodeAt(startPos, startLoc);
  9653. node$2.tag = base;
  9654. node$2.quasi = this$1.parseTemplate({isTagged: true});
  9655. base = this$1.finishNode(node$2, "TaggedTemplateExpression");
  9656. } else {
  9657. return base
  9658. }
  9659. }
  9660. };
  9661. // Parse an atomic expression — either a single token that is an
  9662. // expression, an expression started by a keyword like `function` or
  9663. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  9664. // or `{}`.
  9665. pp$3.parseExprAtom = function(refDestructuringErrors) {
  9666. var node, canBeArrow = this.potentialArrowAt == this.start;
  9667. switch (this.type) {
  9668. case types._super:
  9669. if (!this.inFunction)
  9670. { this.raise(this.start, "'super' outside of function or class"); }
  9671. node = this.startNode();
  9672. this.next();
  9673. // The `super` keyword can appear at below:
  9674. // SuperProperty:
  9675. // super [ Expression ]
  9676. // super . IdentifierName
  9677. // SuperCall:
  9678. // super Arguments
  9679. if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
  9680. { this.unexpected(); }
  9681. return this.finishNode(node, "Super")
  9682. case types._this:
  9683. node = this.startNode();
  9684. this.next();
  9685. return this.finishNode(node, "ThisExpression")
  9686. case types.name:
  9687. var startPos = this.start, startLoc = this.startLoc;
  9688. var id = this.parseIdent(this.type !== types.name);
  9689. if (this.options.ecmaVersion >= 8 && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
  9690. { return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true) }
  9691. if (canBeArrow && !this.canInsertSemicolon()) {
  9692. if (this.eat(types.arrow))
  9693. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
  9694. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name) {
  9695. id = this.parseIdent();
  9696. if (this.canInsertSemicolon() || !this.eat(types.arrow))
  9697. { this.unexpected(); }
  9698. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
  9699. }
  9700. }
  9701. return id
  9702. case types.regexp:
  9703. var value = this.value;
  9704. node = this.parseLiteral(value.value);
  9705. node.regex = {pattern: value.pattern, flags: value.flags};
  9706. return node
  9707. case types.num: case types.string:
  9708. return this.parseLiteral(this.value)
  9709. case types._null: case types._true: case types._false:
  9710. node = this.startNode();
  9711. node.value = this.type === types._null ? null : this.type === types._true;
  9712. node.raw = this.type.keyword;
  9713. this.next();
  9714. return this.finishNode(node, "Literal")
  9715. case types.parenL:
  9716. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
  9717. if (refDestructuringErrors) {
  9718. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  9719. { refDestructuringErrors.parenthesizedAssign = start; }
  9720. if (refDestructuringErrors.parenthesizedBind < 0)
  9721. { refDestructuringErrors.parenthesizedBind = start; }
  9722. }
  9723. return expr
  9724. case types.bracketL:
  9725. node = this.startNode();
  9726. this.next();
  9727. node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
  9728. return this.finishNode(node, "ArrayExpression")
  9729. case types.braceL:
  9730. return this.parseObj(false, refDestructuringErrors)
  9731. case types._function:
  9732. node = this.startNode();
  9733. this.next();
  9734. return this.parseFunction(node, false)
  9735. case types._class:
  9736. return this.parseClass(this.startNode(), false)
  9737. case types._new:
  9738. return this.parseNew()
  9739. case types.backQuote:
  9740. return this.parseTemplate()
  9741. default:
  9742. this.unexpected();
  9743. }
  9744. };
  9745. pp$3.parseLiteral = function(value) {
  9746. var node = this.startNode();
  9747. node.value = value;
  9748. node.raw = this.input.slice(this.start, this.end);
  9749. this.next();
  9750. return this.finishNode(node, "Literal")
  9751. };
  9752. pp$3.parseParenExpression = function() {
  9753. this.expect(types.parenL);
  9754. var val = this.parseExpression();
  9755. this.expect(types.parenR);
  9756. return val
  9757. };
  9758. pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
  9759. var this$1 = this;
  9760. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  9761. if (this.options.ecmaVersion >= 6) {
  9762. this.next();
  9763. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  9764. var exprList = [], first = true, lastIsComma = false;
  9765. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart, innerParenStart;
  9766. this.yieldPos = 0;
  9767. this.awaitPos = 0;
  9768. while (this.type !== types.parenR) {
  9769. first ? first = false : this$1.expect(types.comma);
  9770. if (allowTrailingComma && this$1.afterTrailingComma(types.parenR, true)) {
  9771. lastIsComma = true;
  9772. break
  9773. } else if (this$1.type === types.ellipsis) {
  9774. spreadStart = this$1.start;
  9775. exprList.push(this$1.parseParenItem(this$1.parseRestBinding()));
  9776. if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); }
  9777. break
  9778. } else {
  9779. if (this$1.type === types.parenL && !innerParenStart) {
  9780. innerParenStart = this$1.start;
  9781. }
  9782. exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem));
  9783. }
  9784. }
  9785. var innerEndPos = this.start, innerEndLoc = this.startLoc;
  9786. this.expect(types.parenR);
  9787. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  9788. this.checkPatternErrors(refDestructuringErrors, false);
  9789. this.checkYieldAwaitInDefaultParams();
  9790. if (innerParenStart) { this.unexpected(innerParenStart); }
  9791. this.yieldPos = oldYieldPos;
  9792. this.awaitPos = oldAwaitPos;
  9793. return this.parseParenArrowList(startPos, startLoc, exprList)
  9794. }
  9795. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  9796. if (spreadStart) { this.unexpected(spreadStart); }
  9797. this.checkExpressionErrors(refDestructuringErrors, true);
  9798. this.yieldPos = oldYieldPos || this.yieldPos;
  9799. this.awaitPos = oldAwaitPos || this.awaitPos;
  9800. if (exprList.length > 1) {
  9801. val = this.startNodeAt(innerStartPos, innerStartLoc);
  9802. val.expressions = exprList;
  9803. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  9804. } else {
  9805. val = exprList[0];
  9806. }
  9807. } else {
  9808. val = this.parseParenExpression();
  9809. }
  9810. if (this.options.preserveParens) {
  9811. var par = this.startNodeAt(startPos, startLoc);
  9812. par.expression = val;
  9813. return this.finishNode(par, "ParenthesizedExpression")
  9814. } else {
  9815. return val
  9816. }
  9817. };
  9818. pp$3.parseParenItem = function(item) {
  9819. return item
  9820. };
  9821. pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
  9822. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
  9823. };
  9824. // New's precedence is slightly tricky. It must allow its argument to
  9825. // be a `[]` or dot subscript expression, but not a call — at least,
  9826. // not without wrapping it in parentheses. Thus, it uses the noCalls
  9827. // argument to parseSubscripts to prevent it from consuming the
  9828. // argument list.
  9829. var empty$1 = [];
  9830. pp$3.parseNew = function() {
  9831. var node = this.startNode();
  9832. var meta = this.parseIdent(true);
  9833. if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
  9834. node.meta = meta;
  9835. node.property = this.parseIdent(true);
  9836. if (node.property.name !== "target")
  9837. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); }
  9838. if (!this.inFunction)
  9839. { this.raiseRecoverable(node.start, "new.target can only be used in functions"); }
  9840. return this.finishNode(node, "MetaProperty")
  9841. }
  9842. var startPos = this.start, startLoc = this.startLoc;
  9843. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  9844. if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
  9845. else { node.arguments = empty$1; }
  9846. return this.finishNode(node, "NewExpression")
  9847. };
  9848. // Parse template expression.
  9849. pp$3.parseTemplateElement = function(ref) {
  9850. var isTagged = ref.isTagged;
  9851. var elem = this.startNode();
  9852. if (this.type === types.invalidTemplate) {
  9853. if (!isTagged) {
  9854. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  9855. }
  9856. elem.value = {
  9857. raw: this.value,
  9858. cooked: null
  9859. };
  9860. } else {
  9861. elem.value = {
  9862. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  9863. cooked: this.value
  9864. };
  9865. }
  9866. this.next();
  9867. elem.tail = this.type === types.backQuote;
  9868. return this.finishNode(elem, "TemplateElement")
  9869. };
  9870. pp$3.parseTemplate = function(ref) {
  9871. var this$1 = this;
  9872. if ( ref === void 0 ) ref = {};
  9873. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  9874. var node = this.startNode();
  9875. this.next();
  9876. node.expressions = [];
  9877. var curElt = this.parseTemplateElement({isTagged: isTagged});
  9878. node.quasis = [curElt];
  9879. while (!curElt.tail) {
  9880. this$1.expect(types.dollarBraceL);
  9881. node.expressions.push(this$1.parseExpression());
  9882. this$1.expect(types.braceR);
  9883. node.quasis.push(curElt = this$1.parseTemplateElement({isTagged: isTagged}));
  9884. }
  9885. this.next();
  9886. return this.finishNode(node, "TemplateLiteral")
  9887. };
  9888. pp$3.isAsyncProp = function(prop) {
  9889. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  9890. (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword) &&
  9891. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  9892. };
  9893. // Parse an object literal or binding pattern.
  9894. pp$3.parseObj = function(isPattern, refDestructuringErrors) {
  9895. var this$1 = this;
  9896. var node = this.startNode(), first = true, propHash = {};
  9897. node.properties = [];
  9898. this.next();
  9899. while (!this.eat(types.braceR)) {
  9900. if (!first) {
  9901. this$1.expect(types.comma);
  9902. if (this$1.afterTrailingComma(types.braceR)) { break }
  9903. } else { first = false; }
  9904. var prop = this$1.parseProperty(isPattern, refDestructuringErrors);
  9905. this$1.checkPropClash(prop, propHash);
  9906. node.properties.push(prop);
  9907. }
  9908. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  9909. };
  9910. pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
  9911. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  9912. if (this.options.ecmaVersion >= 6) {
  9913. prop.method = false;
  9914. prop.shorthand = false;
  9915. if (isPattern || refDestructuringErrors) {
  9916. startPos = this.start;
  9917. startLoc = this.startLoc;
  9918. }
  9919. if (!isPattern)
  9920. { isGenerator = this.eat(types.star); }
  9921. }
  9922. this.parsePropertyName(prop);
  9923. if (!isPattern && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  9924. isAsync = true;
  9925. this.parsePropertyName(prop, refDestructuringErrors);
  9926. } else {
  9927. isAsync = false;
  9928. }
  9929. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors);
  9930. return this.finishNode(prop, "Property")
  9931. };
  9932. pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) {
  9933. if ((isGenerator || isAsync) && this.type === types.colon)
  9934. { this.unexpected(); }
  9935. if (this.eat(types.colon)) {
  9936. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  9937. prop.kind = "init";
  9938. } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
  9939. if (isPattern) { this.unexpected(); }
  9940. prop.kind = "init";
  9941. prop.method = true;
  9942. prop.value = this.parseMethod(isGenerator, isAsync);
  9943. } else if (!isPattern &&
  9944. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  9945. (prop.key.name === "get" || prop.key.name === "set") &&
  9946. (this.type != types.comma && this.type != types.braceR)) {
  9947. if (isGenerator || isAsync) { this.unexpected(); }
  9948. prop.kind = prop.key.name;
  9949. this.parsePropertyName(prop);
  9950. prop.value = this.parseMethod(false);
  9951. var paramCount = prop.kind === "get" ? 0 : 1;
  9952. if (prop.value.params.length !== paramCount) {
  9953. var start = prop.value.start;
  9954. if (prop.kind === "get")
  9955. { this.raiseRecoverable(start, "getter should have no params"); }
  9956. else
  9957. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  9958. } else {
  9959. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  9960. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  9961. }
  9962. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  9963. this.checkUnreserved(prop.key);
  9964. prop.kind = "init";
  9965. if (isPattern) {
  9966. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
  9967. } else if (this.type === types.eq && refDestructuringErrors) {
  9968. if (refDestructuringErrors.shorthandAssign < 0)
  9969. { refDestructuringErrors.shorthandAssign = this.start; }
  9970. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
  9971. } else {
  9972. prop.value = prop.key;
  9973. }
  9974. prop.shorthand = true;
  9975. } else { this.unexpected(); }
  9976. };
  9977. pp$3.parsePropertyName = function(prop) {
  9978. if (this.options.ecmaVersion >= 6) {
  9979. if (this.eat(types.bracketL)) {
  9980. prop.computed = true;
  9981. prop.key = this.parseMaybeAssign();
  9982. this.expect(types.bracketR);
  9983. return prop.key
  9984. } else {
  9985. prop.computed = false;
  9986. }
  9987. }
  9988. return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(true)
  9989. };
  9990. // Initialize empty function node.
  9991. pp$3.initFunction = function(node) {
  9992. node.id = null;
  9993. if (this.options.ecmaVersion >= 6) {
  9994. node.generator = false;
  9995. node.expression = false;
  9996. }
  9997. if (this.options.ecmaVersion >= 8)
  9998. { node.async = false; }
  9999. };
  10000. // Parse object or class method.
  10001. pp$3.parseMethod = function(isGenerator, isAsync) {
  10002. var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync,
  10003. oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
  10004. this.initFunction(node);
  10005. if (this.options.ecmaVersion >= 6)
  10006. { node.generator = isGenerator; }
  10007. if (this.options.ecmaVersion >= 8)
  10008. { node.async = !!isAsync; }
  10009. this.inGenerator = node.generator;
  10010. this.inAsync = node.async;
  10011. this.yieldPos = 0;
  10012. this.awaitPos = 0;
  10013. this.inFunction = true;
  10014. this.enterFunctionScope();
  10015. this.expect(types.parenL);
  10016. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  10017. this.checkYieldAwaitInDefaultParams();
  10018. this.parseFunctionBody(node, false);
  10019. this.inGenerator = oldInGen;
  10020. this.inAsync = oldInAsync;
  10021. this.yieldPos = oldYieldPos;
  10022. this.awaitPos = oldAwaitPos;
  10023. this.inFunction = oldInFunc;
  10024. return this.finishNode(node, "FunctionExpression")
  10025. };
  10026. // Parse arrow function expression with given parameters.
  10027. pp$3.parseArrowExpression = function(node, params, isAsync) {
  10028. var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
  10029. oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction;
  10030. this.enterFunctionScope();
  10031. this.initFunction(node);
  10032. if (this.options.ecmaVersion >= 8)
  10033. { node.async = !!isAsync; }
  10034. this.inGenerator = false;
  10035. this.inAsync = node.async;
  10036. this.yieldPos = 0;
  10037. this.awaitPos = 0;
  10038. this.inFunction = true;
  10039. node.params = this.toAssignableList(params, true);
  10040. this.parseFunctionBody(node, true);
  10041. this.inGenerator = oldInGen;
  10042. this.inAsync = oldInAsync;
  10043. this.yieldPos = oldYieldPos;
  10044. this.awaitPos = oldAwaitPos;
  10045. this.inFunction = oldInFunc;
  10046. return this.finishNode(node, "ArrowFunctionExpression")
  10047. };
  10048. // Parse function body and check parameters.
  10049. pp$3.parseFunctionBody = function(node, isArrowFunction) {
  10050. var isExpression = isArrowFunction && this.type !== types.braceL;
  10051. var oldStrict = this.strict, useStrict = false;
  10052. if (isExpression) {
  10053. node.body = this.parseMaybeAssign();
  10054. node.expression = true;
  10055. this.checkParams(node, false);
  10056. } else {
  10057. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  10058. if (!oldStrict || nonSimple) {
  10059. useStrict = this.strictDirective(this.end);
  10060. // If this is a strict mode function, verify that argument names
  10061. // are not repeated, and it does not try to bind the words `eval`
  10062. // or `arguments`.
  10063. if (useStrict && nonSimple)
  10064. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  10065. }
  10066. // Start a new scope with regard to labels and the `inFunction`
  10067. // flag (restore them to their old value afterwards).
  10068. var oldLabels = this.labels;
  10069. this.labels = [];
  10070. if (useStrict) { this.strict = true; }
  10071. // Add the params to varDeclaredNames to ensure that an error is thrown
  10072. // if a let/const declaration in the function clashes with one of the params.
  10073. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && this.isSimpleParamList(node.params));
  10074. node.body = this.parseBlock(false);
  10075. node.expression = false;
  10076. this.adaptDirectivePrologue(node.body.body);
  10077. this.labels = oldLabels;
  10078. }
  10079. this.exitFunctionScope();
  10080. if (this.strict && node.id) {
  10081. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  10082. this.checkLVal(node.id, "none");
  10083. }
  10084. this.strict = oldStrict;
  10085. };
  10086. pp$3.isSimpleParamList = function(params) {
  10087. for (var i = 0, list = params; i < list.length; i += 1)
  10088. {
  10089. var param = list[i];
  10090. if (param.type !== "Identifier") { return false
  10091. } }
  10092. return true
  10093. };
  10094. // Checks function params for various disallowed patterns such as using "eval"
  10095. // or "arguments" and duplicate parameters.
  10096. pp$3.checkParams = function(node, allowDuplicates) {
  10097. var this$1 = this;
  10098. var nameHash = {};
  10099. for (var i = 0, list = node.params; i < list.length; i += 1)
  10100. {
  10101. var param = list[i];
  10102. this$1.checkLVal(param, "var", allowDuplicates ? null : nameHash);
  10103. }
  10104. };
  10105. // Parses a comma-separated list of expressions, and returns them as
  10106. // an array. `close` is the token type that ends the list, and
  10107. // `allowEmpty` can be turned on to allow subsequent commas with
  10108. // nothing in between them to be parsed as `null` (which is needed
  10109. // for array literals).
  10110. pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  10111. var this$1 = this;
  10112. var elts = [], first = true;
  10113. while (!this.eat(close)) {
  10114. if (!first) {
  10115. this$1.expect(types.comma);
  10116. if (allowTrailingComma && this$1.afterTrailingComma(close)) { break }
  10117. } else { first = false; }
  10118. var elt = (void 0);
  10119. if (allowEmpty && this$1.type === types.comma)
  10120. { elt = null; }
  10121. else if (this$1.type === types.ellipsis) {
  10122. elt = this$1.parseSpread(refDestructuringErrors);
  10123. if (refDestructuringErrors && this$1.type === types.comma && refDestructuringErrors.trailingComma < 0)
  10124. { refDestructuringErrors.trailingComma = this$1.start; }
  10125. } else {
  10126. elt = this$1.parseMaybeAssign(false, refDestructuringErrors);
  10127. }
  10128. elts.push(elt);
  10129. }
  10130. return elts
  10131. };
  10132. pp$3.checkUnreserved = function(ref) {
  10133. var start = ref.start;
  10134. var end = ref.end;
  10135. var name = ref.name;
  10136. if (this.inGenerator && name === "yield")
  10137. { this.raiseRecoverable(start, "Can not use 'yield' as identifier inside a generator"); }
  10138. if (this.inAsync && name === "await")
  10139. { this.raiseRecoverable(start, "Can not use 'await' as identifier inside an async function"); }
  10140. if (this.isKeyword(name))
  10141. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  10142. if (this.options.ecmaVersion < 6 &&
  10143. this.input.slice(start, end).indexOf("\\") != -1) { return }
  10144. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  10145. if (re.test(name))
  10146. { this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); }
  10147. };
  10148. // Parse the next token as an identifier. If `liberal` is true (used
  10149. // when parsing properties), it will also convert keywords into
  10150. // identifiers.
  10151. pp$3.parseIdent = function(liberal, isBinding) {
  10152. var node = this.startNode();
  10153. if (liberal && this.options.allowReserved == "never") { liberal = false; }
  10154. if (this.type === types.name) {
  10155. node.name = this.value;
  10156. } else if (this.type.keyword) {
  10157. node.name = this.type.keyword;
  10158. // To fix https://github.com/ternjs/acorn/issues/575
  10159. // `class` and `function` keywords push new context into this.context.
  10160. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  10161. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  10162. if ((node.name === "class" || node.name === "function") &&
  10163. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  10164. this.context.pop();
  10165. }
  10166. } else {
  10167. this.unexpected();
  10168. }
  10169. this.next();
  10170. this.finishNode(node, "Identifier");
  10171. if (!liberal) { this.checkUnreserved(node); }
  10172. return node
  10173. };
  10174. // Parses yield expression inside generator.
  10175. pp$3.parseYield = function() {
  10176. if (!this.yieldPos) { this.yieldPos = this.start; }
  10177. var node = this.startNode();
  10178. this.next();
  10179. if (this.type == types.semi || this.canInsertSemicolon() || (this.type != types.star && !this.type.startsExpr)) {
  10180. node.delegate = false;
  10181. node.argument = null;
  10182. } else {
  10183. node.delegate = this.eat(types.star);
  10184. node.argument = this.parseMaybeAssign();
  10185. }
  10186. return this.finishNode(node, "YieldExpression")
  10187. };
  10188. pp$3.parseAwait = function() {
  10189. if (!this.awaitPos) { this.awaitPos = this.start; }
  10190. var node = this.startNode();
  10191. this.next();
  10192. node.argument = this.parseMaybeUnary(null, true);
  10193. return this.finishNode(node, "AwaitExpression")
  10194. };
  10195. var pp$4 = Parser.prototype;
  10196. // This function is used to raise exceptions on parse errors. It
  10197. // takes an offset integer (into the current `input`) to indicate
  10198. // the location of the error, attaches the position to the end
  10199. // of the error message, and then raises a `SyntaxError` with that
  10200. // message.
  10201. pp$4.raise = function(pos, message) {
  10202. var loc = getLineInfo(this.input, pos);
  10203. message += " (" + loc.line + ":" + loc.column + ")";
  10204. var err = new SyntaxError(message);
  10205. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  10206. throw err
  10207. };
  10208. pp$4.raiseRecoverable = pp$4.raise;
  10209. pp$4.curPosition = function() {
  10210. if (this.options.locations) {
  10211. return new Position(this.curLine, this.pos - this.lineStart)
  10212. }
  10213. };
  10214. var pp$5 = Parser.prototype;
  10215. // Object.assign polyfill
  10216. var assign = Object.assign || function(target) {
  10217. var sources = [], len = arguments.length - 1;
  10218. while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
  10219. for (var i = 0, list = sources; i < list.length; i += 1) {
  10220. var source = list[i];
  10221. for (var key in source) {
  10222. if (has(source, key)) {
  10223. target[key] = source[key];
  10224. }
  10225. }
  10226. }
  10227. return target
  10228. };
  10229. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  10230. pp$5.enterFunctionScope = function() {
  10231. // var: a hash of var-declared names in the current lexical scope
  10232. // lexical: a hash of lexically-declared names in the current lexical scope
  10233. // childVar: a hash of var-declared names in all child lexical scopes of the current lexical scope (within the current function scope)
  10234. // parentLexical: a hash of lexically-declared names in all parent lexical scopes of the current lexical scope (within the current function scope)
  10235. this.scopeStack.push({var: {}, lexical: {}, childVar: {}, parentLexical: {}});
  10236. };
  10237. pp$5.exitFunctionScope = function() {
  10238. this.scopeStack.pop();
  10239. };
  10240. pp$5.enterLexicalScope = function() {
  10241. var parentScope = this.scopeStack[this.scopeStack.length - 1];
  10242. var childScope = {var: {}, lexical: {}, childVar: {}, parentLexical: {}};
  10243. this.scopeStack.push(childScope);
  10244. assign(childScope.parentLexical, parentScope.lexical, parentScope.parentLexical);
  10245. };
  10246. pp$5.exitLexicalScope = function() {
  10247. var childScope = this.scopeStack.pop();
  10248. var parentScope = this.scopeStack[this.scopeStack.length - 1];
  10249. assign(parentScope.childVar, childScope.var, childScope.childVar);
  10250. };
  10251. /**
  10252. * A name can be declared with `var` if there are no variables with the same name declared with `let`/`const`
  10253. * in the current lexical scope or any of the parent lexical scopes in this function.
  10254. */
  10255. pp$5.canDeclareVarName = function(name) {
  10256. var currentScope = this.scopeStack[this.scopeStack.length - 1];
  10257. return !has(currentScope.lexical, name) && !has(currentScope.parentLexical, name)
  10258. };
  10259. /**
  10260. * A name can be declared with `let`/`const` if there are no variables with the same name declared with `let`/`const`
  10261. * in the current scope, and there are no variables with the same name declared with `var` in the current scope or in
  10262. * any child lexical scopes in this function.
  10263. */
  10264. pp$5.canDeclareLexicalName = function(name) {
  10265. var currentScope = this.scopeStack[this.scopeStack.length - 1];
  10266. return !has(currentScope.lexical, name) && !has(currentScope.var, name) && !has(currentScope.childVar, name)
  10267. };
  10268. pp$5.declareVarName = function(name) {
  10269. this.scopeStack[this.scopeStack.length - 1].var[name] = true;
  10270. };
  10271. pp$5.declareLexicalName = function(name) {
  10272. this.scopeStack[this.scopeStack.length - 1].lexical[name] = true;
  10273. };
  10274. var Node = function Node(parser, pos, loc) {
  10275. this.type = "";
  10276. this.start = pos;
  10277. this.end = 0;
  10278. if (parser.options.locations)
  10279. { this.loc = new SourceLocation(parser, loc); }
  10280. if (parser.options.directSourceFile)
  10281. { this.sourceFile = parser.options.directSourceFile; }
  10282. if (parser.options.ranges)
  10283. { this.range = [pos, 0]; }
  10284. };
  10285. // Start an AST node, attaching a start offset.
  10286. var pp$6 = Parser.prototype;
  10287. pp$6.startNode = function() {
  10288. return new Node(this, this.start, this.startLoc)
  10289. };
  10290. pp$6.startNodeAt = function(pos, loc) {
  10291. return new Node(this, pos, loc)
  10292. };
  10293. // Finish an AST node, adding `type` and `end` properties.
  10294. function finishNodeAt(node, type, pos, loc) {
  10295. node.type = type;
  10296. node.end = pos;
  10297. if (this.options.locations)
  10298. { node.loc.end = loc; }
  10299. if (this.options.ranges)
  10300. { node.range[1] = pos; }
  10301. return node
  10302. }
  10303. pp$6.finishNode = function(node, type) {
  10304. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  10305. };
  10306. // Finish node at given position
  10307. pp$6.finishNodeAt = function(node, type, pos, loc) {
  10308. return finishNodeAt.call(this, node, type, pos, loc)
  10309. };
  10310. // The algorithm used to determine whether a regexp can appear at a
  10311. // given point in the program is loosely based on sweet.js' approach.
  10312. // See https://github.com/mozilla/sweet.js/wiki/design
  10313. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  10314. this.token = token;
  10315. this.isExpr = !!isExpr;
  10316. this.preserveSpace = !!preserveSpace;
  10317. this.override = override;
  10318. this.generator = !!generator;
  10319. };
  10320. var types$1 = {
  10321. b_stat: new TokContext("{", false),
  10322. b_expr: new TokContext("{", true),
  10323. b_tmpl: new TokContext("${", false),
  10324. p_stat: new TokContext("(", false),
  10325. p_expr: new TokContext("(", true),
  10326. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  10327. f_stat: new TokContext("function", false),
  10328. f_expr: new TokContext("function", true),
  10329. f_expr_gen: new TokContext("function", true, false, null, true),
  10330. f_gen: new TokContext("function", false, false, null, true)
  10331. };
  10332. var pp$7 = Parser.prototype;
  10333. pp$7.initialContext = function() {
  10334. return [types$1.b_stat]
  10335. };
  10336. pp$7.braceIsBlock = function(prevType) {
  10337. var parent = this.curContext();
  10338. if (parent === types$1.f_expr || parent === types$1.f_stat)
  10339. { return true }
  10340. if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
  10341. { return !parent.isExpr }
  10342. // The check for `tt.name && exprAllowed` detects whether we are
  10343. // after a `yield` or `of` construct. See the `updateContext` for
  10344. // `tt.name`.
  10345. if (prevType === types._return || prevType == types.name && this.exprAllowed)
  10346. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  10347. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType == types.arrow)
  10348. { return true }
  10349. if (prevType == types.braceL)
  10350. { return parent === types$1.b_stat }
  10351. if (prevType == types._var || prevType == types.name)
  10352. { return false }
  10353. return !this.exprAllowed
  10354. };
  10355. pp$7.inGeneratorContext = function() {
  10356. var this$1 = this;
  10357. for (var i = this.context.length - 1; i >= 1; i--) {
  10358. var context = this$1.context[i];
  10359. if (context.token === "function")
  10360. { return context.generator }
  10361. }
  10362. return false
  10363. };
  10364. pp$7.updateContext = function(prevType) {
  10365. var update, type = this.type;
  10366. if (type.keyword && prevType == types.dot)
  10367. { this.exprAllowed = false; }
  10368. else if (update = type.updateContext)
  10369. { update.call(this, prevType); }
  10370. else
  10371. { this.exprAllowed = type.beforeExpr; }
  10372. };
  10373. // Token-specific context update code
  10374. types.parenR.updateContext = types.braceR.updateContext = function() {
  10375. if (this.context.length == 1) {
  10376. this.exprAllowed = true;
  10377. return
  10378. }
  10379. var out = this.context.pop();
  10380. if (out === types$1.b_stat && this.curContext().token === "function") {
  10381. out = this.context.pop();
  10382. }
  10383. this.exprAllowed = !out.isExpr;
  10384. };
  10385. types.braceL.updateContext = function(prevType) {
  10386. this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
  10387. this.exprAllowed = true;
  10388. };
  10389. types.dollarBraceL.updateContext = function() {
  10390. this.context.push(types$1.b_tmpl);
  10391. this.exprAllowed = true;
  10392. };
  10393. types.parenL.updateContext = function(prevType) {
  10394. var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  10395. this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
  10396. this.exprAllowed = true;
  10397. };
  10398. types.incDec.updateContext = function() {
  10399. // tokExprAllowed stays unchanged
  10400. };
  10401. types._function.updateContext = types._class.updateContext = function(prevType) {
  10402. if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else &&
  10403. !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
  10404. { this.context.push(types$1.f_expr); }
  10405. else
  10406. { this.context.push(types$1.f_stat); }
  10407. this.exprAllowed = false;
  10408. };
  10409. types.backQuote.updateContext = function() {
  10410. if (this.curContext() === types$1.q_tmpl)
  10411. { this.context.pop(); }
  10412. else
  10413. { this.context.push(types$1.q_tmpl); }
  10414. this.exprAllowed = false;
  10415. };
  10416. types.star.updateContext = function(prevType) {
  10417. if (prevType == types._function) {
  10418. var index = this.context.length - 1;
  10419. if (this.context[index] === types$1.f_expr)
  10420. { this.context[index] = types$1.f_expr_gen; }
  10421. else
  10422. { this.context[index] = types$1.f_gen; }
  10423. }
  10424. this.exprAllowed = true;
  10425. };
  10426. types.name.updateContext = function(prevType) {
  10427. var allowed = false;
  10428. if (this.options.ecmaVersion >= 6) {
  10429. if (this.value == "of" && !this.exprAllowed ||
  10430. this.value == "yield" && this.inGeneratorContext())
  10431. { allowed = true; }
  10432. }
  10433. this.exprAllowed = allowed;
  10434. };
  10435. // Object type used to represent tokens. Note that normally, tokens
  10436. // simply exist as properties on the parser object. This is only
  10437. // used for the onToken callback and the external tokenizer.
  10438. var Token = function Token(p) {
  10439. this.type = p.type;
  10440. this.value = p.value;
  10441. this.start = p.start;
  10442. this.end = p.end;
  10443. if (p.options.locations)
  10444. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  10445. if (p.options.ranges)
  10446. { this.range = [p.start, p.end]; }
  10447. };
  10448. // ## Tokenizer
  10449. var pp$8 = Parser.prototype;
  10450. // Are we running under Rhino?
  10451. var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]";
  10452. // Move to the next token
  10453. pp$8.next = function() {
  10454. if (this.options.onToken)
  10455. { this.options.onToken(new Token(this)); }
  10456. this.lastTokEnd = this.end;
  10457. this.lastTokStart = this.start;
  10458. this.lastTokEndLoc = this.endLoc;
  10459. this.lastTokStartLoc = this.startLoc;
  10460. this.nextToken();
  10461. };
  10462. pp$8.getToken = function() {
  10463. this.next();
  10464. return new Token(this)
  10465. };
  10466. // If we're in an ES6 environment, make parsers iterable
  10467. if (typeof Symbol !== "undefined")
  10468. { pp$8[Symbol.iterator] = function() {
  10469. var this$1 = this;
  10470. return {
  10471. next: function () {
  10472. var token = this$1.getToken();
  10473. return {
  10474. done: token.type === types.eof,
  10475. value: token
  10476. }
  10477. }
  10478. }
  10479. }; }
  10480. // Toggle strict mode. Re-reads the next number or string to please
  10481. // pedantic tests (`"use strict"; 010;` should fail).
  10482. pp$8.curContext = function() {
  10483. return this.context[this.context.length - 1]
  10484. };
  10485. // Read a single token, updating the parser object's token-related
  10486. // properties.
  10487. pp$8.nextToken = function() {
  10488. var curContext = this.curContext();
  10489. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  10490. this.start = this.pos;
  10491. if (this.options.locations) { this.startLoc = this.curPosition(); }
  10492. if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
  10493. if (curContext.override) { return curContext.override(this) }
  10494. else { this.readToken(this.fullCharCodeAtPos()); }
  10495. };
  10496. pp$8.readToken = function(code) {
  10497. // Identifier or keyword. '\uXXXX' sequences are allowed in
  10498. // identifiers, so '\' also dispatches to that.
  10499. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  10500. { return this.readWord() }
  10501. return this.getTokenFromCode(code)
  10502. };
  10503. pp$8.fullCharCodeAtPos = function() {
  10504. var code = this.input.charCodeAt(this.pos);
  10505. if (code <= 0xd7ff || code >= 0xe000) { return code }
  10506. var next = this.input.charCodeAt(this.pos + 1);
  10507. return (code << 10) + next - 0x35fdc00
  10508. };
  10509. pp$8.skipBlockComment = function() {
  10510. var this$1 = this;
  10511. var startLoc = this.options.onComment && this.curPosition();
  10512. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  10513. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  10514. this.pos = end + 2;
  10515. if (this.options.locations) {
  10516. lineBreakG.lastIndex = start;
  10517. var match;
  10518. while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
  10519. ++this$1.curLine;
  10520. this$1.lineStart = match.index + match[0].length;
  10521. }
  10522. }
  10523. if (this.options.onComment)
  10524. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  10525. startLoc, this.curPosition()); }
  10526. };
  10527. pp$8.skipLineComment = function(startSkip) {
  10528. var this$1 = this;
  10529. var start = this.pos;
  10530. var startLoc = this.options.onComment && this.curPosition();
  10531. var ch = this.input.charCodeAt(this.pos += startSkip);
  10532. while (this.pos < this.input.length && !isNewLine(ch)) {
  10533. ch = this$1.input.charCodeAt(++this$1.pos);
  10534. }
  10535. if (this.options.onComment)
  10536. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  10537. startLoc, this.curPosition()); }
  10538. };
  10539. // Called at the start of the parse and after every token. Skips
  10540. // whitespace and comments, and.
  10541. pp$8.skipSpace = function() {
  10542. var this$1 = this;
  10543. loop: while (this.pos < this.input.length) {
  10544. var ch = this$1.input.charCodeAt(this$1.pos);
  10545. switch (ch) {
  10546. case 32: case 160: // ' '
  10547. ++this$1.pos;
  10548. break
  10549. case 13:
  10550. if (this$1.input.charCodeAt(this$1.pos + 1) === 10) {
  10551. ++this$1.pos;
  10552. }
  10553. case 10: case 8232: case 8233:
  10554. ++this$1.pos;
  10555. if (this$1.options.locations) {
  10556. ++this$1.curLine;
  10557. this$1.lineStart = this$1.pos;
  10558. }
  10559. break
  10560. case 47: // '/'
  10561. switch (this$1.input.charCodeAt(this$1.pos + 1)) {
  10562. case 42: // '*'
  10563. this$1.skipBlockComment();
  10564. break
  10565. case 47:
  10566. this$1.skipLineComment(2);
  10567. break
  10568. default:
  10569. break loop
  10570. }
  10571. break
  10572. default:
  10573. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  10574. ++this$1.pos;
  10575. } else {
  10576. break loop
  10577. }
  10578. }
  10579. }
  10580. };
  10581. // Called at the end of every token. Sets `end`, `val`, and
  10582. // maintains `context` and `exprAllowed`, and skips the space after
  10583. // the token, so that the next one's `start` will point at the
  10584. // right position.
  10585. pp$8.finishToken = function(type, val) {
  10586. this.end = this.pos;
  10587. if (this.options.locations) { this.endLoc = this.curPosition(); }
  10588. var prevType = this.type;
  10589. this.type = type;
  10590. this.value = val;
  10591. this.updateContext(prevType);
  10592. };
  10593. // ### Token reading
  10594. // This is the function that is called to fetch the next token. It
  10595. // is somewhat obscure, because it works in character codes rather
  10596. // than characters, and because operator parsing has been inlined
  10597. // into it.
  10598. //
  10599. // All in the name of speed.
  10600. //
  10601. pp$8.readToken_dot = function() {
  10602. var next = this.input.charCodeAt(this.pos + 1);
  10603. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  10604. var next2 = this.input.charCodeAt(this.pos + 2);
  10605. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  10606. this.pos += 3;
  10607. return this.finishToken(types.ellipsis)
  10608. } else {
  10609. ++this.pos;
  10610. return this.finishToken(types.dot)
  10611. }
  10612. };
  10613. pp$8.readToken_slash = function() { // '/'
  10614. var next = this.input.charCodeAt(this.pos + 1);
  10615. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  10616. if (next === 61) { return this.finishOp(types.assign, 2) }
  10617. return this.finishOp(types.slash, 1)
  10618. };
  10619. pp$8.readToken_mult_modulo_exp = function(code) { // '%*'
  10620. var next = this.input.charCodeAt(this.pos + 1);
  10621. var size = 1;
  10622. var tokentype = code === 42 ? types.star : types.modulo;
  10623. // exponentiation operator ** and **=
  10624. if (this.options.ecmaVersion >= 7 && code == 42 && next === 42) {
  10625. ++size;
  10626. tokentype = types.starstar;
  10627. next = this.input.charCodeAt(this.pos + 2);
  10628. }
  10629. if (next === 61) { return this.finishOp(types.assign, size + 1) }
  10630. return this.finishOp(tokentype, size)
  10631. };
  10632. pp$8.readToken_pipe_amp = function(code) { // '|&'
  10633. var next = this.input.charCodeAt(this.pos + 1);
  10634. if (next === code) { return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) }
  10635. if (next === 61) { return this.finishOp(types.assign, 2) }
  10636. return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
  10637. };
  10638. pp$8.readToken_caret = function() { // '^'
  10639. var next = this.input.charCodeAt(this.pos + 1);
  10640. if (next === 61) { return this.finishOp(types.assign, 2) }
  10641. return this.finishOp(types.bitwiseXOR, 1)
  10642. };
  10643. pp$8.readToken_plus_min = function(code) { // '+-'
  10644. var next = this.input.charCodeAt(this.pos + 1);
  10645. if (next === code) {
  10646. if (next == 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) == 62 &&
  10647. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  10648. // A `-->` line comment
  10649. this.skipLineComment(3);
  10650. this.skipSpace();
  10651. return this.nextToken()
  10652. }
  10653. return this.finishOp(types.incDec, 2)
  10654. }
  10655. if (next === 61) { return this.finishOp(types.assign, 2) }
  10656. return this.finishOp(types.plusMin, 1)
  10657. };
  10658. pp$8.readToken_lt_gt = function(code) { // '<>'
  10659. var next = this.input.charCodeAt(this.pos + 1);
  10660. var size = 1;
  10661. if (next === code) {
  10662. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  10663. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
  10664. return this.finishOp(types.bitShift, size)
  10665. }
  10666. if (next == 33 && code == 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) == 45 &&
  10667. this.input.charCodeAt(this.pos + 3) == 45) {
  10668. // `<!--`, an XML-style comment that should be interpreted as a line comment
  10669. this.skipLineComment(4);
  10670. this.skipSpace();
  10671. return this.nextToken()
  10672. }
  10673. if (next === 61) { size = 2; }
  10674. return this.finishOp(types.relational, size)
  10675. };
  10676. pp$8.readToken_eq_excl = function(code) { // '=!'
  10677. var next = this.input.charCodeAt(this.pos + 1);
  10678. if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  10679. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  10680. this.pos += 2;
  10681. return this.finishToken(types.arrow)
  10682. }
  10683. return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
  10684. };
  10685. pp$8.getTokenFromCode = function(code) {
  10686. switch (code) {
  10687. // The interpretation of a dot depends on whether it is followed
  10688. // by a digit or another two dots.
  10689. case 46: // '.'
  10690. return this.readToken_dot()
  10691. // Punctuation tokens.
  10692. case 40: ++this.pos; return this.finishToken(types.parenL)
  10693. case 41: ++this.pos; return this.finishToken(types.parenR)
  10694. case 59: ++this.pos; return this.finishToken(types.semi)
  10695. case 44: ++this.pos; return this.finishToken(types.comma)
  10696. case 91: ++this.pos; return this.finishToken(types.bracketL)
  10697. case 93: ++this.pos; return this.finishToken(types.bracketR)
  10698. case 123: ++this.pos; return this.finishToken(types.braceL)
  10699. case 125: ++this.pos; return this.finishToken(types.braceR)
  10700. case 58: ++this.pos; return this.finishToken(types.colon)
  10701. case 63: ++this.pos; return this.finishToken(types.question)
  10702. case 96: // '`'
  10703. if (this.options.ecmaVersion < 6) { break }
  10704. ++this.pos;
  10705. return this.finishToken(types.backQuote)
  10706. case 48: // '0'
  10707. var next = this.input.charCodeAt(this.pos + 1);
  10708. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  10709. if (this.options.ecmaVersion >= 6) {
  10710. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  10711. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  10712. }
  10713. // Anything else beginning with a digit is an integer, octal
  10714. // number, or float.
  10715. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  10716. return this.readNumber(false)
  10717. // Quotes produce strings.
  10718. case 34: case 39: // '"', "'"
  10719. return this.readString(code)
  10720. // Operators are parsed inline in tiny state machines. '=' (61) is
  10721. // often referred to. `finishOp` simply skips the amount of
  10722. // characters it is given as second argument, and returns a token
  10723. // of the type given by its first argument.
  10724. case 47: // '/'
  10725. return this.readToken_slash()
  10726. case 37: case 42: // '%*'
  10727. return this.readToken_mult_modulo_exp(code)
  10728. case 124: case 38: // '|&'
  10729. return this.readToken_pipe_amp(code)
  10730. case 94: // '^'
  10731. return this.readToken_caret()
  10732. case 43: case 45: // '+-'
  10733. return this.readToken_plus_min(code)
  10734. case 60: case 62: // '<>'
  10735. return this.readToken_lt_gt(code)
  10736. case 61: case 33: // '=!'
  10737. return this.readToken_eq_excl(code)
  10738. case 126: // '~'
  10739. return this.finishOp(types.prefix, 1)
  10740. }
  10741. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  10742. };
  10743. pp$8.finishOp = function(type, size) {
  10744. var str = this.input.slice(this.pos, this.pos + size);
  10745. this.pos += size;
  10746. return this.finishToken(type, str)
  10747. };
  10748. // Parse a regular expression. Some context-awareness is necessary,
  10749. // since a '/' inside a '[]' set does not end the expression.
  10750. function tryCreateRegexp(src, flags, throwErrorAt, parser) {
  10751. try {
  10752. return new RegExp(src, flags)
  10753. } catch (e) {
  10754. if (throwErrorAt !== undefined) {
  10755. if (e instanceof SyntaxError) { parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message); }
  10756. throw e
  10757. }
  10758. }
  10759. }
  10760. var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u");
  10761. pp$8.readRegexp = function() {
  10762. var this$1 = this;
  10763. var escaped, inClass, start = this.pos;
  10764. for (;;) {
  10765. if (this$1.pos >= this$1.input.length) { this$1.raise(start, "Unterminated regular expression"); }
  10766. var ch = this$1.input.charAt(this$1.pos);
  10767. if (lineBreak.test(ch)) { this$1.raise(start, "Unterminated regular expression"); }
  10768. if (!escaped) {
  10769. if (ch === "[") { inClass = true; }
  10770. else if (ch === "]" && inClass) { inClass = false; }
  10771. else if (ch === "/" && !inClass) { break }
  10772. escaped = ch === "\\";
  10773. } else { escaped = false; }
  10774. ++this$1.pos;
  10775. }
  10776. var content = this.input.slice(start, this.pos);
  10777. ++this.pos;
  10778. // Need to use `readWord1` because '\uXXXX' sequences are allowed
  10779. // here (don't ask).
  10780. var mods = this.readWord1();
  10781. var tmp = content, tmpFlags = "";
  10782. if (mods) {
  10783. var validFlags = /^[gim]*$/;
  10784. if (this.options.ecmaVersion >= 6) { validFlags = /^[gimuy]*$/; }
  10785. if (!validFlags.test(mods)) { this.raise(start, "Invalid regular expression flag"); }
  10786. if (mods.indexOf("u") >= 0) {
  10787. if (regexpUnicodeSupport) {
  10788. tmpFlags = "u";
  10789. } else {
  10790. // Replace each astral symbol and every Unicode escape sequence that
  10791. // possibly represents an astral symbol or a paired surrogate with a
  10792. // single ASCII symbol to avoid throwing on regular expressions that
  10793. // are only valid in combination with the `/u` flag.
  10794. // Note: replacing with the ASCII symbol `x` might cause false
  10795. // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
  10796. // perfectly valid pattern that is equivalent to `[a-b]`, but it would
  10797. // be replaced by `[x-b]` which throws an error.
  10798. tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (_match, code, offset) {
  10799. code = Number("0x" + code);
  10800. if (code > 0x10FFFF) { this$1.raise(start + offset + 3, "Code point out of bounds"); }
  10801. return "x"
  10802. });
  10803. tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
  10804. tmpFlags = tmpFlags.replace("u", "");
  10805. }
  10806. }
  10807. }
  10808. // Detect invalid regular expressions.
  10809. var value = null;
  10810. // Rhino's regular expression parser is flaky and throws uncatchable exceptions,
  10811. // so don't do detection if we are running under Rhino
  10812. if (!isRhino) {
  10813. tryCreateRegexp(tmp, tmpFlags, start, this);
  10814. // Get a regular expression object for this pattern-flag pair, or `null` in
  10815. // case the current environment doesn't support the flags it uses.
  10816. value = tryCreateRegexp(content, mods);
  10817. }
  10818. return this.finishToken(types.regexp, {pattern: content, flags: mods, value: value})
  10819. };
  10820. // Read an integer in the given radix. Return null if zero digits
  10821. // were read, the integer value otherwise. When `len` is given, this
  10822. // will return `null` unless the integer has exactly `len` digits.
  10823. pp$8.readInt = function(radix, len) {
  10824. var this$1 = this;
  10825. var start = this.pos, total = 0;
  10826. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  10827. var code = this$1.input.charCodeAt(this$1.pos), val = (void 0);
  10828. if (code >= 97) { val = code - 97 + 10; } // a
  10829. else if (code >= 65) { val = code - 65 + 10; } // A
  10830. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  10831. else { val = Infinity; }
  10832. if (val >= radix) { break }
  10833. ++this$1.pos;
  10834. total = total * radix + val;
  10835. }
  10836. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  10837. return total
  10838. };
  10839. pp$8.readRadixNumber = function(radix) {
  10840. this.pos += 2; // 0x
  10841. var val = this.readInt(radix);
  10842. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  10843. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  10844. return this.finishToken(types.num, val)
  10845. };
  10846. // Read an integer, octal integer, or floating-point number.
  10847. pp$8.readNumber = function(startsWithDot) {
  10848. var start = this.pos, isFloat = false, octal = this.input.charCodeAt(this.pos) === 48;
  10849. if (!startsWithDot && this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  10850. if (octal && this.pos == start + 1) { octal = false; }
  10851. var next = this.input.charCodeAt(this.pos);
  10852. if (next === 46 && !octal) { // '.'
  10853. ++this.pos;
  10854. this.readInt(10);
  10855. isFloat = true;
  10856. next = this.input.charCodeAt(this.pos);
  10857. }
  10858. if ((next === 69 || next === 101) && !octal) { // 'eE'
  10859. next = this.input.charCodeAt(++this.pos);
  10860. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  10861. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  10862. isFloat = true;
  10863. }
  10864. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  10865. var str = this.input.slice(start, this.pos), val;
  10866. if (isFloat) { val = parseFloat(str); }
  10867. else if (!octal || str.length === 1) { val = parseInt(str, 10); }
  10868. else if (this.strict) { this.raise(start, "Invalid number"); }
  10869. else if (/[89]/.test(str)) { val = parseInt(str, 10); }
  10870. else { val = parseInt(str, 8); }
  10871. return this.finishToken(types.num, val)
  10872. };
  10873. // Read a string value, interpreting backslash-escapes.
  10874. pp$8.readCodePoint = function() {
  10875. var ch = this.input.charCodeAt(this.pos), code;
  10876. if (ch === 123) { // '{'
  10877. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  10878. var codePos = ++this.pos;
  10879. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  10880. ++this.pos;
  10881. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  10882. } else {
  10883. code = this.readHexChar(4);
  10884. }
  10885. return code
  10886. };
  10887. function codePointToString(code) {
  10888. // UTF-16 Decoding
  10889. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  10890. code -= 0x10000;
  10891. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  10892. }
  10893. pp$8.readString = function(quote) {
  10894. var this$1 = this;
  10895. var out = "", chunkStart = ++this.pos;
  10896. for (;;) {
  10897. if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated string constant"); }
  10898. var ch = this$1.input.charCodeAt(this$1.pos);
  10899. if (ch === quote) { break }
  10900. if (ch === 92) { // '\'
  10901. out += this$1.input.slice(chunkStart, this$1.pos);
  10902. out += this$1.readEscapedChar(false);
  10903. chunkStart = this$1.pos;
  10904. } else {
  10905. if (isNewLine(ch)) { this$1.raise(this$1.start, "Unterminated string constant"); }
  10906. ++this$1.pos;
  10907. }
  10908. }
  10909. out += this.input.slice(chunkStart, this.pos++);
  10910. return this.finishToken(types.string, out)
  10911. };
  10912. // Reads template string tokens.
  10913. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  10914. pp$8.tryReadTemplateToken = function() {
  10915. this.inTemplateElement = true;
  10916. try {
  10917. this.readTmplToken();
  10918. } catch (err) {
  10919. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  10920. this.readInvalidTemplateToken();
  10921. } else {
  10922. throw err
  10923. }
  10924. }
  10925. this.inTemplateElement = false;
  10926. };
  10927. pp$8.invalidStringToken = function(position, message) {
  10928. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  10929. throw INVALID_TEMPLATE_ESCAPE_ERROR
  10930. } else {
  10931. this.raise(position, message);
  10932. }
  10933. };
  10934. pp$8.readTmplToken = function() {
  10935. var this$1 = this;
  10936. var out = "", chunkStart = this.pos;
  10937. for (;;) {
  10938. if (this$1.pos >= this$1.input.length) { this$1.raise(this$1.start, "Unterminated template"); }
  10939. var ch = this$1.input.charCodeAt(this$1.pos);
  10940. if (ch === 96 || ch === 36 && this$1.input.charCodeAt(this$1.pos + 1) === 123) { // '`', '${'
  10941. if (this$1.pos === this$1.start && (this$1.type === types.template || this$1.type === types.invalidTemplate)) {
  10942. if (ch === 36) {
  10943. this$1.pos += 2;
  10944. return this$1.finishToken(types.dollarBraceL)
  10945. } else {
  10946. ++this$1.pos;
  10947. return this$1.finishToken(types.backQuote)
  10948. }
  10949. }
  10950. out += this$1.input.slice(chunkStart, this$1.pos);
  10951. return this$1.finishToken(types.template, out)
  10952. }
  10953. if (ch === 92) { // '\'
  10954. out += this$1.input.slice(chunkStart, this$1.pos);
  10955. out += this$1.readEscapedChar(true);
  10956. chunkStart = this$1.pos;
  10957. } else if (isNewLine(ch)) {
  10958. out += this$1.input.slice(chunkStart, this$1.pos);
  10959. ++this$1.pos;
  10960. switch (ch) {
  10961. case 13:
  10962. if (this$1.input.charCodeAt(this$1.pos) === 10) { ++this$1.pos; }
  10963. case 10:
  10964. out += "\n";
  10965. break
  10966. default:
  10967. out += String.fromCharCode(ch);
  10968. break
  10969. }
  10970. if (this$1.options.locations) {
  10971. ++this$1.curLine;
  10972. this$1.lineStart = this$1.pos;
  10973. }
  10974. chunkStart = this$1.pos;
  10975. } else {
  10976. ++this$1.pos;
  10977. }
  10978. }
  10979. };
  10980. // Reads a template token to search for the end, without validating any escape sequences
  10981. pp$8.readInvalidTemplateToken = function() {
  10982. var this$1 = this;
  10983. for (; this.pos < this.input.length; this.pos++) {
  10984. switch (this$1.input[this$1.pos]) {
  10985. case "\\":
  10986. ++this$1.pos;
  10987. break
  10988. case "$":
  10989. if (this$1.input[this$1.pos + 1] !== "{") {
  10990. break
  10991. }
  10992. // falls through
  10993. case "`":
  10994. return this$1.finishToken(types.invalidTemplate, this$1.input.slice(this$1.start, this$1.pos))
  10995. // no default
  10996. }
  10997. }
  10998. this.raise(this.start, "Unterminated template");
  10999. };
  11000. // Used to read escaped characters
  11001. pp$8.readEscapedChar = function(inTemplate) {
  11002. var ch = this.input.charCodeAt(++this.pos);
  11003. ++this.pos;
  11004. switch (ch) {
  11005. case 110: return "\n" // 'n' -> '\n'
  11006. case 114: return "\r" // 'r' -> '\r'
  11007. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  11008. case 117: return codePointToString(this.readCodePoint()) // 'u'
  11009. case 116: return "\t" // 't' -> '\t'
  11010. case 98: return "\b" // 'b' -> '\b'
  11011. case 118: return "\u000b" // 'v' -> '\u000b'
  11012. case 102: return "\f" // 'f' -> '\f'
  11013. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  11014. case 10: // ' \n'
  11015. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  11016. return ""
  11017. default:
  11018. if (ch >= 48 && ch <= 55) {
  11019. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  11020. var octal = parseInt(octalStr, 8);
  11021. if (octal > 255) {
  11022. octalStr = octalStr.slice(0, -1);
  11023. octal = parseInt(octalStr, 8);
  11024. }
  11025. if (octalStr !== "0" && (this.strict || inTemplate)) {
  11026. this.invalidStringToken(this.pos - 2, "Octal literal in strict mode");
  11027. }
  11028. this.pos += octalStr.length - 1;
  11029. return String.fromCharCode(octal)
  11030. }
  11031. return String.fromCharCode(ch)
  11032. }
  11033. };
  11034. // Used to read character escape sequences ('\x', '\u', '\U').
  11035. pp$8.readHexChar = function(len) {
  11036. var codePos = this.pos;
  11037. var n = this.readInt(16, len);
  11038. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  11039. return n
  11040. };
  11041. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  11042. // to whether the word contained a '\u' escape.
  11043. //
  11044. // Incrementally adds only escaped chars, adding other chunks as-is
  11045. // as a micro-optimization.
  11046. pp$8.readWord1 = function() {
  11047. var this$1 = this;
  11048. this.containsEsc = false;
  11049. var word = "", first = true, chunkStart = this.pos;
  11050. var astral = this.options.ecmaVersion >= 6;
  11051. while (this.pos < this.input.length) {
  11052. var ch = this$1.fullCharCodeAtPos();
  11053. if (isIdentifierChar(ch, astral)) {
  11054. this$1.pos += ch <= 0xffff ? 1 : 2;
  11055. } else if (ch === 92) { // "\"
  11056. this$1.containsEsc = true;
  11057. word += this$1.input.slice(chunkStart, this$1.pos);
  11058. var escStart = this$1.pos;
  11059. if (this$1.input.charCodeAt(++this$1.pos) != 117) // "u"
  11060. { this$1.invalidStringToken(this$1.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  11061. ++this$1.pos;
  11062. var esc = this$1.readCodePoint();
  11063. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  11064. { this$1.invalidStringToken(escStart, "Invalid Unicode escape"); }
  11065. word += codePointToString(esc);
  11066. chunkStart = this$1.pos;
  11067. } else {
  11068. break
  11069. }
  11070. first = false;
  11071. }
  11072. return word + this.input.slice(chunkStart, this.pos)
  11073. };
  11074. // Read an identifier or keyword token. Will check for reserved
  11075. // words when necessary.
  11076. pp$8.readWord = function() {
  11077. var word = this.readWord1();
  11078. var type = types.name;
  11079. if (this.keywords.test(word)) {
  11080. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword " + word); }
  11081. type = keywords$1[word];
  11082. }
  11083. return this.finishToken(type, word)
  11084. };
  11085. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  11086. //
  11087. // Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
  11088. // various contributors and released under an MIT license.
  11089. //
  11090. // Git repositories for Acorn are available at
  11091. //
  11092. // http://marijnhaverbeke.nl/git/acorn
  11093. // https://github.com/ternjs/acorn.git
  11094. //
  11095. // Please use the [github bug tracker][ghbt] to report issues.
  11096. //
  11097. // [ghbt]: https://github.com/ternjs/acorn/issues
  11098. //
  11099. // This file defines the main parser interface. The library also comes
  11100. // with a [error-tolerant parser][dammit] and an
  11101. // [abstract syntax tree walker][walk], defined in other files.
  11102. //
  11103. // [dammit]: acorn_loose.js
  11104. // [walk]: util/walk.js
  11105. var version = "5.2.1";
  11106. // The main exported interface (under `self.acorn` when in the
  11107. // browser) is a `parse` function that takes a code string and
  11108. // returns an abstract syntax tree as specified by [Mozilla parser
  11109. // API][api].
  11110. //
  11111. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  11112. function parse(input, options) {
  11113. return new Parser(options, input).parse()
  11114. }
  11115. // This function tries to parse a single expression at a given
  11116. // offset in a string. Useful for parsing mixed-language formats
  11117. // that embed JavaScript expressions.
  11118. function parseExpressionAt(input, pos, options) {
  11119. var p = new Parser(options, input, pos);
  11120. p.nextToken();
  11121. return p.parseExpression()
  11122. }
  11123. // Acorn is organized as a tokenizer and a recursive-descent parser.
  11124. // The `tokenizer` export provides an interface to the tokenizer.
  11125. function tokenizer(input, options) {
  11126. return new Parser(options, input)
  11127. }
  11128. // This is a terrible kludge to support the existing, pre-ES6
  11129. // interface where the loose parser module retroactively adds exports
  11130. // to this module.
  11131. // eslint-disable-line camelcase
  11132. function addLooseExports(parse, Parser$$1, plugins$$1) {
  11133. exports.parse_dammit = parse; // eslint-disable-line camelcase
  11134. exports.LooseParser = Parser$$1;
  11135. exports.pluginsLoose = plugins$$1;
  11136. }
  11137. exports.version = version;
  11138. exports.parse = parse;
  11139. exports.parseExpressionAt = parseExpressionAt;
  11140. exports.tokenizer = tokenizer;
  11141. exports.addLooseExports = addLooseExports;
  11142. exports.Parser = Parser;
  11143. exports.plugins = plugins;
  11144. exports.defaultOptions = defaultOptions;
  11145. exports.Position = Position;
  11146. exports.SourceLocation = SourceLocation;
  11147. exports.getLineInfo = getLineInfo;
  11148. exports.Node = Node;
  11149. exports.TokenType = TokenType;
  11150. exports.tokTypes = types;
  11151. exports.keywordTypes = keywords$1;
  11152. exports.TokContext = TokContext;
  11153. exports.tokContexts = types$1;
  11154. exports.isIdentifierChar = isIdentifierChar;
  11155. exports.isIdentifierStart = isIdentifierStart;
  11156. exports.Token = Token;
  11157. exports.isNewLine = isNewLine;
  11158. exports.lineBreak = lineBreak;
  11159. exports.lineBreakG = lineBreakG;
  11160. exports.nonASCIIwhitespace = nonASCIIwhitespace;
  11161. Object.defineProperty(exports, '__esModule', { value: true });
  11162. })));
  11163. ;
  11164. (function (global, factory) {
  11165. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  11166. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  11167. (factory((global.acorn = global.acorn || {}, global.acorn.walk = global.acorn.walk || {})));
  11168. }(this, (function (exports) { 'use strict';
  11169. // AST walker module for Mozilla Parser API compatible trees
  11170. // A simple walk is one where you simply specify callbacks to be
  11171. // called on specific nodes. The last two arguments are optional. A
  11172. // simple use would be
  11173. //
  11174. // walk.simple(myTree, {
  11175. // Expression: function(node) { ... }
  11176. // });
  11177. //
  11178. // to do something with all expressions. All Parser API node types
  11179. // can be used to identify node types, as well as Expression,
  11180. // Statement, and ScopeBody, which denote categories of nodes.
  11181. //
  11182. // The base argument can be used to pass a custom (recursive)
  11183. // walker, and state can be used to give this walked an initial
  11184. // state.
  11185. function simple(node, visitors, base, state, override) {
  11186. if (!base) { base = exports.base
  11187. ; }(function c(node, st, override) {
  11188. var type = override || node.type, found = visitors[type];
  11189. base[type](node, st, c);
  11190. if (found) { found(node, st); }
  11191. })(node, state, override);
  11192. }
  11193. // An ancestor walk keeps an array of ancestor nodes (including the
  11194. // current node) and passes them to the callback as third parameter
  11195. // (and also as state parameter when no other state is present).
  11196. function ancestor(node, visitors, base, state) {
  11197. if (!base) { base = exports.base; }
  11198. var ancestors = [];(function c(node, st, override) {
  11199. var type = override || node.type, found = visitors[type];
  11200. var isNew = node != ancestors[ancestors.length - 1];
  11201. if (isNew) { ancestors.push(node); }
  11202. base[type](node, st, c);
  11203. if (found) { found(node, st || ancestors, ancestors); }
  11204. if (isNew) { ancestors.pop(); }
  11205. })(node, state);
  11206. }
  11207. // A recursive walk is one where your functions override the default
  11208. // walkers. They can modify and replace the state parameter that's
  11209. // threaded through the walk, and can opt how and whether to walk
  11210. // their child nodes (by calling their third argument on these
  11211. // nodes).
  11212. function recursive(node, state, funcs, base, override) {
  11213. var visitor = funcs ? exports.make(funcs, base) : base;(function c(node, st, override) {
  11214. visitor[override || node.type](node, st, c);
  11215. })(node, state, override);
  11216. }
  11217. function makeTest(test) {
  11218. if (typeof test == "string")
  11219. { return function (type) { return type == test; } }
  11220. else if (!test)
  11221. { return function () { return true; } }
  11222. else
  11223. { return test }
  11224. }
  11225. var Found = function Found(node, state) { this.node = node; this.state = state; };
  11226. // A full walk triggers the callback on each node
  11227. function full(node, callback, base, state, override) {
  11228. if (!base) { base = exports.base
  11229. ; }(function c(node, st, override) {
  11230. var type = override || node.type;
  11231. base[type](node, st, c);
  11232. if (!override) { callback(node, st, type); }
  11233. })(node, state, override);
  11234. }
  11235. // An fullAncestor walk is like an ancestor walk, but triggers
  11236. // the callback on each node
  11237. function fullAncestor(node, callback, base, state) {
  11238. if (!base) { base = exports.base; }
  11239. var ancestors = [];(function c(node, st, override) {
  11240. var type = override || node.type;
  11241. var isNew = node != ancestors[ancestors.length - 1];
  11242. if (isNew) { ancestors.push(node); }
  11243. base[type](node, st, c);
  11244. if (!override) { callback(node, st || ancestors, ancestors, type); }
  11245. if (isNew) { ancestors.pop(); }
  11246. })(node, state);
  11247. }
  11248. // Find a node with a given start, end, and type (all are optional,
  11249. // null can be used as wildcard). Returns a {node, state} object, or
  11250. // undefined when it doesn't find a matching node.
  11251. function findNodeAt(node, start, end, test, base, state) {
  11252. test = makeTest(test);
  11253. if (!base) { base = exports.base; }
  11254. try {
  11255. (function c(node, st, override) {
  11256. var type = override || node.type;
  11257. if ((start == null || node.start <= start) &&
  11258. (end == null || node.end >= end))
  11259. { base[type](node, st, c); }
  11260. if ((start == null || node.start == start) &&
  11261. (end == null || node.end == end) &&
  11262. test(type, node))
  11263. { throw new Found(node, st) }
  11264. })(node, state);
  11265. } catch (e) {
  11266. if (e instanceof Found) { return e }
  11267. throw e
  11268. }
  11269. }
  11270. // Find the innermost node of a given type that contains the given
  11271. // position. Interface similar to findNodeAt.
  11272. function findNodeAround(node, pos, test, base, state) {
  11273. test = makeTest(test);
  11274. if (!base) { base = exports.base; }
  11275. try {
  11276. (function c(node, st, override) {
  11277. var type = override || node.type;
  11278. if (node.start > pos || node.end < pos) { return }
  11279. base[type](node, st, c);
  11280. if (test(type, node)) { throw new Found(node, st) }
  11281. })(node, state);
  11282. } catch (e) {
  11283. if (e instanceof Found) { return e }
  11284. throw e
  11285. }
  11286. }
  11287. // Find the outermost matching node after a given position.
  11288. function findNodeAfter(node, pos, test, base, state) {
  11289. test = makeTest(test);
  11290. if (!base) { base = exports.base; }
  11291. try {
  11292. (function c(node, st, override) {
  11293. if (node.end < pos) { return }
  11294. var type = override || node.type;
  11295. if (node.start >= pos && test(type, node)) { throw new Found(node, st) }
  11296. base[type](node, st, c);
  11297. })(node, state);
  11298. } catch (e) {
  11299. if (e instanceof Found) { return e }
  11300. throw e
  11301. }
  11302. }
  11303. // Find the outermost matching node before a given position.
  11304. function findNodeBefore(node, pos, test, base, state) {
  11305. test = makeTest(test);
  11306. if (!base) { base = exports.base; }
  11307. var max;(function c(node, st, override) {
  11308. if (node.start > pos) { return }
  11309. var type = override || node.type;
  11310. if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))
  11311. { max = new Found(node, st); }
  11312. base[type](node, st, c);
  11313. })(node, state);
  11314. return max
  11315. }
  11316. // Fallback to an Object.create polyfill for older environments.
  11317. var create = Object.create || function(proto) {
  11318. function Ctor() {}
  11319. Ctor.prototype = proto;
  11320. return new Ctor
  11321. };
  11322. // Used to create a custom walker. Will fill in all missing node
  11323. // type properties with the defaults.
  11324. function make(funcs, base) {
  11325. if (!base) { base = exports.base; }
  11326. var visitor = create(base);
  11327. for (var type in funcs) { visitor[type] = funcs[type]; }
  11328. return visitor
  11329. }
  11330. function skipThrough(node, st, c) { c(node, st); }
  11331. function ignore(_node, _st, _c) {}
  11332. // Node walkers.
  11333. var base = {};
  11334. base.Program = base.BlockStatement = function (node, st, c) {
  11335. for (var i = 0, list = node.body; i < list.length; i += 1)
  11336. {
  11337. var stmt = list[i];
  11338. c(stmt, st, "Statement");
  11339. }
  11340. };
  11341. base.Statement = skipThrough;
  11342. base.EmptyStatement = ignore;
  11343. base.ExpressionStatement = base.ParenthesizedExpression =
  11344. function (node, st, c) { return c(node.expression, st, "Expression"); };
  11345. base.IfStatement = function (node, st, c) {
  11346. c(node.test, st, "Expression");
  11347. c(node.consequent, st, "Statement");
  11348. if (node.alternate) { c(node.alternate, st, "Statement"); }
  11349. };
  11350. base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  11351. base.BreakStatement = base.ContinueStatement = ignore;
  11352. base.WithStatement = function (node, st, c) {
  11353. c(node.object, st, "Expression");
  11354. c(node.body, st, "Statement");
  11355. };
  11356. base.SwitchStatement = function (node, st, c) {
  11357. c(node.discriminant, st, "Expression");
  11358. for (var i = 0, list = node.cases; i < list.length; i += 1) {
  11359. var cs = list[i];
  11360. if (cs.test) { c(cs.test, st, "Expression"); }
  11361. for (var i$1 = 0, list$1 = cs.consequent; i$1 < list$1.length; i$1 += 1)
  11362. {
  11363. var cons = list$1[i$1];
  11364. c(cons, st, "Statement");
  11365. }
  11366. }
  11367. };
  11368. base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
  11369. if (node.argument) { c(node.argument, st, "Expression"); }
  11370. };
  11371. base.ThrowStatement = base.SpreadElement =
  11372. function (node, st, c) { return c(node.argument, st, "Expression"); };
  11373. base.TryStatement = function (node, st, c) {
  11374. c(node.block, st, "Statement");
  11375. if (node.handler) { c(node.handler, st); }
  11376. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  11377. };
  11378. base.CatchClause = function (node, st, c) {
  11379. c(node.param, st, "Pattern");
  11380. c(node.body, st, "ScopeBody");
  11381. };
  11382. base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
  11383. c(node.test, st, "Expression");
  11384. c(node.body, st, "Statement");
  11385. };
  11386. base.ForStatement = function (node, st, c) {
  11387. if (node.init) { c(node.init, st, "ForInit"); }
  11388. if (node.test) { c(node.test, st, "Expression"); }
  11389. if (node.update) { c(node.update, st, "Expression"); }
  11390. c(node.body, st, "Statement");
  11391. };
  11392. base.ForInStatement = base.ForOfStatement = function (node, st, c) {
  11393. c(node.left, st, "ForInit");
  11394. c(node.right, st, "Expression");
  11395. c(node.body, st, "Statement");
  11396. };
  11397. base.ForInit = function (node, st, c) {
  11398. if (node.type == "VariableDeclaration") { c(node, st); }
  11399. else { c(node, st, "Expression"); }
  11400. };
  11401. base.DebuggerStatement = ignore;
  11402. base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  11403. base.VariableDeclaration = function (node, st, c) {
  11404. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  11405. {
  11406. var decl = list[i];
  11407. c(decl, st);
  11408. }
  11409. };
  11410. base.VariableDeclarator = function (node, st, c) {
  11411. c(node.id, st, "Pattern");
  11412. if (node.init) { c(node.init, st, "Expression"); }
  11413. };
  11414. base.Function = function (node, st, c) {
  11415. if (node.id) { c(node.id, st, "Pattern"); }
  11416. for (var i = 0, list = node.params; i < list.length; i += 1)
  11417. {
  11418. var param = list[i];
  11419. c(param, st, "Pattern");
  11420. }
  11421. c(node.body, st, node.expression ? "ScopeExpression" : "ScopeBody");
  11422. };
  11423. // FIXME drop these node types in next major version
  11424. // (They are awkward, and in ES6 every block can be a scope.)
  11425. base.ScopeBody = function (node, st, c) { return c(node, st, "Statement"); };
  11426. base.ScopeExpression = function (node, st, c) { return c(node, st, "Expression"); };
  11427. base.Pattern = function (node, st, c) {
  11428. if (node.type == "Identifier")
  11429. { c(node, st, "VariablePattern"); }
  11430. else if (node.type == "MemberExpression")
  11431. { c(node, st, "MemberPattern"); }
  11432. else
  11433. { c(node, st); }
  11434. };
  11435. base.VariablePattern = ignore;
  11436. base.MemberPattern = skipThrough;
  11437. base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  11438. base.ArrayPattern = function (node, st, c) {
  11439. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  11440. var elt = list[i];
  11441. if (elt) { c(elt, st, "Pattern"); }
  11442. }
  11443. };
  11444. base.ObjectPattern = function (node, st, c) {
  11445. for (var i = 0, list = node.properties; i < list.length; i += 1)
  11446. {
  11447. var prop = list[i];
  11448. c(prop.value, st, "Pattern");
  11449. }
  11450. };
  11451. base.Expression = skipThrough;
  11452. base.ThisExpression = base.Super = base.MetaProperty = ignore;
  11453. base.ArrayExpression = function (node, st, c) {
  11454. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  11455. var elt = list[i];
  11456. if (elt) { c(elt, st, "Expression"); }
  11457. }
  11458. };
  11459. base.ObjectExpression = function (node, st, c) {
  11460. for (var i = 0, list = node.properties; i < list.length; i += 1)
  11461. {
  11462. var prop = list[i];
  11463. c(prop, st);
  11464. }
  11465. };
  11466. base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
  11467. base.SequenceExpression = base.TemplateLiteral = function (node, st, c) {
  11468. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  11469. {
  11470. var expr = list[i];
  11471. c(expr, st, "Expression");
  11472. }
  11473. };
  11474. base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
  11475. c(node.argument, st, "Expression");
  11476. };
  11477. base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
  11478. c(node.left, st, "Expression");
  11479. c(node.right, st, "Expression");
  11480. };
  11481. base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
  11482. c(node.left, st, "Pattern");
  11483. c(node.right, st, "Expression");
  11484. };
  11485. base.ConditionalExpression = function (node, st, c) {
  11486. c(node.test, st, "Expression");
  11487. c(node.consequent, st, "Expression");
  11488. c(node.alternate, st, "Expression");
  11489. };
  11490. base.NewExpression = base.CallExpression = function (node, st, c) {
  11491. c(node.callee, st, "Expression");
  11492. if (node.arguments)
  11493. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  11494. {
  11495. var arg = list[i];
  11496. c(arg, st, "Expression");
  11497. } }
  11498. };
  11499. base.MemberExpression = function (node, st, c) {
  11500. c(node.object, st, "Expression");
  11501. if (node.computed) { c(node.property, st, "Expression"); }
  11502. };
  11503. base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
  11504. if (node.declaration)
  11505. { c(node.declaration, st, node.type == "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  11506. if (node.source) { c(node.source, st, "Expression"); }
  11507. };
  11508. base.ExportAllDeclaration = function (node, st, c) {
  11509. c(node.source, st, "Expression");
  11510. };
  11511. base.ImportDeclaration = function (node, st, c) {
  11512. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  11513. {
  11514. var spec = list[i];
  11515. c(spec, st);
  11516. }
  11517. c(node.source, st, "Expression");
  11518. };
  11519. base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore;
  11520. base.TaggedTemplateExpression = function (node, st, c) {
  11521. c(node.tag, st, "Expression");
  11522. c(node.quasi, st);
  11523. };
  11524. base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  11525. base.Class = function (node, st, c) {
  11526. if (node.id) { c(node.id, st, "Pattern"); }
  11527. if (node.superClass) { c(node.superClass, st, "Expression"); }
  11528. for (var i = 0, list = node.body.body; i < list.length; i += 1)
  11529. {
  11530. var item = list[i];
  11531. c(item, st);
  11532. }
  11533. };
  11534. base.MethodDefinition = base.Property = function (node, st, c) {
  11535. if (node.computed) { c(node.key, st, "Expression"); }
  11536. c(node.value, st, "Expression");
  11537. };
  11538. exports.simple = simple;
  11539. exports.ancestor = ancestor;
  11540. exports.recursive = recursive;
  11541. exports.full = full;
  11542. exports.fullAncestor = fullAncestor;
  11543. exports.findNodeAt = findNodeAt;
  11544. exports.findNodeAround = findNodeAround;
  11545. exports.findNodeAfter = findNodeAfter;
  11546. exports.findNodeBefore = findNodeBefore;
  11547. exports.make = make;
  11548. exports.base = base;
  11549. Object.defineProperty(exports, '__esModule', { value: true });
  11550. })));
  11551. (function (global, factory) {
  11552. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('./acorn')) :
  11553. typeof define === 'function' && define.amd ? define(['exports', './acorn'], factory) :
  11554. (factory((global.acorn = global.acorn || {}, global.acorn.loose = global.acorn.loose || {}),global.acorn));
  11555. }(this, (function (exports,__acorn) { 'use strict';
  11556. // Registered plugins
  11557. var pluginsLoose = {};
  11558. var LooseParser = function LooseParser(input, options) {
  11559. if ( options === void 0 ) options = {};
  11560. this.toks = __acorn.tokenizer(input, options);
  11561. this.options = this.toks.options;
  11562. this.input = this.toks.input;
  11563. this.tok = this.last = {type: __acorn.tokTypes.eof, start: 0, end: 0};
  11564. if (this.options.locations) {
  11565. var here = this.toks.curPosition();
  11566. this.tok.loc = new __acorn.SourceLocation(this.toks, here, here);
  11567. }
  11568. this.ahead = []; // Tokens ahead
  11569. this.context = []; // Indentation contexted
  11570. this.curIndent = 0;
  11571. this.curLineStart = 0;
  11572. this.nextLineStart = this.lineEnd(this.curLineStart) + 1;
  11573. this.inAsync = false;
  11574. // Load plugins
  11575. this.options.pluginsLoose = options.pluginsLoose || {};
  11576. this.loadPlugins(this.options.pluginsLoose);
  11577. };
  11578. LooseParser.prototype.startNode = function startNode () {
  11579. return new __acorn.Node(this.toks, this.tok.start, this.options.locations ? this.tok.loc.start : null)
  11580. };
  11581. LooseParser.prototype.storeCurrentPos = function storeCurrentPos () {
  11582. return this.options.locations ? [this.tok.start, this.tok.loc.start] : this.tok.start
  11583. };
  11584. LooseParser.prototype.startNodeAt = function startNodeAt (pos) {
  11585. if (this.options.locations) {
  11586. return new __acorn.Node(this.toks, pos[0], pos[1])
  11587. } else {
  11588. return new __acorn.Node(this.toks, pos)
  11589. }
  11590. };
  11591. LooseParser.prototype.finishNode = function finishNode (node, type) {
  11592. node.type = type;
  11593. node.end = this.last.end;
  11594. if (this.options.locations)
  11595. { node.loc.end = this.last.loc.end; }
  11596. if (this.options.ranges)
  11597. { node.range[1] = this.last.end; }
  11598. return node
  11599. };
  11600. LooseParser.prototype.dummyNode = function dummyNode (type) {
  11601. var dummy = this.startNode();
  11602. dummy.type = type;
  11603. dummy.end = dummy.start;
  11604. if (this.options.locations)
  11605. { dummy.loc.end = dummy.loc.start; }
  11606. if (this.options.ranges)
  11607. { dummy.range[1] = dummy.start; }
  11608. this.last = {type: __acorn.tokTypes.name, start: dummy.start, end: dummy.start, loc: dummy.loc};
  11609. return dummy
  11610. };
  11611. LooseParser.prototype.dummyIdent = function dummyIdent () {
  11612. var dummy = this.dummyNode("Identifier");
  11613. dummy.name = "✖";
  11614. return dummy
  11615. };
  11616. LooseParser.prototype.dummyString = function dummyString () {
  11617. var dummy = this.dummyNode("Literal");
  11618. dummy.value = dummy.raw = "✖";
  11619. return dummy
  11620. };
  11621. LooseParser.prototype.eat = function eat (type) {
  11622. if (this.tok.type === type) {
  11623. this.next();
  11624. return true
  11625. } else {
  11626. return false
  11627. }
  11628. };
  11629. LooseParser.prototype.isContextual = function isContextual (name) {
  11630. return this.tok.type === __acorn.tokTypes.name && this.tok.value === name
  11631. };
  11632. LooseParser.prototype.eatContextual = function eatContextual (name) {
  11633. return this.tok.value === name && this.eat(__acorn.tokTypes.name)
  11634. };
  11635. LooseParser.prototype.canInsertSemicolon = function canInsertSemicolon () {
  11636. return this.tok.type === __acorn.tokTypes.eof || this.tok.type === __acorn.tokTypes.braceR ||
  11637. __acorn.lineBreak.test(this.input.slice(this.last.end, this.tok.start))
  11638. };
  11639. LooseParser.prototype.semicolon = function semicolon () {
  11640. return this.eat(__acorn.tokTypes.semi)
  11641. };
  11642. LooseParser.prototype.expect = function expect (type) {
  11643. var this$1 = this;
  11644. if (this.eat(type)) { return true }
  11645. for (var i = 1; i <= 2; i++) {
  11646. if (this$1.lookAhead(i).type == type) {
  11647. for (var j = 0; j < i; j++) { this$1.next(); }
  11648. return true
  11649. }
  11650. }
  11651. };
  11652. LooseParser.prototype.pushCx = function pushCx () {
  11653. this.context.push(this.curIndent);
  11654. };
  11655. LooseParser.prototype.popCx = function popCx () {
  11656. this.curIndent = this.context.pop();
  11657. };
  11658. LooseParser.prototype.lineEnd = function lineEnd (pos) {
  11659. while (pos < this.input.length && !__acorn.isNewLine(this.input.charCodeAt(pos))) { ++pos; }
  11660. return pos
  11661. };
  11662. LooseParser.prototype.indentationAfter = function indentationAfter (pos) {
  11663. var this$1 = this;
  11664. for (var count = 0;; ++pos) {
  11665. var ch = this$1.input.charCodeAt(pos);
  11666. if (ch === 32) { ++count; }
  11667. else if (ch === 9) { count += this$1.options.tabSize; }
  11668. else { return count }
  11669. }
  11670. };
  11671. LooseParser.prototype.closes = function closes (closeTok, indent, line, blockHeuristic) {
  11672. if (this.tok.type === closeTok || this.tok.type === __acorn.tokTypes.eof) { return true }
  11673. return line != this.curLineStart && this.curIndent < indent && this.tokenStartsLine() &&
  11674. (!blockHeuristic || this.nextLineStart >= this.input.length ||
  11675. this.indentationAfter(this.nextLineStart) < indent)
  11676. };
  11677. LooseParser.prototype.tokenStartsLine = function tokenStartsLine () {
  11678. var this$1 = this;
  11679. for (var p = this.tok.start - 1; p >= this.curLineStart; --p) {
  11680. var ch = this$1.input.charCodeAt(p);
  11681. if (ch !== 9 && ch !== 32) { return false }
  11682. }
  11683. return true
  11684. };
  11685. LooseParser.prototype.extend = function extend (name, f) {
  11686. this[name] = f(this[name]);
  11687. };
  11688. LooseParser.prototype.loadPlugins = function loadPlugins (pluginConfigs) {
  11689. var this$1 = this;
  11690. for (var name in pluginConfigs) {
  11691. var plugin = pluginsLoose[name];
  11692. if (!plugin) { throw new Error("Plugin '" + name + "' not found") }
  11693. plugin(this$1, pluginConfigs[name]);
  11694. }
  11695. };
  11696. LooseParser.prototype.parse = function parse () {
  11697. this.next();
  11698. return this.parseTopLevel()
  11699. };
  11700. var lp = LooseParser.prototype;
  11701. function isSpace(ch) {
  11702. return (ch < 14 && ch > 8) || ch === 32 || ch === 160 || __acorn.isNewLine(ch)
  11703. }
  11704. lp.next = function() {
  11705. var this$1 = this;
  11706. this.last = this.tok;
  11707. if (this.ahead.length)
  11708. { this.tok = this.ahead.shift(); }
  11709. else
  11710. { this.tok = this.readToken(); }
  11711. if (this.tok.start >= this.nextLineStart) {
  11712. while (this.tok.start >= this.nextLineStart) {
  11713. this$1.curLineStart = this$1.nextLineStart;
  11714. this$1.nextLineStart = this$1.lineEnd(this$1.curLineStart) + 1;
  11715. }
  11716. this.curIndent = this.indentationAfter(this.curLineStart);
  11717. }
  11718. };
  11719. lp.readToken = function() {
  11720. var this$1 = this;
  11721. for (;;) {
  11722. try {
  11723. this$1.toks.next();
  11724. if (this$1.toks.type === __acorn.tokTypes.dot &&
  11725. this$1.input.substr(this$1.toks.end, 1) === "." &&
  11726. this$1.options.ecmaVersion >= 6) {
  11727. this$1.toks.end++;
  11728. this$1.toks.type = __acorn.tokTypes.ellipsis;
  11729. }
  11730. return new __acorn.Token(this$1.toks)
  11731. } catch (e) {
  11732. if (!(e instanceof SyntaxError)) { throw e }
  11733. // Try to skip some text, based on the error message, and then continue
  11734. var msg = e.message, pos = e.raisedAt, replace = true;
  11735. if (/unterminated/i.test(msg)) {
  11736. pos = this$1.lineEnd(e.pos + 1);
  11737. if (/string/.test(msg)) {
  11738. replace = {start: e.pos, end: pos, type: __acorn.tokTypes.string, value: this$1.input.slice(e.pos + 1, pos)};
  11739. } else if (/regular expr/i.test(msg)) {
  11740. var re = this$1.input.slice(e.pos, pos);
  11741. try { re = new RegExp(re); } catch (e) { /* ignore compilation error due to new syntax */ }
  11742. replace = {start: e.pos, end: pos, type: __acorn.tokTypes.regexp, value: re};
  11743. } else if (/template/.test(msg)) {
  11744. replace = {
  11745. start: e.pos,
  11746. end: pos,
  11747. type: __acorn.tokTypes.template,
  11748. value: this$1.input.slice(e.pos, pos)
  11749. };
  11750. } else {
  11751. replace = false;
  11752. }
  11753. } else if (/invalid (unicode|regexp|number)|expecting unicode|octal literal|is reserved|directly after number|expected number in radix/i.test(msg)) {
  11754. while (pos < this.input.length && !isSpace(this.input.charCodeAt(pos))) { ++pos; }
  11755. } else if (/character escape|expected hexadecimal/i.test(msg)) {
  11756. while (pos < this.input.length) {
  11757. var ch = this$1.input.charCodeAt(pos++);
  11758. if (ch === 34 || ch === 39 || __acorn.isNewLine(ch)) { break }
  11759. }
  11760. } else if (/unexpected character/i.test(msg)) {
  11761. pos++;
  11762. replace = false;
  11763. } else if (/regular expression/i.test(msg)) {
  11764. replace = true;
  11765. } else {
  11766. throw e
  11767. }
  11768. this$1.resetTo(pos);
  11769. if (replace === true) { replace = {start: pos, end: pos, type: __acorn.tokTypes.name, value: "✖"}; }
  11770. if (replace) {
  11771. if (this$1.options.locations)
  11772. { replace.loc = new __acorn.SourceLocation(
  11773. this$1.toks,
  11774. __acorn.getLineInfo(this$1.input, replace.start),
  11775. __acorn.getLineInfo(this$1.input, replace.end)); }
  11776. return replace
  11777. }
  11778. }
  11779. }
  11780. };
  11781. lp.resetTo = function(pos) {
  11782. var this$1 = this;
  11783. this.toks.pos = pos;
  11784. var ch = this.input.charAt(pos - 1);
  11785. this.toks.exprAllowed = !ch || /[[{(,;:?/*=+\-~!|&%^<>]/.test(ch) ||
  11786. /[enwfd]/.test(ch) &&
  11787. /\b(keywords|case|else|return|throw|new|in|(instance|type)of|delete|void)$/.test(this.input.slice(pos - 10, pos));
  11788. if (this.options.locations) {
  11789. this.toks.curLine = 1;
  11790. this.toks.lineStart = __acorn.lineBreakG.lastIndex = 0;
  11791. var match;
  11792. while ((match = __acorn.lineBreakG.exec(this.input)) && match.index < pos) {
  11793. ++this$1.toks.curLine;
  11794. this$1.toks.lineStart = match.index + match[0].length;
  11795. }
  11796. }
  11797. };
  11798. lp.lookAhead = function(n) {
  11799. var this$1 = this;
  11800. while (n > this.ahead.length)
  11801. { this$1.ahead.push(this$1.readToken()); }
  11802. return this.ahead[n - 1]
  11803. };
  11804. function isDummy(node) { return node.name == "✖" }
  11805. var lp$1 = LooseParser.prototype;
  11806. lp$1.parseTopLevel = function() {
  11807. var this$1 = this;
  11808. var node = this.startNodeAt(this.options.locations ? [0, __acorn.getLineInfo(this.input, 0)] : 0);
  11809. node.body = [];
  11810. while (this.tok.type !== __acorn.tokTypes.eof) { node.body.push(this$1.parseStatement()); }
  11811. this.toks.adaptDirectivePrologue(node.body);
  11812. this.last = this.tok;
  11813. if (this.options.ecmaVersion >= 6) {
  11814. node.sourceType = this.options.sourceType;
  11815. }
  11816. return this.finishNode(node, "Program")
  11817. };
  11818. lp$1.parseStatement = function() {
  11819. var this$1 = this;
  11820. var starttype = this.tok.type, node = this.startNode(), kind;
  11821. if (this.toks.isLet()) {
  11822. starttype = __acorn.tokTypes._var;
  11823. kind = "let";
  11824. }
  11825. switch (starttype) {
  11826. case __acorn.tokTypes._break: case __acorn.tokTypes._continue:
  11827. this.next();
  11828. var isBreak = starttype === __acorn.tokTypes._break;
  11829. if (this.semicolon() || this.canInsertSemicolon()) {
  11830. node.label = null;
  11831. } else {
  11832. node.label = this.tok.type === __acorn.tokTypes.name ? this.parseIdent() : null;
  11833. this.semicolon();
  11834. }
  11835. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  11836. case __acorn.tokTypes._debugger:
  11837. this.next();
  11838. this.semicolon();
  11839. return this.finishNode(node, "DebuggerStatement")
  11840. case __acorn.tokTypes._do:
  11841. this.next();
  11842. node.body = this.parseStatement();
  11843. node.test = this.eat(__acorn.tokTypes._while) ? this.parseParenExpression() : this.dummyIdent();
  11844. this.semicolon();
  11845. return this.finishNode(node, "DoWhileStatement")
  11846. case __acorn.tokTypes._for:
  11847. this.next();
  11848. this.pushCx();
  11849. this.expect(__acorn.tokTypes.parenL);
  11850. if (this.tok.type === __acorn.tokTypes.semi) { return this.parseFor(node, null) }
  11851. var isLet = this.toks.isLet();
  11852. if (isLet || this.tok.type === __acorn.tokTypes._var || this.tok.type === __acorn.tokTypes._const) {
  11853. var init$1 = this.parseVar(true, isLet ? "let" : this.tok.value);
  11854. if (init$1.declarations.length === 1 && (this.tok.type === __acorn.tokTypes._in || this.isContextual("of"))) {
  11855. return this.parseForIn(node, init$1)
  11856. }
  11857. return this.parseFor(node, init$1)
  11858. }
  11859. var init = this.parseExpression(true);
  11860. if (this.tok.type === __acorn.tokTypes._in || this.isContextual("of"))
  11861. { return this.parseForIn(node, this.toAssignable(init)) }
  11862. return this.parseFor(node, init)
  11863. case __acorn.tokTypes._function:
  11864. this.next();
  11865. return this.parseFunction(node, true)
  11866. case __acorn.tokTypes._if:
  11867. this.next();
  11868. node.test = this.parseParenExpression();
  11869. node.consequent = this.parseStatement();
  11870. node.alternate = this.eat(__acorn.tokTypes._else) ? this.parseStatement() : null;
  11871. return this.finishNode(node, "IfStatement")
  11872. case __acorn.tokTypes._return:
  11873. this.next();
  11874. if (this.eat(__acorn.tokTypes.semi) || this.canInsertSemicolon()) { node.argument = null; }
  11875. else { node.argument = this.parseExpression(); this.semicolon(); }
  11876. return this.finishNode(node, "ReturnStatement")
  11877. case __acorn.tokTypes._switch:
  11878. var blockIndent = this.curIndent, line = this.curLineStart;
  11879. this.next();
  11880. node.discriminant = this.parseParenExpression();
  11881. node.cases = [];
  11882. this.pushCx();
  11883. this.expect(__acorn.tokTypes.braceL);
  11884. var cur;
  11885. while (!this.closes(__acorn.tokTypes.braceR, blockIndent, line, true)) {
  11886. if (this$1.tok.type === __acorn.tokTypes._case || this$1.tok.type === __acorn.tokTypes._default) {
  11887. var isCase = this$1.tok.type === __acorn.tokTypes._case;
  11888. if (cur) { this$1.finishNode(cur, "SwitchCase"); }
  11889. node.cases.push(cur = this$1.startNode());
  11890. cur.consequent = [];
  11891. this$1.next();
  11892. if (isCase) { cur.test = this$1.parseExpression(); }
  11893. else { cur.test = null; }
  11894. this$1.expect(__acorn.tokTypes.colon);
  11895. } else {
  11896. if (!cur) {
  11897. node.cases.push(cur = this$1.startNode());
  11898. cur.consequent = [];
  11899. cur.test = null;
  11900. }
  11901. cur.consequent.push(this$1.parseStatement());
  11902. }
  11903. }
  11904. if (cur) { this.finishNode(cur, "SwitchCase"); }
  11905. this.popCx();
  11906. this.eat(__acorn.tokTypes.braceR);
  11907. return this.finishNode(node, "SwitchStatement")
  11908. case __acorn.tokTypes._throw:
  11909. this.next();
  11910. node.argument = this.parseExpression();
  11911. this.semicolon();
  11912. return this.finishNode(node, "ThrowStatement")
  11913. case __acorn.tokTypes._try:
  11914. this.next();
  11915. node.block = this.parseBlock();
  11916. node.handler = null;
  11917. if (this.tok.type === __acorn.tokTypes._catch) {
  11918. var clause = this.startNode();
  11919. this.next();
  11920. this.expect(__acorn.tokTypes.parenL);
  11921. clause.param = this.toAssignable(this.parseExprAtom(), true);
  11922. this.expect(__acorn.tokTypes.parenR);
  11923. clause.body = this.parseBlock();
  11924. node.handler = this.finishNode(clause, "CatchClause");
  11925. }
  11926. node.finalizer = this.eat(__acorn.tokTypes._finally) ? this.parseBlock() : null;
  11927. if (!node.handler && !node.finalizer) { return node.block }
  11928. return this.finishNode(node, "TryStatement")
  11929. case __acorn.tokTypes._var:
  11930. case __acorn.tokTypes._const:
  11931. return this.parseVar(false, kind || this.tok.value)
  11932. case __acorn.tokTypes._while:
  11933. this.next();
  11934. node.test = this.parseParenExpression();
  11935. node.body = this.parseStatement();
  11936. return this.finishNode(node, "WhileStatement")
  11937. case __acorn.tokTypes._with:
  11938. this.next();
  11939. node.object = this.parseParenExpression();
  11940. node.body = this.parseStatement();
  11941. return this.finishNode(node, "WithStatement")
  11942. case __acorn.tokTypes.braceL:
  11943. return this.parseBlock()
  11944. case __acorn.tokTypes.semi:
  11945. this.next();
  11946. return this.finishNode(node, "EmptyStatement")
  11947. case __acorn.tokTypes._class:
  11948. return this.parseClass(true)
  11949. case __acorn.tokTypes._import:
  11950. return this.parseImport()
  11951. case __acorn.tokTypes._export:
  11952. return this.parseExport()
  11953. default:
  11954. if (this.toks.isAsyncFunction()) {
  11955. this.next();
  11956. this.next();
  11957. return this.parseFunction(node, true, true)
  11958. }
  11959. var expr = this.parseExpression();
  11960. if (isDummy(expr)) {
  11961. this.next();
  11962. if (this.tok.type === __acorn.tokTypes.eof) { return this.finishNode(node, "EmptyStatement") }
  11963. return this.parseStatement()
  11964. } else if (starttype === __acorn.tokTypes.name && expr.type === "Identifier" && this.eat(__acorn.tokTypes.colon)) {
  11965. node.body = this.parseStatement();
  11966. node.label = expr;
  11967. return this.finishNode(node, "LabeledStatement")
  11968. } else {
  11969. node.expression = expr;
  11970. this.semicolon();
  11971. return this.finishNode(node, "ExpressionStatement")
  11972. }
  11973. }
  11974. };
  11975. lp$1.parseBlock = function() {
  11976. var this$1 = this;
  11977. var node = this.startNode();
  11978. this.pushCx();
  11979. this.expect(__acorn.tokTypes.braceL);
  11980. var blockIndent = this.curIndent, line = this.curLineStart;
  11981. node.body = [];
  11982. while (!this.closes(__acorn.tokTypes.braceR, blockIndent, line, true))
  11983. { node.body.push(this$1.parseStatement()); }
  11984. this.popCx();
  11985. this.eat(__acorn.tokTypes.braceR);
  11986. return this.finishNode(node, "BlockStatement")
  11987. };
  11988. lp$1.parseFor = function(node, init) {
  11989. node.init = init;
  11990. node.test = node.update = null;
  11991. if (this.eat(__acorn.tokTypes.semi) && this.tok.type !== __acorn.tokTypes.semi) { node.test = this.parseExpression(); }
  11992. if (this.eat(__acorn.tokTypes.semi) && this.tok.type !== __acorn.tokTypes.parenR) { node.update = this.parseExpression(); }
  11993. this.popCx();
  11994. this.expect(__acorn.tokTypes.parenR);
  11995. node.body = this.parseStatement();
  11996. return this.finishNode(node, "ForStatement")
  11997. };
  11998. lp$1.parseForIn = function(node, init) {
  11999. var type = this.tok.type === __acorn.tokTypes._in ? "ForInStatement" : "ForOfStatement";
  12000. this.next();
  12001. node.left = init;
  12002. node.right = this.parseExpression();
  12003. this.popCx();
  12004. this.expect(__acorn.tokTypes.parenR);
  12005. node.body = this.parseStatement();
  12006. return this.finishNode(node, type)
  12007. };
  12008. lp$1.parseVar = function(noIn, kind) {
  12009. var this$1 = this;
  12010. var node = this.startNode();
  12011. node.kind = kind;
  12012. this.next();
  12013. node.declarations = [];
  12014. do {
  12015. var decl = this$1.startNode();
  12016. decl.id = this$1.options.ecmaVersion >= 6 ? this$1.toAssignable(this$1.parseExprAtom(), true) : this$1.parseIdent();
  12017. decl.init = this$1.eat(__acorn.tokTypes.eq) ? this$1.parseMaybeAssign(noIn) : null;
  12018. node.declarations.push(this$1.finishNode(decl, "VariableDeclarator"));
  12019. } while (this.eat(__acorn.tokTypes.comma))
  12020. if (!node.declarations.length) {
  12021. var decl$1 = this.startNode();
  12022. decl$1.id = this.dummyIdent();
  12023. node.declarations.push(this.finishNode(decl$1, "VariableDeclarator"));
  12024. }
  12025. if (!noIn) { this.semicolon(); }
  12026. return this.finishNode(node, "VariableDeclaration")
  12027. };
  12028. lp$1.parseClass = function(isStatement) {
  12029. var this$1 = this;
  12030. var node = this.startNode();
  12031. this.next();
  12032. if (this.tok.type === __acorn.tokTypes.name) { node.id = this.parseIdent(); }
  12033. else if (isStatement === true) { node.id = this.dummyIdent(); }
  12034. else { node.id = null; }
  12035. node.superClass = this.eat(__acorn.tokTypes._extends) ? this.parseExpression() : null;
  12036. node.body = this.startNode();
  12037. node.body.body = [];
  12038. this.pushCx();
  12039. var indent = this.curIndent + 1, line = this.curLineStart;
  12040. this.eat(__acorn.tokTypes.braceL);
  12041. if (this.curIndent + 1 < indent) { indent = this.curIndent; line = this.curLineStart; }
  12042. while (!this.closes(__acorn.tokTypes.braceR, indent, line)) {
  12043. if (this$1.semicolon()) { continue }
  12044. var method = this$1.startNode(), isGenerator = (void 0), isAsync = (void 0);
  12045. if (this$1.options.ecmaVersion >= 6) {
  12046. method.static = false;
  12047. isGenerator = this$1.eat(__acorn.tokTypes.star);
  12048. }
  12049. this$1.parsePropertyName(method);
  12050. if (isDummy(method.key)) { if (isDummy(this$1.parseMaybeAssign())) { this$1.next(); } this$1.eat(__acorn.tokTypes.comma); continue }
  12051. if (method.key.type === "Identifier" && !method.computed && method.key.name === "static" &&
  12052. (this$1.tok.type != __acorn.tokTypes.parenL && this$1.tok.type != __acorn.tokTypes.braceL)) {
  12053. method.static = true;
  12054. isGenerator = this$1.eat(__acorn.tokTypes.star);
  12055. this$1.parsePropertyName(method);
  12056. } else {
  12057. method.static = false;
  12058. }
  12059. if (!method.computed &&
  12060. method.key.type === "Identifier" && method.key.name === "async" && this$1.tok.type !== __acorn.tokTypes.parenL &&
  12061. !this$1.canInsertSemicolon()) {
  12062. this$1.parsePropertyName(method);
  12063. isAsync = true;
  12064. } else {
  12065. isAsync = false;
  12066. }
  12067. if (this$1.options.ecmaVersion >= 5 && method.key.type === "Identifier" &&
  12068. !method.computed && (method.key.name === "get" || method.key.name === "set") &&
  12069. this$1.tok.type !== __acorn.tokTypes.parenL && this$1.tok.type !== __acorn.tokTypes.braceL) {
  12070. method.kind = method.key.name;
  12071. this$1.parsePropertyName(method);
  12072. method.value = this$1.parseMethod(false);
  12073. } else {
  12074. if (!method.computed && !method.static && !isGenerator && !isAsync && (
  12075. method.key.type === "Identifier" && method.key.name === "constructor" ||
  12076. method.key.type === "Literal" && method.key.value === "constructor")) {
  12077. method.kind = "constructor";
  12078. } else {
  12079. method.kind = "method";
  12080. }
  12081. method.value = this$1.parseMethod(isGenerator, isAsync);
  12082. }
  12083. node.body.body.push(this$1.finishNode(method, "MethodDefinition"));
  12084. }
  12085. this.popCx();
  12086. if (!this.eat(__acorn.tokTypes.braceR)) {
  12087. // If there is no closing brace, make the node span to the start
  12088. // of the next token (this is useful for Tern)
  12089. this.last.end = this.tok.start;
  12090. if (this.options.locations) { this.last.loc.end = this.tok.loc.start; }
  12091. }
  12092. this.semicolon();
  12093. this.finishNode(node.body, "ClassBody");
  12094. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  12095. };
  12096. lp$1.parseFunction = function(node, isStatement, isAsync) {
  12097. var oldInAsync = this.inAsync;
  12098. this.initFunction(node);
  12099. if (this.options.ecmaVersion >= 6) {
  12100. node.generator = this.eat(__acorn.tokTypes.star);
  12101. }
  12102. if (this.options.ecmaVersion >= 8) {
  12103. node.async = !!isAsync;
  12104. }
  12105. if (this.tok.type === __acorn.tokTypes.name) { node.id = this.parseIdent(); }
  12106. else if (isStatement === true) { node.id = this.dummyIdent(); }
  12107. this.inAsync = node.async;
  12108. node.params = this.parseFunctionParams();
  12109. node.body = this.parseBlock();
  12110. this.toks.adaptDirectivePrologue(node.body.body);
  12111. this.inAsync = oldInAsync;
  12112. return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression")
  12113. };
  12114. lp$1.parseExport = function() {
  12115. var node = this.startNode();
  12116. this.next();
  12117. if (this.eat(__acorn.tokTypes.star)) {
  12118. node.source = this.eatContextual("from") ? this.parseExprAtom() : this.dummyString();
  12119. return this.finishNode(node, "ExportAllDeclaration")
  12120. }
  12121. if (this.eat(__acorn.tokTypes._default)) {
  12122. // export default (function foo() {}) // This is FunctionExpression.
  12123. var isAsync;
  12124. if (this.tok.type === __acorn.tokTypes._function || (isAsync = this.toks.isAsyncFunction())) {
  12125. var fNode = this.startNode();
  12126. this.next();
  12127. if (isAsync) { this.next(); }
  12128. node.declaration = this.parseFunction(fNode, "nullableID", isAsync);
  12129. } else if (this.tok.type === __acorn.tokTypes._class) {
  12130. node.declaration = this.parseClass("nullableID");
  12131. } else {
  12132. node.declaration = this.parseMaybeAssign();
  12133. this.semicolon();
  12134. }
  12135. return this.finishNode(node, "ExportDefaultDeclaration")
  12136. }
  12137. if (this.tok.type.keyword || this.toks.isLet() || this.toks.isAsyncFunction()) {
  12138. node.declaration = this.parseStatement();
  12139. node.specifiers = [];
  12140. node.source = null;
  12141. } else {
  12142. node.declaration = null;
  12143. node.specifiers = this.parseExportSpecifierList();
  12144. node.source = this.eatContextual("from") ? this.parseExprAtom() : null;
  12145. this.semicolon();
  12146. }
  12147. return this.finishNode(node, "ExportNamedDeclaration")
  12148. };
  12149. lp$1.parseImport = function() {
  12150. var node = this.startNode();
  12151. this.next();
  12152. if (this.tok.type === __acorn.tokTypes.string) {
  12153. node.specifiers = [];
  12154. node.source = this.parseExprAtom();
  12155. } else {
  12156. var elt;
  12157. if (this.tok.type === __acorn.tokTypes.name && this.tok.value !== "from") {
  12158. elt = this.startNode();
  12159. elt.local = this.parseIdent();
  12160. this.finishNode(elt, "ImportDefaultSpecifier");
  12161. this.eat(__acorn.tokTypes.comma);
  12162. }
  12163. node.specifiers = this.parseImportSpecifierList();
  12164. node.source = this.eatContextual("from") && this.tok.type == __acorn.tokTypes.string ? this.parseExprAtom() : this.dummyString();
  12165. if (elt) { node.specifiers.unshift(elt); }
  12166. }
  12167. this.semicolon();
  12168. return this.finishNode(node, "ImportDeclaration")
  12169. };
  12170. lp$1.parseImportSpecifierList = function() {
  12171. var this$1 = this;
  12172. var elts = [];
  12173. if (this.tok.type === __acorn.tokTypes.star) {
  12174. var elt = this.startNode();
  12175. this.next();
  12176. elt.local = this.eatContextual("as") ? this.parseIdent() : this.dummyIdent();
  12177. elts.push(this.finishNode(elt, "ImportNamespaceSpecifier"));
  12178. } else {
  12179. var indent = this.curIndent, line = this.curLineStart, continuedLine = this.nextLineStart;
  12180. this.pushCx();
  12181. this.eat(__acorn.tokTypes.braceL);
  12182. if (this.curLineStart > continuedLine) { continuedLine = this.curLineStart; }
  12183. while (!this.closes(__acorn.tokTypes.braceR, indent + (this.curLineStart <= continuedLine ? 1 : 0), line)) {
  12184. var elt$1 = this$1.startNode();
  12185. if (this$1.eat(__acorn.tokTypes.star)) {
  12186. elt$1.local = this$1.eatContextual("as") ? this$1.parseIdent() : this$1.dummyIdent();
  12187. this$1.finishNode(elt$1, "ImportNamespaceSpecifier");
  12188. } else {
  12189. if (this$1.isContextual("from")) { break }
  12190. elt$1.imported = this$1.parseIdent();
  12191. if (isDummy(elt$1.imported)) { break }
  12192. elt$1.local = this$1.eatContextual("as") ? this$1.parseIdent() : elt$1.imported;
  12193. this$1.finishNode(elt$1, "ImportSpecifier");
  12194. }
  12195. elts.push(elt$1);
  12196. this$1.eat(__acorn.tokTypes.comma);
  12197. }
  12198. this.eat(__acorn.tokTypes.braceR);
  12199. this.popCx();
  12200. }
  12201. return elts
  12202. };
  12203. lp$1.parseExportSpecifierList = function() {
  12204. var this$1 = this;
  12205. var elts = [];
  12206. var indent = this.curIndent, line = this.curLineStart, continuedLine = this.nextLineStart;
  12207. this.pushCx();
  12208. this.eat(__acorn.tokTypes.braceL);
  12209. if (this.curLineStart > continuedLine) { continuedLine = this.curLineStart; }
  12210. while (!this.closes(__acorn.tokTypes.braceR, indent + (this.curLineStart <= continuedLine ? 1 : 0), line)) {
  12211. if (this$1.isContextual("from")) { break }
  12212. var elt = this$1.startNode();
  12213. elt.local = this$1.parseIdent();
  12214. if (isDummy(elt.local)) { break }
  12215. elt.exported = this$1.eatContextual("as") ? this$1.parseIdent() : elt.local;
  12216. this$1.finishNode(elt, "ExportSpecifier");
  12217. elts.push(elt);
  12218. this$1.eat(__acorn.tokTypes.comma);
  12219. }
  12220. this.eat(__acorn.tokTypes.braceR);
  12221. this.popCx();
  12222. return elts
  12223. };
  12224. var lp$2 = LooseParser.prototype;
  12225. lp$2.checkLVal = function(expr) {
  12226. if (!expr) { return expr }
  12227. switch (expr.type) {
  12228. case "Identifier":
  12229. case "MemberExpression":
  12230. return expr
  12231. case "ParenthesizedExpression":
  12232. expr.expression = this.checkLVal(expr.expression);
  12233. return expr
  12234. default:
  12235. return this.dummyIdent()
  12236. }
  12237. };
  12238. lp$2.parseExpression = function(noIn) {
  12239. var this$1 = this;
  12240. var start = this.storeCurrentPos();
  12241. var expr = this.parseMaybeAssign(noIn);
  12242. if (this.tok.type === __acorn.tokTypes.comma) {
  12243. var node = this.startNodeAt(start);
  12244. node.expressions = [expr];
  12245. while (this.eat(__acorn.tokTypes.comma)) { node.expressions.push(this$1.parseMaybeAssign(noIn)); }
  12246. return this.finishNode(node, "SequenceExpression")
  12247. }
  12248. return expr
  12249. };
  12250. lp$2.parseParenExpression = function() {
  12251. this.pushCx();
  12252. this.expect(__acorn.tokTypes.parenL);
  12253. var val = this.parseExpression();
  12254. this.popCx();
  12255. this.expect(__acorn.tokTypes.parenR);
  12256. return val
  12257. };
  12258. lp$2.parseMaybeAssign = function(noIn) {
  12259. if (this.toks.isContextual("yield")) {
  12260. var node = this.startNode();
  12261. this.next();
  12262. if (this.semicolon() || this.canInsertSemicolon() || (this.tok.type != __acorn.tokTypes.star && !this.tok.type.startsExpr)) {
  12263. node.delegate = false;
  12264. node.argument = null;
  12265. } else {
  12266. node.delegate = this.eat(__acorn.tokTypes.star);
  12267. node.argument = this.parseMaybeAssign();
  12268. }
  12269. return this.finishNode(node, "YieldExpression")
  12270. }
  12271. var start = this.storeCurrentPos();
  12272. var left = this.parseMaybeConditional(noIn);
  12273. if (this.tok.type.isAssign) {
  12274. var node$1 = this.startNodeAt(start);
  12275. node$1.operator = this.tok.value;
  12276. node$1.left = this.tok.type === __acorn.tokTypes.eq ? this.toAssignable(left) : this.checkLVal(left);
  12277. this.next();
  12278. node$1.right = this.parseMaybeAssign(noIn);
  12279. return this.finishNode(node$1, "AssignmentExpression")
  12280. }
  12281. return left
  12282. };
  12283. lp$2.parseMaybeConditional = function(noIn) {
  12284. var start = this.storeCurrentPos();
  12285. var expr = this.parseExprOps(noIn);
  12286. if (this.eat(__acorn.tokTypes.question)) {
  12287. var node = this.startNodeAt(start);
  12288. node.test = expr;
  12289. node.consequent = this.parseMaybeAssign();
  12290. node.alternate = this.expect(__acorn.tokTypes.colon) ? this.parseMaybeAssign(noIn) : this.dummyIdent();
  12291. return this.finishNode(node, "ConditionalExpression")
  12292. }
  12293. return expr
  12294. };
  12295. lp$2.parseExprOps = function(noIn) {
  12296. var start = this.storeCurrentPos();
  12297. var indent = this.curIndent, line = this.curLineStart;
  12298. return this.parseExprOp(this.parseMaybeUnary(false), start, -1, noIn, indent, line)
  12299. };
  12300. lp$2.parseExprOp = function(left, start, minPrec, noIn, indent, line) {
  12301. if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) { return left }
  12302. var prec = this.tok.type.binop;
  12303. if (prec != null && (!noIn || this.tok.type !== __acorn.tokTypes._in)) {
  12304. if (prec > minPrec) {
  12305. var node = this.startNodeAt(start);
  12306. node.left = left;
  12307. node.operator = this.tok.value;
  12308. this.next();
  12309. if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) {
  12310. node.right = this.dummyIdent();
  12311. } else {
  12312. var rightStart = this.storeCurrentPos();
  12313. node.right = this.parseExprOp(this.parseMaybeUnary(false), rightStart, prec, noIn, indent, line);
  12314. }
  12315. this.finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression");
  12316. return this.parseExprOp(node, start, minPrec, noIn, indent, line)
  12317. }
  12318. }
  12319. return left
  12320. };
  12321. lp$2.parseMaybeUnary = function(sawUnary) {
  12322. var this$1 = this;
  12323. var start = this.storeCurrentPos(), expr;
  12324. if (this.options.ecmaVersion >= 8 && this.inAsync && this.toks.isContextual("await")) {
  12325. expr = this.parseAwait();
  12326. sawUnary = true;
  12327. } else if (this.tok.type.prefix) {
  12328. var node = this.startNode(), update = this.tok.type === __acorn.tokTypes.incDec;
  12329. if (!update) { sawUnary = true; }
  12330. node.operator = this.tok.value;
  12331. node.prefix = true;
  12332. this.next();
  12333. node.argument = this.parseMaybeUnary(true);
  12334. if (update) { node.argument = this.checkLVal(node.argument); }
  12335. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  12336. } else if (this.tok.type === __acorn.tokTypes.ellipsis) {
  12337. var node$1 = this.startNode();
  12338. this.next();
  12339. node$1.argument = this.parseMaybeUnary(sawUnary);
  12340. expr = this.finishNode(node$1, "SpreadElement");
  12341. } else {
  12342. expr = this.parseExprSubscripts();
  12343. while (this.tok.type.postfix && !this.canInsertSemicolon()) {
  12344. var node$2 = this$1.startNodeAt(start);
  12345. node$2.operator = this$1.tok.value;
  12346. node$2.prefix = false;
  12347. node$2.argument = this$1.checkLVal(expr);
  12348. this$1.next();
  12349. expr = this$1.finishNode(node$2, "UpdateExpression");
  12350. }
  12351. }
  12352. if (!sawUnary && this.eat(__acorn.tokTypes.starstar)) {
  12353. var node$3 = this.startNodeAt(start);
  12354. node$3.operator = "**";
  12355. node$3.left = expr;
  12356. node$3.right = this.parseMaybeUnary(false);
  12357. return this.finishNode(node$3, "BinaryExpression")
  12358. }
  12359. return expr
  12360. };
  12361. lp$2.parseExprSubscripts = function() {
  12362. var start = this.storeCurrentPos();
  12363. return this.parseSubscripts(this.parseExprAtom(), start, false, this.curIndent, this.curLineStart)
  12364. };
  12365. lp$2.parseSubscripts = function(base, start, noCalls, startIndent, line) {
  12366. var this$1 = this;
  12367. for (;;) {
  12368. if (this$1.curLineStart != line && this$1.curIndent <= startIndent && this$1.tokenStartsLine()) {
  12369. if (this$1.tok.type == __acorn.tokTypes.dot && this$1.curIndent == startIndent)
  12370. { --startIndent; }
  12371. else
  12372. { return base }
  12373. }
  12374. var maybeAsyncArrow = base.type === "Identifier" && base.name === "async" && !this$1.canInsertSemicolon();
  12375. if (this$1.eat(__acorn.tokTypes.dot)) {
  12376. var node = this$1.startNodeAt(start);
  12377. node.object = base;
  12378. if (this$1.curLineStart != line && this$1.curIndent <= startIndent && this$1.tokenStartsLine())
  12379. { node.property = this$1.dummyIdent(); }
  12380. else
  12381. { node.property = this$1.parsePropertyAccessor() || this$1.dummyIdent(); }
  12382. node.computed = false;
  12383. base = this$1.finishNode(node, "MemberExpression");
  12384. } else if (this$1.tok.type == __acorn.tokTypes.bracketL) {
  12385. this$1.pushCx();
  12386. this$1.next();
  12387. var node$1 = this$1.startNodeAt(start);
  12388. node$1.object = base;
  12389. node$1.property = this$1.parseExpression();
  12390. node$1.computed = true;
  12391. this$1.popCx();
  12392. this$1.expect(__acorn.tokTypes.bracketR);
  12393. base = this$1.finishNode(node$1, "MemberExpression");
  12394. } else if (!noCalls && this$1.tok.type == __acorn.tokTypes.parenL) {
  12395. var exprList = this$1.parseExprList(__acorn.tokTypes.parenR);
  12396. if (maybeAsyncArrow && this$1.eat(__acorn.tokTypes.arrow))
  12397. { return this$1.parseArrowExpression(this$1.startNodeAt(start), exprList, true) }
  12398. var node$2 = this$1.startNodeAt(start);
  12399. node$2.callee = base;
  12400. node$2.arguments = exprList;
  12401. base = this$1.finishNode(node$2, "CallExpression");
  12402. } else if (this$1.tok.type == __acorn.tokTypes.backQuote) {
  12403. var node$3 = this$1.startNodeAt(start);
  12404. node$3.tag = base;
  12405. node$3.quasi = this$1.parseTemplate();
  12406. base = this$1.finishNode(node$3, "TaggedTemplateExpression");
  12407. } else {
  12408. return base
  12409. }
  12410. }
  12411. };
  12412. lp$2.parseExprAtom = function() {
  12413. var node;
  12414. switch (this.tok.type) {
  12415. case __acorn.tokTypes._this:
  12416. case __acorn.tokTypes._super:
  12417. var type = this.tok.type === __acorn.tokTypes._this ? "ThisExpression" : "Super";
  12418. node = this.startNode();
  12419. this.next();
  12420. return this.finishNode(node, type)
  12421. case __acorn.tokTypes.name:
  12422. var start = this.storeCurrentPos();
  12423. var id = this.parseIdent();
  12424. var isAsync = false;
  12425. if (id.name === "async" && !this.canInsertSemicolon()) {
  12426. if (this.eat(__acorn.tokTypes._function))
  12427. { return this.parseFunction(this.startNodeAt(start), false, true) }
  12428. if (this.tok.type === __acorn.tokTypes.name) {
  12429. id = this.parseIdent();
  12430. isAsync = true;
  12431. }
  12432. }
  12433. return this.eat(__acorn.tokTypes.arrow) ? this.parseArrowExpression(this.startNodeAt(start), [id], isAsync) : id
  12434. case __acorn.tokTypes.regexp:
  12435. node = this.startNode();
  12436. var val = this.tok.value;
  12437. node.regex = {pattern: val.pattern, flags: val.flags};
  12438. node.value = val.value;
  12439. node.raw = this.input.slice(this.tok.start, this.tok.end);
  12440. this.next();
  12441. return this.finishNode(node, "Literal")
  12442. case __acorn.tokTypes.num: case __acorn.tokTypes.string:
  12443. node = this.startNode();
  12444. node.value = this.tok.value;
  12445. node.raw = this.input.slice(this.tok.start, this.tok.end);
  12446. this.next();
  12447. return this.finishNode(node, "Literal")
  12448. case __acorn.tokTypes._null: case __acorn.tokTypes._true: case __acorn.tokTypes._false:
  12449. node = this.startNode();
  12450. node.value = this.tok.type === __acorn.tokTypes._null ? null : this.tok.type === __acorn.tokTypes._true;
  12451. node.raw = this.tok.type.keyword;
  12452. this.next();
  12453. return this.finishNode(node, "Literal")
  12454. case __acorn.tokTypes.parenL:
  12455. var parenStart = this.storeCurrentPos();
  12456. this.next();
  12457. var inner = this.parseExpression();
  12458. this.expect(__acorn.tokTypes.parenR);
  12459. if (this.eat(__acorn.tokTypes.arrow)) {
  12460. // (a,)=>a // SequenceExpression makes dummy in the last hole. Drop the dummy.
  12461. var params = inner.expressions || [inner];
  12462. if (params.length && isDummy(params[params.length - 1]))
  12463. { params.pop(); }
  12464. return this.parseArrowExpression(this.startNodeAt(parenStart), params)
  12465. }
  12466. if (this.options.preserveParens) {
  12467. var par = this.startNodeAt(parenStart);
  12468. par.expression = inner;
  12469. inner = this.finishNode(par, "ParenthesizedExpression");
  12470. }
  12471. return inner
  12472. case __acorn.tokTypes.bracketL:
  12473. node = this.startNode();
  12474. node.elements = this.parseExprList(__acorn.tokTypes.bracketR, true);
  12475. return this.finishNode(node, "ArrayExpression")
  12476. case __acorn.tokTypes.braceL:
  12477. return this.parseObj()
  12478. case __acorn.tokTypes._class:
  12479. return this.parseClass(false)
  12480. case __acorn.tokTypes._function:
  12481. node = this.startNode();
  12482. this.next();
  12483. return this.parseFunction(node, false)
  12484. case __acorn.tokTypes._new:
  12485. return this.parseNew()
  12486. case __acorn.tokTypes.backQuote:
  12487. return this.parseTemplate()
  12488. default:
  12489. return this.dummyIdent()
  12490. }
  12491. };
  12492. lp$2.parseNew = function() {
  12493. var node = this.startNode(), startIndent = this.curIndent, line = this.curLineStart;
  12494. var meta = this.parseIdent(true);
  12495. if (this.options.ecmaVersion >= 6 && this.eat(__acorn.tokTypes.dot)) {
  12496. node.meta = meta;
  12497. node.property = this.parseIdent(true);
  12498. return this.finishNode(node, "MetaProperty")
  12499. }
  12500. var start = this.storeCurrentPos();
  12501. node.callee = this.parseSubscripts(this.parseExprAtom(), start, true, startIndent, line);
  12502. if (this.tok.type == __acorn.tokTypes.parenL) {
  12503. node.arguments = this.parseExprList(__acorn.tokTypes.parenR);
  12504. } else {
  12505. node.arguments = [];
  12506. }
  12507. return this.finishNode(node, "NewExpression")
  12508. };
  12509. lp$2.parseTemplateElement = function() {
  12510. var elem = this.startNode();
  12511. // The loose parser accepts invalid unicode escapes even in untagged templates.
  12512. if (this.tok.type === __acorn.tokTypes.invalidTemplate) {
  12513. elem.value = {
  12514. raw: this.tok.value,
  12515. cooked: null
  12516. };
  12517. } else {
  12518. elem.value = {
  12519. raw: this.input.slice(this.tok.start, this.tok.end).replace(/\r\n?/g, "\n"),
  12520. cooked: this.tok.value
  12521. };
  12522. }
  12523. this.next();
  12524. elem.tail = this.tok.type === __acorn.tokTypes.backQuote;
  12525. return this.finishNode(elem, "TemplateElement")
  12526. };
  12527. lp$2.parseTemplate = function() {
  12528. var this$1 = this;
  12529. var node = this.startNode();
  12530. this.next();
  12531. node.expressions = [];
  12532. var curElt = this.parseTemplateElement();
  12533. node.quasis = [curElt];
  12534. while (!curElt.tail) {
  12535. this$1.next();
  12536. node.expressions.push(this$1.parseExpression());
  12537. if (this$1.expect(__acorn.tokTypes.braceR)) {
  12538. curElt = this$1.parseTemplateElement();
  12539. } else {
  12540. curElt = this$1.startNode();
  12541. curElt.value = {cooked: "", raw: ""};
  12542. curElt.tail = true;
  12543. this$1.finishNode(curElt, "TemplateElement");
  12544. }
  12545. node.quasis.push(curElt);
  12546. }
  12547. this.expect(__acorn.tokTypes.backQuote);
  12548. return this.finishNode(node, "TemplateLiteral")
  12549. };
  12550. lp$2.parseObj = function() {
  12551. var this$1 = this;
  12552. var node = this.startNode();
  12553. node.properties = [];
  12554. this.pushCx();
  12555. var indent = this.curIndent + 1, line = this.curLineStart;
  12556. this.eat(__acorn.tokTypes.braceL);
  12557. if (this.curIndent + 1 < indent) { indent = this.curIndent; line = this.curLineStart; }
  12558. while (!this.closes(__acorn.tokTypes.braceR, indent, line)) {
  12559. var prop = this$1.startNode(), isGenerator = (void 0), isAsync = (void 0), start = (void 0);
  12560. if (this$1.options.ecmaVersion >= 6) {
  12561. start = this$1.storeCurrentPos();
  12562. prop.method = false;
  12563. prop.shorthand = false;
  12564. isGenerator = this$1.eat(__acorn.tokTypes.star);
  12565. }
  12566. this$1.parsePropertyName(prop);
  12567. if (this$1.toks.isAsyncProp(prop)) {
  12568. this$1.parsePropertyName(prop);
  12569. isAsync = true;
  12570. } else {
  12571. isAsync = false;
  12572. }
  12573. if (isDummy(prop.key)) { if (isDummy(this$1.parseMaybeAssign())) { this$1.next(); } this$1.eat(__acorn.tokTypes.comma); continue }
  12574. if (this$1.eat(__acorn.tokTypes.colon)) {
  12575. prop.kind = "init";
  12576. prop.value = this$1.parseMaybeAssign();
  12577. } else if (this$1.options.ecmaVersion >= 6 && (this$1.tok.type === __acorn.tokTypes.parenL || this$1.tok.type === __acorn.tokTypes.braceL)) {
  12578. prop.kind = "init";
  12579. prop.method = true;
  12580. prop.value = this$1.parseMethod(isGenerator, isAsync);
  12581. } else if (this$1.options.ecmaVersion >= 5 && prop.key.type === "Identifier" &&
  12582. !prop.computed && (prop.key.name === "get" || prop.key.name === "set") &&
  12583. (this$1.tok.type != __acorn.tokTypes.comma && this$1.tok.type != __acorn.tokTypes.braceR && this$1.tok.type != __acorn.tokTypes.eq)) {
  12584. prop.kind = prop.key.name;
  12585. this$1.parsePropertyName(prop);
  12586. prop.value = this$1.parseMethod(false);
  12587. } else {
  12588. prop.kind = "init";
  12589. if (this$1.options.ecmaVersion >= 6) {
  12590. if (this$1.eat(__acorn.tokTypes.eq)) {
  12591. var assign = this$1.startNodeAt(start);
  12592. assign.operator = "=";
  12593. assign.left = prop.key;
  12594. assign.right = this$1.parseMaybeAssign();
  12595. prop.value = this$1.finishNode(assign, "AssignmentExpression");
  12596. } else {
  12597. prop.value = prop.key;
  12598. }
  12599. } else {
  12600. prop.value = this$1.dummyIdent();
  12601. }
  12602. prop.shorthand = true;
  12603. }
  12604. node.properties.push(this$1.finishNode(prop, "Property"));
  12605. this$1.eat(__acorn.tokTypes.comma);
  12606. }
  12607. this.popCx();
  12608. if (!this.eat(__acorn.tokTypes.braceR)) {
  12609. // If there is no closing brace, make the node span to the start
  12610. // of the next token (this is useful for Tern)
  12611. this.last.end = this.tok.start;
  12612. if (this.options.locations) { this.last.loc.end = this.tok.loc.start; }
  12613. }
  12614. return this.finishNode(node, "ObjectExpression")
  12615. };
  12616. lp$2.parsePropertyName = function(prop) {
  12617. if (this.options.ecmaVersion >= 6) {
  12618. if (this.eat(__acorn.tokTypes.bracketL)) {
  12619. prop.computed = true;
  12620. prop.key = this.parseExpression();
  12621. this.expect(__acorn.tokTypes.bracketR);
  12622. return
  12623. } else {
  12624. prop.computed = false;
  12625. }
  12626. }
  12627. var key = (this.tok.type === __acorn.tokTypes.num || this.tok.type === __acorn.tokTypes.string) ? this.parseExprAtom() : this.parseIdent();
  12628. prop.key = key || this.dummyIdent();
  12629. };
  12630. lp$2.parsePropertyAccessor = function() {
  12631. if (this.tok.type === __acorn.tokTypes.name || this.tok.type.keyword) { return this.parseIdent() }
  12632. };
  12633. lp$2.parseIdent = function() {
  12634. var name = this.tok.type === __acorn.tokTypes.name ? this.tok.value : this.tok.type.keyword;
  12635. if (!name) { return this.dummyIdent() }
  12636. var node = this.startNode();
  12637. this.next();
  12638. node.name = name;
  12639. return this.finishNode(node, "Identifier")
  12640. };
  12641. lp$2.initFunction = function(node) {
  12642. node.id = null;
  12643. node.params = [];
  12644. if (this.options.ecmaVersion >= 6) {
  12645. node.generator = false;
  12646. node.expression = false;
  12647. }
  12648. if (this.options.ecmaVersion >= 8)
  12649. { node.async = false; }
  12650. };
  12651. // Convert existing expression atom to assignable pattern
  12652. // if possible.
  12653. lp$2.toAssignable = function(node, binding) {
  12654. var this$1 = this;
  12655. if (!node || node.type == "Identifier" || (node.type == "MemberExpression" && !binding)) {
  12656. // Okay
  12657. } else if (node.type == "ParenthesizedExpression") {
  12658. this.toAssignable(node.expression, binding);
  12659. } else if (this.options.ecmaVersion < 6) {
  12660. return this.dummyIdent()
  12661. } else if (node.type == "ObjectExpression") {
  12662. node.type = "ObjectPattern";
  12663. var props = node.properties;
  12664. for (var i = 0, list = props; i < list.length; i += 1)
  12665. {
  12666. var prop = list[i];
  12667. this$1.toAssignable(prop.value, binding);
  12668. }
  12669. } else if (node.type == "ArrayExpression") {
  12670. node.type = "ArrayPattern";
  12671. this.toAssignableList(node.elements, binding);
  12672. } else if (node.type == "SpreadElement") {
  12673. node.type = "RestElement";
  12674. this.toAssignable(node.argument, binding);
  12675. } else if (node.type == "AssignmentExpression") {
  12676. node.type = "AssignmentPattern";
  12677. delete node.operator;
  12678. } else {
  12679. return this.dummyIdent()
  12680. }
  12681. return node
  12682. };
  12683. lp$2.toAssignableList = function(exprList, binding) {
  12684. var this$1 = this;
  12685. for (var i = 0, list = exprList; i < list.length; i += 1)
  12686. {
  12687. var expr = list[i];
  12688. this$1.toAssignable(expr, binding);
  12689. }
  12690. return exprList
  12691. };
  12692. lp$2.parseFunctionParams = function(params) {
  12693. params = this.parseExprList(__acorn.tokTypes.parenR);
  12694. return this.toAssignableList(params, true)
  12695. };
  12696. lp$2.parseMethod = function(isGenerator, isAsync) {
  12697. var node = this.startNode(), oldInAsync = this.inAsync;
  12698. this.initFunction(node);
  12699. if (this.options.ecmaVersion >= 6)
  12700. { node.generator = !!isGenerator; }
  12701. if (this.options.ecmaVersion >= 8)
  12702. { node.async = !!isAsync; }
  12703. this.inAsync = node.async;
  12704. node.params = this.parseFunctionParams();
  12705. node.body = this.parseBlock();
  12706. this.toks.adaptDirectivePrologue(node.body.body);
  12707. this.inAsync = oldInAsync;
  12708. return this.finishNode(node, "FunctionExpression")
  12709. };
  12710. lp$2.parseArrowExpression = function(node, params, isAsync) {
  12711. var oldInAsync = this.inAsync;
  12712. this.initFunction(node);
  12713. if (this.options.ecmaVersion >= 8)
  12714. { node.async = !!isAsync; }
  12715. this.inAsync = node.async;
  12716. node.params = this.toAssignableList(params, true);
  12717. node.expression = this.tok.type !== __acorn.tokTypes.braceL;
  12718. if (node.expression) {
  12719. node.body = this.parseMaybeAssign();
  12720. } else {
  12721. node.body = this.parseBlock();
  12722. this.toks.adaptDirectivePrologue(node.body.body);
  12723. }
  12724. this.inAsync = oldInAsync;
  12725. return this.finishNode(node, "ArrowFunctionExpression")
  12726. };
  12727. lp$2.parseExprList = function(close, allowEmpty) {
  12728. var this$1 = this;
  12729. this.pushCx();
  12730. var indent = this.curIndent, line = this.curLineStart, elts = [];
  12731. this.next(); // Opening bracket
  12732. while (!this.closes(close, indent + 1, line)) {
  12733. if (this$1.eat(__acorn.tokTypes.comma)) {
  12734. elts.push(allowEmpty ? null : this$1.dummyIdent());
  12735. continue
  12736. }
  12737. var elt = this$1.parseMaybeAssign();
  12738. if (isDummy(elt)) {
  12739. if (this$1.closes(close, indent, line)) { break }
  12740. this$1.next();
  12741. } else {
  12742. elts.push(elt);
  12743. }
  12744. this$1.eat(__acorn.tokTypes.comma);
  12745. }
  12746. this.popCx();
  12747. if (!this.eat(close)) {
  12748. // If there is no closing brace, make the node span to the start
  12749. // of the next token (this is useful for Tern)
  12750. this.last.end = this.tok.start;
  12751. if (this.options.locations) { this.last.loc.end = this.tok.loc.start; }
  12752. }
  12753. return elts
  12754. };
  12755. lp$2.parseAwait = function() {
  12756. var node = this.startNode();
  12757. this.next();
  12758. node.argument = this.parseMaybeUnary();
  12759. return this.finishNode(node, "AwaitExpression")
  12760. };
  12761. // Acorn: Loose parser
  12762. //
  12763. // This module provides an alternative parser (`parse_dammit`) that
  12764. // exposes that same interface as `parse`, but will try to parse
  12765. // anything as JavaScript, repairing syntax error the best it can.
  12766. // There are circumstances in which it will raise an error and give
  12767. // up, but they are very rare. The resulting AST will be a mostly
  12768. // valid JavaScript AST (as per the [Mozilla parser API][api], except
  12769. // that:
  12770. //
  12771. // - Return outside functions is allowed
  12772. //
  12773. // - Label consistency (no conflicts, break only to existing labels)
  12774. // is not enforced.
  12775. //
  12776. // - Bogus Identifier nodes with a name of `"✖"` are inserted whenever
  12777. // the parser got too confused to return anything meaningful.
  12778. //
  12779. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  12780. //
  12781. // The expected use for this is to *first* try `acorn.parse`, and only
  12782. // if that fails switch to `parse_dammit`. The loose parser might
  12783. // parse badly indented code incorrectly, so **don't** use it as
  12784. // your default parser.
  12785. //
  12786. // Quite a lot of acorn.js is duplicated here. The alternative was to
  12787. // add a *lot* of extra cruft to that file, making it less readable
  12788. // and slower. Copying and editing the code allowed me to make
  12789. // invasive changes and simplifications without creating a complicated
  12790. // tangle.
  12791. __acorn.defaultOptions.tabSize = 4;
  12792. // eslint-disable-next-line camelcase
  12793. function parse_dammit(input, options) {
  12794. return new LooseParser(input, options).parse()
  12795. }
  12796. __acorn.addLooseExports(parse_dammit, LooseParser, pluginsLoose);
  12797. exports.parse_dammit = parse_dammit;
  12798. exports.LooseParser = LooseParser;
  12799. exports.pluginsLoose = pluginsLoose;
  12800. Object.defineProperty(exports, '__esModule', { value: true });
  12801. })));
  12802. /* <<< acorn-es7-plugin/acorn-v4.js >>> */
  12803. (function(acorn) {
  12804. var module = {exports: {}};
  12805. var asyncExit = /^async[\t ]+(return|throw)/ ;
  12806. var atomOrPropertyOrLabel = /^\s*[):;]/ ;
  12807. var removeComments = /([^\n])\/\*(\*(?!\/)|[^\n*])*\*\/([^\n])/g ;
  12808. function hasLineTerminatorBeforeNext(st, since) {
  12809. return st.lineStart >= since;
  12810. }
  12811. function test(regex,st,noComment) {
  12812. var src = st.input.slice(st.start) ;
  12813. if (noComment) {
  12814. src = src.replace(removeComments,"$1 $3") ;
  12815. }
  12816. return regex.test(src);
  12817. }
  12818. /* Create a new parser derived from the specified parser, so that in the
  12819. * event of an error we can back out and try again */
  12820. function subParse(parser, pos, extensions) {
  12821. var p = new parser.constructor(parser.options, parser.input, pos);
  12822. if (extensions)
  12823. for (var k in extensions)
  12824. p[k] = extensions[k] ;
  12825. var src = parser ;
  12826. var dest = p ;
  12827. ['inFunction','inAsync','inGenerator','inModule'].forEach(function(k){
  12828. if (k in src)
  12829. dest[k] = src[k] ;
  12830. }) ;
  12831. p.nextToken();
  12832. return p;
  12833. }
  12834. function asyncAwaitPlugin (parser,options){
  12835. if (!options || typeof options !== "object")
  12836. options = {} ;
  12837. parser.extend("parse",function(base){
  12838. return function(){
  12839. this.inAsync = options.inAsyncFunction ;
  12840. if (options.awaitAnywhere && options.inAsyncFunction)
  12841. parser.raise(node.start,"The options awaitAnywhere and inAsyncFunction are mutually exclusive") ;
  12842. return base.apply(this,arguments);
  12843. }
  12844. }) ;
  12845. parser.extend("parseStatement",function(base){
  12846. return function (declaration, topLevel) {
  12847. var start = this.start;
  12848. var startLoc = this.startLoc;
  12849. if (this.type.label==='name') {
  12850. if ((options.asyncExits) && test(asyncExit,this)) {
  12851. // TODO: Ensure this function is itself nested in an async function or Method
  12852. this.next() ;
  12853. var r = this.parseStatement(declaration, topLevel) ;
  12854. r.async = true ;
  12855. r.start = start;
  12856. r.loc && (r.loc.start = startLoc);
  12857. r.range && (r.range[0] = start);
  12858. return r ;
  12859. }
  12860. }
  12861. return base.apply(this,arguments);
  12862. }
  12863. }) ;
  12864. parser.extend("parseIdent",function(base){
  12865. return function(liberal) {
  12866. if (this.options.sourceType==='module' && this.options.ecmaVersion >= 8 && options.awaitAnywhere)
  12867. return base.call(this,true) ; // Force liberal mode if awaitAnywhere is set
  12868. return base.apply(this,arguments) ;
  12869. }
  12870. }) ;
  12871. parser.extend("parseExprAtom",function(base){
  12872. var NotAsync = {};
  12873. return function(refShorthandDefaultPos){
  12874. var start = this.start ;
  12875. var startLoc = this.startLoc;
  12876. var rhs,r = base.apply(this,arguments);
  12877. if (r.type==='Identifier') {
  12878. if (r.name==='await' && !this.inAsync) {
  12879. if (options.awaitAnywhere) {
  12880. var n = this.startNodeAt(r.start, r.loc && r.loc.start);
  12881. start = this.start ;
  12882. var parseHooks = {
  12883. raise:function(){
  12884. try {
  12885. return pp.raise.apply(this,arguments) ;
  12886. } catch(ex) {
  12887. throw /*inBody?ex:*/NotAsync ;
  12888. }
  12889. }
  12890. } ;
  12891. try {
  12892. rhs = subParse(this,start-4,parseHooks).parseExprSubscripts() ;
  12893. if (rhs.end<=start) {
  12894. rhs = subParse(this,start,parseHooks).parseExprSubscripts() ;
  12895. n.argument = rhs ;
  12896. n = this.finishNodeAt(n,'AwaitExpression', rhs.end, rhs.loc && rhs.loc.end) ;
  12897. this.pos = rhs.end;
  12898. this.end = rhs.end ;
  12899. this.endLoc = rhs.endLoc ;
  12900. this.next();
  12901. return n ;
  12902. }
  12903. } catch (ex) {
  12904. if (ex===NotAsync)
  12905. return r ;
  12906. throw ex ;
  12907. }
  12908. }
  12909. }
  12910. }
  12911. return r ;
  12912. }
  12913. }) ;
  12914. var allowedPropValues = {
  12915. undefined:true,
  12916. get:true,
  12917. set:true,
  12918. static:true,
  12919. async:true,
  12920. constructor:true
  12921. };
  12922. parser.extend("parsePropertyName",function(base){
  12923. return function (prop) {
  12924. var prevName = prop.key && prop.key.name ;
  12925. var key = base.apply(this,arguments) ;
  12926. if (this.value==='get') {
  12927. prop.__maybeStaticAsyncGetter = true ;
  12928. }
  12929. var next ;
  12930. if (allowedPropValues[this.value])
  12931. return key ;
  12932. if (key.type === "Identifier" && (key.name === "async" || prevName === "async") && !hasLineTerminatorBeforeNext(this, key.end)
  12933. // Look-ahead to see if this is really a property or label called async or await
  12934. && !this.input.slice(key.end).match(atomOrPropertyOrLabel)) {
  12935. if (prop.kind === 'set' || key.name === 'set')
  12936. this.raise(key.start,"'set <member>(value)' cannot be be async") ;
  12937. else {
  12938. this.__isAsyncProp = true ;
  12939. key = base.apply(this,arguments) ;
  12940. if (key.type==='Identifier') {
  12941. if (key.name==='set')
  12942. this.raise(key.start,"'set <member>(value)' cannot be be async") ;
  12943. }
  12944. }
  12945. } else {
  12946. delete prop.__maybeStaticAsyncGetter ;
  12947. }
  12948. return key;
  12949. };
  12950. }) ;
  12951. parser.extend("parseClassMethod",function(base){
  12952. return function (classBody, method, isGenerator) {
  12953. var r = base.apply(this,arguments) ;
  12954. if (method.__maybeStaticAsyncGetter) {
  12955. delete method.__maybeStaticAsyncGetter ;
  12956. if (method.key.name!=='get')
  12957. method.kind = "get" ;
  12958. }
  12959. return r ;
  12960. }
  12961. }) ;
  12962. parser.extend("parseFunctionBody",function(base){
  12963. return function (node, isArrowFunction) {
  12964. var wasAsync = this.inAsync ;
  12965. if (this.__isAsyncProp) {
  12966. node.async = true ;
  12967. this.inAsync = true ;
  12968. delete this.__isAsyncProp ;
  12969. }
  12970. var r = base.apply(this,arguments) ;
  12971. this.inAsync = wasAsync ;
  12972. return r ;
  12973. }
  12974. }) ;
  12975. }
  12976. module.exports = asyncAwaitPlugin ;
  12977. acorn.plugins.asyncawait = module.exports;
  12978. })(this.acorn);
  12979. /* <<< acorn-object-spread/inject.js >>> */
  12980. (function(acorn) {
  12981. var module = {exports: {}};
  12982. 'use strict';
  12983. module.exports = function(acorn) {
  12984. if (acorn.version.substr(0, 1) !== "5") {
  12985. throw new Error("Unsupported acorn version " + acorn.version + ", please use acorn 5");
  12986. }
  12987. var tt = acorn.tokTypes;
  12988. var pp = acorn.Parser.prototype;
  12989. // this is the same parseObj that acorn has with...
  12990. function parseObj(isPattern, refDestructuringErrors) {
  12991. var node = this.startNode(), first = true, propHash = {}
  12992. node.properties = []
  12993. this.next()
  12994. while (!this.eat(tt.braceR)) {
  12995. if (!first) {
  12996. this.expect(tt.comma)
  12997. if (this.afterTrailingComma(tt.braceR)) break
  12998. } else first = false
  12999. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc
  13000. if (this.options.ecmaVersion >= 6) {
  13001. // ...the spread logic borrowed from babylon :)
  13002. if (this.type === tt.ellipsis) {
  13003. if (isPattern) {
  13004. this.next()
  13005. prop.argument = this.parseIdent()
  13006. this.finishNode(prop, "RestElement")
  13007. } else {
  13008. prop = this.parseSpread(refDestructuringErrors)
  13009. }
  13010. node.properties.push(prop)
  13011. if (this.type === tt.comma) {
  13012. if (isPattern) {
  13013. this.raise(this.start, "Comma is not permitted after the rest element")
  13014. } else if (refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  13015. refDestructuringErrors.trailingComma = this.start
  13016. }
  13017. }
  13018. continue
  13019. }
  13020. prop.method = false
  13021. prop.shorthand = false
  13022. if (isPattern || refDestructuringErrors) {
  13023. startPos = this.start
  13024. startLoc = this.startLoc
  13025. }
  13026. if (!isPattern)
  13027. isGenerator = this.eat(tt.star)
  13028. }
  13029. this.parsePropertyName(prop)
  13030. if (!isPattern && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  13031. isAsync = true
  13032. this.parsePropertyName(prop, refDestructuringErrors)
  13033. } else {
  13034. isAsync = false
  13035. }
  13036. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors)
  13037. if (!isPattern) this.checkPropClash(prop, propHash)
  13038. node.properties.push(this.finishNode(prop, "Property"))
  13039. }
  13040. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  13041. }
  13042. const getCheckLVal = origCheckLVal => function (expr, bindingType, checkClashes) {
  13043. if (expr.type == "ObjectPattern") {
  13044. for (var prop of expr.properties)
  13045. this.checkLVal(prop, bindingType, checkClashes)
  13046. return
  13047. } else if (expr.type === "Property") {
  13048. // AssignmentProperty has type == "Property"
  13049. return this.checkLVal(expr.value, bindingType, checkClashes)
  13050. }
  13051. return origCheckLVal.apply(this, arguments)
  13052. }
  13053. acorn.plugins.objectSpread = function objectSpreadPlugin(instance) {
  13054. pp.parseObj = parseObj;
  13055. instance.extend("checkLVal", getCheckLVal)
  13056. instance.extend("toAssignable", nextMethod => function(node, isBinding) {
  13057. if (this.options.ecmaVersion >= 6 && node) {
  13058. if (node.type == "ObjectExpression") {
  13059. node.type = "ObjectPattern"
  13060. for (var prop of node.properties)
  13061. this.toAssignable(prop, isBinding)
  13062. return node
  13063. } else if (node.type === "Property") {
  13064. // AssignmentProperty has type == "Property"
  13065. if (node.kind !== "init") this.raise(node.key.start, "Object pattern can't contain getter or setter")
  13066. return this.toAssignable(node.value, isBinding)
  13067. } else if (node.type === "SpreadElement") {
  13068. node.type = "RestElement"
  13069. return this.toAssignable(node.argument, isBinding)
  13070. }
  13071. }
  13072. return nextMethod.apply(this, arguments)
  13073. })
  13074. instance.extend("checkPatternExport", nextMethod => function(exports, pat) {
  13075. if (pat.type == "ObjectPattern") {
  13076. for (var prop of pat.properties)
  13077. this.checkPatternExport(exports, prop)
  13078. return
  13079. } else if (pat.type === "Property") {
  13080. return this.checkPatternExport(exports, pat.value)
  13081. } else if (pat.type === "RestElement") {
  13082. return this.checkPatternExport(exports, pat.argument)
  13083. }
  13084. nextMethod.apply(this, arguments)
  13085. })
  13086. };
  13087. return acorn;
  13088. };
  13089. module.exports(acorn);
  13090. })(this.acorn);
  13091. /* <<< acorn-jsx/inject.js >>> */
  13092. (function(acorn) {
  13093. var module = {exports: {}};
  13094. 'use strict';
  13095. var XHTMLEntities = {
  13096. quot: '\u0022',
  13097. amp: '&',
  13098. apos: '\u0027',
  13099. lt: '<',
  13100. gt: '>',
  13101. nbsp: '\u00A0',
  13102. iexcl: '\u00A1',
  13103. cent: '\u00A2',
  13104. pound: '\u00A3',
  13105. curren: '\u00A4',
  13106. yen: '\u00A5',
  13107. brvbar: '\u00A6',
  13108. sect: '\u00A7',
  13109. uml: '\u00A8',
  13110. copy: '\u00A9',
  13111. ordf: '\u00AA',
  13112. laquo: '\u00AB',
  13113. not: '\u00AC',
  13114. shy: '\u00AD',
  13115. reg: '\u00AE',
  13116. macr: '\u00AF',
  13117. deg: '\u00B0',
  13118. plusmn: '\u00B1',
  13119. sup2: '\u00B2',
  13120. sup3: '\u00B3',
  13121. acute: '\u00B4',
  13122. micro: '\u00B5',
  13123. para: '\u00B6',
  13124. middot: '\u00B7',
  13125. cedil: '\u00B8',
  13126. sup1: '\u00B9',
  13127. ordm: '\u00BA',
  13128. raquo: '\u00BB',
  13129. frac14: '\u00BC',
  13130. frac12: '\u00BD',
  13131. frac34: '\u00BE',
  13132. iquest: '\u00BF',
  13133. Agrave: '\u00C0',
  13134. Aacute: '\u00C1',
  13135. Acirc: '\u00C2',
  13136. Atilde: '\u00C3',
  13137. Auml: '\u00C4',
  13138. Aring: '\u00C5',
  13139. AElig: '\u00C6',
  13140. Ccedil: '\u00C7',
  13141. Egrave: '\u00C8',
  13142. Eacute: '\u00C9',
  13143. Ecirc: '\u00CA',
  13144. Euml: '\u00CB',
  13145. Igrave: '\u00CC',
  13146. Iacute: '\u00CD',
  13147. Icirc: '\u00CE',
  13148. Iuml: '\u00CF',
  13149. ETH: '\u00D0',
  13150. Ntilde: '\u00D1',
  13151. Ograve: '\u00D2',
  13152. Oacute: '\u00D3',
  13153. Ocirc: '\u00D4',
  13154. Otilde: '\u00D5',
  13155. Ouml: '\u00D6',
  13156. times: '\u00D7',
  13157. Oslash: '\u00D8',
  13158. Ugrave: '\u00D9',
  13159. Uacute: '\u00DA',
  13160. Ucirc: '\u00DB',
  13161. Uuml: '\u00DC',
  13162. Yacute: '\u00DD',
  13163. THORN: '\u00DE',
  13164. szlig: '\u00DF',
  13165. agrave: '\u00E0',
  13166. aacute: '\u00E1',
  13167. acirc: '\u00E2',
  13168. atilde: '\u00E3',
  13169. auml: '\u00E4',
  13170. aring: '\u00E5',
  13171. aelig: '\u00E6',
  13172. ccedil: '\u00E7',
  13173. egrave: '\u00E8',
  13174. eacute: '\u00E9',
  13175. ecirc: '\u00EA',
  13176. euml: '\u00EB',
  13177. igrave: '\u00EC',
  13178. iacute: '\u00ED',
  13179. icirc: '\u00EE',
  13180. iuml: '\u00EF',
  13181. eth: '\u00F0',
  13182. ntilde: '\u00F1',
  13183. ograve: '\u00F2',
  13184. oacute: '\u00F3',
  13185. ocirc: '\u00F4',
  13186. otilde: '\u00F5',
  13187. ouml: '\u00F6',
  13188. divide: '\u00F7',
  13189. oslash: '\u00F8',
  13190. ugrave: '\u00F9',
  13191. uacute: '\u00FA',
  13192. ucirc: '\u00FB',
  13193. uuml: '\u00FC',
  13194. yacute: '\u00FD',
  13195. thorn: '\u00FE',
  13196. yuml: '\u00FF',
  13197. OElig: '\u0152',
  13198. oelig: '\u0153',
  13199. Scaron: '\u0160',
  13200. scaron: '\u0161',
  13201. Yuml: '\u0178',
  13202. fnof: '\u0192',
  13203. circ: '\u02C6',
  13204. tilde: '\u02DC',
  13205. Alpha: '\u0391',
  13206. Beta: '\u0392',
  13207. Gamma: '\u0393',
  13208. Delta: '\u0394',
  13209. Epsilon: '\u0395',
  13210. Zeta: '\u0396',
  13211. Eta: '\u0397',
  13212. Theta: '\u0398',
  13213. Iota: '\u0399',
  13214. Kappa: '\u039A',
  13215. Lambda: '\u039B',
  13216. Mu: '\u039C',
  13217. Nu: '\u039D',
  13218. Xi: '\u039E',
  13219. Omicron: '\u039F',
  13220. Pi: '\u03A0',
  13221. Rho: '\u03A1',
  13222. Sigma: '\u03A3',
  13223. Tau: '\u03A4',
  13224. Upsilon: '\u03A5',
  13225. Phi: '\u03A6',
  13226. Chi: '\u03A7',
  13227. Psi: '\u03A8',
  13228. Omega: '\u03A9',
  13229. alpha: '\u03B1',
  13230. beta: '\u03B2',
  13231. gamma: '\u03B3',
  13232. delta: '\u03B4',
  13233. epsilon: '\u03B5',
  13234. zeta: '\u03B6',
  13235. eta: '\u03B7',
  13236. theta: '\u03B8',
  13237. iota: '\u03B9',
  13238. kappa: '\u03BA',
  13239. lambda: '\u03BB',
  13240. mu: '\u03BC',
  13241. nu: '\u03BD',
  13242. xi: '\u03BE',
  13243. omicron: '\u03BF',
  13244. pi: '\u03C0',
  13245. rho: '\u03C1',
  13246. sigmaf: '\u03C2',
  13247. sigma: '\u03C3',
  13248. tau: '\u03C4',
  13249. upsilon: '\u03C5',
  13250. phi: '\u03C6',
  13251. chi: '\u03C7',
  13252. psi: '\u03C8',
  13253. omega: '\u03C9',
  13254. thetasym: '\u03D1',
  13255. upsih: '\u03D2',
  13256. piv: '\u03D6',
  13257. ensp: '\u2002',
  13258. emsp: '\u2003',
  13259. thinsp: '\u2009',
  13260. zwnj: '\u200C',
  13261. zwj: '\u200D',
  13262. lrm: '\u200E',
  13263. rlm: '\u200F',
  13264. ndash: '\u2013',
  13265. mdash: '\u2014',
  13266. lsquo: '\u2018',
  13267. rsquo: '\u2019',
  13268. sbquo: '\u201A',
  13269. ldquo: '\u201C',
  13270. rdquo: '\u201D',
  13271. bdquo: '\u201E',
  13272. dagger: '\u2020',
  13273. Dagger: '\u2021',
  13274. bull: '\u2022',
  13275. hellip: '\u2026',
  13276. permil: '\u2030',
  13277. prime: '\u2032',
  13278. Prime: '\u2033',
  13279. lsaquo: '\u2039',
  13280. rsaquo: '\u203A',
  13281. oline: '\u203E',
  13282. frasl: '\u2044',
  13283. euro: '\u20AC',
  13284. image: '\u2111',
  13285. weierp: '\u2118',
  13286. real: '\u211C',
  13287. trade: '\u2122',
  13288. alefsym: '\u2135',
  13289. larr: '\u2190',
  13290. uarr: '\u2191',
  13291. rarr: '\u2192',
  13292. darr: '\u2193',
  13293. harr: '\u2194',
  13294. crarr: '\u21B5',
  13295. lArr: '\u21D0',
  13296. uArr: '\u21D1',
  13297. rArr: '\u21D2',
  13298. dArr: '\u21D3',
  13299. hArr: '\u21D4',
  13300. forall: '\u2200',
  13301. part: '\u2202',
  13302. exist: '\u2203',
  13303. empty: '\u2205',
  13304. nabla: '\u2207',
  13305. isin: '\u2208',
  13306. notin: '\u2209',
  13307. ni: '\u220B',
  13308. prod: '\u220F',
  13309. sum: '\u2211',
  13310. minus: '\u2212',
  13311. lowast: '\u2217',
  13312. radic: '\u221A',
  13313. prop: '\u221D',
  13314. infin: '\u221E',
  13315. ang: '\u2220',
  13316. and: '\u2227',
  13317. or: '\u2228',
  13318. cap: '\u2229',
  13319. cup: '\u222A',
  13320. 'int': '\u222B',
  13321. there4: '\u2234',
  13322. sim: '\u223C',
  13323. cong: '\u2245',
  13324. asymp: '\u2248',
  13325. ne: '\u2260',
  13326. equiv: '\u2261',
  13327. le: '\u2264',
  13328. ge: '\u2265',
  13329. sub: '\u2282',
  13330. sup: '\u2283',
  13331. nsub: '\u2284',
  13332. sube: '\u2286',
  13333. supe: '\u2287',
  13334. oplus: '\u2295',
  13335. otimes: '\u2297',
  13336. perp: '\u22A5',
  13337. sdot: '\u22C5',
  13338. lceil: '\u2308',
  13339. rceil: '\u2309',
  13340. lfloor: '\u230A',
  13341. rfloor: '\u230B',
  13342. lang: '\u2329',
  13343. rang: '\u232A',
  13344. loz: '\u25CA',
  13345. spades: '\u2660',
  13346. clubs: '\u2663',
  13347. hearts: '\u2665',
  13348. diams: '\u2666'
  13349. };
  13350. var hexNumber = /^[\da-fA-F]+$/;
  13351. var decimalNumber = /^\d+$/;
  13352. module.exports = function(acorn) {
  13353. var tt = acorn.tokTypes;
  13354. var tc = acorn.tokContexts;
  13355. tc.j_oTag = new acorn.TokContext('<tag', false);
  13356. tc.j_cTag = new acorn.TokContext('</tag', false);
  13357. tc.j_expr = new acorn.TokContext('<tag>...</tag>', true, true);
  13358. tt.jsxName = new acorn.TokenType('jsxName');
  13359. tt.jsxText = new acorn.TokenType('jsxText', {beforeExpr: true});
  13360. tt.jsxTagStart = new acorn.TokenType('jsxTagStart');
  13361. tt.jsxTagEnd = new acorn.TokenType('jsxTagEnd');
  13362. tt.jsxTagStart.updateContext = function() {
  13363. this.context.push(tc.j_expr); // treat as beginning of JSX expression
  13364. this.context.push(tc.j_oTag); // start opening tag context
  13365. this.exprAllowed = false;
  13366. };
  13367. tt.jsxTagEnd.updateContext = function(prevType) {
  13368. var out = this.context.pop();
  13369. if (out === tc.j_oTag && prevType === tt.slash || out === tc.j_cTag) {
  13370. this.context.pop();
  13371. this.exprAllowed = this.curContext() === tc.j_expr;
  13372. } else {
  13373. this.exprAllowed = true;
  13374. }
  13375. };
  13376. var pp = acorn.Parser.prototype;
  13377. // Reads inline JSX contents token.
  13378. pp.jsx_readToken = function() {
  13379. var out = '', chunkStart = this.pos;
  13380. for (;;) {
  13381. if (this.pos >= this.input.length)
  13382. this.raise(this.start, 'Unterminated JSX contents');
  13383. var ch = this.input.charCodeAt(this.pos);
  13384. switch (ch) {
  13385. case 60: // '<'
  13386. case 123: // '{'
  13387. if (this.pos === this.start) {
  13388. if (ch === 60 && this.exprAllowed) {
  13389. ++this.pos;
  13390. return this.finishToken(tt.jsxTagStart);
  13391. }
  13392. return this.getTokenFromCode(ch);
  13393. }
  13394. out += this.input.slice(chunkStart, this.pos);
  13395. return this.finishToken(tt.jsxText, out);
  13396. case 38: // '&'
  13397. out += this.input.slice(chunkStart, this.pos);
  13398. out += this.jsx_readEntity();
  13399. chunkStart = this.pos;
  13400. break;
  13401. default:
  13402. if (acorn.isNewLine(ch)) {
  13403. out += this.input.slice(chunkStart, this.pos);
  13404. out += this.jsx_readNewLine(true);
  13405. chunkStart = this.pos;
  13406. } else {
  13407. ++this.pos;
  13408. }
  13409. }
  13410. }
  13411. };
  13412. pp.jsx_readNewLine = function(normalizeCRLF) {
  13413. var ch = this.input.charCodeAt(this.pos);
  13414. var out;
  13415. ++this.pos;
  13416. if (ch === 13 && this.input.charCodeAt(this.pos) === 10) {
  13417. ++this.pos;
  13418. out = normalizeCRLF ? '\n' : '\r\n';
  13419. } else {
  13420. out = String.fromCharCode(ch);
  13421. }
  13422. if (this.options.locations) {
  13423. ++this.curLine;
  13424. this.lineStart = this.pos;
  13425. }
  13426. return out;
  13427. };
  13428. pp.jsx_readString = function(quote) {
  13429. var out = '', chunkStart = ++this.pos;
  13430. for (;;) {
  13431. if (this.pos >= this.input.length)
  13432. this.raise(this.start, 'Unterminated string constant');
  13433. var ch = this.input.charCodeAt(this.pos);
  13434. if (ch === quote) break;
  13435. if (ch === 38) { // '&'
  13436. out += this.input.slice(chunkStart, this.pos);
  13437. out += this.jsx_readEntity();
  13438. chunkStart = this.pos;
  13439. } else if (acorn.isNewLine(ch)) {
  13440. out += this.input.slice(chunkStart, this.pos);
  13441. out += this.jsx_readNewLine(false);
  13442. chunkStart = this.pos;
  13443. } else {
  13444. ++this.pos;
  13445. }
  13446. }
  13447. out += this.input.slice(chunkStart, this.pos++);
  13448. return this.finishToken(tt.string, out);
  13449. };
  13450. pp.jsx_readEntity = function() {
  13451. var str = '', count = 0, entity;
  13452. var ch = this.input[this.pos];
  13453. if (ch !== '&')
  13454. this.raise(this.pos, 'Entity must start with an ampersand');
  13455. var startPos = ++this.pos;
  13456. while (this.pos < this.input.length && count++ < 10) {
  13457. ch = this.input[this.pos++];
  13458. if (ch === ';') {
  13459. if (str[0] === '#') {
  13460. if (str[1] === 'x') {
  13461. str = str.substr(2);
  13462. if (hexNumber.test(str))
  13463. entity = String.fromCharCode(parseInt(str, 16));
  13464. } else {
  13465. str = str.substr(1);
  13466. if (decimalNumber.test(str))
  13467. entity = String.fromCharCode(parseInt(str, 10));
  13468. }
  13469. } else {
  13470. entity = XHTMLEntities[str];
  13471. }
  13472. break;
  13473. }
  13474. str += ch;
  13475. }
  13476. if (!entity) {
  13477. this.pos = startPos;
  13478. return '&';
  13479. }
  13480. return entity;
  13481. };
  13482. // Read a JSX identifier (valid tag or attribute name).
  13483. //
  13484. // Optimized version since JSX identifiers can't contain
  13485. // escape characters and so can be read as single slice.
  13486. // Also assumes that first character was already checked
  13487. // by isIdentifierStart in readToken.
  13488. pp.jsx_readWord = function() {
  13489. var ch, start = this.pos;
  13490. do {
  13491. ch = this.input.charCodeAt(++this.pos);
  13492. } while (acorn.isIdentifierChar(ch) || ch === 45); // '-'
  13493. return this.finishToken(tt.jsxName, this.input.slice(start, this.pos));
  13494. };
  13495. // Transforms JSX element name to string.
  13496. function getQualifiedJSXName(object) {
  13497. if (!object)
  13498. return object;
  13499. if (object.type === 'JSXIdentifier')
  13500. return object.name;
  13501. if (object.type === 'JSXNamespacedName')
  13502. return object.namespace.name + ':' + object.name.name;
  13503. if (object.type === 'JSXMemberExpression')
  13504. return getQualifiedJSXName(object.object) + '.' +
  13505. getQualifiedJSXName(object.property);
  13506. }
  13507. // Parse next token as JSX identifier
  13508. pp.jsx_parseIdentifier = function() {
  13509. var node = this.startNode();
  13510. if (this.type === tt.jsxName)
  13511. node.name = this.value;
  13512. else if (this.type.keyword)
  13513. node.name = this.type.keyword;
  13514. else
  13515. this.unexpected();
  13516. this.next();
  13517. return this.finishNode(node, 'JSXIdentifier');
  13518. };
  13519. // Parse namespaced identifier.
  13520. pp.jsx_parseNamespacedName = function() {
  13521. var startPos = this.start, startLoc = this.startLoc;
  13522. var name = this.jsx_parseIdentifier();
  13523. if (!this.options.plugins.jsx.allowNamespaces || !this.eat(tt.colon)) return name;
  13524. var node = this.startNodeAt(startPos, startLoc);
  13525. node.namespace = name;
  13526. node.name = this.jsx_parseIdentifier();
  13527. return this.finishNode(node, 'JSXNamespacedName');
  13528. };
  13529. // Parses element name in any form - namespaced, member
  13530. // or single identifier.
  13531. pp.jsx_parseElementName = function() {
  13532. if (this.type === tt.jsxTagEnd)
  13533. return '';
  13534. var startPos = this.start, startLoc = this.startLoc;
  13535. var node = this.jsx_parseNamespacedName();
  13536. if (this.type === tt.dot && node.type === 'JSXNamespacedName' && !this.options.plugins.jsx.allowNamespacedObjects) {
  13537. this.unexpected();
  13538. }
  13539. while (this.eat(tt.dot)) {
  13540. var newNode = this.startNodeAt(startPos, startLoc);
  13541. newNode.object = node;
  13542. newNode.property = this.jsx_parseIdentifier();
  13543. node = this.finishNode(newNode, 'JSXMemberExpression');
  13544. }
  13545. return node;
  13546. };
  13547. // Parses any type of JSX attribute value.
  13548. pp.jsx_parseAttributeValue = function() {
  13549. switch (this.type) {
  13550. case tt.braceL:
  13551. var node = this.jsx_parseExpressionContainer();
  13552. if (node.expression.type === 'JSXEmptyExpression')
  13553. this.raise(node.start, 'JSX attributes must only be assigned a non-empty expression');
  13554. return node;
  13555. case tt.jsxTagStart:
  13556. case tt.string:
  13557. return this.parseExprAtom();
  13558. default:
  13559. this.raise(this.start, 'JSX value should be either an expression or a quoted JSX text');
  13560. }
  13561. };
  13562. // JSXEmptyExpression is unique type since it doesn't actually parse anything,
  13563. // and so it should start at the end of last read token (left brace) and finish
  13564. // at the beginning of the next one (right brace).
  13565. pp.jsx_parseEmptyExpression = function() {
  13566. var node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc);
  13567. return this.finishNodeAt(node, 'JSXEmptyExpression', this.start, this.startLoc);
  13568. };
  13569. // Parses JSX expression enclosed into curly brackets.
  13570. pp.jsx_parseExpressionContainer = function() {
  13571. var node = this.startNode();
  13572. this.next();
  13573. node.expression = this.type === tt.braceR
  13574. ? this.jsx_parseEmptyExpression()
  13575. : this.parseExpression();
  13576. this.expect(tt.braceR);
  13577. return this.finishNode(node, 'JSXExpressionContainer');
  13578. };
  13579. // Parses following JSX attribute name-value pair.
  13580. pp.jsx_parseAttribute = function() {
  13581. var node = this.startNode();
  13582. if (this.eat(tt.braceL)) {
  13583. this.expect(tt.ellipsis);
  13584. node.argument = this.parseMaybeAssign();
  13585. this.expect(tt.braceR);
  13586. return this.finishNode(node, 'JSXSpreadAttribute');
  13587. }
  13588. node.name = this.jsx_parseNamespacedName();
  13589. node.value = this.eat(tt.eq) ? this.jsx_parseAttributeValue() : null;
  13590. return this.finishNode(node, 'JSXAttribute');
  13591. };
  13592. // Parses JSX opening tag starting after '<'.
  13593. pp.jsx_parseOpeningElementAt = function(startPos, startLoc) {
  13594. var node = this.startNodeAt(startPos, startLoc);
  13595. node.attributes = [];
  13596. node.name = this.jsx_parseElementName();
  13597. while (this.type !== tt.slash && this.type !== tt.jsxTagEnd)
  13598. node.attributes.push(this.jsx_parseAttribute());
  13599. node.selfClosing = this.eat(tt.slash);
  13600. this.expect(tt.jsxTagEnd);
  13601. return this.finishNode(node, 'JSXOpeningElement');
  13602. };
  13603. // Parses JSX closing tag starting after '</'.
  13604. pp.jsx_parseClosingElementAt = function(startPos, startLoc) {
  13605. var node = this.startNodeAt(startPos, startLoc);
  13606. node.name = this.jsx_parseElementName();
  13607. this.expect(tt.jsxTagEnd);
  13608. return this.finishNode(node, 'JSXClosingElement');
  13609. };
  13610. // Parses entire JSX element, including it's opening tag
  13611. // (starting after '<'), attributes, contents and closing tag.
  13612. pp.jsx_parseElementAt = function(startPos, startLoc) {
  13613. var node = this.startNodeAt(startPos, startLoc);
  13614. var children = [];
  13615. var openingElement = this.jsx_parseOpeningElementAt(startPos, startLoc);
  13616. var closingElement = null;
  13617. if (!openingElement.selfClosing) {
  13618. contents: for (;;) {
  13619. switch (this.type) {
  13620. case tt.jsxTagStart:
  13621. startPos = this.start; startLoc = this.startLoc;
  13622. this.next();
  13623. if (this.eat(tt.slash)) {
  13624. closingElement = this.jsx_parseClosingElementAt(startPos, startLoc);
  13625. break contents;
  13626. }
  13627. children.push(this.jsx_parseElementAt(startPos, startLoc));
  13628. break;
  13629. case tt.jsxText:
  13630. children.push(this.parseExprAtom());
  13631. break;
  13632. case tt.braceL:
  13633. children.push(this.jsx_parseExpressionContainer());
  13634. break;
  13635. default:
  13636. this.unexpected();
  13637. }
  13638. }
  13639. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  13640. this.raise(
  13641. closingElement.start,
  13642. 'Expected corresponding JSX closing tag for <' + getQualifiedJSXName(openingElement.name) + '>');
  13643. }
  13644. }
  13645. node.openingElement = openingElement;
  13646. node.closingElement = closingElement;
  13647. node.children = children;
  13648. if (this.type === tt.relational && this.value === "<") {
  13649. this.raise(this.start, "Adjacent JSX elements must be wrapped in an enclosing tag");
  13650. }
  13651. return this.finishNode(node, openingElement.name ? 'JSXElement' : 'JSXFragment');
  13652. };
  13653. // Parse JSX text
  13654. pp.jsx_parseText = function(value) {
  13655. var node = this.parseLiteral(value);
  13656. node.type = "JSXText";
  13657. return node;
  13658. };
  13659. // Parses entire JSX element from current position.
  13660. pp.jsx_parseElement = function() {
  13661. var startPos = this.start, startLoc = this.startLoc;
  13662. this.next();
  13663. return this.jsx_parseElementAt(startPos, startLoc);
  13664. };
  13665. acorn.plugins.jsx = function(instance, opts) {
  13666. if (!opts) {
  13667. return;
  13668. }
  13669. if (typeof opts !== 'object') {
  13670. opts = {};
  13671. }
  13672. instance.options.plugins.jsx = {
  13673. allowNamespaces: opts.allowNamespaces !== false,
  13674. allowNamespacedObjects: !!opts.allowNamespacedObjects
  13675. };
  13676. instance.extend('parseExprAtom', function(inner) {
  13677. return function(refShortHandDefaultPos) {
  13678. if (this.type === tt.jsxText)
  13679. return this.jsx_parseText(this.value);
  13680. else if (this.type === tt.jsxTagStart)
  13681. return this.jsx_parseElement();
  13682. else
  13683. return inner.call(this, refShortHandDefaultPos);
  13684. };
  13685. });
  13686. instance.extend('readToken', function(inner) {
  13687. return function(code) {
  13688. var context = this.curContext();
  13689. if (context === tc.j_expr) return this.jsx_readToken();
  13690. if (context === tc.j_oTag || context === tc.j_cTag) {
  13691. if (acorn.isIdentifierStart(code)) return this.jsx_readWord();
  13692. if (code == 62) {
  13693. ++this.pos;
  13694. return this.finishToken(tt.jsxTagEnd);
  13695. }
  13696. if ((code === 34 || code === 39) && context == tc.j_oTag)
  13697. return this.jsx_readString(code);
  13698. }
  13699. if (code === 60 && this.exprAllowed && this.input.charCodeAt(this.pos + 1) !== 33) {
  13700. ++this.pos;
  13701. return this.finishToken(tt.jsxTagStart);
  13702. }
  13703. return inner.call(this, code);
  13704. };
  13705. });
  13706. instance.extend('updateContext', function(inner) {
  13707. return function(prevType) {
  13708. if (this.type == tt.braceL) {
  13709. var curContext = this.curContext();
  13710. if (curContext == tc.j_oTag) this.context.push(tc.b_expr);
  13711. else if (curContext == tc.j_expr) this.context.push(tc.b_tmpl);
  13712. else inner.call(this, prevType);
  13713. this.exprAllowed = true;
  13714. } else if (this.type === tt.slash && prevType === tt.jsxTagStart) {
  13715. this.context.length -= 2; // do not consider JSX expr -> JSX open tag -> ... anymore
  13716. this.context.push(tc.j_cTag); // reconsider as closing tag context
  13717. this.exprAllowed = false;
  13718. } else {
  13719. return inner.call(this, prevType);
  13720. }
  13721. };
  13722. });
  13723. };
  13724. return acorn;
  13725. };
  13726. module.exports(acorn);
  13727. })(this.acorn);
  13728. return this.acorn;
  13729. })();;
  13730. ;(function(GLOBAL) {
  13731. // Generated by CommonJS Everywhere 0.9.7
  13732. (function (global) {
  13733. function require(file, parentModule) {
  13734. if ({}.hasOwnProperty.call(require.cache, file))
  13735. return require.cache[file];
  13736. var resolved = require.resolve(file);
  13737. if (!resolved)
  13738. throw new Error('Failed to resolve module ' + file);
  13739. var module$ = {
  13740. id: file,
  13741. require: require,
  13742. filename: file,
  13743. exports: {},
  13744. loaded: false,
  13745. parent: parentModule,
  13746. children: []
  13747. };
  13748. if (parentModule)
  13749. parentModule.children.push(module$);
  13750. var dirname = file.slice(0, file.lastIndexOf('/') + 1);
  13751. require.cache[file] = module$.exports;
  13752. resolved.call(module$.exports, module$, module$.exports, dirname, file);
  13753. module$.loaded = true;
  13754. return require.cache[file] = module$.exports;
  13755. }
  13756. require.modules = {};
  13757. require.cache = {};
  13758. require.resolve = function (file) {
  13759. return {}.hasOwnProperty.call(require.modules, file) ? require.modules[file] : void 0;
  13760. };
  13761. require.define = function (file, fn) {
  13762. require.modules[file] = fn;
  13763. };
  13764. var process = function () {
  13765. var cwd = '/';
  13766. return {
  13767. title: 'browser',
  13768. version: 'v8.6.0',
  13769. browser: true,
  13770. env: {},
  13771. argv: [],
  13772. nextTick: global.setImmediate || function (fn) {
  13773. setTimeout(fn, 0);
  13774. },
  13775. cwd: function () {
  13776. return cwd;
  13777. },
  13778. chdir: function (dir) {
  13779. cwd = dir;
  13780. }
  13781. };
  13782. }();
  13783. require.define('/tools/entry-point.js', function (module, exports, __dirname, __filename) {
  13784. (function () {
  13785. 'use strict';
  13786. global.escodegen = require('/escodegen.js', module);
  13787. GLOBAL.escodegen.browser = true;
  13788. }());
  13789. });
  13790. require.define('/escodegen.js', function (module, exports, __dirname, __filename) {
  13791. (function () {
  13792. 'use strict';
  13793. var Syntax, Precedence, BinaryPrecedence, SourceNode, estraverse, esutils, isArray, base, indent, json, renumber, hexadecimal, quotes, escapeless, newline, space, parentheses, semicolons, safeConcatenation, directive, extra, parse, sourceMap, sourceCode, preserveBlankLines, FORMAT_MINIFY, FORMAT_DEFAULTS;
  13794. estraverse = require('/node_modules/estraverse/estraverse.js', module);
  13795. esutils = require('/node_modules/esutils/lib/utils.js', module);
  13796. Syntax = estraverse.Syntax;
  13797. function isExpression(node) {
  13798. return CodeGenerator.Expression.hasOwnProperty(node.type);
  13799. }
  13800. function isStatement(node) {
  13801. return CodeGenerator.Statement.hasOwnProperty(node.type);
  13802. }
  13803. Precedence = {
  13804. Sequence: 0,
  13805. Yield: 1,
  13806. Await: 1,
  13807. Assignment: 1,
  13808. Conditional: 2,
  13809. ArrowFunction: 2,
  13810. LogicalOR: 3,
  13811. LogicalAND: 4,
  13812. BitwiseOR: 5,
  13813. BitwiseXOR: 6,
  13814. BitwiseAND: 7,
  13815. Equality: 8,
  13816. Relational: 9,
  13817. BitwiseSHIFT: 10,
  13818. Additive: 11,
  13819. Multiplicative: 12,
  13820. Exponentiation: 13,
  13821. Unary: 14,
  13822. Postfix: 15,
  13823. Call: 16,
  13824. New: 17,
  13825. TaggedTemplate: 18,
  13826. Member: 19,
  13827. Primary: 20
  13828. };
  13829. BinaryPrecedence = {
  13830. '||': Precedence.LogicalOR,
  13831. '&&': Precedence.LogicalAND,
  13832. '|': Precedence.BitwiseOR,
  13833. '^': Precedence.BitwiseXOR,
  13834. '&': Precedence.BitwiseAND,
  13835. '==': Precedence.Equality,
  13836. '!=': Precedence.Equality,
  13837. '===': Precedence.Equality,
  13838. '!==': Precedence.Equality,
  13839. 'is': Precedence.Equality,
  13840. 'isnt': Precedence.Equality,
  13841. '<': Precedence.Relational,
  13842. '>': Precedence.Relational,
  13843. '<=': Precedence.Relational,
  13844. '>=': Precedence.Relational,
  13845. 'in': Precedence.Relational,
  13846. 'instanceof': Precedence.Relational,
  13847. '<<': Precedence.BitwiseSHIFT,
  13848. '>>': Precedence.BitwiseSHIFT,
  13849. '>>>': Precedence.BitwiseSHIFT,
  13850. '+': Precedence.Additive,
  13851. '-': Precedence.Additive,
  13852. '*': Precedence.Multiplicative,
  13853. '%': Precedence.Multiplicative,
  13854. '/': Precedence.Multiplicative,
  13855. '**': Precedence.Exponentiation
  13856. };
  13857. var F_ALLOW_IN = 1, F_ALLOW_CALL = 1 << 1, F_ALLOW_UNPARATH_NEW = 1 << 2, F_FUNC_BODY = 1 << 3, F_DIRECTIVE_CTX = 1 << 4, F_SEMICOLON_OPT = 1 << 5;
  13858. var F_XJS_NOINDENT = 1 << 8, F_XJS_NOPAREN = 1 << 9;
  13859. var E_FTT = F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, E_TTF = F_ALLOW_IN | F_ALLOW_CALL, E_TTT = F_ALLOW_IN | F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, E_TFF = F_ALLOW_IN, E_FFT = F_ALLOW_UNPARATH_NEW, E_TFT = F_ALLOW_IN | F_ALLOW_UNPARATH_NEW;
  13860. var S_TFFF = F_ALLOW_IN, S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT, S_FFFF = 0, S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX, S_TTFF = F_ALLOW_IN | F_FUNC_BODY;
  13861. function getDefaultOptions() {
  13862. return {
  13863. indent: null,
  13864. base: null,
  13865. parse: null,
  13866. comment: false,
  13867. format: {
  13868. indent: {
  13869. style: ' ',
  13870. base: 0,
  13871. adjustMultilineComment: false
  13872. },
  13873. newline: '\n',
  13874. space: ' ',
  13875. json: false,
  13876. renumber: false,
  13877. hexadecimal: false,
  13878. quotes: 'single',
  13879. escapeless: false,
  13880. compact: false,
  13881. parentheses: true,
  13882. semicolons: true,
  13883. safeConcatenation: false,
  13884. preserveBlankLines: false
  13885. },
  13886. moz: {
  13887. comprehensionExpressionStartsWithAssignment: false,
  13888. starlessGenerator: false
  13889. },
  13890. sourceMap: null,
  13891. sourceMapRoot: null,
  13892. sourceMapWithCode: false,
  13893. directive: false,
  13894. raw: true,
  13895. verbatim: null,
  13896. sourceCode: null
  13897. };
  13898. }
  13899. function stringRepeat(str, num) {
  13900. var result = '';
  13901. for (num |= 0; num > 0; num >>>= 1, str += str) {
  13902. if (num & 1) {
  13903. result += str;
  13904. }
  13905. }
  13906. return result;
  13907. }
  13908. isArray = Array.isArray;
  13909. if (!isArray) {
  13910. isArray = function isArray(array) {
  13911. return Object.prototype.toString.call(array) === '[object Array]';
  13912. };
  13913. }
  13914. function hasLineTerminator(str) {
  13915. return /[\r\n]/g.test(str);
  13916. }
  13917. function endsWithLineTerminator(str) {
  13918. var len = str.length;
  13919. return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1));
  13920. }
  13921. function merge(target, override) {
  13922. var key;
  13923. for (key in override) {
  13924. if (override.hasOwnProperty(key)) {
  13925. target[key] = override[key];
  13926. }
  13927. }
  13928. return target;
  13929. }
  13930. function updateDeeply(target, override) {
  13931. var key, val;
  13932. function isHashObject(target) {
  13933. return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp);
  13934. }
  13935. for (key in override) {
  13936. if (override.hasOwnProperty(key)) {
  13937. val = override[key];
  13938. if (isHashObject(val)) {
  13939. if (isHashObject(target[key])) {
  13940. updateDeeply(target[key], val);
  13941. } else {
  13942. target[key] = updateDeeply({}, val);
  13943. }
  13944. } else {
  13945. target[key] = val;
  13946. }
  13947. }
  13948. }
  13949. return target;
  13950. }
  13951. function generateNumber(value) {
  13952. var result, point, temp, exponent, pos;
  13953. if (value !== value) {
  13954. throw new Error('Numeric literal whose value is NaN');
  13955. }
  13956. if (value < 0 || value === 0 && 1 / value < 0) {
  13957. throw new Error('Numeric literal whose value is negative');
  13958. }
  13959. if (value === 1 / 0) {
  13960. return json ? 'null' : renumber ? '1e400' : '1e+400';
  13961. }
  13962. result = '' + value;
  13963. if (!renumber || result.length < 3) {
  13964. return result;
  13965. }
  13966. point = result.indexOf('.');
  13967. if (!json && result.charCodeAt(0) === 48 && point === 1) {
  13968. point = 0;
  13969. result = result.slice(1);
  13970. }
  13971. temp = result;
  13972. result = result.replace('e+', 'e');
  13973. exponent = 0;
  13974. if ((pos = temp.indexOf('e')) > 0) {
  13975. exponent = +temp.slice(pos + 1);
  13976. temp = temp.slice(0, pos);
  13977. }
  13978. if (point >= 0) {
  13979. exponent -= temp.length - point - 1;
  13980. temp = +(temp.slice(0, point) + temp.slice(point + 1)) + '';
  13981. }
  13982. pos = 0;
  13983. while (temp.charCodeAt(temp.length + pos - 1) === 48) {
  13984. --pos;
  13985. }
  13986. if (pos !== 0) {
  13987. exponent -= pos;
  13988. temp = temp.slice(0, pos);
  13989. }
  13990. if (exponent !== 0) {
  13991. temp += 'e' + exponent;
  13992. }
  13993. if ((temp.length < result.length || hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length) && +temp === value) {
  13994. result = temp;
  13995. }
  13996. return result;
  13997. }
  13998. function escapeRegExpCharacter(ch, previousIsBackslash) {
  13999. if ((ch & ~1) === 8232) {
  14000. return (previousIsBackslash ? 'u' : '\\u') + (ch === 8232 ? '2028' : '2029');
  14001. } else if (ch === 10 || ch === 13) {
  14002. return (previousIsBackslash ? '' : '\\') + (ch === 10 ? 'n' : 'r');
  14003. }
  14004. return String.fromCharCode(ch);
  14005. }
  14006. function generateRegExp(reg) {
  14007. var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash;
  14008. result = reg.toString();
  14009. if (reg.source) {
  14010. match = result.match(/\/([^\/]*)$/);
  14011. if (!match) {
  14012. return result;
  14013. }
  14014. flags = match[1];
  14015. result = '';
  14016. characterInBrack = false;
  14017. previousIsBackslash = false;
  14018. for (i = 0, iz = reg.source.length; i < iz; ++i) {
  14019. ch = reg.source.charCodeAt(i);
  14020. if (!previousIsBackslash) {
  14021. if (characterInBrack) {
  14022. if (ch === 93) {
  14023. characterInBrack = false;
  14024. }
  14025. } else {
  14026. if (ch === 47) {
  14027. result += '\\';
  14028. } else if (ch === 91) {
  14029. characterInBrack = true;
  14030. }
  14031. }
  14032. result += escapeRegExpCharacter(ch, previousIsBackslash);
  14033. previousIsBackslash = ch === 92;
  14034. } else {
  14035. result += escapeRegExpCharacter(ch, previousIsBackslash);
  14036. previousIsBackslash = false;
  14037. }
  14038. }
  14039. return '/' + result + '/' + flags;
  14040. }
  14041. return result;
  14042. }
  14043. function escapeAllowedCharacter(code, next) {
  14044. var hex;
  14045. if (code === 8) {
  14046. return '\\b';
  14047. }
  14048. if (code === 12) {
  14049. return '\\f';
  14050. }
  14051. if (code === 9) {
  14052. return '\\t';
  14053. }
  14054. hex = code.toString(16).toUpperCase();
  14055. if (json || code > 255) {
  14056. return '\\u' + '0000'.slice(hex.length) + hex;
  14057. } else if (code === 0 && !esutils.code.isDecimalDigit(next)) {
  14058. return '\\0';
  14059. } else if (code === 11) {
  14060. return '\\x0B';
  14061. } else {
  14062. return '\\x' + '00'.slice(hex.length) + hex;
  14063. }
  14064. }
  14065. function escapeDisallowedCharacter(code) {
  14066. if (code === 92) {
  14067. return '\\\\';
  14068. }
  14069. if (code === 10) {
  14070. return '\\n';
  14071. }
  14072. if (code === 13) {
  14073. return '\\r';
  14074. }
  14075. if (code === 8232) {
  14076. return '\\u2028';
  14077. }
  14078. if (code === 8233) {
  14079. return '\\u2029';
  14080. }
  14081. throw new Error('Incorrectly classified character');
  14082. }
  14083. function escapeDirective(str) {
  14084. var i, iz, code, quote;
  14085. quote = quotes === 'double' ? '"' : "'";
  14086. for (i = 0, iz = str.length; i < iz; ++i) {
  14087. code = str.charCodeAt(i);
  14088. if (code === 39) {
  14089. quote = '"';
  14090. break;
  14091. } else if (code === 34) {
  14092. quote = "'";
  14093. break;
  14094. } else if (code === 92) {
  14095. ++i;
  14096. }
  14097. }
  14098. return quote + str + quote;
  14099. }
  14100. function escapeString(str) {
  14101. var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote;
  14102. for (i = 0, len = str.length; i < len; ++i) {
  14103. code = str.charCodeAt(i);
  14104. if (code === 39) {
  14105. ++singleQuotes;
  14106. } else if (code === 34) {
  14107. ++doubleQuotes;
  14108. } else if (code === 47 && json) {
  14109. result += '\\';
  14110. } else if (esutils.code.isLineTerminator(code) || code === 92) {
  14111. result += escapeDisallowedCharacter(code);
  14112. continue;
  14113. } else if (!esutils.code.isIdentifierPartES5(code) && (json && code < 32 || !json && !escapeless && (code < 32 || code > 126))) {
  14114. result += escapeAllowedCharacter(code, str.charCodeAt(i + 1));
  14115. continue;
  14116. }
  14117. result += String.fromCharCode(code);
  14118. }
  14119. single = !(quotes === 'double' || quotes === 'auto' && doubleQuotes < singleQuotes);
  14120. quote = single ? "'" : '"';
  14121. if (!(single ? singleQuotes : doubleQuotes)) {
  14122. return quote + result + quote;
  14123. }
  14124. str = result;
  14125. result = quote;
  14126. for (i = 0, len = str.length; i < len; ++i) {
  14127. code = str.charCodeAt(i);
  14128. if (code === 39 && single || code === 34 && !single) {
  14129. result += '\\';
  14130. }
  14131. result += String.fromCharCode(code);
  14132. }
  14133. return result + quote;
  14134. }
  14135. function flattenToString(arr) {
  14136. var i, iz, elem, result = '';
  14137. for (i = 0, iz = arr.length; i < iz; ++i) {
  14138. elem = arr[i];
  14139. result += isArray(elem) ? flattenToString(elem) : elem;
  14140. }
  14141. return result;
  14142. }
  14143. function toSourceNodeWhenNeeded(generated, node) {
  14144. if (!sourceMap) {
  14145. if (isArray(generated)) {
  14146. return flattenToString(generated);
  14147. } else {
  14148. return generated;
  14149. }
  14150. }
  14151. if (node == null) {
  14152. if (generated instanceof SourceNode) {
  14153. return generated;
  14154. } else {
  14155. node = {};
  14156. }
  14157. }
  14158. if (node.loc == null) {
  14159. return new SourceNode(null, null, sourceMap, generated, node.name || null);
  14160. }
  14161. return new SourceNode(node.loc.start.line, node.loc.start.column, sourceMap === true ? node.loc.source || null : sourceMap, generated, node.name || null);
  14162. }
  14163. function noEmptySpace() {
  14164. return space ? space : ' ';
  14165. }
  14166. function join(left, right) {
  14167. var leftSource, rightSource, leftCharCode, rightCharCode;
  14168. leftSource = toSourceNodeWhenNeeded(left).toString();
  14169. if (leftSource.length === 0) {
  14170. return [right];
  14171. }
  14172. rightSource = toSourceNodeWhenNeeded(right).toString();
  14173. if (rightSource.length === 0) {
  14174. return [left];
  14175. }
  14176. leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
  14177. rightCharCode = rightSource.charCodeAt(0);
  14178. if ((leftCharCode === 43 || leftCharCode === 45) && leftCharCode === rightCharCode || esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode) || leftCharCode === 47 && rightCharCode === 105) {
  14179. return [
  14180. left,
  14181. noEmptySpace(),
  14182. right
  14183. ];
  14184. } else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) || esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) {
  14185. return [
  14186. left,
  14187. right
  14188. ];
  14189. }
  14190. return [
  14191. left,
  14192. space,
  14193. right
  14194. ];
  14195. }
  14196. function addIndent(stmt) {
  14197. return [
  14198. base,
  14199. stmt
  14200. ];
  14201. }
  14202. function withIndent(fn) {
  14203. var previousBase;
  14204. previousBase = base;
  14205. base += indent;
  14206. fn(base);
  14207. base = previousBase;
  14208. }
  14209. function calculateSpaces(str) {
  14210. var i;
  14211. for (i = str.length - 1; i >= 0; --i) {
  14212. if (esutils.code.isLineTerminator(str.charCodeAt(i))) {
  14213. break;
  14214. }
  14215. }
  14216. return str.length - 1 - i;
  14217. }
  14218. function adjustMultilineComment(value, specialBase) {
  14219. var array, i, len, line, j, spaces, previousBase, sn;
  14220. array = value.split(/\r\n|[\r\n]/);
  14221. spaces = Number.MAX_VALUE;
  14222. for (i = 1, len = array.length; i < len; ++i) {
  14223. line = array[i];
  14224. j = 0;
  14225. while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) {
  14226. ++j;
  14227. }
  14228. if (spaces > j) {
  14229. spaces = j;
  14230. }
  14231. }
  14232. if (typeof specialBase !== 'undefined') {
  14233. previousBase = base;
  14234. if (array[1][spaces] === '*') {
  14235. specialBase += ' ';
  14236. }
  14237. base = specialBase;
  14238. } else {
  14239. if (spaces & 1) {
  14240. --spaces;
  14241. }
  14242. previousBase = base;
  14243. }
  14244. for (i = 1, len = array.length; i < len; ++i) {
  14245. sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces)));
  14246. array[i] = sourceMap ? sn.join('') : sn;
  14247. }
  14248. base = previousBase;
  14249. return array.join('\n');
  14250. }
  14251. function generateComment(comment, specialBase) {
  14252. if (comment.type === 'Line') {
  14253. if (endsWithLineTerminator(comment.value)) {
  14254. return '//' + comment.value;
  14255. } else {
  14256. var result = '//' + comment.value;
  14257. if (!preserveBlankLines) {
  14258. result += '\n';
  14259. }
  14260. return result;
  14261. }
  14262. }
  14263. if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) {
  14264. return adjustMultilineComment('/*' + comment.value + '*/', specialBase);
  14265. }
  14266. return '/*' + comment.value + '*/';
  14267. }
  14268. function addComments(stmt, result) {
  14269. var i, len, comment, save, tailingToStatement, specialBase, fragment, extRange, range, prevRange, prefix, infix, suffix, count;
  14270. if (stmt.leadingComments && stmt.leadingComments.length > 0) {
  14271. save = result;
  14272. if (preserveBlankLines) {
  14273. comment = stmt.leadingComments[0];
  14274. result = [];
  14275. extRange = comment.extendedRange;
  14276. range = comment.range;
  14277. prefix = sourceCode.substring(extRange[0], range[0]);
  14278. count = (prefix.match(/\n/g) || []).length;
  14279. if (count > 0) {
  14280. result.push(stringRepeat('\n', count));
  14281. result.push(addIndent(generateComment(comment)));
  14282. } else {
  14283. result.push(prefix);
  14284. result.push(generateComment(comment));
  14285. }
  14286. prevRange = range;
  14287. for (i = 1, len = stmt.leadingComments.length; i < len; i++) {
  14288. comment = stmt.leadingComments[i];
  14289. range = comment.range;
  14290. infix = sourceCode.substring(prevRange[1], range[0]);
  14291. count = (infix.match(/\n/g) || []).length;
  14292. result.push(stringRepeat('\n', count));
  14293. result.push(addIndent(generateComment(comment)));
  14294. prevRange = range;
  14295. }
  14296. suffix = sourceCode.substring(range[1], extRange[1]);
  14297. count = (suffix.match(/\n/g) || []).length;
  14298. result.push(stringRepeat('\n', count));
  14299. } else {
  14300. comment = stmt.leadingComments[0];
  14301. result = [];
  14302. if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) {
  14303. result.push('\n');
  14304. }
  14305. result.push(generateComment(comment));
  14306. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  14307. result.push('\n');
  14308. }
  14309. for (i = 1, len = stmt.leadingComments.length; i < len; ++i) {
  14310. comment = stmt.leadingComments[i];
  14311. fragment = [generateComment(comment)];
  14312. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  14313. fragment.push('\n');
  14314. }
  14315. result.push(addIndent(fragment));
  14316. }
  14317. }
  14318. result.push(addIndent(save));
  14319. }
  14320. if (stmt.trailingComments) {
  14321. if (preserveBlankLines) {
  14322. comment = stmt.trailingComments[0];
  14323. extRange = comment.extendedRange;
  14324. range = comment.range;
  14325. prefix = sourceCode.substring(extRange[0], range[0]);
  14326. count = (prefix.match(/\n/g) || []).length;
  14327. if (count > 0) {
  14328. result.push(stringRepeat('\n', count));
  14329. result.push(addIndent(generateComment(comment)));
  14330. } else {
  14331. result.push(prefix);
  14332. result.push(generateComment(comment));
  14333. }
  14334. } else {
  14335. tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
  14336. specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([
  14337. base,
  14338. result,
  14339. indent
  14340. ]).toString()));
  14341. for (i = 0, len = stmt.trailingComments.length; i < len; ++i) {
  14342. comment = stmt.trailingComments[i];
  14343. if (tailingToStatement) {
  14344. if (i === 0) {
  14345. result = [
  14346. result,
  14347. indent
  14348. ];
  14349. } else {
  14350. result = [
  14351. result,
  14352. specialBase
  14353. ];
  14354. }
  14355. result.push(generateComment(comment, specialBase));
  14356. } else {
  14357. result = [
  14358. result,
  14359. addIndent(generateComment(comment))
  14360. ];
  14361. }
  14362. if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  14363. result = [
  14364. result,
  14365. '\n'
  14366. ];
  14367. }
  14368. }
  14369. }
  14370. }
  14371. return result;
  14372. }
  14373. function generateBlankLines(start, end, result) {
  14374. var j, newlineCount = 0;
  14375. for (j = start; j < end; j++) {
  14376. if (sourceCode[j] === '\n') {
  14377. newlineCount++;
  14378. }
  14379. }
  14380. for (j = 1; j < newlineCount; j++) {
  14381. result.push(newline);
  14382. }
  14383. }
  14384. function parenthesize(text, current, should) {
  14385. if (current < should) {
  14386. return [
  14387. '(',
  14388. text,
  14389. ')'
  14390. ];
  14391. }
  14392. return text;
  14393. }
  14394. function generateVerbatimString(string) {
  14395. var i, iz, result;
  14396. result = string.split(/\r\n|\n/);
  14397. for (i = 1, iz = result.length; i < iz; i++) {
  14398. result[i] = newline + base + result[i];
  14399. }
  14400. return result;
  14401. }
  14402. function generateVerbatim(expr, precedence) {
  14403. var verbatim, result, prec;
  14404. verbatim = expr[extra.verbatim];
  14405. if (typeof verbatim === 'string') {
  14406. result = parenthesize(generateVerbatimString(verbatim), Precedence.Sequence, precedence);
  14407. } else {
  14408. result = generateVerbatimString(verbatim.content);
  14409. prec = verbatim.precedence != null ? verbatim.precedence : Precedence.Sequence;
  14410. result = parenthesize(result, prec, precedence);
  14411. }
  14412. return toSourceNodeWhenNeeded(result, expr);
  14413. }
  14414. function CodeGenerator() {
  14415. }
  14416. CodeGenerator.prototype.maybeBlock = function (stmt, flags) {
  14417. var result, noLeadingComment, that = this;
  14418. noLeadingComment = !extra.comment || !stmt.leadingComments;
  14419. if (stmt.type === Syntax.BlockStatement && noLeadingComment) {
  14420. return [
  14421. space,
  14422. this.generateStatement(stmt, flags)
  14423. ];
  14424. }
  14425. if (stmt.type === Syntax.EmptyStatement && noLeadingComment) {
  14426. return ';';
  14427. }
  14428. withIndent(function () {
  14429. result = [
  14430. newline,
  14431. addIndent(that.generateStatement(stmt, flags))
  14432. ];
  14433. });
  14434. return result;
  14435. };
  14436. CodeGenerator.prototype.maybeBlockSuffix = function (stmt, result) {
  14437. var ends = endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
  14438. if (stmt.type === Syntax.BlockStatement && (!extra.comment || !stmt.leadingComments) && !ends) {
  14439. return [
  14440. result,
  14441. space
  14442. ];
  14443. }
  14444. if (ends) {
  14445. return [
  14446. result,
  14447. base
  14448. ];
  14449. }
  14450. return [
  14451. result,
  14452. newline,
  14453. base
  14454. ];
  14455. };
  14456. function generateIdentifier(node) {
  14457. return toSourceNodeWhenNeeded(node.name, node);
  14458. }
  14459. function generateAsyncPrefix(node, spaceRequired) {
  14460. return node.async ? 'async' + (spaceRequired ? noEmptySpace() : space) : '';
  14461. }
  14462. function generateStarSuffix(node) {
  14463. var isGenerator = node.generator && !extra.moz.starlessGenerator;
  14464. return isGenerator ? '*' + space : '';
  14465. }
  14466. function generateMethodPrefix(prop) {
  14467. var func = prop.value;
  14468. if (func.async) {
  14469. return generateAsyncPrefix(func, !prop.computed);
  14470. } else {
  14471. return generateStarSuffix(func) ? '*' : '';
  14472. }
  14473. }
  14474. CodeGenerator.prototype.generatePattern = function (node, precedence, flags) {
  14475. if (node.type === Syntax.Identifier) {
  14476. return generateIdentifier(node);
  14477. }
  14478. return this.generateExpression(node, precedence, flags);
  14479. };
  14480. CodeGenerator.prototype.generateFunctionParams = function (node) {
  14481. var i, iz, result, hasDefault;
  14482. hasDefault = false;
  14483. if (node.type === Syntax.ArrowFunctionExpression && !node.rest && (!node.defaults || node.defaults.length === 0) && node.params.length === 1 && node.params[0].type === Syntax.Identifier) {
  14484. result = [
  14485. generateAsyncPrefix(node, true),
  14486. generateIdentifier(node.params[0])
  14487. ];
  14488. } else {
  14489. result = node.type === Syntax.ArrowFunctionExpression ? [generateAsyncPrefix(node, false)] : [];
  14490. result.push('(');
  14491. if (node.defaults) {
  14492. hasDefault = true;
  14493. }
  14494. for (i = 0, iz = node.params.length; i < iz; ++i) {
  14495. if (hasDefault && node.defaults[i]) {
  14496. result.push(this.generateAssignment(node.params[i], node.defaults[i], '=', Precedence.Assignment, E_TTT));
  14497. } else {
  14498. result.push(this.generatePattern(node.params[i], Precedence.Assignment, E_TTT));
  14499. }
  14500. if (i + 1 < iz) {
  14501. result.push(',' + space);
  14502. }
  14503. }
  14504. if (node.rest) {
  14505. if (node.params.length) {
  14506. result.push(',' + space);
  14507. }
  14508. result.push('...');
  14509. result.push(generateIdentifier(node.rest));
  14510. }
  14511. result.push(')');
  14512. }
  14513. return result;
  14514. };
  14515. CodeGenerator.prototype.generateFunctionBody = function (node) {
  14516. var result, expr;
  14517. result = this.generateFunctionParams(node);
  14518. if (node.type === Syntax.ArrowFunctionExpression) {
  14519. result.push(space);
  14520. result.push('=>');
  14521. }
  14522. if (node.expression) {
  14523. result.push(space);
  14524. expr = this.generateExpression(node.body, Precedence.Assignment, E_TTT);
  14525. if (expr.toString().charAt(0) === '{') {
  14526. expr = [
  14527. '(',
  14528. expr,
  14529. ')'
  14530. ];
  14531. }
  14532. result.push(expr);
  14533. } else {
  14534. result.push(this.maybeBlock(node.body, S_TTFF));
  14535. }
  14536. return result;
  14537. };
  14538. CodeGenerator.prototype.generateIterationForStatement = function (operator, stmt, flags) {
  14539. var result = ['for' + space + '('], that = this;
  14540. withIndent(function () {
  14541. if (stmt.left.type === Syntax.VariableDeclaration) {
  14542. withIndent(function () {
  14543. result.push(stmt.left.kind + noEmptySpace());
  14544. result.push(that.generateStatement(stmt.left.declarations[0], S_FFFF));
  14545. });
  14546. } else {
  14547. result.push(that.generateExpression(stmt.left, Precedence.Call, E_TTT));
  14548. }
  14549. result = join(result, operator);
  14550. result = [
  14551. join(result, that.generateExpression(stmt.right, Precedence.Sequence + (operator === 'of' ? 1 : 0), E_TTT)),
  14552. ')'
  14553. ];
  14554. });
  14555. result.push(this.maybeBlock(stmt.body, flags));
  14556. return result;
  14557. };
  14558. CodeGenerator.prototype.generatePropertyKey = function (expr, computed) {
  14559. var result = [];
  14560. if (computed) {
  14561. result.push('[');
  14562. }
  14563. result.push(this.generateExpression(expr, Precedence.Sequence, E_TTT));
  14564. if (computed) {
  14565. result.push(']');
  14566. }
  14567. return result;
  14568. };
  14569. CodeGenerator.prototype.generateAssignment = function (left, right, operator, precedence, flags) {
  14570. if (Precedence.Assignment < precedence) {
  14571. flags |= F_ALLOW_IN;
  14572. }
  14573. return parenthesize([
  14574. this.generateExpression(left, Precedence.Call, flags),
  14575. space + operator + space,
  14576. this.generateExpression(right, Precedence.Assignment, flags)
  14577. ], Precedence.Assignment, precedence);
  14578. };
  14579. CodeGenerator.prototype.semicolon = function (flags) {
  14580. if (!semicolons && flags & F_SEMICOLON_OPT) {
  14581. return '';
  14582. }
  14583. return ';';
  14584. };
  14585. CodeGenerator.Statement = {
  14586. BlockStatement: function (stmt, flags) {
  14587. var range, content, result = [
  14588. '{',
  14589. newline
  14590. ], that = this;
  14591. withIndent(function () {
  14592. if (stmt.body.length === 0 && preserveBlankLines) {
  14593. range = stmt.range;
  14594. if (range[1] - range[0] > 2) {
  14595. content = sourceCode.substring(range[0] + 1, range[1] - 1);
  14596. if (content[0] === '\n') {
  14597. result = ['{'];
  14598. }
  14599. result.push(content);
  14600. }
  14601. }
  14602. var i, iz, fragment, bodyFlags;
  14603. bodyFlags = S_TFFF;
  14604. if (flags & F_FUNC_BODY) {
  14605. bodyFlags |= F_DIRECTIVE_CTX;
  14606. }
  14607. for (i = 0, iz = stmt.body.length; i < iz; ++i) {
  14608. if (preserveBlankLines) {
  14609. if (i === 0) {
  14610. if (stmt.body[0].leadingComments) {
  14611. range = stmt.body[0].leadingComments[0].extendedRange;
  14612. content = sourceCode.substring(range[0], range[1]);
  14613. if (content[0] === '\n') {
  14614. result = ['{'];
  14615. }
  14616. }
  14617. if (!stmt.body[0].leadingComments) {
  14618. generateBlankLines(stmt.range[0], stmt.body[0].range[0], result);
  14619. }
  14620. }
  14621. if (i > 0) {
  14622. if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
  14623. generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
  14624. }
  14625. }
  14626. }
  14627. if (i === iz - 1) {
  14628. bodyFlags |= F_SEMICOLON_OPT;
  14629. }
  14630. if (stmt.body[i].leadingComments && preserveBlankLines) {
  14631. fragment = that.generateStatement(stmt.body[i], bodyFlags);
  14632. } else {
  14633. fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags));
  14634. }
  14635. result.push(fragment);
  14636. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  14637. if (preserveBlankLines && i < iz - 1) {
  14638. if (!stmt.body[i + 1].leadingComments) {
  14639. result.push(newline);
  14640. }
  14641. } else {
  14642. result.push(newline);
  14643. }
  14644. }
  14645. if (preserveBlankLines) {
  14646. if (i === iz - 1) {
  14647. if (!stmt.body[i].trailingComments) {
  14648. generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
  14649. }
  14650. }
  14651. }
  14652. }
  14653. });
  14654. result.push(addIndent('}'));
  14655. return result;
  14656. },
  14657. BreakStatement: function (stmt, flags) {
  14658. if (stmt.label) {
  14659. return 'break ' + stmt.label.name + this.semicolon(flags);
  14660. }
  14661. return 'break' + this.semicolon(flags);
  14662. },
  14663. ContinueStatement: function (stmt, flags) {
  14664. if (stmt.label) {
  14665. return 'continue ' + stmt.label.name + this.semicolon(flags);
  14666. }
  14667. return 'continue' + this.semicolon(flags);
  14668. },
  14669. ClassBody: function (stmt, flags) {
  14670. var result = [
  14671. '{',
  14672. newline
  14673. ], that = this;
  14674. withIndent(function (indent) {
  14675. var i, iz;
  14676. for (i = 0, iz = stmt.body.length; i < iz; ++i) {
  14677. result.push(indent);
  14678. result.push(that.generateExpression(stmt.body[i], Precedence.Sequence, E_TTT));
  14679. if (i + 1 < iz) {
  14680. result.push(newline);
  14681. }
  14682. }
  14683. });
  14684. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  14685. result.push(newline);
  14686. }
  14687. result.push(base);
  14688. result.push('}');
  14689. return result;
  14690. },
  14691. ClassDeclaration: function (stmt, flags) {
  14692. var result, fragment;
  14693. result = ['class'];
  14694. if (stmt.id) {
  14695. result = join(result, this.generateExpression(stmt.id, Precedence.Sequence, E_TTT));
  14696. }
  14697. if (stmt.superClass) {
  14698. fragment = join('extends', this.generateExpression(stmt.superClass, Precedence.Assignment, E_TTT));
  14699. result = join(result, fragment);
  14700. }
  14701. result.push(space);
  14702. result.push(this.generateStatement(stmt.body, S_TFFT));
  14703. return result;
  14704. },
  14705. DirectiveStatement: function (stmt, flags) {
  14706. if (extra.raw && stmt.raw) {
  14707. return stmt.raw + this.semicolon(flags);
  14708. }
  14709. return escapeDirective(stmt.directive) + this.semicolon(flags);
  14710. },
  14711. DoWhileStatement: function (stmt, flags) {
  14712. var result = join('do', this.maybeBlock(stmt.body, S_TFFF));
  14713. result = this.maybeBlockSuffix(stmt.body, result);
  14714. return join(result, [
  14715. 'while' + space + '(',
  14716. this.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
  14717. ')' + this.semicolon(flags)
  14718. ]);
  14719. },
  14720. CatchClause: function (stmt, flags) {
  14721. var result, that = this;
  14722. withIndent(function () {
  14723. var guard;
  14724. result = [
  14725. 'catch' + space + '(',
  14726. that.generateExpression(stmt.param, Precedence.Sequence, E_TTT),
  14727. ')'
  14728. ];
  14729. if (stmt.guard) {
  14730. guard = that.generateExpression(stmt.guard, Precedence.Sequence, E_TTT);
  14731. result.splice(2, 0, ' if ', guard);
  14732. }
  14733. });
  14734. result.push(this.maybeBlock(stmt.body, S_TFFF));
  14735. return result;
  14736. },
  14737. DebuggerStatement: function (stmt, flags) {
  14738. return 'debugger' + this.semicolon(flags);
  14739. },
  14740. EmptyStatement: function (stmt, flags) {
  14741. return ';';
  14742. },
  14743. ExportDefaultDeclaration: function (stmt, flags) {
  14744. var result = ['export'], bodyFlags;
  14745. bodyFlags = flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF;
  14746. result = join(result, 'default');
  14747. if (isStatement(stmt.declaration)) {
  14748. result = join(result, this.generateStatement(stmt.declaration, bodyFlags));
  14749. } else {
  14750. result = join(result, this.generateExpression(stmt.declaration, Precedence.Assignment, E_TTT) + this.semicolon(flags));
  14751. }
  14752. return result;
  14753. },
  14754. ExportNamedDeclaration: function (stmt, flags) {
  14755. var result = ['export'], bodyFlags, that = this;
  14756. bodyFlags = flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF;
  14757. if (stmt.declaration) {
  14758. return join(result, this.generateStatement(stmt.declaration, bodyFlags));
  14759. }
  14760. if (stmt.specifiers) {
  14761. if (stmt.specifiers.length === 0) {
  14762. result = join(result, '{' + space + '}');
  14763. } else if (stmt.specifiers[0].type === Syntax.ExportBatchSpecifier) {
  14764. result = join(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT));
  14765. } else {
  14766. result = join(result, '{');
  14767. withIndent(function (indent) {
  14768. var i, iz;
  14769. result.push(newline);
  14770. for (i = 0, iz = stmt.specifiers.length; i < iz; ++i) {
  14771. result.push(indent);
  14772. result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
  14773. if (i + 1 < iz) {
  14774. result.push(',' + newline);
  14775. }
  14776. }
  14777. });
  14778. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  14779. result.push(newline);
  14780. }
  14781. result.push(base + '}');
  14782. }
  14783. if (stmt.source) {
  14784. result = join(result, [
  14785. 'from' + space,
  14786. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  14787. this.semicolon(flags)
  14788. ]);
  14789. } else {
  14790. result.push(this.semicolon(flags));
  14791. }
  14792. }
  14793. return result;
  14794. },
  14795. ExportAllDeclaration: function (stmt, flags) {
  14796. return [
  14797. 'export' + space,
  14798. '*' + space,
  14799. 'from' + space,
  14800. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  14801. this.semicolon(flags)
  14802. ];
  14803. },
  14804. ExpressionStatement: function (stmt, flags) {
  14805. var result, fragment;
  14806. function isClassPrefixed(fragment) {
  14807. var code;
  14808. if (fragment.slice(0, 5) !== 'class') {
  14809. return false;
  14810. }
  14811. code = fragment.charCodeAt(5);
  14812. return code === 123 || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code);
  14813. }
  14814. function isFunctionPrefixed(fragment) {
  14815. var code;
  14816. if (fragment.slice(0, 8) !== 'function') {
  14817. return false;
  14818. }
  14819. code = fragment.charCodeAt(8);
  14820. return code === 40 || esutils.code.isWhiteSpace(code) || code === 42 || esutils.code.isLineTerminator(code);
  14821. }
  14822. function isAsyncPrefixed(fragment) {
  14823. var code, i, iz;
  14824. if (fragment.slice(0, 5) !== 'async') {
  14825. return false;
  14826. }
  14827. if (!esutils.code.isWhiteSpace(fragment.charCodeAt(5))) {
  14828. return false;
  14829. }
  14830. for (i = 6, iz = fragment.length; i < iz; ++i) {
  14831. if (!esutils.code.isWhiteSpace(fragment.charCodeAt(i))) {
  14832. break;
  14833. }
  14834. }
  14835. if (i === iz) {
  14836. return false;
  14837. }
  14838. if (fragment.slice(i, i + 8) !== 'function') {
  14839. return false;
  14840. }
  14841. code = fragment.charCodeAt(i + 8);
  14842. return code === 40 || esutils.code.isWhiteSpace(code) || code === 42 || esutils.code.isLineTerminator(code);
  14843. }
  14844. result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT | F_XJS_NOINDENT)];
  14845. fragment = toSourceNodeWhenNeeded(result).toString();
  14846. if (fragment.charCodeAt(0) === 123 || isClassPrefixed(fragment) || isFunctionPrefixed(fragment) || isAsyncPrefixed(fragment) || directive && flags & F_DIRECTIVE_CTX && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === 'string') {
  14847. result = [
  14848. '(',
  14849. result,
  14850. ')' + this.semicolon(flags)
  14851. ];
  14852. } else {
  14853. result.push(this.semicolon(flags));
  14854. }
  14855. return result;
  14856. },
  14857. ImportDeclaration: function (stmt, flags) {
  14858. var result, cursor, that = this;
  14859. if (stmt.specifiers.length === 0) {
  14860. return [
  14861. 'import',
  14862. space,
  14863. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  14864. this.semicolon(flags)
  14865. ];
  14866. }
  14867. result = ['import'];
  14868. cursor = 0;
  14869. if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) {
  14870. result = join(result, [this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)]);
  14871. ++cursor;
  14872. }
  14873. if (stmt.specifiers[cursor]) {
  14874. if (cursor !== 0) {
  14875. result.push(',');
  14876. }
  14877. if (stmt.specifiers[cursor].type === Syntax.ImportNamespaceSpecifier) {
  14878. result = join(result, [
  14879. space,
  14880. this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
  14881. ]);
  14882. } else {
  14883. result.push(space + '{');
  14884. if (stmt.specifiers.length - cursor === 1) {
  14885. result.push(space);
  14886. result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT));
  14887. result.push(space + '}' + space);
  14888. } else {
  14889. withIndent(function (indent) {
  14890. var i, iz;
  14891. result.push(newline);
  14892. for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) {
  14893. result.push(indent);
  14894. result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
  14895. if (i + 1 < iz) {
  14896. result.push(',' + newline);
  14897. }
  14898. }
  14899. });
  14900. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  14901. result.push(newline);
  14902. }
  14903. result.push(base + '}' + space);
  14904. }
  14905. }
  14906. }
  14907. result = join(result, [
  14908. 'from' + space,
  14909. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  14910. this.semicolon(flags)
  14911. ]);
  14912. return result;
  14913. },
  14914. VariableDeclarator: function (stmt, flags) {
  14915. var itemFlags = flags & F_ALLOW_IN ? E_TTT : E_FTT;
  14916. if (stmt.init) {
  14917. return [
  14918. this.generateExpression(stmt.id, Precedence.Assignment, itemFlags),
  14919. space,
  14920. '=',
  14921. space,
  14922. this.generateExpression(stmt.init, Precedence.Assignment, itemFlags)
  14923. ];
  14924. }
  14925. return this.generatePattern(stmt.id, Precedence.Assignment, itemFlags);
  14926. },
  14927. VariableDeclaration: function (stmt, flags) {
  14928. var result, i, iz, node, bodyFlags, that = this;
  14929. result = [stmt.kind];
  14930. bodyFlags = flags & F_ALLOW_IN ? S_TFFF : S_FFFF;
  14931. function block() {
  14932. node = stmt.declarations[0];
  14933. if (extra.comment && node.leadingComments) {
  14934. result.push('\n');
  14935. result.push(addIndent(that.generateStatement(node, bodyFlags)));
  14936. } else {
  14937. result.push(noEmptySpace());
  14938. result.push(that.generateStatement(node, bodyFlags));
  14939. }
  14940. for (i = 1, iz = stmt.declarations.length; i < iz; ++i) {
  14941. node = stmt.declarations[i];
  14942. if (extra.comment && node.leadingComments) {
  14943. result.push(',' + newline);
  14944. result.push(addIndent(that.generateStatement(node, bodyFlags)));
  14945. } else {
  14946. result.push(',' + space);
  14947. result.push(that.generateStatement(node, bodyFlags));
  14948. }
  14949. }
  14950. }
  14951. if (stmt.declarations.length > 1) {
  14952. withIndent(block);
  14953. } else {
  14954. block();
  14955. }
  14956. result.push(this.semicolon(flags));
  14957. return result;
  14958. },
  14959. ThrowStatement: function (stmt, flags) {
  14960. return [
  14961. join('throw', this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)),
  14962. this.semicolon(flags)
  14963. ];
  14964. },
  14965. TryStatement: function (stmt, flags) {
  14966. var result, i, iz, guardedHandlers;
  14967. result = [
  14968. 'try',
  14969. this.maybeBlock(stmt.block, S_TFFF)
  14970. ];
  14971. result = this.maybeBlockSuffix(stmt.block, result);
  14972. if (stmt.handlers) {
  14973. for (i = 0, iz = stmt.handlers.length; i < iz; ++i) {
  14974. result = join(result, this.generateStatement(stmt.handlers[i], S_TFFF));
  14975. if (stmt.finalizer || i + 1 !== iz) {
  14976. result = this.maybeBlockSuffix(stmt.handlers[i].body, result);
  14977. }
  14978. }
  14979. } else {
  14980. guardedHandlers = stmt.guardedHandlers || [];
  14981. for (i = 0, iz = guardedHandlers.length; i < iz; ++i) {
  14982. result = join(result, this.generateStatement(guardedHandlers[i], S_TFFF));
  14983. if (stmt.finalizer || i + 1 !== iz) {
  14984. result = this.maybeBlockSuffix(guardedHandlers[i].body, result);
  14985. }
  14986. }
  14987. if (stmt.handler) {
  14988. if (isArray(stmt.handler)) {
  14989. for (i = 0, iz = stmt.handler.length; i < iz; ++i) {
  14990. result = join(result, this.generateStatement(stmt.handler[i], S_TFFF));
  14991. if (stmt.finalizer || i + 1 !== iz) {
  14992. result = this.maybeBlockSuffix(stmt.handler[i].body, result);
  14993. }
  14994. }
  14995. } else {
  14996. result = join(result, this.generateStatement(stmt.handler, S_TFFF));
  14997. if (stmt.finalizer) {
  14998. result = this.maybeBlockSuffix(stmt.handler.body, result);
  14999. }
  15000. }
  15001. }
  15002. }
  15003. if (stmt.finalizer) {
  15004. result = join(result, [
  15005. 'finally',
  15006. this.maybeBlock(stmt.finalizer, S_TFFF)
  15007. ]);
  15008. }
  15009. return result;
  15010. },
  15011. SwitchStatement: function (stmt, flags) {
  15012. var result, fragment, i, iz, bodyFlags, that = this;
  15013. withIndent(function () {
  15014. result = [
  15015. 'switch' + space + '(',
  15016. that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT),
  15017. ')' + space + '{' + newline
  15018. ];
  15019. });
  15020. if (stmt.cases) {
  15021. bodyFlags = S_TFFF;
  15022. for (i = 0, iz = stmt.cases.length; i < iz; ++i) {
  15023. if (i === iz - 1) {
  15024. bodyFlags |= F_SEMICOLON_OPT;
  15025. }
  15026. fragment = addIndent(this.generateStatement(stmt.cases[i], bodyFlags));
  15027. result.push(fragment);
  15028. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  15029. result.push(newline);
  15030. }
  15031. }
  15032. }
  15033. result.push(addIndent('}'));
  15034. return result;
  15035. },
  15036. SwitchCase: function (stmt, flags) {
  15037. var result, fragment, i, iz, bodyFlags, that = this;
  15038. withIndent(function () {
  15039. if (stmt.test) {
  15040. result = [
  15041. join('case', that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)),
  15042. ':'
  15043. ];
  15044. } else {
  15045. result = ['default:'];
  15046. }
  15047. i = 0;
  15048. iz = stmt.consequent.length;
  15049. if (iz && stmt.consequent[0].type === Syntax.BlockStatement) {
  15050. fragment = that.maybeBlock(stmt.consequent[0], S_TFFF);
  15051. result.push(fragment);
  15052. i = 1;
  15053. }
  15054. if (i !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  15055. result.push(newline);
  15056. }
  15057. bodyFlags = S_TFFF;
  15058. for (; i < iz; ++i) {
  15059. if (i === iz - 1 && flags & F_SEMICOLON_OPT) {
  15060. bodyFlags |= F_SEMICOLON_OPT;
  15061. }
  15062. fragment = addIndent(that.generateStatement(stmt.consequent[i], bodyFlags));
  15063. result.push(fragment);
  15064. if (i + 1 !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  15065. result.push(newline);
  15066. }
  15067. }
  15068. });
  15069. return result;
  15070. },
  15071. IfStatement: function (stmt, flags) {
  15072. var result, bodyFlags, semicolonOptional, that = this;
  15073. withIndent(function () {
  15074. result = [
  15075. 'if' + space + '(',
  15076. that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
  15077. ')'
  15078. ];
  15079. });
  15080. semicolonOptional = flags & F_SEMICOLON_OPT;
  15081. bodyFlags = S_TFFF;
  15082. if (semicolonOptional) {
  15083. bodyFlags |= F_SEMICOLON_OPT;
  15084. }
  15085. if (stmt.alternate) {
  15086. result.push(this.maybeBlock(stmt.consequent, S_TFFF));
  15087. result = this.maybeBlockSuffix(stmt.consequent, result);
  15088. if (stmt.alternate.type === Syntax.IfStatement) {
  15089. result = join(result, [
  15090. 'else ',
  15091. this.generateStatement(stmt.alternate, bodyFlags)
  15092. ]);
  15093. } else {
  15094. result = join(result, join('else', this.maybeBlock(stmt.alternate, bodyFlags)));
  15095. }
  15096. } else {
  15097. result.push(this.maybeBlock(stmt.consequent, bodyFlags));
  15098. }
  15099. return result;
  15100. },
  15101. ForStatement: function (stmt, flags) {
  15102. var result, that = this;
  15103. withIndent(function () {
  15104. result = ['for' + space + '('];
  15105. if (stmt.init) {
  15106. if (stmt.init.type === Syntax.VariableDeclaration) {
  15107. result.push(that.generateStatement(stmt.init, S_FFFF));
  15108. } else {
  15109. result.push(that.generateExpression(stmt.init, Precedence.Sequence, E_FTT));
  15110. result.push(';');
  15111. }
  15112. } else {
  15113. result.push(';');
  15114. }
  15115. if (stmt.test) {
  15116. result.push(space);
  15117. result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT));
  15118. result.push(';');
  15119. } else {
  15120. result.push(';');
  15121. }
  15122. if (stmt.update) {
  15123. result.push(space);
  15124. result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT));
  15125. result.push(')');
  15126. } else {
  15127. result.push(')');
  15128. }
  15129. });
  15130. result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
  15131. return result;
  15132. },
  15133. ForInStatement: function (stmt, flags) {
  15134. return this.generateIterationForStatement('in', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
  15135. },
  15136. ForOfStatement: function (stmt, flags) {
  15137. return this.generateIterationForStatement('of', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
  15138. },
  15139. LabeledStatement: function (stmt, flags) {
  15140. return [
  15141. stmt.label.name + ':',
  15142. this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)
  15143. ];
  15144. },
  15145. Program: function (stmt, flags) {
  15146. var result, fragment, i, iz, bodyFlags;
  15147. iz = stmt.body.length;
  15148. result = [safeConcatenation && iz > 0 ? '\n' : ''];
  15149. bodyFlags = S_TFTF;
  15150. for (i = 0; i < iz; ++i) {
  15151. if (!safeConcatenation && i === iz - 1) {
  15152. bodyFlags |= F_SEMICOLON_OPT;
  15153. }
  15154. if (preserveBlankLines) {
  15155. if (i === 0) {
  15156. if (!stmt.body[0].leadingComments) {
  15157. generateBlankLines(stmt.range[0], stmt.body[i].range[0], result);
  15158. }
  15159. }
  15160. if (i > 0) {
  15161. if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
  15162. generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
  15163. }
  15164. }
  15165. }
  15166. fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags));
  15167. result.push(fragment);
  15168. if (i + 1 < iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  15169. if (preserveBlankLines) {
  15170. if (!stmt.body[i + 1].leadingComments) {
  15171. result.push(newline);
  15172. }
  15173. } else {
  15174. result.push(newline);
  15175. }
  15176. }
  15177. if (preserveBlankLines) {
  15178. if (i === iz - 1) {
  15179. if (!stmt.body[i].trailingComments) {
  15180. generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
  15181. }
  15182. }
  15183. }
  15184. }
  15185. return result;
  15186. },
  15187. FunctionDeclaration: function (stmt, flags) {
  15188. return [
  15189. generateAsyncPrefix(stmt, true),
  15190. 'function',
  15191. generateStarSuffix(stmt) || noEmptySpace(),
  15192. stmt.id ? generateIdentifier(stmt.id) : '',
  15193. this.generateFunctionBody(stmt)
  15194. ];
  15195. },
  15196. ReturnStatement: function (stmt, flags) {
  15197. if (stmt.argument) {
  15198. return [
  15199. join('return', this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)),
  15200. this.semicolon(flags)
  15201. ];
  15202. }
  15203. return ['return' + this.semicolon(flags)];
  15204. },
  15205. WhileStatement: function (stmt, flags) {
  15206. var result, that = this;
  15207. withIndent(function () {
  15208. result = [
  15209. 'while' + space + '(',
  15210. that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
  15211. ')'
  15212. ];
  15213. });
  15214. result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
  15215. return result;
  15216. },
  15217. WithStatement: function (stmt, flags) {
  15218. var result, that = this;
  15219. withIndent(function () {
  15220. result = [
  15221. 'with' + space + '(',
  15222. that.generateExpression(stmt.object, Precedence.Sequence, E_TTT),
  15223. ')'
  15224. ];
  15225. });
  15226. result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
  15227. return result;
  15228. }
  15229. };
  15230. merge(CodeGenerator.prototype, CodeGenerator.Statement);
  15231. CodeGenerator.Expression = {
  15232. SequenceExpression: function (expr, precedence, flags) {
  15233. var result, i, iz;
  15234. if (Precedence.Sequence < precedence) {
  15235. flags |= F_ALLOW_IN;
  15236. }
  15237. result = [];
  15238. for (i = 0, iz = expr.expressions.length; i < iz; ++i) {
  15239. result.push(this.generateExpression(expr.expressions[i], Precedence.Assignment, flags));
  15240. if (i + 1 < iz) {
  15241. result.push(',' + space);
  15242. }
  15243. }
  15244. return parenthesize(result, Precedence.Sequence, precedence);
  15245. },
  15246. AssignmentExpression: function (expr, precedence, flags) {
  15247. return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags);
  15248. },
  15249. ArrowFunctionExpression: function (expr, precedence, flags) {
  15250. return parenthesize(this.generateFunctionBody(expr), Precedence.ArrowFunction, precedence);
  15251. },
  15252. ConditionalExpression: function (expr, precedence, flags) {
  15253. if (Precedence.Conditional < precedence) {
  15254. flags |= F_ALLOW_IN;
  15255. }
  15256. return parenthesize([
  15257. this.generateExpression(expr.test, Precedence.LogicalOR, flags),
  15258. space + '?' + space,
  15259. this.generateExpression(expr.consequent, Precedence.Assignment, flags),
  15260. space + ':' + space,
  15261. this.generateExpression(expr.alternate, Precedence.Assignment, flags)
  15262. ], Precedence.Conditional, precedence);
  15263. },
  15264. LogicalExpression: function (expr, precedence, flags) {
  15265. return this.BinaryExpression(expr, precedence, flags);
  15266. },
  15267. BinaryExpression: function (expr, precedence, flags) {
  15268. var result, currentPrecedence, fragment, leftSource;
  15269. currentPrecedence = BinaryPrecedence[expr.operator];
  15270. if (currentPrecedence < precedence) {
  15271. flags |= F_ALLOW_IN;
  15272. }
  15273. fragment = this.generateExpression(expr.left, currentPrecedence, flags);
  15274. leftSource = fragment.toString();
  15275. if (leftSource.charCodeAt(leftSource.length - 1) === 47 && esutils.code.isIdentifierPartES5(expr.operator.charCodeAt(0))) {
  15276. result = [
  15277. fragment,
  15278. noEmptySpace(),
  15279. expr.operator
  15280. ];
  15281. } else {
  15282. result = join(fragment, expr.operator);
  15283. }
  15284. fragment = this.generateExpression(expr.right, currentPrecedence + 1, flags);
  15285. if (expr.operator === '/' && fragment.toString().charAt(0) === '/' || expr.operator.slice(-1) === '<' && fragment.toString().slice(0, 3) === '!--') {
  15286. result.push(noEmptySpace());
  15287. result.push(fragment);
  15288. } else {
  15289. result = join(result, fragment);
  15290. }
  15291. if (expr.operator === 'in' && !(flags & F_ALLOW_IN)) {
  15292. return [
  15293. '(',
  15294. result,
  15295. ')'
  15296. ];
  15297. }
  15298. return parenthesize(result, currentPrecedence, precedence);
  15299. },
  15300. CallExpression: function (expr, precedence, flags) {
  15301. var result, i, iz;
  15302. result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)];
  15303. result.push('(');
  15304. for (i = 0, iz = expr['arguments'].length; i < iz; ++i) {
  15305. result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT | F_XJS_NOPAREN));
  15306. if (i + 1 < iz) {
  15307. result.push(',' + space);
  15308. }
  15309. }
  15310. result.push(')');
  15311. if (!(flags & F_ALLOW_CALL)) {
  15312. return [
  15313. '(',
  15314. result,
  15315. ')'
  15316. ];
  15317. }
  15318. return parenthesize(result, Precedence.Call, precedence);
  15319. },
  15320. NewExpression: function (expr, precedence, flags) {
  15321. var result, length, i, iz, itemFlags;
  15322. length = expr['arguments'].length;
  15323. itemFlags = flags & F_ALLOW_UNPARATH_NEW && !parentheses && length === 0 ? E_TFT : E_TFF;
  15324. result = join('new', this.generateExpression(expr.callee, Precedence.New, itemFlags));
  15325. if (!(flags & F_ALLOW_UNPARATH_NEW) || parentheses || length > 0) {
  15326. result.push('(');
  15327. for (i = 0, iz = length; i < iz; ++i) {
  15328. result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
  15329. if (i + 1 < iz) {
  15330. result.push(',' + space);
  15331. }
  15332. }
  15333. result.push(')');
  15334. }
  15335. return parenthesize(result, Precedence.New, precedence);
  15336. },
  15337. MemberExpression: function (expr, precedence, flags) {
  15338. var result, fragment;
  15339. result = [this.generateExpression(expr.object, Precedence.Call, flags & F_ALLOW_CALL ? E_TTF : E_TFF)];
  15340. if (expr.computed) {
  15341. result.push('[');
  15342. result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT));
  15343. result.push(']');
  15344. } else {
  15345. if (expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') {
  15346. fragment = toSourceNodeWhenNeeded(result).toString();
  15347. if (fragment.indexOf('.') < 0 && !/[eExX]/.test(fragment) && esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) && !(fragment.length >= 2 && fragment.charCodeAt(0) === 48)) {
  15348. result.push('.');
  15349. }
  15350. }
  15351. result.push('.');
  15352. result.push(generateIdentifier(expr.property));
  15353. }
  15354. return parenthesize(result, Precedence.Member, precedence);
  15355. },
  15356. MetaProperty: function (expr, precedence, flags) {
  15357. var result, meta, property;
  15358. meta = expr.meta && typeof expr.meta.type === 'string' && expr.meta.type === Syntax.Identifier ? expr.meta.name : expr.meta;
  15359. property = expr.property && typeof expr.property.type === 'string' && expr.property.type === Syntax.Identifier ? expr.property.name : expr.property;
  15360. result = [
  15361. meta,
  15362. '.',
  15363. property
  15364. ];
  15365. return parenthesize(result, Precedence.Member, precedence);
  15366. },
  15367. UnaryExpression: function (expr, precedence, flags) {
  15368. var result, fragment, rightCharCode, leftSource, leftCharCode;
  15369. fragment = this.generateExpression(expr.argument, Precedence.Unary, E_TTT);
  15370. if (space === '') {
  15371. result = join(expr.operator, fragment);
  15372. } else {
  15373. result = [expr.operator];
  15374. if (expr.operator.length > 2) {
  15375. result = join(result, fragment);
  15376. } else {
  15377. leftSource = toSourceNodeWhenNeeded(result).toString();
  15378. leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
  15379. rightCharCode = fragment.toString().charCodeAt(0);
  15380. if ((leftCharCode === 43 || leftCharCode === 45) && leftCharCode === rightCharCode || esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode)) {
  15381. result.push(noEmptySpace());
  15382. result.push(fragment);
  15383. } else {
  15384. result.push(fragment);
  15385. }
  15386. }
  15387. }
  15388. return parenthesize(result, Precedence.Unary, precedence);
  15389. },
  15390. YieldExpression: function (expr, precedence, flags) {
  15391. var result;
  15392. if (expr.delegate) {
  15393. result = 'yield*';
  15394. } else {
  15395. result = 'yield';
  15396. }
  15397. if (expr.argument) {
  15398. result = join(result, this.generateExpression(expr.argument, Precedence.Yield, E_TTT));
  15399. }
  15400. return parenthesize(result, Precedence.Yield, precedence);
  15401. },
  15402. AwaitExpression: function (expr, precedence, flags) {
  15403. var result = join(expr.all ? 'await*' : 'await', this.generateExpression(expr.argument, Precedence.Await, E_TTT));
  15404. return parenthesize(result, Precedence.Await, precedence);
  15405. },
  15406. UpdateExpression: function (expr, precedence, flags) {
  15407. if (expr.prefix) {
  15408. return parenthesize([
  15409. expr.operator,
  15410. this.generateExpression(expr.argument, Precedence.Unary, E_TTT)
  15411. ], Precedence.Unary, precedence);
  15412. }
  15413. return parenthesize([
  15414. this.generateExpression(expr.argument, Precedence.Postfix, E_TTT),
  15415. expr.operator
  15416. ], Precedence.Postfix, precedence);
  15417. },
  15418. FunctionExpression: function (expr, precedence, flags) {
  15419. var result = [
  15420. generateAsyncPrefix(expr, true),
  15421. 'function'
  15422. ];
  15423. if (expr.id) {
  15424. result.push(generateStarSuffix(expr) || noEmptySpace());
  15425. result.push(generateIdentifier(expr.id));
  15426. } else {
  15427. result.push(generateStarSuffix(expr) || space);
  15428. }
  15429. result.push(this.generateFunctionBody(expr));
  15430. return result;
  15431. },
  15432. ArrayPattern: function (expr, precedence, flags) {
  15433. return this.ArrayExpression(expr, precedence, flags, true);
  15434. },
  15435. ArrayExpression: function (expr, precedence, flags, isPattern) {
  15436. var result, multiline, that = this;
  15437. if (!expr.elements.length) {
  15438. return '[]';
  15439. }
  15440. multiline = isPattern ? false : expr.elements.length > 1;
  15441. result = [
  15442. '[',
  15443. multiline ? newline : ''
  15444. ];
  15445. withIndent(function (indent) {
  15446. var i, iz;
  15447. for (i = 0, iz = expr.elements.length; i < iz; ++i) {
  15448. if (!expr.elements[i]) {
  15449. if (multiline) {
  15450. result.push(indent);
  15451. }
  15452. if (i + 1 === iz) {
  15453. result.push(',');
  15454. }
  15455. } else {
  15456. result.push(multiline ? indent : '');
  15457. result.push(that.generateExpression(expr.elements[i], Precedence.Assignment, E_TTT | F_XJS_NOINDENT | F_XJS_NOPAREN));
  15458. }
  15459. if (i + 1 < iz) {
  15460. result.push(',' + (multiline ? newline : space));
  15461. }
  15462. }
  15463. });
  15464. if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  15465. result.push(newline);
  15466. }
  15467. result.push(multiline ? base : '');
  15468. result.push(']');
  15469. return result;
  15470. },
  15471. ClassExpression: function (expr, precedence, flags) {
  15472. var result, fragment;
  15473. result = ['class'];
  15474. if (expr.id) {
  15475. result = join(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT));
  15476. }
  15477. if (expr.superClass) {
  15478. fragment = join('extends', this.generateExpression(expr.superClass, Precedence.Assignment, E_TTT));
  15479. result = join(result, fragment);
  15480. }
  15481. result.push(space);
  15482. result.push(this.generateStatement(expr.body, S_TFFT));
  15483. return result;
  15484. },
  15485. MethodDefinition: function (expr, precedence, flags) {
  15486. var result, fragment;
  15487. if (expr['static']) {
  15488. result = ['static' + space];
  15489. } else {
  15490. result = [];
  15491. }
  15492. if (expr.kind === 'get' || expr.kind === 'set') {
  15493. fragment = [
  15494. join(expr.kind, this.generatePropertyKey(expr.key, expr.computed)),
  15495. this.generateFunctionBody(expr.value)
  15496. ];
  15497. } else {
  15498. fragment = [
  15499. generateMethodPrefix(expr),
  15500. this.generatePropertyKey(expr.key, expr.computed),
  15501. this.generateFunctionBody(expr.value)
  15502. ];
  15503. }
  15504. return join(result, fragment);
  15505. },
  15506. Property: function (expr, precedence, flags) {
  15507. if (expr.kind === 'get' || expr.kind === 'set') {
  15508. return [
  15509. expr.kind,
  15510. noEmptySpace(),
  15511. this.generatePropertyKey(expr.key, expr.computed),
  15512. this.generateFunctionBody(expr.value)
  15513. ];
  15514. }
  15515. if (expr.kind === 'init' && !expr.method && expr.shorthand) {
  15516. return this.generatePattern(expr.value, Precedence.Assignment, E_TTT);
  15517. }
  15518. if (expr.shorthand) {
  15519. return this.generatePropertyKey(expr.key, expr.computed);
  15520. }
  15521. if (expr.method) {
  15522. return [
  15523. generateMethodPrefix(expr),
  15524. this.generatePropertyKey(expr.key, expr.computed),
  15525. this.generateFunctionBody(expr.value)
  15526. ];
  15527. }
  15528. return [
  15529. this.generatePropertyKey(expr.key, expr.computed),
  15530. ':' + space,
  15531. this.generateExpression(expr.value, Precedence.Assignment, E_TTT)
  15532. ];
  15533. },
  15534. ObjectExpression: function (expr, precedence, flags) {
  15535. var multiline, result, fragment, that = this;
  15536. if (!expr.properties.length) {
  15537. return '{}';
  15538. }
  15539. multiline = expr.properties.length > 1;
  15540. withIndent(function () {
  15541. fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT);
  15542. });
  15543. if (!multiline) {
  15544. if (!hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  15545. return [
  15546. '{',
  15547. space,
  15548. fragment,
  15549. space,
  15550. '}'
  15551. ];
  15552. }
  15553. }
  15554. withIndent(function (indent) {
  15555. var i, iz;
  15556. result = [
  15557. '{',
  15558. newline,
  15559. indent,
  15560. fragment
  15561. ];
  15562. if (multiline) {
  15563. result.push(',' + newline);
  15564. for (i = 1, iz = expr.properties.length; i < iz; ++i) {
  15565. result.push(indent);
  15566. result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));
  15567. if (i + 1 < iz) {
  15568. result.push(',' + newline);
  15569. }
  15570. }
  15571. }
  15572. });
  15573. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  15574. result.push(newline);
  15575. }
  15576. result.push(base);
  15577. result.push('}');
  15578. return result;
  15579. },
  15580. AssignmentPattern: function (expr, precedence, flags) {
  15581. return this.generateAssignment(expr.left, expr.right, '=', precedence, flags);
  15582. },
  15583. ObjectPattern: function (expr, precedence, flags) {
  15584. var result, i, iz, multiline, property, that = this;
  15585. if (!expr.properties.length) {
  15586. return '{}';
  15587. }
  15588. multiline = false;
  15589. if (expr.properties.length === 1) {
  15590. property = expr.properties[0];
  15591. if (property.value && property.value.type !== Syntax.Identifier) {
  15592. multiline = true;
  15593. }
  15594. } else {
  15595. for (i = 0, iz = expr.properties.length; i < iz; ++i) {
  15596. property = expr.properties[i];
  15597. if (!property.shorthand) {
  15598. multiline = true;
  15599. break;
  15600. }
  15601. }
  15602. }
  15603. result = [
  15604. '{',
  15605. multiline ? newline : ''
  15606. ];
  15607. withIndent(function (indent) {
  15608. var i, iz;
  15609. for (i = 0, iz = expr.properties.length; i < iz; ++i) {
  15610. result.push(multiline ? indent : '');
  15611. result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));
  15612. if (i + 1 < iz) {
  15613. result.push(',' + (multiline ? newline : space));
  15614. }
  15615. }
  15616. });
  15617. if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  15618. result.push(newline);
  15619. }
  15620. result.push(multiline ? base : '');
  15621. result.push('}');
  15622. return result;
  15623. },
  15624. ThisExpression: function (expr, precedence, flags) {
  15625. return 'this';
  15626. },
  15627. Super: function (expr, precedence, flags) {
  15628. return 'super';
  15629. },
  15630. Identifier: function (expr, precedence, flags) {
  15631. return generateIdentifier(expr);
  15632. },
  15633. Import: function (expr, precedence, flags) {
  15634. return 'import';
  15635. },
  15636. ImportDefaultSpecifier: function (expr, precedence, flags) {
  15637. return generateIdentifier(expr.id || expr.local);
  15638. },
  15639. ImportNamespaceSpecifier: function (expr, precedence, flags) {
  15640. var result = ['*'];
  15641. var id = expr.id || expr.local;
  15642. if (id) {
  15643. result.push(space + 'as' + noEmptySpace() + generateIdentifier(id));
  15644. }
  15645. return result;
  15646. },
  15647. ImportSpecifier: function (expr, precedence, flags) {
  15648. var imported = expr.imported;
  15649. var result = [imported.name];
  15650. var local = expr.local;
  15651. if (local && local.name !== imported.name) {
  15652. result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(local));
  15653. }
  15654. return result;
  15655. },
  15656. ExportSpecifier: function (expr, precedence, flags) {
  15657. var local = expr.local;
  15658. var result = [local.name];
  15659. var exported = expr.exported;
  15660. if (exported && exported.name !== local.name) {
  15661. result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(exported));
  15662. }
  15663. return result;
  15664. },
  15665. Literal: function (expr, precedence, flags) {
  15666. var raw;
  15667. if (expr.hasOwnProperty('raw') && parse && extra.raw) {
  15668. try {
  15669. raw = parse(expr.raw).body[0].expression;
  15670. if (raw.type === Syntax.Literal) {
  15671. if (raw.value === expr.value) {
  15672. return expr.raw;
  15673. }
  15674. }
  15675. } catch (e) {
  15676. }
  15677. }
  15678. if (expr.value === null) {
  15679. return 'null';
  15680. }
  15681. if (typeof expr.value === 'string') {
  15682. return escapeString(expr.value);
  15683. }
  15684. if (typeof expr.value === 'number') {
  15685. return generateNumber(expr.value);
  15686. }
  15687. if (typeof expr.value === 'boolean') {
  15688. return expr.value ? 'true' : 'false';
  15689. }
  15690. return generateRegExp(expr.value);
  15691. },
  15692. GeneratorExpression: function (expr, precedence, flags) {
  15693. return this.ComprehensionExpression(expr, precedence, flags);
  15694. },
  15695. ComprehensionExpression: function (expr, precedence, flags) {
  15696. var result, i, iz, fragment, that = this;
  15697. result = expr.type === Syntax.GeneratorExpression ? ['('] : ['['];
  15698. if (extra.moz.comprehensionExpressionStartsWithAssignment) {
  15699. fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
  15700. result.push(fragment);
  15701. }
  15702. if (expr.blocks) {
  15703. withIndent(function () {
  15704. for (i = 0, iz = expr.blocks.length; i < iz; ++i) {
  15705. fragment = that.generateExpression(expr.blocks[i], Precedence.Sequence, E_TTT);
  15706. if (i > 0 || extra.moz.comprehensionExpressionStartsWithAssignment) {
  15707. result = join(result, fragment);
  15708. } else {
  15709. result.push(fragment);
  15710. }
  15711. }
  15712. });
  15713. }
  15714. if (expr.filter) {
  15715. result = join(result, 'if' + space);
  15716. fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT);
  15717. result = join(result, [
  15718. '(',
  15719. fragment,
  15720. ')'
  15721. ]);
  15722. }
  15723. if (!extra.moz.comprehensionExpressionStartsWithAssignment) {
  15724. fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
  15725. result = join(result, fragment);
  15726. }
  15727. result.push(expr.type === Syntax.GeneratorExpression ? ')' : ']');
  15728. return result;
  15729. },
  15730. ComprehensionBlock: function (expr, precedence, flags) {
  15731. var fragment;
  15732. if (expr.left.type === Syntax.VariableDeclaration) {
  15733. fragment = [
  15734. expr.left.kind,
  15735. noEmptySpace(),
  15736. this.generateStatement(expr.left.declarations[0], S_FFFF)
  15737. ];
  15738. } else {
  15739. fragment = this.generateExpression(expr.left, Precedence.Call, E_TTT);
  15740. }
  15741. fragment = join(fragment, expr.of ? 'of' : 'in');
  15742. fragment = join(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT));
  15743. return [
  15744. 'for' + space + '(',
  15745. fragment,
  15746. ')'
  15747. ];
  15748. },
  15749. SpreadElement: function (expr, precedence, flags) {
  15750. return [
  15751. '...',
  15752. this.generateExpression(expr.argument, Precedence.Assignment, E_TTT)
  15753. ];
  15754. },
  15755. RestElement: function (expr, precedence, flags) {
  15756. return [
  15757. '...',
  15758. this.generatePattern(expr.argument, Precedence.Assignment, E_TTT)
  15759. ];
  15760. },
  15761. SpreadProperty: function (expr, precedence, flags) {
  15762. return [
  15763. '...',
  15764. this.generateExpression(expr.argument, Precedence.Assignment, E_TTT)
  15765. ];
  15766. },
  15767. RestProperty: function (expr, precedence, flags) {
  15768. return [
  15769. '...',
  15770. this.generatePattern(expr.argument, Precedence.Assignment, E_TTT)
  15771. ];
  15772. },
  15773. TaggedTemplateExpression: function (expr, precedence, flags) {
  15774. var itemFlags = E_TTF;
  15775. if (!(flags & F_ALLOW_CALL)) {
  15776. itemFlags = E_TFF;
  15777. }
  15778. var result = [
  15779. this.generateExpression(expr.tag, Precedence.Call, itemFlags),
  15780. this.generateExpression(expr.quasi, Precedence.Primary, E_FFT)
  15781. ];
  15782. return parenthesize(result, Precedence.TaggedTemplate, precedence);
  15783. },
  15784. TemplateElement: function (expr, precedence, flags) {
  15785. return expr.value.raw;
  15786. },
  15787. TemplateLiteral: function (expr, precedence, flags) {
  15788. var result, i, iz;
  15789. result = ['`'];
  15790. for (i = 0, iz = expr.quasis.length; i < iz; ++i) {
  15791. result.push(this.generateExpression(expr.quasis[i], Precedence.Primary, E_TTT));
  15792. if (i + 1 < iz) {
  15793. result.push('${' + space);
  15794. result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT));
  15795. result.push(space + '}');
  15796. }
  15797. }
  15798. result.push('`');
  15799. return result;
  15800. },
  15801. ModuleSpecifier: function (expr, precedence, flags) {
  15802. return this.Literal(expr, precedence, flags);
  15803. },
  15804. JSXText: function (expr, precedence, flags) {
  15805. if (expr.hasOwnProperty('raw')) {
  15806. return expr.raw;
  15807. }
  15808. return String(expr.value);
  15809. },
  15810. JSXAttribute: function (expr, precedence, flags) {
  15811. var result = [];
  15812. var fragment = this.generateExpression(expr.name, Precedence.Sequence, {
  15813. allowIn: true,
  15814. allowCall: true
  15815. });
  15816. result.push(fragment);
  15817. if (expr.value) {
  15818. result.push('=');
  15819. if (expr.value.type === Syntax.Literal) {
  15820. fragment = xjsEscapeAttr(expr.value.value, expr.value.raw);
  15821. } else {
  15822. fragment = this.generateExpression(expr.value, Precedence.Sequence, {
  15823. allowIn: true,
  15824. allowCall: true
  15825. });
  15826. }
  15827. result.push(fragment);
  15828. }
  15829. return result;
  15830. },
  15831. JSXClosingElement: function (expr, precedence, flags) {
  15832. return [
  15833. '</',
  15834. this.generateExpression(expr.name, Precedence.Sequence, 0),
  15835. '>'
  15836. ];
  15837. },
  15838. JSXElement: function (expr, precedence, flags) {
  15839. var result = [], that = this;
  15840. if (!(flags & F_XJS_NOINDENT)) {
  15841. base += indent;
  15842. }
  15843. var fragment = this.generateExpression(expr.openingElement, Precedence.JSXElement, {
  15844. allowIn: true,
  15845. allowCall: true
  15846. });
  15847. result.push(fragment);
  15848. var xjsFragments = [];
  15849. var i, len;
  15850. withIndent(function (indent) {
  15851. for (i = 0, len = expr.children.length; i < len; ++i) {
  15852. if (expr.children[i].type === Syntax.Literal) {
  15853. fragment = expr.children[i].raw;
  15854. if (fragment) {
  15855. xjsFragments.push(fragment);
  15856. }
  15857. continue;
  15858. }
  15859. fragment = that.generateExpression(expr.children[i], Precedence.JSXElement, E_TTF | F_XJS_NOINDENT);
  15860. xjsFragments.push(fragment);
  15861. }
  15862. for (i = 0, len = xjsFragments.length; i < len; ++i) {
  15863. result.push(xjsFragments[i]);
  15864. }
  15865. });
  15866. if (expr.closingElement) {
  15867. fragment = that.generateExpression(expr.closingElement, Precedence.JSXElement, 0);
  15868. result.push(fragment);
  15869. }
  15870. if (!(flags & F_XJS_NOINDENT)) {
  15871. base = base.slice(0, base.length - indent.length);
  15872. if (hasLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  15873. if (flags & F_XJS_NOPAREN) {
  15874. result = [
  15875. newline + base + indent,
  15876. result
  15877. ];
  15878. } else {
  15879. result = [
  15880. '(' + newline + base + indent,
  15881. result,
  15882. newline + base + ')'
  15883. ];
  15884. }
  15885. }
  15886. }
  15887. return result;
  15888. },
  15889. JSXExpressionContainer: function (expr, precedence, flags) {
  15890. return [
  15891. '{',
  15892. this.generateExpression(expr.expression, Precedence.Sequence, E_TTF),
  15893. '}'
  15894. ];
  15895. },
  15896. JSXIdentifier: function (expr, precedence, flags) {
  15897. return expr.name;
  15898. },
  15899. JSXMemberExpression: function (expr, precedence, flags) {
  15900. return [
  15901. this.generateExpression(expr.object, Precedence.Sequence, E_TFF),
  15902. '.',
  15903. this.generateExpression(expr.property, Precedence.Sequence, 0)
  15904. ];
  15905. },
  15906. JSXNamespacedName: function (expr, precedence, flags) {
  15907. return [
  15908. this.generateExpression(expr.namespace, Precedence.Sequence, 0),
  15909. ':',
  15910. this.generateExpression(expr.name, Precedence.Sequence, 0)
  15911. ];
  15912. },
  15913. JSXOpeningElement: function (expr, precedence, flags) {
  15914. var result = ['<'], that = this;
  15915. var fragment = this.generateExpression(expr.name, Precedence.Sequence, 0);
  15916. result.push(fragment);
  15917. var xjsFragments = [];
  15918. for (var i = 0, len = expr.attributes.length; i < len; ++i) {
  15919. fragment = that.generateExpression(expr.attributes[i], Precedence.Sequence, E_TTF);
  15920. xjsFragments.push({
  15921. expr: expr.attributes[i],
  15922. name: expr.attributes[i].name && expr.attributes[i].name.name,
  15923. fragment: fragment,
  15924. multiline: hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())
  15925. });
  15926. if (expr.attributes.length > 3 && expr.attributes[i].value && expr.attributes[i].value.type !== Syntax.Literal) {
  15927. xjsFragments[xjsFragments.length - 1].multiline = true;
  15928. }
  15929. }
  15930. withIndent(function (indent) {
  15931. for (var i = 0, len = xjsFragments.length; i < len; ++i) {
  15932. if (i > 0 && i % 3 === 0 || xjsFragments[i].multiline) {
  15933. result.push(newline + indent);
  15934. } else {
  15935. result.push(' ');
  15936. }
  15937. result.push(that.generateExpression(xjsFragments[i].expr, Precedence.Sequence, E_TTF));
  15938. }
  15939. });
  15940. result.push(expr.selfClosing ? '/>' : '>');
  15941. return result;
  15942. },
  15943. JSXSpreadAttribute: function (expr, precedence, flags) {
  15944. return [
  15945. '{...',
  15946. this.generateExpression(expr.argument, Precedence.Sequence, {
  15947. allowIn: true,
  15948. allowCall: true
  15949. }),
  15950. '}'
  15951. ];
  15952. }
  15953. };
  15954. merge(CodeGenerator.prototype, CodeGenerator.Expression);
  15955. CodeGenerator.prototype.generateExpression = function (expr, precedence, flags) {
  15956. var result, type;
  15957. type = expr.type || Syntax.Property;
  15958. if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) {
  15959. return generateVerbatim(expr, precedence);
  15960. }
  15961. result = this[type](expr, precedence, flags);
  15962. if (extra.comment) {
  15963. result = addComments(expr, result);
  15964. }
  15965. return toSourceNodeWhenNeeded(result, expr);
  15966. };
  15967. CodeGenerator.prototype.generateStatement = function (stmt, flags) {
  15968. var result, fragment;
  15969. result = this[stmt.type](stmt, flags);
  15970. if (extra.comment) {
  15971. result = addComments(stmt, result);
  15972. }
  15973. fragment = toSourceNodeWhenNeeded(result).toString();
  15974. if (stmt.type === Syntax.Program && !safeConcatenation && newline === '' && fragment.charAt(fragment.length - 1) === '\n') {
  15975. result = sourceMap ? toSourceNodeWhenNeeded(result).replaceRight(/\s+$/, '') : fragment.replace(/\s+$/, '');
  15976. }
  15977. return toSourceNodeWhenNeeded(result, stmt);
  15978. };
  15979. function generateInternal(node) {
  15980. var codegen;
  15981. codegen = new CodeGenerator;
  15982. if (isStatement(node)) {
  15983. return codegen.generateStatement(node, S_TFFF);
  15984. }
  15985. if (isExpression(node)) {
  15986. return codegen.generateExpression(node, Precedence.Sequence, E_TTT);
  15987. }
  15988. throw new Error('Unknown node type: ' + node.type);
  15989. }
  15990. function generate(node, options) {
  15991. var defaultOptions = getDefaultOptions(), result, pair;
  15992. if (options != null) {
  15993. if (typeof options.indent === 'string') {
  15994. defaultOptions.format.indent.style = options.indent;
  15995. }
  15996. if (typeof options.base === 'number') {
  15997. defaultOptions.format.indent.base = options.base;
  15998. }
  15999. options = updateDeeply(defaultOptions, options);
  16000. indent = options.format.indent.style;
  16001. if (typeof options.base === 'string') {
  16002. base = options.base;
  16003. } else {
  16004. base = stringRepeat(indent, options.format.indent.base);
  16005. }
  16006. } else {
  16007. options = defaultOptions;
  16008. indent = options.format.indent.style;
  16009. base = stringRepeat(indent, options.format.indent.base);
  16010. }
  16011. json = options.format.json;
  16012. renumber = options.format.renumber;
  16013. hexadecimal = json ? false : options.format.hexadecimal;
  16014. quotes = json ? 'double' : options.format.quotes;
  16015. escapeless = options.format.escapeless;
  16016. newline = options.format.newline;
  16017. space = options.format.space;
  16018. if (options.format.compact) {
  16019. newline = space = indent = base = '';
  16020. }
  16021. parentheses = options.format.parentheses;
  16022. semicolons = options.format.semicolons;
  16023. safeConcatenation = options.format.safeConcatenation;
  16024. directive = options.directive;
  16025. parse = json ? null : options.parse;
  16026. sourceMap = options.sourceMap;
  16027. sourceCode = options.sourceCode;
  16028. preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null;
  16029. extra = options;
  16030. if (sourceMap) {
  16031. if (!exports.browser) {
  16032. SourceNode = require('/node_modules/source-map/lib/source-map.js', module).SourceNode;
  16033. } else {
  16034. SourceNode = global.sourceMap.SourceNode;
  16035. }
  16036. }
  16037. result = generateInternal(node);
  16038. if (!sourceMap) {
  16039. pair = {
  16040. code: result.toString(),
  16041. map: null
  16042. };
  16043. return options.sourceMapWithCode ? pair : pair.code;
  16044. }
  16045. pair = result.toStringWithSourceMap({
  16046. file: options.file,
  16047. sourceRoot: options.sourceMapRoot
  16048. });
  16049. if (options.sourceContent) {
  16050. pair.map.setSourceContent(options.sourceMap, options.sourceContent);
  16051. }
  16052. if (options.sourceMapWithCode) {
  16053. return pair;
  16054. }
  16055. return pair.map.toString();
  16056. }
  16057. function xjsEscapeAttr(s, raw) {
  16058. if (s.indexOf('"') >= 0 || s.indexOf("'") >= 0) {
  16059. return raw;
  16060. }
  16061. return quotes === 'double' ? '"' + s + '"' : "'" + s + "'";
  16062. }
  16063. FORMAT_MINIFY = {
  16064. indent: {
  16065. style: '',
  16066. base: 0
  16067. },
  16068. renumber: true,
  16069. hexadecimal: true,
  16070. quotes: 'auto',
  16071. escapeless: true,
  16072. compact: true,
  16073. parentheses: false,
  16074. semicolons: false
  16075. };
  16076. FORMAT_DEFAULTS = getDefaultOptions().format;
  16077. exports.version = require('/package.json', module).version;
  16078. exports.generate = generate;
  16079. exports.attachComments = estraverse.attachComments;
  16080. exports.Precedence = updateDeeply({}, Precedence);
  16081. exports.browser = false;
  16082. exports.FORMAT_MINIFY = FORMAT_MINIFY;
  16083. exports.FORMAT_DEFAULTS = FORMAT_DEFAULTS;
  16084. }());
  16085. });
  16086. require.define('/package.json', function (module, exports, __dirname, __filename) {
  16087. module.exports = {
  16088. 'name': 'escodegen-wallaby',
  16089. 'description': 'ECMAScript code generator with JSX support',
  16090. 'homepage': 'http://github.com/wallabyjs/escodegen',
  16091. 'main': 'escodegen.js',
  16092. 'bin': {
  16093. 'esgenerate': './bin/esgenerate.js',
  16094. 'escodegen': './bin/escodegen.js'
  16095. },
  16096. 'files': [
  16097. 'LICENSE.BSD',
  16098. 'LICENSE.source-map',
  16099. 'README.md',
  16100. 'bin',
  16101. 'escodegen.js',
  16102. 'package.json'
  16103. ],
  16104. 'version': '1.6.12',
  16105. 'engines': { 'node': '>=0.10.0' },
  16106. 'maintainers': [{
  16107. 'name': 'Artem Govorov',
  16108. 'email': 'artem.govorov@gmail.com',
  16109. 'web': 'http://dm.gl'
  16110. }],
  16111. 'repository': {
  16112. 'type': 'git',
  16113. 'url': 'http://github.com/wallabyjs/escodegen.git'
  16114. },
  16115. 'dependencies': {
  16116. 'estraverse': '^1.9.1',
  16117. 'esutils': '^2.0.2',
  16118. 'esprima': '^2.7.1',
  16119. 'optionator': '^0.8.1'
  16120. },
  16121. 'optionalDependencies': { 'source-map': '~0.2.0' },
  16122. 'devDependencies': {
  16123. 'acorn': '^2.7.0',
  16124. 'acorn-babel': '^0.11.1-38',
  16125. 'bluebird': '^2.3.11',
  16126. 'bower-registry-client': '^0.2.1',
  16127. 'chai': '^1.10.0',
  16128. 'commonjs-everywhere': '^0.9.7',
  16129. 'gulp': '^3.8.10',
  16130. 'gulp-eslint': '^0.2.0',
  16131. 'gulp-mocha': '^2.0.0',
  16132. 'semver': '^5.1.0'
  16133. },
  16134. 'licenses': [{
  16135. 'type': 'BSD',
  16136. 'url': 'http://github.com/wallabyjs/escodegen/raw/master/LICENSE.BSD'
  16137. }],
  16138. 'scripts': {
  16139. 'test': 'gulp travis',
  16140. 'unit-test': 'gulp test',
  16141. 'lint': 'gulp lint',
  16142. 'release': 'node tools/release.js',
  16143. 'build-min': './node_modules/.bin/cjsify -ma path: tools/entry-point.js > escodegen.browser.min.js',
  16144. 'build': './node_modules/.bin/cjsify -a path: tools/entry-point.js > escodegen.browser.js'
  16145. }
  16146. };
  16147. });
  16148. require.define('/node_modules/source-map/lib/source-map.js', function (module, exports, __dirname, __filename) {
  16149. exports.SourceMapGenerator = require('/node_modules/source-map/lib/source-map/source-map-generator.js', module).SourceMapGenerator;
  16150. exports.SourceMapConsumer = require('/node_modules/source-map/lib/source-map/source-map-consumer.js', module).SourceMapConsumer;
  16151. exports.SourceNode = require('/node_modules/source-map/lib/source-map/source-node.js', module).SourceNode;
  16152. });
  16153. require.define('/node_modules/source-map/lib/source-map/source-node.js', function (module, exports, __dirname, __filename) {
  16154. if (typeof define !== 'function') {
  16155. var define = require('/node_modules/amdefine/amdefine.js', module)(module, require);
  16156. }
  16157. define(function (require, exports, module) {
  16158. var SourceMapGenerator = require('/node_modules/source-map/lib/source-map/source-map-generator.js', module).SourceMapGenerator;
  16159. var util = require('/node_modules/source-map/lib/source-map/util.js', module);
  16160. var REGEX_NEWLINE = /(\r?\n)/;
  16161. var NEWLINE_CODE = 10;
  16162. var isSourceNode = '$$$isSourceNode$$$';
  16163. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  16164. this.children = [];
  16165. this.sourceContents = {};
  16166. this.line = aLine == null ? null : aLine;
  16167. this.column = aColumn == null ? null : aColumn;
  16168. this.source = aSource == null ? null : aSource;
  16169. this.name = aName == null ? null : aName;
  16170. this[isSourceNode] = true;
  16171. if (aChunks != null)
  16172. this.add(aChunks);
  16173. }
  16174. SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  16175. var node = new SourceNode;
  16176. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  16177. var shiftNextLine = function () {
  16178. var lineContents = remainingLines.shift();
  16179. var newLine = remainingLines.shift() || '';
  16180. return lineContents + newLine;
  16181. };
  16182. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  16183. var lastMapping = null;
  16184. aSourceMapConsumer.eachMapping(function (mapping) {
  16185. if (lastMapping !== null) {
  16186. if (lastGeneratedLine < mapping.generatedLine) {
  16187. var code = '';
  16188. addMappingWithCode(lastMapping, shiftNextLine());
  16189. lastGeneratedLine++;
  16190. lastGeneratedColumn = 0;
  16191. } else {
  16192. var nextLine = remainingLines[0];
  16193. var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
  16194. remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
  16195. lastGeneratedColumn = mapping.generatedColumn;
  16196. addMappingWithCode(lastMapping, code);
  16197. lastMapping = mapping;
  16198. return;
  16199. }
  16200. }
  16201. while (lastGeneratedLine < mapping.generatedLine) {
  16202. node.add(shiftNextLine());
  16203. lastGeneratedLine++;
  16204. }
  16205. if (lastGeneratedColumn < mapping.generatedColumn) {
  16206. var nextLine = remainingLines[0];
  16207. node.add(nextLine.substr(0, mapping.generatedColumn));
  16208. remainingLines[0] = nextLine.substr(mapping.generatedColumn);
  16209. lastGeneratedColumn = mapping.generatedColumn;
  16210. }
  16211. lastMapping = mapping;
  16212. }, this);
  16213. if (remainingLines.length > 0) {
  16214. if (lastMapping) {
  16215. addMappingWithCode(lastMapping, shiftNextLine());
  16216. }
  16217. node.add(remainingLines.join(''));
  16218. }
  16219. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  16220. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  16221. if (content != null) {
  16222. if (aRelativePath != null) {
  16223. sourceFile = util.join(aRelativePath, sourceFile);
  16224. }
  16225. node.setSourceContent(sourceFile, content);
  16226. }
  16227. });
  16228. return node;
  16229. function addMappingWithCode(mapping, code) {
  16230. if (mapping === null || mapping.source === undefined) {
  16231. node.add(code);
  16232. } else {
  16233. var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source;
  16234. node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name));
  16235. }
  16236. }
  16237. };
  16238. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  16239. if (Array.isArray(aChunk)) {
  16240. aChunk.forEach(function (chunk) {
  16241. this.add(chunk);
  16242. }, this);
  16243. } else if (aChunk[isSourceNode] || typeof aChunk === 'string') {
  16244. if (aChunk) {
  16245. this.children.push(aChunk);
  16246. }
  16247. } else {
  16248. throw new TypeError('Expected a SourceNode, string, or an array of SourceNodes and strings. Got ' + aChunk);
  16249. }
  16250. return this;
  16251. };
  16252. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  16253. if (Array.isArray(aChunk)) {
  16254. for (var i = aChunk.length - 1; i >= 0; i--) {
  16255. this.prepend(aChunk[i]);
  16256. }
  16257. } else if (aChunk[isSourceNode] || typeof aChunk === 'string') {
  16258. this.children.unshift(aChunk);
  16259. } else {
  16260. throw new TypeError('Expected a SourceNode, string, or an array of SourceNodes and strings. Got ' + aChunk);
  16261. }
  16262. return this;
  16263. };
  16264. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  16265. var chunk;
  16266. for (var i = 0, len = this.children.length; i < len; i++) {
  16267. chunk = this.children[i];
  16268. if (chunk[isSourceNode]) {
  16269. chunk.walk(aFn);
  16270. } else {
  16271. if (chunk !== '') {
  16272. aFn(chunk, {
  16273. source: this.source,
  16274. line: this.line,
  16275. column: this.column,
  16276. name: this.name
  16277. });
  16278. }
  16279. }
  16280. }
  16281. };
  16282. SourceNode.prototype.join = function SourceNode_join(aSep) {
  16283. var newChildren;
  16284. var i;
  16285. var len = this.children.length;
  16286. if (len > 0) {
  16287. newChildren = [];
  16288. for (i = 0; i < len - 1; i++) {
  16289. newChildren.push(this.children[i]);
  16290. newChildren.push(aSep);
  16291. }
  16292. newChildren.push(this.children[i]);
  16293. this.children = newChildren;
  16294. }
  16295. return this;
  16296. };
  16297. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  16298. var lastChild = this.children[this.children.length - 1];
  16299. if (lastChild[isSourceNode]) {
  16300. lastChild.replaceRight(aPattern, aReplacement);
  16301. } else if (typeof lastChild === 'string') {
  16302. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  16303. } else {
  16304. this.children.push(''.replace(aPattern, aReplacement));
  16305. }
  16306. return this;
  16307. };
  16308. SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  16309. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  16310. };
  16311. SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) {
  16312. for (var i = 0, len = this.children.length; i < len; i++) {
  16313. if (this.children[i][isSourceNode]) {
  16314. this.children[i].walkSourceContents(aFn);
  16315. }
  16316. }
  16317. var sources = Object.keys(this.sourceContents);
  16318. for (var i = 0, len = sources.length; i < len; i++) {
  16319. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  16320. }
  16321. };
  16322. SourceNode.prototype.toString = function SourceNode_toString() {
  16323. var str = '';
  16324. this.walk(function (chunk) {
  16325. str += chunk;
  16326. });
  16327. return str;
  16328. };
  16329. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  16330. var generated = {
  16331. code: '',
  16332. line: 1,
  16333. column: 0
  16334. };
  16335. var map = new SourceMapGenerator(aArgs);
  16336. var sourceMappingActive = false;
  16337. var lastOriginalSource = null;
  16338. var lastOriginalLine = null;
  16339. var lastOriginalColumn = null;
  16340. var lastOriginalName = null;
  16341. this.walk(function (chunk, original) {
  16342. generated.code += chunk;
  16343. if (original.source !== null && original.line !== null && original.column !== null) {
  16344. if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
  16345. map.addMapping({
  16346. source: original.source,
  16347. original: {
  16348. line: original.line,
  16349. column: original.column
  16350. },
  16351. generated: {
  16352. line: generated.line,
  16353. column: generated.column
  16354. },
  16355. name: original.name
  16356. });
  16357. }
  16358. lastOriginalSource = original.source;
  16359. lastOriginalLine = original.line;
  16360. lastOriginalColumn = original.column;
  16361. lastOriginalName = original.name;
  16362. sourceMappingActive = true;
  16363. } else if (sourceMappingActive) {
  16364. map.addMapping({
  16365. generated: {
  16366. line: generated.line,
  16367. column: generated.column
  16368. }
  16369. });
  16370. lastOriginalSource = null;
  16371. sourceMappingActive = false;
  16372. }
  16373. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  16374. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  16375. generated.line++;
  16376. generated.column = 0;
  16377. if (idx + 1 === length) {
  16378. lastOriginalSource = null;
  16379. sourceMappingActive = false;
  16380. } else if (sourceMappingActive) {
  16381. map.addMapping({
  16382. source: original.source,
  16383. original: {
  16384. line: original.line,
  16385. column: original.column
  16386. },
  16387. generated: {
  16388. line: generated.line,
  16389. column: generated.column
  16390. },
  16391. name: original.name
  16392. });
  16393. }
  16394. } else {
  16395. generated.column++;
  16396. }
  16397. }
  16398. });
  16399. this.walkSourceContents(function (sourceFile, sourceContent) {
  16400. map.setSourceContent(sourceFile, sourceContent);
  16401. });
  16402. return {
  16403. code: generated.code,
  16404. map: map
  16405. };
  16406. };
  16407. exports.SourceNode = SourceNode;
  16408. });
  16409. });
  16410. require.define('/node_modules/source-map/lib/source-map/util.js', function (module, exports, __dirname, __filename) {
  16411. if (typeof define !== 'function') {
  16412. var define = require('/node_modules/amdefine/amdefine.js', module)(module, require);
  16413. }
  16414. define(function (require, exports, module) {
  16415. function getArg(aArgs, aName, aDefaultValue) {
  16416. if (aName in aArgs) {
  16417. return aArgs[aName];
  16418. } else if (arguments.length === 3) {
  16419. return aDefaultValue;
  16420. } else {
  16421. throw new Error('"' + aName + '" is a required argument.');
  16422. }
  16423. }
  16424. exports.getArg = getArg;
  16425. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
  16426. var dataUrlRegexp = /^data:.+\,.+$/;
  16427. function urlParse(aUrl) {
  16428. var match = aUrl.match(urlRegexp);
  16429. if (!match) {
  16430. return null;
  16431. }
  16432. return {
  16433. scheme: match[1],
  16434. auth: match[2],
  16435. host: match[3],
  16436. port: match[4],
  16437. path: match[5]
  16438. };
  16439. }
  16440. exports.urlParse = urlParse;
  16441. function urlGenerate(aParsedUrl) {
  16442. var url = '';
  16443. if (aParsedUrl.scheme) {
  16444. url += aParsedUrl.scheme + ':';
  16445. }
  16446. url += '//';
  16447. if (aParsedUrl.auth) {
  16448. url += aParsedUrl.auth + '@';
  16449. }
  16450. if (aParsedUrl.host) {
  16451. url += aParsedUrl.host;
  16452. }
  16453. if (aParsedUrl.port) {
  16454. url += ':' + aParsedUrl.port;
  16455. }
  16456. if (aParsedUrl.path) {
  16457. url += aParsedUrl.path;
  16458. }
  16459. return url;
  16460. }
  16461. exports.urlGenerate = urlGenerate;
  16462. function normalize(aPath) {
  16463. var path = aPath;
  16464. var url = urlParse(aPath);
  16465. if (url) {
  16466. if (!url.path) {
  16467. return aPath;
  16468. }
  16469. path = url.path;
  16470. }
  16471. var isAbsolute = path.charAt(0) === '/';
  16472. var parts = path.split(/\/+/);
  16473. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  16474. part = parts[i];
  16475. if (part === '.') {
  16476. parts.splice(i, 1);
  16477. } else if (part === '..') {
  16478. up++;
  16479. } else if (up > 0) {
  16480. if (part === '') {
  16481. parts.splice(i + 1, up);
  16482. up = 0;
  16483. } else {
  16484. parts.splice(i, 2);
  16485. up--;
  16486. }
  16487. }
  16488. }
  16489. path = parts.join('/');
  16490. if (path === '') {
  16491. path = isAbsolute ? '/' : '.';
  16492. }
  16493. if (url) {
  16494. url.path = path;
  16495. return urlGenerate(url);
  16496. }
  16497. return path;
  16498. }
  16499. exports.normalize = normalize;
  16500. function join(aRoot, aPath) {
  16501. if (aRoot === '') {
  16502. aRoot = '.';
  16503. }
  16504. if (aPath === '') {
  16505. aPath = '.';
  16506. }
  16507. var aPathUrl = urlParse(aPath);
  16508. var aRootUrl = urlParse(aRoot);
  16509. if (aRootUrl) {
  16510. aRoot = aRootUrl.path || '/';
  16511. }
  16512. if (aPathUrl && !aPathUrl.scheme) {
  16513. if (aRootUrl) {
  16514. aPathUrl.scheme = aRootUrl.scheme;
  16515. }
  16516. return urlGenerate(aPathUrl);
  16517. }
  16518. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  16519. return aPath;
  16520. }
  16521. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  16522. aRootUrl.host = aPath;
  16523. return urlGenerate(aRootUrl);
  16524. }
  16525. var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  16526. if (aRootUrl) {
  16527. aRootUrl.path = joined;
  16528. return urlGenerate(aRootUrl);
  16529. }
  16530. return joined;
  16531. }
  16532. exports.join = join;
  16533. function relative(aRoot, aPath) {
  16534. if (aRoot === '') {
  16535. aRoot = '.';
  16536. }
  16537. aRoot = aRoot.replace(/\/$/, '');
  16538. var url = urlParse(aRoot);
  16539. if (aPath.charAt(0) == '/' && url && url.path == '/') {
  16540. return aPath.slice(1);
  16541. }
  16542. return aPath.indexOf(aRoot + '/') === 0 ? aPath.substr(aRoot.length + 1) : aPath;
  16543. }
  16544. exports.relative = relative;
  16545. function toSetString(aStr) {
  16546. return '$' + aStr;
  16547. }
  16548. exports.toSetString = toSetString;
  16549. function fromSetString(aStr) {
  16550. return aStr.substr(1);
  16551. }
  16552. exports.fromSetString = fromSetString;
  16553. function strcmp(aStr1, aStr2) {
  16554. var s1 = aStr1 || '';
  16555. var s2 = aStr2 || '';
  16556. return (s1 > s2) - (s1 < s2);
  16557. }
  16558. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  16559. var cmp;
  16560. cmp = strcmp(mappingA.source, mappingB.source);
  16561. if (cmp) {
  16562. return cmp;
  16563. }
  16564. cmp = mappingA.originalLine - mappingB.originalLine;
  16565. if (cmp) {
  16566. return cmp;
  16567. }
  16568. cmp = mappingA.originalColumn - mappingB.originalColumn;
  16569. if (cmp || onlyCompareOriginal) {
  16570. return cmp;
  16571. }
  16572. cmp = strcmp(mappingA.name, mappingB.name);
  16573. if (cmp) {
  16574. return cmp;
  16575. }
  16576. cmp = mappingA.generatedLine - mappingB.generatedLine;
  16577. if (cmp) {
  16578. return cmp;
  16579. }
  16580. return mappingA.generatedColumn - mappingB.generatedColumn;
  16581. }
  16582. ;
  16583. exports.compareByOriginalPositions = compareByOriginalPositions;
  16584. function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
  16585. var cmp;
  16586. cmp = mappingA.generatedLine - mappingB.generatedLine;
  16587. if (cmp) {
  16588. return cmp;
  16589. }
  16590. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  16591. if (cmp || onlyCompareGenerated) {
  16592. return cmp;
  16593. }
  16594. cmp = strcmp(mappingA.source, mappingB.source);
  16595. if (cmp) {
  16596. return cmp;
  16597. }
  16598. cmp = mappingA.originalLine - mappingB.originalLine;
  16599. if (cmp) {
  16600. return cmp;
  16601. }
  16602. cmp = mappingA.originalColumn - mappingB.originalColumn;
  16603. if (cmp) {
  16604. return cmp;
  16605. }
  16606. return strcmp(mappingA.name, mappingB.name);
  16607. }
  16608. ;
  16609. exports.compareByGeneratedPositions = compareByGeneratedPositions;
  16610. });
  16611. });
  16612. require.define('/node_modules/amdefine/amdefine.js', function (module, exports, __dirname, __filename) {
  16613. 'use strict';
  16614. function amdefine(module, requireFn) {
  16615. 'use strict';
  16616. var defineCache = {}, loaderCache = {}, alreadyCalled = false, path = require('path', module), makeRequire, stringRequire;
  16617. function trimDots(ary) {
  16618. var i, part;
  16619. for (i = 0; ary[i]; i += 1) {
  16620. part = ary[i];
  16621. if (part === '.') {
  16622. ary.splice(i, 1);
  16623. i -= 1;
  16624. } else if (part === '..') {
  16625. if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
  16626. break;
  16627. } else if (i > 0) {
  16628. ary.splice(i - 1, 2);
  16629. i -= 2;
  16630. }
  16631. }
  16632. }
  16633. }
  16634. function normalize(name, baseName) {
  16635. var baseParts;
  16636. if (name && name.charAt(0) === '.') {
  16637. if (baseName) {
  16638. baseParts = baseName.split('/');
  16639. baseParts = baseParts.slice(0, baseParts.length - 1);
  16640. baseParts = baseParts.concat(name.split('/'));
  16641. trimDots(baseParts);
  16642. name = baseParts.join('/');
  16643. }
  16644. }
  16645. return name;
  16646. }
  16647. function makeNormalize(relName) {
  16648. return function (name) {
  16649. return normalize(name, relName);
  16650. };
  16651. }
  16652. function makeLoad(id) {
  16653. function load(value) {
  16654. loaderCache[id] = value;
  16655. }
  16656. load.fromText = function (id, text) {
  16657. throw new Error('amdefine does not implement load.fromText');
  16658. };
  16659. return load;
  16660. }
  16661. makeRequire = function (systemRequire, exports, module, relId) {
  16662. function amdRequire(deps, callback) {
  16663. if (typeof deps === 'string') {
  16664. return stringRequire(systemRequire, exports, module, deps, relId);
  16665. } else {
  16666. deps = deps.map(function (depName) {
  16667. return stringRequire(systemRequire, exports, module, depName, relId);
  16668. });
  16669. if (callback) {
  16670. process.nextTick(function () {
  16671. callback.apply(null, deps);
  16672. });
  16673. }
  16674. }
  16675. }
  16676. amdRequire.toUrl = function (filePath) {
  16677. if (filePath.indexOf('.') === 0) {
  16678. return normalize(filePath, path.dirname(module.filename));
  16679. } else {
  16680. return filePath;
  16681. }
  16682. };
  16683. return amdRequire;
  16684. };
  16685. requireFn = requireFn || function req() {
  16686. return module.require.apply(module, arguments);
  16687. };
  16688. function runFactory(id, deps, factory) {
  16689. var r, e, m, result;
  16690. if (id) {
  16691. e = loaderCache[id] = {};
  16692. m = {
  16693. id: id,
  16694. uri: __filename,
  16695. exports: e
  16696. };
  16697. r = makeRequire(requireFn, e, m, id);
  16698. } else {
  16699. if (alreadyCalled) {
  16700. throw new Error('amdefine with no module ID cannot be called more than once per file.');
  16701. }
  16702. alreadyCalled = true;
  16703. e = module.exports;
  16704. m = module;
  16705. r = makeRequire(requireFn, e, m, module.id);
  16706. }
  16707. if (deps) {
  16708. deps = deps.map(function (depName) {
  16709. return r(depName);
  16710. });
  16711. }
  16712. if (typeof factory === 'function') {
  16713. result = factory.apply(m.exports, deps);
  16714. } else {
  16715. result = factory;
  16716. }
  16717. if (result !== undefined) {
  16718. m.exports = result;
  16719. if (id) {
  16720. loaderCache[id] = m.exports;
  16721. }
  16722. }
  16723. }
  16724. stringRequire = function (systemRequire, exports, module, id, relId) {
  16725. var index = id.indexOf('!'), originalId = id, prefix, plugin;
  16726. if (index === -1) {
  16727. id = normalize(id, relId);
  16728. if (id === 'require') {
  16729. return makeRequire(systemRequire, exports, module, relId);
  16730. } else if (id === 'exports') {
  16731. return exports;
  16732. } else if (id === 'module') {
  16733. return module;
  16734. } else if (loaderCache.hasOwnProperty(id)) {
  16735. return loaderCache[id];
  16736. } else if (defineCache[id]) {
  16737. runFactory.apply(null, defineCache[id]);
  16738. return loaderCache[id];
  16739. } else {
  16740. if (systemRequire) {
  16741. return systemRequire(originalId);
  16742. } else {
  16743. throw new Error('No module with ID: ' + id);
  16744. }
  16745. }
  16746. } else {
  16747. prefix = id.substring(0, index);
  16748. id = id.substring(index + 1, id.length);
  16749. plugin = stringRequire(systemRequire, exports, module, prefix, relId);
  16750. if (plugin.normalize) {
  16751. id = plugin.normalize(id, makeNormalize(relId));
  16752. } else {
  16753. id = normalize(id, relId);
  16754. }
  16755. if (loaderCache[id]) {
  16756. return loaderCache[id];
  16757. } else {
  16758. plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
  16759. return loaderCache[id];
  16760. }
  16761. }
  16762. };
  16763. function define(id, deps, factory) {
  16764. if (Array.isArray(id)) {
  16765. factory = deps;
  16766. deps = id;
  16767. id = undefined;
  16768. } else if (typeof id !== 'string') {
  16769. factory = id;
  16770. id = deps = undefined;
  16771. }
  16772. if (deps && !Array.isArray(deps)) {
  16773. factory = deps;
  16774. deps = undefined;
  16775. }
  16776. if (!deps) {
  16777. deps = [
  16778. 'require',
  16779. 'exports',
  16780. 'module'
  16781. ];
  16782. }
  16783. if (id) {
  16784. defineCache[id] = [
  16785. id,
  16786. deps,
  16787. factory
  16788. ];
  16789. } else {
  16790. runFactory(id, deps, factory);
  16791. }
  16792. }
  16793. define.require = function (id) {
  16794. if (loaderCache[id]) {
  16795. return loaderCache[id];
  16796. }
  16797. if (defineCache[id]) {
  16798. runFactory.apply(null, defineCache[id]);
  16799. return loaderCache[id];
  16800. }
  16801. };
  16802. define.amd = {};
  16803. return define;
  16804. }
  16805. module.exports = amdefine;
  16806. });
  16807. require.define('/node_modules/source-map/lib/source-map/source-map-generator.js', function (module, exports, __dirname, __filename) {
  16808. if (typeof define !== 'function') {
  16809. var define = require('/node_modules/amdefine/amdefine.js', module)(module, require);
  16810. }
  16811. define(function (require, exports, module) {
  16812. var base64VLQ = require('/node_modules/source-map/lib/source-map/base64-vlq.js', module);
  16813. var util = require('/node_modules/source-map/lib/source-map/util.js', module);
  16814. var ArraySet = require('/node_modules/source-map/lib/source-map/array-set.js', module).ArraySet;
  16815. var MappingList = require('/node_modules/source-map/lib/source-map/mapping-list.js', module).MappingList;
  16816. function SourceMapGenerator(aArgs) {
  16817. if (!aArgs) {
  16818. aArgs = {};
  16819. }
  16820. this._file = util.getArg(aArgs, 'file', null);
  16821. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  16822. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  16823. this._sources = new ArraySet;
  16824. this._names = new ArraySet;
  16825. this._mappings = new MappingList;
  16826. this._sourcesContents = null;
  16827. }
  16828. SourceMapGenerator.prototype._version = 3;
  16829. SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  16830. var sourceRoot = aSourceMapConsumer.sourceRoot;
  16831. var generator = new SourceMapGenerator({
  16832. file: aSourceMapConsumer.file,
  16833. sourceRoot: sourceRoot
  16834. });
  16835. aSourceMapConsumer.eachMapping(function (mapping) {
  16836. var newMapping = {
  16837. generated: {
  16838. line: mapping.generatedLine,
  16839. column: mapping.generatedColumn
  16840. }
  16841. };
  16842. if (mapping.source != null) {
  16843. newMapping.source = mapping.source;
  16844. if (sourceRoot != null) {
  16845. newMapping.source = util.relative(sourceRoot, newMapping.source);
  16846. }
  16847. newMapping.original = {
  16848. line: mapping.originalLine,
  16849. column: mapping.originalColumn
  16850. };
  16851. if (mapping.name != null) {
  16852. newMapping.name = mapping.name;
  16853. }
  16854. }
  16855. generator.addMapping(newMapping);
  16856. });
  16857. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  16858. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  16859. if (content != null) {
  16860. generator.setSourceContent(sourceFile, content);
  16861. }
  16862. });
  16863. return generator;
  16864. };
  16865. SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) {
  16866. var generated = util.getArg(aArgs, 'generated');
  16867. var original = util.getArg(aArgs, 'original', null);
  16868. var source = util.getArg(aArgs, 'source', null);
  16869. var name = util.getArg(aArgs, 'name', null);
  16870. if (!this._skipValidation) {
  16871. this._validateMapping(generated, original, source, name);
  16872. }
  16873. if (source != null && !this._sources.has(source)) {
  16874. this._sources.add(source);
  16875. }
  16876. if (name != null && !this._names.has(name)) {
  16877. this._names.add(name);
  16878. }
  16879. this._mappings.add({
  16880. generatedLine: generated.line,
  16881. generatedColumn: generated.column,
  16882. originalLine: original != null && original.line,
  16883. originalColumn: original != null && original.column,
  16884. source: source,
  16885. name: name
  16886. });
  16887. };
  16888. SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  16889. var source = aSourceFile;
  16890. if (this._sourceRoot != null) {
  16891. source = util.relative(this._sourceRoot, source);
  16892. }
  16893. if (aSourceContent != null) {
  16894. if (!this._sourcesContents) {
  16895. this._sourcesContents = {};
  16896. }
  16897. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  16898. } else if (this._sourcesContents) {
  16899. delete this._sourcesContents[util.toSetString(source)];
  16900. if (Object.keys(this._sourcesContents).length === 0) {
  16901. this._sourcesContents = null;
  16902. }
  16903. }
  16904. };
  16905. SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  16906. var sourceFile = aSourceFile;
  16907. if (aSourceFile == null) {
  16908. if (aSourceMapConsumer.file == null) {
  16909. throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.');
  16910. }
  16911. sourceFile = aSourceMapConsumer.file;
  16912. }
  16913. var sourceRoot = this._sourceRoot;
  16914. if (sourceRoot != null) {
  16915. sourceFile = util.relative(sourceRoot, sourceFile);
  16916. }
  16917. var newSources = new ArraySet;
  16918. var newNames = new ArraySet;
  16919. this._mappings.unsortedForEach(function (mapping) {
  16920. if (mapping.source === sourceFile && mapping.originalLine != null) {
  16921. var original = aSourceMapConsumer.originalPositionFor({
  16922. line: mapping.originalLine,
  16923. column: mapping.originalColumn
  16924. });
  16925. if (original.source != null) {
  16926. mapping.source = original.source;
  16927. if (aSourceMapPath != null) {
  16928. mapping.source = util.join(aSourceMapPath, mapping.source);
  16929. }
  16930. if (sourceRoot != null) {
  16931. mapping.source = util.relative(sourceRoot, mapping.source);
  16932. }
  16933. mapping.originalLine = original.line;
  16934. mapping.originalColumn = original.column;
  16935. if (original.name != null) {
  16936. mapping.name = original.name;
  16937. }
  16938. }
  16939. }
  16940. var source = mapping.source;
  16941. if (source != null && !newSources.has(source)) {
  16942. newSources.add(source);
  16943. }
  16944. var name = mapping.name;
  16945. if (name != null && !newNames.has(name)) {
  16946. newNames.add(name);
  16947. }
  16948. }, this);
  16949. this._sources = newSources;
  16950. this._names = newNames;
  16951. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  16952. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  16953. if (content != null) {
  16954. if (aSourceMapPath != null) {
  16955. sourceFile = util.join(aSourceMapPath, sourceFile);
  16956. }
  16957. if (sourceRoot != null) {
  16958. sourceFile = util.relative(sourceRoot, sourceFile);
  16959. }
  16960. this.setSourceContent(sourceFile, content);
  16961. }
  16962. }, this);
  16963. };
  16964. SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
  16965. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
  16966. return;
  16967. } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
  16968. return;
  16969. } else {
  16970. throw new Error('Invalid mapping: ' + JSON.stringify({
  16971. generated: aGenerated,
  16972. source: aSource,
  16973. original: aOriginal,
  16974. name: aName
  16975. }));
  16976. }
  16977. };
  16978. SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() {
  16979. var previousGeneratedColumn = 0;
  16980. var previousGeneratedLine = 1;
  16981. var previousOriginalColumn = 0;
  16982. var previousOriginalLine = 0;
  16983. var previousName = 0;
  16984. var previousSource = 0;
  16985. var result = '';
  16986. var mapping;
  16987. var mappings = this._mappings.toArray();
  16988. for (var i = 0, len = mappings.length; i < len; i++) {
  16989. mapping = mappings[i];
  16990. if (mapping.generatedLine !== previousGeneratedLine) {
  16991. previousGeneratedColumn = 0;
  16992. while (mapping.generatedLine !== previousGeneratedLine) {
  16993. result += ';';
  16994. previousGeneratedLine++;
  16995. }
  16996. } else {
  16997. if (i > 0) {
  16998. if (!util.compareByGeneratedPositions(mapping, mappings[i - 1])) {
  16999. continue;
  17000. }
  17001. result += ',';
  17002. }
  17003. }
  17004. result += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn);
  17005. previousGeneratedColumn = mapping.generatedColumn;
  17006. if (mapping.source != null) {
  17007. result += base64VLQ.encode(this._sources.indexOf(mapping.source) - previousSource);
  17008. previousSource = this._sources.indexOf(mapping.source);
  17009. result += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine);
  17010. previousOriginalLine = mapping.originalLine - 1;
  17011. result += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn);
  17012. previousOriginalColumn = mapping.originalColumn;
  17013. if (mapping.name != null) {
  17014. result += base64VLQ.encode(this._names.indexOf(mapping.name) - previousName);
  17015. previousName = this._names.indexOf(mapping.name);
  17016. }
  17017. }
  17018. }
  17019. return result;
  17020. };
  17021. SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  17022. return aSources.map(function (source) {
  17023. if (!this._sourcesContents) {
  17024. return null;
  17025. }
  17026. if (aSourceRoot != null) {
  17027. source = util.relative(aSourceRoot, source);
  17028. }
  17029. var key = util.toSetString(source);
  17030. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
  17031. }, this);
  17032. };
  17033. SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
  17034. var map = {
  17035. version: this._version,
  17036. sources: this._sources.toArray(),
  17037. names: this._names.toArray(),
  17038. mappings: this._serializeMappings()
  17039. };
  17040. if (this._file != null) {
  17041. map.file = this._file;
  17042. }
  17043. if (this._sourceRoot != null) {
  17044. map.sourceRoot = this._sourceRoot;
  17045. }
  17046. if (this._sourcesContents) {
  17047. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  17048. }
  17049. return map;
  17050. };
  17051. SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() {
  17052. return JSON.stringify(this);
  17053. };
  17054. exports.SourceMapGenerator = SourceMapGenerator;
  17055. });
  17056. });
  17057. require.define('/node_modules/source-map/lib/source-map/mapping-list.js', function (module, exports, __dirname, __filename) {
  17058. if (typeof define !== 'function') {
  17059. var define = require('/node_modules/amdefine/amdefine.js', module)(module, require);
  17060. }
  17061. define(function (require, exports, module) {
  17062. var util = require('/node_modules/source-map/lib/source-map/util.js', module);
  17063. function generatedPositionAfter(mappingA, mappingB) {
  17064. var lineA = mappingA.generatedLine;
  17065. var lineB = mappingB.generatedLine;
  17066. var columnA = mappingA.generatedColumn;
  17067. var columnB = mappingB.generatedColumn;
  17068. return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositions(mappingA, mappingB) <= 0;
  17069. }
  17070. function MappingList() {
  17071. this._array = [];
  17072. this._sorted = true;
  17073. this._last = {
  17074. generatedLine: -1,
  17075. generatedColumn: 0
  17076. };
  17077. }
  17078. MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) {
  17079. this._array.forEach(aCallback, aThisArg);
  17080. };
  17081. MappingList.prototype.add = function MappingList_add(aMapping) {
  17082. var mapping;
  17083. if (generatedPositionAfter(this._last, aMapping)) {
  17084. this._last = aMapping;
  17085. this._array.push(aMapping);
  17086. } else {
  17087. this._sorted = false;
  17088. this._array.push(aMapping);
  17089. }
  17090. };
  17091. MappingList.prototype.toArray = function MappingList_toArray() {
  17092. if (!this._sorted) {
  17093. this._array.sort(util.compareByGeneratedPositions);
  17094. this._sorted = true;
  17095. }
  17096. return this._array;
  17097. };
  17098. exports.MappingList = MappingList;
  17099. });
  17100. });
  17101. require.define('/node_modules/source-map/lib/source-map/array-set.js', function (module, exports, __dirname, __filename) {
  17102. if (typeof define !== 'function') {
  17103. var define = require('/node_modules/amdefine/amdefine.js', module)(module, require);
  17104. }
  17105. define(function (require, exports, module) {
  17106. var util = require('/node_modules/source-map/lib/source-map/util.js', module);
  17107. function ArraySet() {
  17108. this._array = [];
  17109. this._set = {};
  17110. }
  17111. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  17112. var set = new ArraySet;
  17113. for (var i = 0, len = aArray.length; i < len; i++) {
  17114. set.add(aArray[i], aAllowDuplicates);
  17115. }
  17116. return set;
  17117. };
  17118. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  17119. var isDuplicate = this.has(aStr);
  17120. var idx = this._array.length;
  17121. if (!isDuplicate || aAllowDuplicates) {
  17122. this._array.push(aStr);
  17123. }
  17124. if (!isDuplicate) {
  17125. this._set[util.toSetString(aStr)] = idx;
  17126. }
  17127. };
  17128. ArraySet.prototype.has = function ArraySet_has(aStr) {
  17129. return Object.prototype.hasOwnProperty.call(this._set, util.toSetString(aStr));
  17130. };
  17131. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  17132. if (this.has(aStr)) {
  17133. return this._set[util.toSetString(aStr)];
  17134. }
  17135. throw new Error('"' + aStr + '" is not in the set.');
  17136. };
  17137. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  17138. if (aIdx >= 0 && aIdx < this._array.length) {
  17139. return this._array[aIdx];
  17140. }
  17141. throw new Error('No element indexed by ' + aIdx);
  17142. };
  17143. ArraySet.prototype.toArray = function ArraySet_toArray() {
  17144. return this._array.slice();
  17145. };
  17146. exports.ArraySet = ArraySet;
  17147. });
  17148. });
  17149. require.define('/node_modules/source-map/lib/source-map/base64-vlq.js', function (module, exports, __dirname, __filename) {
  17150. if (typeof define !== 'function') {
  17151. var define = require('/node_modules/amdefine/amdefine.js', module)(module, require);
  17152. }
  17153. define(function (require, exports, module) {
  17154. var base64 = require('/node_modules/source-map/lib/source-map/base64.js', module);
  17155. var VLQ_BASE_SHIFT = 5;
  17156. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  17157. var VLQ_BASE_MASK = VLQ_BASE - 1;
  17158. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  17159. function toVLQSigned(aValue) {
  17160. return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
  17161. }
  17162. function fromVLQSigned(aValue) {
  17163. var isNegative = (aValue & 1) === 1;
  17164. var shifted = aValue >> 1;
  17165. return isNegative ? -shifted : shifted;
  17166. }
  17167. exports.encode = function base64VLQ_encode(aValue) {
  17168. var encoded = '';
  17169. var digit;
  17170. var vlq = toVLQSigned(aValue);
  17171. do {
  17172. digit = vlq & VLQ_BASE_MASK;
  17173. vlq >>>= VLQ_BASE_SHIFT;
  17174. if (vlq > 0) {
  17175. digit |= VLQ_CONTINUATION_BIT;
  17176. }
  17177. encoded += base64.encode(digit);
  17178. } while (vlq > 0);
  17179. return encoded;
  17180. };
  17181. exports.decode = function base64VLQ_decode(aStr, aOutParam) {
  17182. var i = 0;
  17183. var strLen = aStr.length;
  17184. var result = 0;
  17185. var shift = 0;
  17186. var continuation, digit;
  17187. do {
  17188. if (i >= strLen) {
  17189. throw new Error('Expected more digits in base 64 VLQ value.');
  17190. }
  17191. digit = base64.decode(aStr.charAt(i++));
  17192. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  17193. digit &= VLQ_BASE_MASK;
  17194. result = result + (digit << shift);
  17195. shift += VLQ_BASE_SHIFT;
  17196. } while (continuation);
  17197. aOutParam.value = fromVLQSigned(result);
  17198. aOutParam.rest = aStr.slice(i);
  17199. };
  17200. });
  17201. });
  17202. require.define('/node_modules/source-map/lib/source-map/base64.js', function (module, exports, __dirname, __filename) {
  17203. if (typeof define !== 'function') {
  17204. var define = require('/node_modules/amdefine/amdefine.js', module)(module, require);
  17205. }
  17206. define(function (require, exports, module) {
  17207. var charToIntMap = {};
  17208. var intToCharMap = {};
  17209. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('').forEach(function (ch, index) {
  17210. charToIntMap[ch] = index;
  17211. intToCharMap[index] = ch;
  17212. });
  17213. exports.encode = function base64_encode(aNumber) {
  17214. if (aNumber in intToCharMap) {
  17215. return intToCharMap[aNumber];
  17216. }
  17217. throw new TypeError('Must be between 0 and 63: ' + aNumber);
  17218. };
  17219. exports.decode = function base64_decode(aChar) {
  17220. if (aChar in charToIntMap) {
  17221. return charToIntMap[aChar];
  17222. }
  17223. throw new TypeError('Not a valid base 64 digit: ' + aChar);
  17224. };
  17225. });
  17226. });
  17227. require.define('/node_modules/source-map/lib/source-map/source-map-consumer.js', function (module, exports, __dirname, __filename) {
  17228. if (typeof define !== 'function') {
  17229. var define = require('/node_modules/amdefine/amdefine.js', module)(module, require);
  17230. }
  17231. define(function (require, exports, module) {
  17232. var util = require('/node_modules/source-map/lib/source-map/util.js', module);
  17233. function SourceMapConsumer(aSourceMap) {
  17234. var sourceMap = aSourceMap;
  17235. if (typeof aSourceMap === 'string') {
  17236. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  17237. }
  17238. if (sourceMap.sections != null) {
  17239. var indexedSourceMapConsumer = require('/node_modules/source-map/lib/source-map/indexed-source-map-consumer.js', module);
  17240. return new indexedSourceMapConsumer.IndexedSourceMapConsumer(sourceMap);
  17241. } else {
  17242. var basicSourceMapConsumer = require('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js', module);
  17243. return new basicSourceMapConsumer.BasicSourceMapConsumer(sourceMap);
  17244. }
  17245. }
  17246. SourceMapConsumer.fromSourceMap = function (aSourceMap) {
  17247. var basicSourceMapConsumer = require('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js', module);
  17248. return basicSourceMapConsumer.BasicSourceMapConsumer.fromSourceMap(aSourceMap);
  17249. };
  17250. SourceMapConsumer.prototype._version = 3;
  17251. SourceMapConsumer.prototype.__generatedMappings = null;
  17252. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  17253. get: function () {
  17254. if (!this.__generatedMappings) {
  17255. this.__generatedMappings = [];
  17256. this.__originalMappings = [];
  17257. this._parseMappings(this._mappings, this.sourceRoot);
  17258. }
  17259. return this.__generatedMappings;
  17260. }
  17261. });
  17262. SourceMapConsumer.prototype.__originalMappings = null;
  17263. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  17264. get: function () {
  17265. if (!this.__originalMappings) {
  17266. this.__generatedMappings = [];
  17267. this.__originalMappings = [];
  17268. this._parseMappings(this._mappings, this.sourceRoot);
  17269. }
  17270. return this.__originalMappings;
  17271. }
  17272. });
  17273. SourceMapConsumer.prototype._nextCharIsMappingSeparator = function SourceMapConsumer_nextCharIsMappingSeparator(aStr) {
  17274. var c = aStr.charAt(0);
  17275. return c === ';' || c === ',';
  17276. };
  17277. SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  17278. throw new Error('Subclasses must implement _parseMappings');
  17279. };
  17280. SourceMapConsumer.GENERATED_ORDER = 1;
  17281. SourceMapConsumer.ORIGINAL_ORDER = 2;
  17282. SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  17283. var context = aContext || null;
  17284. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  17285. var mappings;
  17286. switch (order) {
  17287. case SourceMapConsumer.GENERATED_ORDER:
  17288. mappings = this._generatedMappings;
  17289. break;
  17290. case SourceMapConsumer.ORIGINAL_ORDER:
  17291. mappings = this._originalMappings;
  17292. break;
  17293. default:
  17294. throw new Error('Unknown order of iteration.');
  17295. }
  17296. var sourceRoot = this.sourceRoot;
  17297. mappings.map(function (mapping) {
  17298. var source = mapping.source;
  17299. if (source != null && sourceRoot != null) {
  17300. source = util.join(sourceRoot, source);
  17301. }
  17302. return {
  17303. source: source,
  17304. generatedLine: mapping.generatedLine,
  17305. generatedColumn: mapping.generatedColumn,
  17306. originalLine: mapping.originalLine,
  17307. originalColumn: mapping.originalColumn,
  17308. name: mapping.name
  17309. };
  17310. }).forEach(aCallback, context);
  17311. };
  17312. SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  17313. var needle = {
  17314. source: util.getArg(aArgs, 'source'),
  17315. originalLine: util.getArg(aArgs, 'line'),
  17316. originalColumn: Infinity
  17317. };
  17318. if (this.sourceRoot != null) {
  17319. needle.source = util.relative(this.sourceRoot, needle.source);
  17320. }
  17321. var mappings = [];
  17322. var index = this._findMapping(needle, this._originalMappings, 'originalLine', 'originalColumn', util.compareByOriginalPositions);
  17323. if (index >= 0) {
  17324. var mapping = this._originalMappings[index];
  17325. while (mapping && mapping.originalLine === needle.originalLine) {
  17326. mappings.push({
  17327. line: util.getArg(mapping, 'generatedLine', null),
  17328. column: util.getArg(mapping, 'generatedColumn', null),
  17329. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  17330. });
  17331. mapping = this._originalMappings[--index];
  17332. }
  17333. }
  17334. return mappings.reverse();
  17335. };
  17336. exports.SourceMapConsumer = SourceMapConsumer;
  17337. });
  17338. });
  17339. require.define('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js', function (module, exports, __dirname, __filename) {
  17340. if (typeof define !== 'function') {
  17341. var define = require('/node_modules/amdefine/amdefine.js', module)(module, require);
  17342. }
  17343. define(function (require, exports, module) {
  17344. var util = require('/node_modules/source-map/lib/source-map/util.js', module);
  17345. var binarySearch = require('/node_modules/source-map/lib/source-map/binary-search.js', module);
  17346. var ArraySet = require('/node_modules/source-map/lib/source-map/array-set.js', module).ArraySet;
  17347. var base64VLQ = require('/node_modules/source-map/lib/source-map/base64-vlq.js', module);
  17348. var SourceMapConsumer = require('/node_modules/source-map/lib/source-map/source-map-consumer.js', module).SourceMapConsumer;
  17349. function BasicSourceMapConsumer(aSourceMap) {
  17350. var sourceMap = aSourceMap;
  17351. if (typeof aSourceMap === 'string') {
  17352. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  17353. }
  17354. var version = util.getArg(sourceMap, 'version');
  17355. var sources = util.getArg(sourceMap, 'sources');
  17356. var names = util.getArg(sourceMap, 'names', []);
  17357. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  17358. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  17359. var mappings = util.getArg(sourceMap, 'mappings');
  17360. var file = util.getArg(sourceMap, 'file', null);
  17361. if (version != this._version) {
  17362. throw new Error('Unsupported version: ' + version);
  17363. }
  17364. sources = sources.map(util.normalize);
  17365. this._names = ArraySet.fromArray(names, true);
  17366. this._sources = ArraySet.fromArray(sources, true);
  17367. this.sourceRoot = sourceRoot;
  17368. this.sourcesContent = sourcesContent;
  17369. this._mappings = mappings;
  17370. this.file = file;
  17371. }
  17372. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  17373. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  17374. BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) {
  17375. var smc = Object.create(BasicSourceMapConsumer.prototype);
  17376. smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  17377. smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  17378. smc.sourceRoot = aSourceMap._sourceRoot;
  17379. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot);
  17380. smc.file = aSourceMap._file;
  17381. smc.__generatedMappings = aSourceMap._mappings.toArray().slice();
  17382. smc.__originalMappings = aSourceMap._mappings.toArray().slice().sort(util.compareByOriginalPositions);
  17383. return smc;
  17384. };
  17385. BasicSourceMapConsumer.prototype._version = 3;
  17386. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  17387. get: function () {
  17388. return this._sources.toArray().map(function (s) {
  17389. return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
  17390. }, this);
  17391. }
  17392. });
  17393. BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  17394. var generatedLine = 1;
  17395. var previousGeneratedColumn = 0;
  17396. var previousOriginalLine = 0;
  17397. var previousOriginalColumn = 0;
  17398. var previousSource = 0;
  17399. var previousName = 0;
  17400. var str = aStr;
  17401. var temp = {};
  17402. var mapping;
  17403. while (str.length > 0) {
  17404. if (str.charAt(0) === ';') {
  17405. generatedLine++;
  17406. str = str.slice(1);
  17407. previousGeneratedColumn = 0;
  17408. } else if (str.charAt(0) === ',') {
  17409. str = str.slice(1);
  17410. } else {
  17411. mapping = {};
  17412. mapping.generatedLine = generatedLine;
  17413. base64VLQ.decode(str, temp);
  17414. mapping.generatedColumn = previousGeneratedColumn + temp.value;
  17415. previousGeneratedColumn = mapping.generatedColumn;
  17416. str = temp.rest;
  17417. if (str.length > 0 && !this._nextCharIsMappingSeparator(str)) {
  17418. base64VLQ.decode(str, temp);
  17419. mapping.source = this._sources.at(previousSource + temp.value);
  17420. previousSource += temp.value;
  17421. str = temp.rest;
  17422. if (str.length === 0 || this._nextCharIsMappingSeparator(str)) {
  17423. throw new Error('Found a source, but no line and column');
  17424. }
  17425. base64VLQ.decode(str, temp);
  17426. mapping.originalLine = previousOriginalLine + temp.value;
  17427. previousOriginalLine = mapping.originalLine;
  17428. mapping.originalLine += 1;
  17429. str = temp.rest;
  17430. if (str.length === 0 || this._nextCharIsMappingSeparator(str)) {
  17431. throw new Error('Found a source and line, but no column');
  17432. }
  17433. base64VLQ.decode(str, temp);
  17434. mapping.originalColumn = previousOriginalColumn + temp.value;
  17435. previousOriginalColumn = mapping.originalColumn;
  17436. str = temp.rest;
  17437. if (str.length > 0 && !this._nextCharIsMappingSeparator(str)) {
  17438. base64VLQ.decode(str, temp);
  17439. mapping.name = this._names.at(previousName + temp.value);
  17440. previousName += temp.value;
  17441. str = temp.rest;
  17442. }
  17443. }
  17444. this.__generatedMappings.push(mapping);
  17445. if (typeof mapping.originalLine === 'number') {
  17446. this.__originalMappings.push(mapping);
  17447. }
  17448. }
  17449. }
  17450. this.__generatedMappings.sort(util.compareByGeneratedPositions);
  17451. this.__originalMappings.sort(util.compareByOriginalPositions);
  17452. };
  17453. BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator) {
  17454. if (aNeedle[aLineName] <= 0) {
  17455. throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]);
  17456. }
  17457. if (aNeedle[aColumnName] < 0) {
  17458. throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]);
  17459. }
  17460. return binarySearch.search(aNeedle, aMappings, aComparator);
  17461. };
  17462. BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() {
  17463. for (var index = 0; index < this._generatedMappings.length; ++index) {
  17464. var mapping = this._generatedMappings[index];
  17465. if (index + 1 < this._generatedMappings.length) {
  17466. var nextMapping = this._generatedMappings[index + 1];
  17467. if (mapping.generatedLine === nextMapping.generatedLine) {
  17468. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  17469. continue;
  17470. }
  17471. }
  17472. mapping.lastGeneratedColumn = Infinity;
  17473. }
  17474. };
  17475. BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
  17476. var needle = {
  17477. generatedLine: util.getArg(aArgs, 'line'),
  17478. generatedColumn: util.getArg(aArgs, 'column')
  17479. };
  17480. var index = this._findMapping(needle, this._generatedMappings, 'generatedLine', 'generatedColumn', util.compareByGeneratedPositions);
  17481. if (index >= 0) {
  17482. var mapping = this._generatedMappings[index];
  17483. if (mapping.generatedLine === needle.generatedLine) {
  17484. var source = util.getArg(mapping, 'source', null);
  17485. if (source != null && this.sourceRoot != null) {
  17486. source = util.join(this.sourceRoot, source);
  17487. }
  17488. return {
  17489. source: source,
  17490. line: util.getArg(mapping, 'originalLine', null),
  17491. column: util.getArg(mapping, 'originalColumn', null),
  17492. name: util.getArg(mapping, 'name', null)
  17493. };
  17494. }
  17495. }
  17496. return {
  17497. source: null,
  17498. line: null,
  17499. column: null,
  17500. name: null
  17501. };
  17502. };
  17503. BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  17504. if (!this.sourcesContent) {
  17505. return null;
  17506. }
  17507. if (this.sourceRoot != null) {
  17508. aSource = util.relative(this.sourceRoot, aSource);
  17509. }
  17510. if (this._sources.has(aSource)) {
  17511. return this.sourcesContent[this._sources.indexOf(aSource)];
  17512. }
  17513. var url;
  17514. if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) {
  17515. var fileUriAbsPath = aSource.replace(/^file:\/\//, '');
  17516. if (url.scheme == 'file' && this._sources.has(fileUriAbsPath)) {
  17517. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
  17518. }
  17519. if ((!url.path || url.path == '/') && this._sources.has('/' + aSource)) {
  17520. return this.sourcesContent[this._sources.indexOf('/' + aSource)];
  17521. }
  17522. }
  17523. if (nullOnMissing) {
  17524. return null;
  17525. } else {
  17526. throw new Error('"' + aSource + '" is not in the SourceMap.');
  17527. }
  17528. };
  17529. BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
  17530. var needle = {
  17531. source: util.getArg(aArgs, 'source'),
  17532. originalLine: util.getArg(aArgs, 'line'),
  17533. originalColumn: util.getArg(aArgs, 'column')
  17534. };
  17535. if (this.sourceRoot != null) {
  17536. needle.source = util.relative(this.sourceRoot, needle.source);
  17537. }
  17538. var index = this._findMapping(needle, this._originalMappings, 'originalLine', 'originalColumn', util.compareByOriginalPositions);
  17539. if (index >= 0) {
  17540. var mapping = this._originalMappings[index];
  17541. return {
  17542. line: util.getArg(mapping, 'generatedLine', null),
  17543. column: util.getArg(mapping, 'generatedColumn', null),
  17544. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  17545. };
  17546. }
  17547. return {
  17548. line: null,
  17549. column: null,
  17550. lastColumn: null
  17551. };
  17552. };
  17553. exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
  17554. });
  17555. });
  17556. require.define('/node_modules/source-map/lib/source-map/binary-search.js', function (module, exports, __dirname, __filename) {
  17557. if (typeof define !== 'function') {
  17558. var define = require('/node_modules/amdefine/amdefine.js', module)(module, require);
  17559. }
  17560. define(function (require, exports, module) {
  17561. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
  17562. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  17563. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  17564. if (cmp === 0) {
  17565. return mid;
  17566. } else if (cmp > 0) {
  17567. if (aHigh - mid > 1) {
  17568. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
  17569. }
  17570. return mid;
  17571. } else {
  17572. if (mid - aLow > 1) {
  17573. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
  17574. }
  17575. return aLow < 0 ? -1 : aLow;
  17576. }
  17577. }
  17578. exports.search = function search(aNeedle, aHaystack, aCompare) {
  17579. if (aHaystack.length === 0) {
  17580. return -1;
  17581. }
  17582. return recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare);
  17583. };
  17584. });
  17585. });
  17586. require.define('/node_modules/source-map/lib/source-map/indexed-source-map-consumer.js', function (module, exports, __dirname, __filename) {
  17587. if (typeof define !== 'function') {
  17588. var define = require('/node_modules/amdefine/amdefine.js', module)(module, require);
  17589. }
  17590. define(function (require, exports, module) {
  17591. var util = require('/node_modules/source-map/lib/source-map/util.js', module);
  17592. var binarySearch = require('/node_modules/source-map/lib/source-map/binary-search.js', module);
  17593. var SourceMapConsumer = require('/node_modules/source-map/lib/source-map/source-map-consumer.js', module).SourceMapConsumer;
  17594. var BasicSourceMapConsumer = require('/node_modules/source-map/lib/source-map/basic-source-map-consumer.js', module).BasicSourceMapConsumer;
  17595. function IndexedSourceMapConsumer(aSourceMap) {
  17596. var sourceMap = aSourceMap;
  17597. if (typeof aSourceMap === 'string') {
  17598. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  17599. }
  17600. var version = util.getArg(sourceMap, 'version');
  17601. var sections = util.getArg(sourceMap, 'sections');
  17602. if (version != this._version) {
  17603. throw new Error('Unsupported version: ' + version);
  17604. }
  17605. var lastOffset = {
  17606. line: -1,
  17607. column: 0
  17608. };
  17609. this._sections = sections.map(function (s) {
  17610. if (s.url) {
  17611. throw new Error('Support for url field in sections not implemented.');
  17612. }
  17613. var offset = util.getArg(s, 'offset');
  17614. var offsetLine = util.getArg(offset, 'line');
  17615. var offsetColumn = util.getArg(offset, 'column');
  17616. if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
  17617. throw new Error('Section offsets must be ordered and non-overlapping.');
  17618. }
  17619. lastOffset = offset;
  17620. return {
  17621. generatedOffset: {
  17622. generatedLine: offsetLine + 1,
  17623. generatedColumn: offsetColumn + 1
  17624. },
  17625. consumer: new SourceMapConsumer(util.getArg(s, 'map'))
  17626. };
  17627. });
  17628. }
  17629. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  17630. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  17631. IndexedSourceMapConsumer.prototype._version = 3;
  17632. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  17633. get: function () {
  17634. var sources = [];
  17635. for (var i = 0; i < this._sections.length; i++) {
  17636. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  17637. sources.push(this._sections[i].consumer.sources[j]);
  17638. }
  17639. }
  17640. ;
  17641. return sources;
  17642. }
  17643. });
  17644. IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  17645. var needle = {
  17646. generatedLine: util.getArg(aArgs, 'line'),
  17647. generatedColumn: util.getArg(aArgs, 'column')
  17648. };
  17649. var sectionIndex = binarySearch.search(needle, this._sections, function (needle, section) {
  17650. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  17651. if (cmp) {
  17652. return cmp;
  17653. }
  17654. return needle.generatedColumn - section.generatedOffset.generatedColumn;
  17655. });
  17656. var section = this._sections[sectionIndex];
  17657. if (!section) {
  17658. return {
  17659. source: null,
  17660. line: null,
  17661. column: null,
  17662. name: null
  17663. };
  17664. }
  17665. return section.consumer.originalPositionFor({
  17666. line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
  17667. column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0)
  17668. });
  17669. };
  17670. IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  17671. for (var i = 0; i < this._sections.length; i++) {
  17672. var section = this._sections[i];
  17673. var content = section.consumer.sourceContentFor(aSource, true);
  17674. if (content) {
  17675. return content;
  17676. }
  17677. }
  17678. if (nullOnMissing) {
  17679. return null;
  17680. } else {
  17681. throw new Error('"' + aSource + '" is not in the SourceMap.');
  17682. }
  17683. };
  17684. IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  17685. for (var i = 0; i < this._sections.length; i++) {
  17686. var section = this._sections[i];
  17687. if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {
  17688. continue;
  17689. }
  17690. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  17691. if (generatedPosition) {
  17692. var ret = {
  17693. line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
  17694. column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
  17695. };
  17696. return ret;
  17697. }
  17698. }
  17699. return {
  17700. line: null,
  17701. column: null
  17702. };
  17703. };
  17704. IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  17705. this.__generatedMappings = [];
  17706. this.__originalMappings = [];
  17707. for (var i = 0; i < this._sections.length; i++) {
  17708. var section = this._sections[i];
  17709. var sectionMappings = section.consumer._generatedMappings;
  17710. for (var j = 0; j < sectionMappings.length; j++) {
  17711. var mapping = sectionMappings[i];
  17712. var source = mapping.source;
  17713. var sourceRoot = section.consumer.sourceRoot;
  17714. if (source != null && sourceRoot != null) {
  17715. source = util.join(sourceRoot, source);
  17716. }
  17717. var adjustedMapping = {
  17718. source: source,
  17719. generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
  17720. generatedColumn: mapping.column + (section.generatedOffset.generatedLine === mapping.generatedLine) ? section.generatedOffset.generatedColumn - 1 : 0,
  17721. originalLine: mapping.originalLine,
  17722. originalColumn: mapping.originalColumn,
  17723. name: mapping.name
  17724. };
  17725. this.__generatedMappings.push(adjustedMapping);
  17726. if (typeof adjustedMapping.originalLine === 'number') {
  17727. this.__originalMappings.push(adjustedMapping);
  17728. }
  17729. }
  17730. ;
  17731. }
  17732. ;
  17733. this.__generatedMappings.sort(util.compareByGeneratedPositions);
  17734. this.__originalMappings.sort(util.compareByOriginalPositions);
  17735. };
  17736. exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  17737. });
  17738. });
  17739. require.define('/node_modules/esutils/lib/utils.js', function (module, exports, __dirname, __filename) {
  17740. (function () {
  17741. 'use strict';
  17742. exports.ast = require('/node_modules/esutils/lib/ast.js', module);
  17743. exports.code = require('/node_modules/esutils/lib/code.js', module);
  17744. exports.keyword = require('/node_modules/esutils/lib/keyword.js', module);
  17745. }());
  17746. });
  17747. require.define('/node_modules/esutils/lib/keyword.js', function (module, exports, __dirname, __filename) {
  17748. (function () {
  17749. 'use strict';
  17750. var code = require('/node_modules/esutils/lib/code.js', module);
  17751. function isStrictModeReservedWordES6(id) {
  17752. switch (id) {
  17753. case 'implements':
  17754. case 'interface':
  17755. case 'package':
  17756. case 'private':
  17757. case 'protected':
  17758. case 'public':
  17759. case 'static':
  17760. case 'let':
  17761. return true;
  17762. default:
  17763. return false;
  17764. }
  17765. }
  17766. function isKeywordES5(id, strict) {
  17767. if (!strict && id === 'yield') {
  17768. return false;
  17769. }
  17770. return isKeywordES6(id, strict);
  17771. }
  17772. function isKeywordES6(id, strict) {
  17773. if (strict && isStrictModeReservedWordES6(id)) {
  17774. return true;
  17775. }
  17776. switch (id.length) {
  17777. case 2:
  17778. return id === 'if' || id === 'in' || id === 'do';
  17779. case 3:
  17780. return id === 'var' || id === 'for' || id === 'new' || id === 'try';
  17781. case 4:
  17782. return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
  17783. case 5:
  17784. return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
  17785. case 6:
  17786. return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
  17787. case 7:
  17788. return id === 'default' || id === 'finally' || id === 'extends';
  17789. case 8:
  17790. return id === 'function' || id === 'continue' || id === 'debugger';
  17791. case 10:
  17792. return id === 'instanceof';
  17793. default:
  17794. return false;
  17795. }
  17796. }
  17797. function isReservedWordES5(id, strict) {
  17798. return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
  17799. }
  17800. function isReservedWordES6(id, strict) {
  17801. return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
  17802. }
  17803. function isRestrictedWord(id) {
  17804. return id === 'eval' || id === 'arguments';
  17805. }
  17806. function isIdentifierNameES5(id) {
  17807. var i, iz, ch;
  17808. if (id.length === 0) {
  17809. return false;
  17810. }
  17811. ch = id.charCodeAt(0);
  17812. if (!code.isIdentifierStartES5(ch)) {
  17813. return false;
  17814. }
  17815. for (i = 1, iz = id.length; i < iz; ++i) {
  17816. ch = id.charCodeAt(i);
  17817. if (!code.isIdentifierPartES5(ch)) {
  17818. return false;
  17819. }
  17820. }
  17821. return true;
  17822. }
  17823. function decodeUtf16(lead, trail) {
  17824. return (lead - 55296) * 1024 + (trail - 56320) + 65536;
  17825. }
  17826. function isIdentifierNameES6(id) {
  17827. var i, iz, ch, lowCh, check;
  17828. if (id.length === 0) {
  17829. return false;
  17830. }
  17831. check = code.isIdentifierStartES6;
  17832. for (i = 0, iz = id.length; i < iz; ++i) {
  17833. ch = id.charCodeAt(i);
  17834. if (55296 <= ch && ch <= 56319) {
  17835. ++i;
  17836. if (i >= iz) {
  17837. return false;
  17838. }
  17839. lowCh = id.charCodeAt(i);
  17840. if (!(56320 <= lowCh && lowCh <= 57343)) {
  17841. return false;
  17842. }
  17843. ch = decodeUtf16(ch, lowCh);
  17844. }
  17845. if (!check(ch)) {
  17846. return false;
  17847. }
  17848. check = code.isIdentifierPartES6;
  17849. }
  17850. return true;
  17851. }
  17852. function isIdentifierES5(id, strict) {
  17853. return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
  17854. }
  17855. function isIdentifierES6(id, strict) {
  17856. return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
  17857. }
  17858. module.exports = {
  17859. isKeywordES5: isKeywordES5,
  17860. isKeywordES6: isKeywordES6,
  17861. isReservedWordES5: isReservedWordES5,
  17862. isReservedWordES6: isReservedWordES6,
  17863. isRestrictedWord: isRestrictedWord,
  17864. isIdentifierNameES5: isIdentifierNameES5,
  17865. isIdentifierNameES6: isIdentifierNameES6,
  17866. isIdentifierES5: isIdentifierES5,
  17867. isIdentifierES6: isIdentifierES6
  17868. };
  17869. }());
  17870. });
  17871. require.define('/node_modules/esutils/lib/code.js', function (module, exports, __dirname, __filename) {
  17872. (function () {
  17873. 'use strict';
  17874. var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch;
  17875. ES5Regex = {
  17876. NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,
  17877. NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/
  17878. };
  17879. ES6Regex = {
  17880. NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,
  17881. NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
  17882. };
  17883. function isDecimalDigit(ch) {
  17884. return 48 <= ch && ch <= 57;
  17885. }
  17886. function isHexDigit(ch) {
  17887. return 48 <= ch && ch <= 57 || 97 <= ch && ch <= 102 || 65 <= ch && ch <= 70;
  17888. }
  17889. function isOctalDigit(ch) {
  17890. return ch >= 48 && ch <= 55;
  17891. }
  17892. NON_ASCII_WHITESPACES = [
  17893. 5760,
  17894. 6158,
  17895. 8192,
  17896. 8193,
  17897. 8194,
  17898. 8195,
  17899. 8196,
  17900. 8197,
  17901. 8198,
  17902. 8199,
  17903. 8200,
  17904. 8201,
  17905. 8202,
  17906. 8239,
  17907. 8287,
  17908. 12288,
  17909. 65279
  17910. ];
  17911. function isWhiteSpace(ch) {
  17912. return ch === 32 || ch === 9 || ch === 11 || ch === 12 || ch === 160 || ch >= 5760 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
  17913. }
  17914. function isLineTerminator(ch) {
  17915. return ch === 10 || ch === 13 || ch === 8232 || ch === 8233;
  17916. }
  17917. function fromCodePoint(cp) {
  17918. if (cp <= 65535) {
  17919. return String.fromCharCode(cp);
  17920. }
  17921. var cu1 = String.fromCharCode(Math.floor((cp - 65536) / 1024) + 55296);
  17922. var cu2 = String.fromCharCode((cp - 65536) % 1024 + 56320);
  17923. return cu1 + cu2;
  17924. }
  17925. IDENTIFIER_START = new Array(128);
  17926. for (ch = 0; ch < 128; ++ch) {
  17927. IDENTIFIER_START[ch] = ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90 || ch === 36 || ch === 95;
  17928. }
  17929. IDENTIFIER_PART = new Array(128);
  17930. for (ch = 0; ch < 128; ++ch) {
  17931. IDENTIFIER_PART[ch] = ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90 || ch >= 48 && ch <= 57 || ch === 36 || ch === 95;
  17932. }
  17933. function isIdentifierStartES5(ch) {
  17934. return ch < 128 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
  17935. }
  17936. function isIdentifierPartES5(ch) {
  17937. return ch < 128 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
  17938. }
  17939. function isIdentifierStartES6(ch) {
  17940. return ch < 128 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
  17941. }
  17942. function isIdentifierPartES6(ch) {
  17943. return ch < 128 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
  17944. }
  17945. module.exports = {
  17946. isDecimalDigit: isDecimalDigit,
  17947. isHexDigit: isHexDigit,
  17948. isOctalDigit: isOctalDigit,
  17949. isWhiteSpace: isWhiteSpace,
  17950. isLineTerminator: isLineTerminator,
  17951. isIdentifierStartES5: isIdentifierStartES5,
  17952. isIdentifierPartES5: isIdentifierPartES5,
  17953. isIdentifierStartES6: isIdentifierStartES6,
  17954. isIdentifierPartES6: isIdentifierPartES6
  17955. };
  17956. }());
  17957. });
  17958. require.define('/node_modules/esutils/lib/ast.js', function (module, exports, __dirname, __filename) {
  17959. (function () {
  17960. 'use strict';
  17961. function isExpression(node) {
  17962. if (node == null) {
  17963. return false;
  17964. }
  17965. switch (node.type) {
  17966. case 'ArrayExpression':
  17967. case 'AssignmentExpression':
  17968. case 'BinaryExpression':
  17969. case 'CallExpression':
  17970. case 'ConditionalExpression':
  17971. case 'FunctionExpression':
  17972. case 'Identifier':
  17973. case 'Literal':
  17974. case 'LogicalExpression':
  17975. case 'MemberExpression':
  17976. case 'NewExpression':
  17977. case 'ObjectExpression':
  17978. case 'SequenceExpression':
  17979. case 'ThisExpression':
  17980. case 'UnaryExpression':
  17981. case 'UpdateExpression':
  17982. return true;
  17983. }
  17984. return false;
  17985. }
  17986. function isIterationStatement(node) {
  17987. if (node == null) {
  17988. return false;
  17989. }
  17990. switch (node.type) {
  17991. case 'DoWhileStatement':
  17992. case 'ForInStatement':
  17993. case 'ForStatement':
  17994. case 'WhileStatement':
  17995. return true;
  17996. }
  17997. return false;
  17998. }
  17999. function isStatement(node) {
  18000. if (node == null) {
  18001. return false;
  18002. }
  18003. switch (node.type) {
  18004. case 'BlockStatement':
  18005. case 'BreakStatement':
  18006. case 'ContinueStatement':
  18007. case 'DebuggerStatement':
  18008. case 'DoWhileStatement':
  18009. case 'EmptyStatement':
  18010. case 'ExpressionStatement':
  18011. case 'ForInStatement':
  18012. case 'ForStatement':
  18013. case 'IfStatement':
  18014. case 'LabeledStatement':
  18015. case 'ReturnStatement':
  18016. case 'SwitchStatement':
  18017. case 'ThrowStatement':
  18018. case 'TryStatement':
  18019. case 'VariableDeclaration':
  18020. case 'WhileStatement':
  18021. case 'WithStatement':
  18022. return true;
  18023. }
  18024. return false;
  18025. }
  18026. function isSourceElement(node) {
  18027. return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
  18028. }
  18029. function trailingStatement(node) {
  18030. switch (node.type) {
  18031. case 'IfStatement':
  18032. if (node.alternate != null) {
  18033. return node.alternate;
  18034. }
  18035. return node.consequent;
  18036. case 'LabeledStatement':
  18037. case 'ForStatement':
  18038. case 'ForInStatement':
  18039. case 'WhileStatement':
  18040. case 'WithStatement':
  18041. return node.body;
  18042. }
  18043. return null;
  18044. }
  18045. function isProblematicIfStatement(node) {
  18046. var current;
  18047. if (node.type !== 'IfStatement') {
  18048. return false;
  18049. }
  18050. if (node.alternate == null) {
  18051. return false;
  18052. }
  18053. current = node.consequent;
  18054. do {
  18055. if (current.type === 'IfStatement') {
  18056. if (current.alternate == null) {
  18057. return true;
  18058. }
  18059. }
  18060. current = trailingStatement(current);
  18061. } while (current);
  18062. return false;
  18063. }
  18064. module.exports = {
  18065. isExpression: isExpression,
  18066. isStatement: isStatement,
  18067. isIterationStatement: isIterationStatement,
  18068. isSourceElement: isSourceElement,
  18069. isProblematicIfStatement: isProblematicIfStatement,
  18070. trailingStatement: trailingStatement
  18071. };
  18072. }());
  18073. });
  18074. require.define('/node_modules/estraverse/estraverse.js', function (module, exports, __dirname, __filename) {
  18075. (function (root, factory) {
  18076. 'use strict';
  18077. if (typeof define === 'function' && define.amd) {
  18078. define(['exports'], factory);
  18079. } else if (typeof exports !== 'undefined') {
  18080. factory(exports);
  18081. } else {
  18082. factory(root.estraverse = {});
  18083. }
  18084. }(this, function clone(exports) {
  18085. 'use strict';
  18086. var Syntax, isArray, VisitorOption, VisitorKeys, objectCreate, objectKeys, BREAK, SKIP, REMOVE;
  18087. function ignoreJSHintError() {
  18088. }
  18089. isArray = Array.isArray;
  18090. if (!isArray) {
  18091. isArray = function isArray(array) {
  18092. return Object.prototype.toString.call(array) === '[object Array]';
  18093. };
  18094. }
  18095. function deepCopy(obj) {
  18096. var ret = {}, key, val;
  18097. for (key in obj) {
  18098. if (obj.hasOwnProperty(key)) {
  18099. val = obj[key];
  18100. if (typeof val === 'object' && val !== null) {
  18101. ret[key] = deepCopy(val);
  18102. } else {
  18103. ret[key] = val;
  18104. }
  18105. }
  18106. }
  18107. return ret;
  18108. }
  18109. function shallowCopy(obj) {
  18110. var ret = {}, key;
  18111. for (key in obj) {
  18112. if (obj.hasOwnProperty(key)) {
  18113. ret[key] = obj[key];
  18114. }
  18115. }
  18116. return ret;
  18117. }
  18118. ignoreJSHintError(shallowCopy);
  18119. function upperBound(array, func) {
  18120. var diff, len, i, current;
  18121. len = array.length;
  18122. i = 0;
  18123. while (len) {
  18124. diff = len >>> 1;
  18125. current = i + diff;
  18126. if (func(array[current])) {
  18127. len = diff;
  18128. } else {
  18129. i = current + 1;
  18130. len -= diff + 1;
  18131. }
  18132. }
  18133. return i;
  18134. }
  18135. function lowerBound(array, func) {
  18136. var diff, len, i, current;
  18137. len = array.length;
  18138. i = 0;
  18139. while (len) {
  18140. diff = len >>> 1;
  18141. current = i + diff;
  18142. if (func(array[current])) {
  18143. i = current + 1;
  18144. len -= diff + 1;
  18145. } else {
  18146. len = diff;
  18147. }
  18148. }
  18149. return i;
  18150. }
  18151. ignoreJSHintError(lowerBound);
  18152. objectCreate = Object.create || function () {
  18153. function F() {
  18154. }
  18155. return function (o) {
  18156. F.prototype = o;
  18157. return new F;
  18158. };
  18159. }();
  18160. objectKeys = Object.keys || function (o) {
  18161. var keys = [], key;
  18162. for (key in o) {
  18163. keys.push(key);
  18164. }
  18165. return keys;
  18166. };
  18167. function extend(to, from) {
  18168. var keys = objectKeys(from), key, i, len;
  18169. for (i = 0, len = keys.length; i < len; i += 1) {
  18170. key = keys[i];
  18171. to[key] = from[key];
  18172. }
  18173. return to;
  18174. }
  18175. Syntax = {
  18176. AssignmentExpression: 'AssignmentExpression',
  18177. ArrayExpression: 'ArrayExpression',
  18178. ArrayPattern: 'ArrayPattern',
  18179. ArrowFunctionExpression: 'ArrowFunctionExpression',
  18180. AwaitExpression: 'AwaitExpression',
  18181. BlockStatement: 'BlockStatement',
  18182. BinaryExpression: 'BinaryExpression',
  18183. BreakStatement: 'BreakStatement',
  18184. CallExpression: 'CallExpression',
  18185. CatchClause: 'CatchClause',
  18186. ClassBody: 'ClassBody',
  18187. ClassDeclaration: 'ClassDeclaration',
  18188. ClassExpression: 'ClassExpression',
  18189. ComprehensionBlock: 'ComprehensionBlock',
  18190. ComprehensionExpression: 'ComprehensionExpression',
  18191. ConditionalExpression: 'ConditionalExpression',
  18192. ContinueStatement: 'ContinueStatement',
  18193. DebuggerStatement: 'DebuggerStatement',
  18194. DirectiveStatement: 'DirectiveStatement',
  18195. DoWhileStatement: 'DoWhileStatement',
  18196. EmptyStatement: 'EmptyStatement',
  18197. ExportBatchSpecifier: 'ExportBatchSpecifier',
  18198. ExportDeclaration: 'ExportDeclaration',
  18199. ExportSpecifier: 'ExportSpecifier',
  18200. ExpressionStatement: 'ExpressionStatement',
  18201. ForStatement: 'ForStatement',
  18202. ForInStatement: 'ForInStatement',
  18203. ForOfStatement: 'ForOfStatement',
  18204. FunctionDeclaration: 'FunctionDeclaration',
  18205. FunctionExpression: 'FunctionExpression',
  18206. GeneratorExpression: 'GeneratorExpression',
  18207. Identifier: 'Identifier',
  18208. IfStatement: 'IfStatement',
  18209. ImportDeclaration: 'ImportDeclaration',
  18210. ImportDefaultSpecifier: 'ImportDefaultSpecifier',
  18211. ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
  18212. ImportSpecifier: 'ImportSpecifier',
  18213. Literal: 'Literal',
  18214. LabeledStatement: 'LabeledStatement',
  18215. LogicalExpression: 'LogicalExpression',
  18216. MemberExpression: 'MemberExpression',
  18217. MethodDefinition: 'MethodDefinition',
  18218. ModuleSpecifier: 'ModuleSpecifier',
  18219. NewExpression: 'NewExpression',
  18220. ObjectExpression: 'ObjectExpression',
  18221. ObjectPattern: 'ObjectPattern',
  18222. Program: 'Program',
  18223. Property: 'Property',
  18224. ReturnStatement: 'ReturnStatement',
  18225. SequenceExpression: 'SequenceExpression',
  18226. SpreadElement: 'SpreadElement',
  18227. SwitchStatement: 'SwitchStatement',
  18228. SwitchCase: 'SwitchCase',
  18229. TaggedTemplateExpression: 'TaggedTemplateExpression',
  18230. TemplateElement: 'TemplateElement',
  18231. TemplateLiteral: 'TemplateLiteral',
  18232. ThisExpression: 'ThisExpression',
  18233. ThrowStatement: 'ThrowStatement',
  18234. TryStatement: 'TryStatement',
  18235. UnaryExpression: 'UnaryExpression',
  18236. UpdateExpression: 'UpdateExpression',
  18237. VariableDeclaration: 'VariableDeclaration',
  18238. VariableDeclarator: 'VariableDeclarator',
  18239. WhileStatement: 'WhileStatement',
  18240. WithStatement: 'WithStatement',
  18241. YieldExpression: 'YieldExpression'
  18242. };
  18243. VisitorKeys = {
  18244. AssignmentExpression: [
  18245. 'left',
  18246. 'right'
  18247. ],
  18248. ArrayExpression: ['elements'],
  18249. ArrayPattern: ['elements'],
  18250. ArrowFunctionExpression: [
  18251. 'params',
  18252. 'defaults',
  18253. 'rest',
  18254. 'body'
  18255. ],
  18256. AwaitExpression: ['argument'],
  18257. BlockStatement: ['body'],
  18258. BinaryExpression: [
  18259. 'left',
  18260. 'right'
  18261. ],
  18262. BreakStatement: ['label'],
  18263. CallExpression: [
  18264. 'callee',
  18265. 'arguments'
  18266. ],
  18267. CatchClause: [
  18268. 'param',
  18269. 'body'
  18270. ],
  18271. ClassBody: ['body'],
  18272. ClassDeclaration: [
  18273. 'id',
  18274. 'body',
  18275. 'superClass'
  18276. ],
  18277. ClassExpression: [
  18278. 'id',
  18279. 'body',
  18280. 'superClass'
  18281. ],
  18282. ComprehensionBlock: [
  18283. 'left',
  18284. 'right'
  18285. ],
  18286. ComprehensionExpression: [
  18287. 'blocks',
  18288. 'filter',
  18289. 'body'
  18290. ],
  18291. ConditionalExpression: [
  18292. 'test',
  18293. 'consequent',
  18294. 'alternate'
  18295. ],
  18296. ContinueStatement: ['label'],
  18297. DebuggerStatement: [],
  18298. DirectiveStatement: [],
  18299. DoWhileStatement: [
  18300. 'body',
  18301. 'test'
  18302. ],
  18303. EmptyStatement: [],
  18304. ExportBatchSpecifier: [],
  18305. ExportDeclaration: [
  18306. 'declaration',
  18307. 'specifiers',
  18308. 'source'
  18309. ],
  18310. ExportSpecifier: [
  18311. 'id',
  18312. 'name'
  18313. ],
  18314. ExpressionStatement: ['expression'],
  18315. ForStatement: [
  18316. 'init',
  18317. 'test',
  18318. 'update',
  18319. 'body'
  18320. ],
  18321. ForInStatement: [
  18322. 'left',
  18323. 'right',
  18324. 'body'
  18325. ],
  18326. ForOfStatement: [
  18327. 'left',
  18328. 'right',
  18329. 'body'
  18330. ],
  18331. FunctionDeclaration: [
  18332. 'id',
  18333. 'params',
  18334. 'defaults',
  18335. 'rest',
  18336. 'body'
  18337. ],
  18338. FunctionExpression: [
  18339. 'id',
  18340. 'params',
  18341. 'defaults',
  18342. 'rest',
  18343. 'body'
  18344. ],
  18345. GeneratorExpression: [
  18346. 'blocks',
  18347. 'filter',
  18348. 'body'
  18349. ],
  18350. Identifier: [],
  18351. IfStatement: [
  18352. 'test',
  18353. 'consequent',
  18354. 'alternate'
  18355. ],
  18356. ImportDeclaration: [
  18357. 'specifiers',
  18358. 'source'
  18359. ],
  18360. ImportDefaultSpecifier: ['id'],
  18361. ImportNamespaceSpecifier: ['id'],
  18362. ImportSpecifier: [
  18363. 'id',
  18364. 'name'
  18365. ],
  18366. Literal: [],
  18367. LabeledStatement: [
  18368. 'label',
  18369. 'body'
  18370. ],
  18371. LogicalExpression: [
  18372. 'left',
  18373. 'right'
  18374. ],
  18375. MemberExpression: [
  18376. 'object',
  18377. 'property'
  18378. ],
  18379. MethodDefinition: [
  18380. 'key',
  18381. 'value'
  18382. ],
  18383. ModuleSpecifier: [],
  18384. NewExpression: [
  18385. 'callee',
  18386. 'arguments'
  18387. ],
  18388. ObjectExpression: ['properties'],
  18389. ObjectPattern: ['properties'],
  18390. Program: ['body'],
  18391. Property: [
  18392. 'key',
  18393. 'value'
  18394. ],
  18395. ReturnStatement: ['argument'],
  18396. SequenceExpression: ['expressions'],
  18397. SpreadElement: ['argument'],
  18398. SwitchStatement: [
  18399. 'discriminant',
  18400. 'cases'
  18401. ],
  18402. SwitchCase: [
  18403. 'test',
  18404. 'consequent'
  18405. ],
  18406. TaggedTemplateExpression: [
  18407. 'tag',
  18408. 'quasi'
  18409. ],
  18410. TemplateElement: [],
  18411. TemplateLiteral: [
  18412. 'quasis',
  18413. 'expressions'
  18414. ],
  18415. ThisExpression: [],
  18416. ThrowStatement: ['argument'],
  18417. TryStatement: [
  18418. 'block',
  18419. 'handlers',
  18420. 'handler',
  18421. 'guardedHandlers',
  18422. 'finalizer'
  18423. ],
  18424. UnaryExpression: ['argument'],
  18425. UpdateExpression: ['argument'],
  18426. VariableDeclaration: ['declarations'],
  18427. VariableDeclarator: [
  18428. 'id',
  18429. 'init'
  18430. ],
  18431. WhileStatement: [
  18432. 'test',
  18433. 'body'
  18434. ],
  18435. WithStatement: [
  18436. 'object',
  18437. 'body'
  18438. ],
  18439. YieldExpression: ['argument']
  18440. };
  18441. BREAK = {};
  18442. SKIP = {};
  18443. REMOVE = {};
  18444. VisitorOption = {
  18445. Break: BREAK,
  18446. Skip: SKIP,
  18447. Remove: REMOVE
  18448. };
  18449. function Reference(parent, key) {
  18450. this.parent = parent;
  18451. this.key = key;
  18452. }
  18453. Reference.prototype.replace = function replace(node) {
  18454. this.parent[this.key] = node;
  18455. };
  18456. Reference.prototype.remove = function remove() {
  18457. if (isArray(this.parent)) {
  18458. this.parent.splice(this.key, 1);
  18459. return true;
  18460. } else {
  18461. this.replace(null);
  18462. return false;
  18463. }
  18464. };
  18465. function Element(node, path, wrap, ref) {
  18466. this.node = node;
  18467. this.path = path;
  18468. this.wrap = wrap;
  18469. this.ref = ref;
  18470. }
  18471. function Controller() {
  18472. }
  18473. Controller.prototype.path = function path() {
  18474. var i, iz, j, jz, result, element;
  18475. function addToPath(result, path) {
  18476. if (isArray(path)) {
  18477. for (j = 0, jz = path.length; j < jz; ++j) {
  18478. result.push(path[j]);
  18479. }
  18480. } else {
  18481. result.push(path);
  18482. }
  18483. }
  18484. if (!this.__current.path) {
  18485. return null;
  18486. }
  18487. result = [];
  18488. for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
  18489. element = this.__leavelist[i];
  18490. addToPath(result, element.path);
  18491. }
  18492. addToPath(result, this.__current.path);
  18493. return result;
  18494. };
  18495. Controller.prototype.type = function () {
  18496. var node = this.current();
  18497. return node.type || this.__current.wrap;
  18498. };
  18499. Controller.prototype.parents = function parents() {
  18500. var i, iz, result;
  18501. result = [];
  18502. for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
  18503. result.push(this.__leavelist[i].node);
  18504. }
  18505. return result;
  18506. };
  18507. Controller.prototype.current = function current() {
  18508. return this.__current.node;
  18509. };
  18510. Controller.prototype.__execute = function __execute(callback, element) {
  18511. var previous, result;
  18512. result = undefined;
  18513. previous = this.__current;
  18514. this.__current = element;
  18515. this.__state = null;
  18516. if (callback) {
  18517. result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
  18518. }
  18519. this.__current = previous;
  18520. return result;
  18521. };
  18522. Controller.prototype.notify = function notify(flag) {
  18523. this.__state = flag;
  18524. };
  18525. Controller.prototype.skip = function () {
  18526. this.notify(SKIP);
  18527. };
  18528. Controller.prototype['break'] = function () {
  18529. this.notify(BREAK);
  18530. };
  18531. Controller.prototype.remove = function () {
  18532. this.notify(REMOVE);
  18533. };
  18534. Controller.prototype.__initialize = function (root, visitor) {
  18535. this.visitor = visitor;
  18536. this.root = root;
  18537. this.__worklist = [];
  18538. this.__leavelist = [];
  18539. this.__current = null;
  18540. this.__state = null;
  18541. this.__fallback = visitor.fallback === 'iteration';
  18542. this.__keys = VisitorKeys;
  18543. if (visitor.keys) {
  18544. this.__keys = extend(objectCreate(this.__keys), visitor.keys);
  18545. }
  18546. };
  18547. function isNode(node) {
  18548. if (node == null) {
  18549. return false;
  18550. }
  18551. return typeof node === 'object' && typeof node.type === 'string';
  18552. }
  18553. function isProperty(nodeType, key) {
  18554. return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
  18555. }
  18556. Controller.prototype.traverse = function traverse(root, visitor) {
  18557. var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel;
  18558. this.__initialize(root, visitor);
  18559. sentinel = {};
  18560. worklist = this.__worklist;
  18561. leavelist = this.__leavelist;
  18562. worklist.push(new Element(root, null, null, null));
  18563. leavelist.push(new Element(null, null, null, null));
  18564. while (worklist.length) {
  18565. element = worklist.pop();
  18566. if (element === sentinel) {
  18567. element = leavelist.pop();
  18568. ret = this.__execute(visitor.leave, element);
  18569. if (this.__state === BREAK || ret === BREAK) {
  18570. return;
  18571. }
  18572. continue;
  18573. }
  18574. if (element.node) {
  18575. ret = this.__execute(visitor.enter, element);
  18576. if (this.__state === BREAK || ret === BREAK) {
  18577. return;
  18578. }
  18579. worklist.push(sentinel);
  18580. leavelist.push(element);
  18581. if (this.__state === SKIP || ret === SKIP) {
  18582. continue;
  18583. }
  18584. node = element.node;
  18585. nodeType = element.wrap || node.type;
  18586. candidates = this.__keys[nodeType];
  18587. if (!candidates) {
  18588. if (this.__fallback) {
  18589. candidates = objectKeys(node);
  18590. } else {
  18591. throw new Error('Unknown node type ' + nodeType + '.');
  18592. }
  18593. }
  18594. current = candidates.length;
  18595. while ((current -= 1) >= 0) {
  18596. key = candidates[current];
  18597. candidate = node[key];
  18598. if (!candidate) {
  18599. continue;
  18600. }
  18601. if (isArray(candidate)) {
  18602. current2 = candidate.length;
  18603. while ((current2 -= 1) >= 0) {
  18604. if (!candidate[current2]) {
  18605. continue;
  18606. }
  18607. if (isProperty(nodeType, candidates[current])) {
  18608. element = new Element(candidate[current2], [
  18609. key,
  18610. current2
  18611. ], 'Property', null);
  18612. } else if (isNode(candidate[current2])) {
  18613. element = new Element(candidate[current2], [
  18614. key,
  18615. current2
  18616. ], null, null);
  18617. } else {
  18618. continue;
  18619. }
  18620. worklist.push(element);
  18621. }
  18622. } else if (isNode(candidate)) {
  18623. worklist.push(new Element(candidate, key, null, null));
  18624. }
  18625. }
  18626. }
  18627. }
  18628. };
  18629. Controller.prototype.replace = function replace(root, visitor) {
  18630. function removeElem(element) {
  18631. var i, key, nextElem, parent;
  18632. if (element.ref.remove()) {
  18633. key = element.ref.key;
  18634. parent = element.ref.parent;
  18635. i = worklist.length;
  18636. while (i--) {
  18637. nextElem = worklist[i];
  18638. if (nextElem.ref && nextElem.ref.parent === parent) {
  18639. if (nextElem.ref.key < key) {
  18640. break;
  18641. }
  18642. --nextElem.ref.key;
  18643. }
  18644. }
  18645. }
  18646. }
  18647. var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key;
  18648. this.__initialize(root, visitor);
  18649. sentinel = {};
  18650. worklist = this.__worklist;
  18651. leavelist = this.__leavelist;
  18652. outer = { root: root };
  18653. element = new Element(root, null, null, new Reference(outer, 'root'));
  18654. worklist.push(element);
  18655. leavelist.push(element);
  18656. while (worklist.length) {
  18657. element = worklist.pop();
  18658. if (element === sentinel) {
  18659. element = leavelist.pop();
  18660. target = this.__execute(visitor.leave, element);
  18661. if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
  18662. element.ref.replace(target);
  18663. }
  18664. if (this.__state === REMOVE || target === REMOVE) {
  18665. removeElem(element);
  18666. }
  18667. if (this.__state === BREAK || target === BREAK) {
  18668. return outer.root;
  18669. }
  18670. continue;
  18671. }
  18672. target = this.__execute(visitor.enter, element);
  18673. if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
  18674. element.ref.replace(target);
  18675. element.node = target;
  18676. }
  18677. if (this.__state === REMOVE || target === REMOVE) {
  18678. removeElem(element);
  18679. element.node = null;
  18680. }
  18681. if (this.__state === BREAK || target === BREAK) {
  18682. return outer.root;
  18683. }
  18684. node = element.node;
  18685. if (!node) {
  18686. continue;
  18687. }
  18688. worklist.push(sentinel);
  18689. leavelist.push(element);
  18690. if (this.__state === SKIP || target === SKIP) {
  18691. continue;
  18692. }
  18693. nodeType = element.wrap || node.type;
  18694. candidates = this.__keys[nodeType];
  18695. if (!candidates) {
  18696. if (this.__fallback) {
  18697. candidates = objectKeys(node);
  18698. } else {
  18699. throw new Error('Unknown node type ' + nodeType + '.');
  18700. }
  18701. }
  18702. current = candidates.length;
  18703. while ((current -= 1) >= 0) {
  18704. key = candidates[current];
  18705. candidate = node[key];
  18706. if (!candidate) {
  18707. continue;
  18708. }
  18709. if (isArray(candidate)) {
  18710. current2 = candidate.length;
  18711. while ((current2 -= 1) >= 0) {
  18712. if (!candidate[current2]) {
  18713. continue;
  18714. }
  18715. if (isProperty(nodeType, candidates[current])) {
  18716. element = new Element(candidate[current2], [
  18717. key,
  18718. current2
  18719. ], 'Property', new Reference(candidate, current2));
  18720. } else if (isNode(candidate[current2])) {
  18721. element = new Element(candidate[current2], [
  18722. key,
  18723. current2
  18724. ], null, new Reference(candidate, current2));
  18725. } else {
  18726. continue;
  18727. }
  18728. worklist.push(element);
  18729. }
  18730. } else if (isNode(candidate)) {
  18731. worklist.push(new Element(candidate, key, null, new Reference(node, key)));
  18732. }
  18733. }
  18734. }
  18735. return outer.root;
  18736. };
  18737. function traverse(root, visitor) {
  18738. var controller = new Controller;
  18739. return controller.traverse(root, visitor);
  18740. }
  18741. function replace(root, visitor) {
  18742. var controller = new Controller;
  18743. return controller.replace(root, visitor);
  18744. }
  18745. function extendCommentRange(comment, tokens) {
  18746. var target;
  18747. target = upperBound(tokens, function search(token) {
  18748. return token.range[0] > comment.range[0];
  18749. });
  18750. comment.extendedRange = [
  18751. comment.range[0],
  18752. comment.range[1]
  18753. ];
  18754. if (target !== tokens.length) {
  18755. comment.extendedRange[1] = tokens[target].range[0];
  18756. }
  18757. target -= 1;
  18758. if (target >= 0) {
  18759. comment.extendedRange[0] = tokens[target].range[1];
  18760. }
  18761. return comment;
  18762. }
  18763. function attachComments(tree, providedComments, tokens) {
  18764. var comments = [], comment, len, i, cursor;
  18765. if (!tree.range) {
  18766. throw new Error('attachComments needs range information');
  18767. }
  18768. if (!tokens.length) {
  18769. if (providedComments.length) {
  18770. for (i = 0, len = providedComments.length; i < len; i += 1) {
  18771. comment = deepCopy(providedComments[i]);
  18772. comment.extendedRange = [
  18773. 0,
  18774. tree.range[0]
  18775. ];
  18776. comments.push(comment);
  18777. }
  18778. tree.leadingComments = comments;
  18779. }
  18780. return tree;
  18781. }
  18782. for (i = 0, len = providedComments.length; i < len; i += 1) {
  18783. comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
  18784. }
  18785. cursor = 0;
  18786. traverse(tree, {
  18787. enter: function (node) {
  18788. var comment;
  18789. while (cursor < comments.length) {
  18790. comment = comments[cursor];
  18791. if (comment.extendedRange[1] > node.range[0]) {
  18792. break;
  18793. }
  18794. if (comment.extendedRange[1] === node.range[0]) {
  18795. if (!node.leadingComments) {
  18796. node.leadingComments = [];
  18797. }
  18798. node.leadingComments.push(comment);
  18799. comments.splice(cursor, 1);
  18800. } else {
  18801. cursor += 1;
  18802. }
  18803. }
  18804. if (cursor === comments.length) {
  18805. return VisitorOption.Break;
  18806. }
  18807. if (comments[cursor].extendedRange[0] > node.range[1]) {
  18808. return VisitorOption.Skip;
  18809. }
  18810. }
  18811. });
  18812. cursor = 0;
  18813. traverse(tree, {
  18814. leave: function (node) {
  18815. var comment;
  18816. while (cursor < comments.length) {
  18817. comment = comments[cursor];
  18818. if (node.range[1] < comment.extendedRange[0]) {
  18819. break;
  18820. }
  18821. if (node.range[1] === comment.extendedRange[0]) {
  18822. if (!node.trailingComments) {
  18823. node.trailingComments = [];
  18824. }
  18825. node.trailingComments.push(comment);
  18826. comments.splice(cursor, 1);
  18827. } else {
  18828. cursor += 1;
  18829. }
  18830. }
  18831. if (cursor === comments.length) {
  18832. return VisitorOption.Break;
  18833. }
  18834. if (comments[cursor].extendedRange[0] > node.range[1]) {
  18835. return VisitorOption.Skip;
  18836. }
  18837. }
  18838. });
  18839. return tree;
  18840. }
  18841. exports.version = '1.8.1-dev';
  18842. exports.Syntax = Syntax;
  18843. exports.traverse = traverse;
  18844. exports.replace = replace;
  18845. exports.attachComments = attachComments;
  18846. exports.VisitorKeys = VisitorKeys;
  18847. exports.VisitorOption = VisitorOption;
  18848. exports.Controller = Controller;
  18849. exports.cloneEnvironment = function () {
  18850. return clone({});
  18851. };
  18852. return exports;
  18853. }));
  18854. });
  18855. require('/tools/entry-point.js');
  18856. }.call(GLOBAL, GLOBAL));
  18857. })(typeof window !== "undefined" ? window :
  18858. typeof global!=="undefined" ? global :
  18859. typeof self!=="undefined" ? self : this);
  18860. ;
  18861. })();
  18862. (function() {
  18863. this.lively = this.lively || {};
  18864. (function (exports,lively_lang,escodegen,acorn$1) {
  18865. 'use strict';
  18866. // <<<<<<<<<<<<< BEGIN OF AUTO GENERATED CODE <<<<<<<<<<<<<
  18867. // Generated on 17-11-28 13:01 PST
  18868. function Visitor() {}
  18869. Visitor.prototype.accept = function accept(node, state, path) {
  18870. if (!node) throw new Error("Undefined AST node in Visitor.accept:\n " + path.join(".") + "\n " + node);
  18871. if (!node.type) throw new Error("Strangee AST node without type in Visitor.accept:\n " + path.join(".") + "\n " + JSON.stringify(node));
  18872. switch (node.type) {
  18873. case "Node":
  18874. return this.visitNode(node, state, path);
  18875. case "SourceLocation":
  18876. return this.visitSourceLocation(node, state, path);
  18877. case "Position":
  18878. return this.visitPosition(node, state, path);
  18879. case "Program":
  18880. return this.visitProgram(node, state, path);
  18881. case "Function":
  18882. return this.visitFunction(node, state, path);
  18883. case "Statement":
  18884. return this.visitStatement(node, state, path);
  18885. case "Directive":
  18886. return this.visitDirective(node, state, path);
  18887. case "SwitchCase":
  18888. return this.visitSwitchCase(node, state, path);
  18889. case "CatchClause":
  18890. return this.visitCatchClause(node, state, path);
  18891. case "VariableDeclarator":
  18892. return this.visitVariableDeclarator(node, state, path);
  18893. case "Expression":
  18894. return this.visitExpression(node, state, path);
  18895. case "Property":
  18896. return this.visitProperty(node, state, path);
  18897. case "Pattern":
  18898. return this.visitPattern(node, state, path);
  18899. case "Super":
  18900. return this.visitSuper(node, state, path);
  18901. case "SpreadElement":
  18902. return this.visitSpreadElement(node, state, path);
  18903. case "TemplateElement":
  18904. return this.visitTemplateElement(node, state, path);
  18905. case "Class":
  18906. return this.visitClass(node, state, path);
  18907. case "ClassBody":
  18908. return this.visitClassBody(node, state, path);
  18909. case "MethodDefinition":
  18910. return this.visitMethodDefinition(node, state, path);
  18911. case "ModuleDeclaration":
  18912. return this.visitModuleDeclaration(node, state, path);
  18913. case "ModuleSpecifier":
  18914. return this.visitModuleSpecifier(node, state, path);
  18915. case "JSXEmptyExpression":
  18916. return this.visitJSXEmptyExpression(node, state, path);
  18917. case "JSXExpressionContainer":
  18918. return this.visitJSXExpressionContainer(node, state, path);
  18919. case "JSXSpreadChild":
  18920. return this.visitJSXSpreadChild(node, state, path);
  18921. case "JSXBoundaryElement":
  18922. return this.visitJSXBoundaryElement(node, state, path);
  18923. case "JSXAttribute":
  18924. return this.visitJSXAttribute(node, state, path);
  18925. case "JSXText":
  18926. return this.visitJSXText(node, state, path);
  18927. case "JSXOpeningFragment":
  18928. return this.visitJSXOpeningFragment(node, state, path);
  18929. case "JSXClosingFragment":
  18930. return this.visitJSXClosingFragment(node, state, path);
  18931. case "Identifier":
  18932. return this.visitIdentifier(node, state, path);
  18933. case "Literal":
  18934. return this.visitLiteral(node, state, path);
  18935. case "ExpressionStatement":
  18936. return this.visitExpressionStatement(node, state, path);
  18937. case "BlockStatement":
  18938. return this.visitBlockStatement(node, state, path);
  18939. case "EmptyStatement":
  18940. return this.visitEmptyStatement(node, state, path);
  18941. case "DebuggerStatement":
  18942. return this.visitDebuggerStatement(node, state, path);
  18943. case "WithStatement":
  18944. return this.visitWithStatement(node, state, path);
  18945. case "ReturnStatement":
  18946. return this.visitReturnStatement(node, state, path);
  18947. case "LabeledStatement":
  18948. return this.visitLabeledStatement(node, state, path);
  18949. case "BreakStatement":
  18950. return this.visitBreakStatement(node, state, path);
  18951. case "ContinueStatement":
  18952. return this.visitContinueStatement(node, state, path);
  18953. case "IfStatement":
  18954. return this.visitIfStatement(node, state, path);
  18955. case "SwitchStatement":
  18956. return this.visitSwitchStatement(node, state, path);
  18957. case "ThrowStatement":
  18958. return this.visitThrowStatement(node, state, path);
  18959. case "TryStatement":
  18960. return this.visitTryStatement(node, state, path);
  18961. case "WhileStatement":
  18962. return this.visitWhileStatement(node, state, path);
  18963. case "DoWhileStatement":
  18964. return this.visitDoWhileStatement(node, state, path);
  18965. case "ForStatement":
  18966. return this.visitForStatement(node, state, path);
  18967. case "ForInStatement":
  18968. return this.visitForInStatement(node, state, path);
  18969. case "Declaration":
  18970. return this.visitDeclaration(node, state, path);
  18971. case "ThisExpression":
  18972. return this.visitThisExpression(node, state, path);
  18973. case "ArrayExpression":
  18974. return this.visitArrayExpression(node, state, path);
  18975. case "ObjectExpression":
  18976. return this.visitObjectExpression(node, state, path);
  18977. case "FunctionExpression":
  18978. return this.visitFunctionExpression(node, state, path);
  18979. case "UnaryExpression":
  18980. return this.visitUnaryExpression(node, state, path);
  18981. case "UpdateExpression":
  18982. return this.visitUpdateExpression(node, state, path);
  18983. case "BinaryExpression":
  18984. return this.visitBinaryExpression(node, state, path);
  18985. case "AssignmentExpression":
  18986. return this.visitAssignmentExpression(node, state, path);
  18987. case "LogicalExpression":
  18988. return this.visitLogicalExpression(node, state, path);
  18989. case "MemberExpression":
  18990. return this.visitMemberExpression(node, state, path);
  18991. case "ConditionalExpression":
  18992. return this.visitConditionalExpression(node, state, path);
  18993. case "CallExpression":
  18994. return this.visitCallExpression(node, state, path);
  18995. case "NewExpression":
  18996. return this.visitNewExpression(node, state, path);
  18997. case "SequenceExpression":
  18998. return this.visitSequenceExpression(node, state, path);
  18999. case "ArrowFunctionExpression":
  19000. return this.visitArrowFunctionExpression(node, state, path);
  19001. case "YieldExpression":
  19002. return this.visitYieldExpression(node, state, path);
  19003. case "TemplateLiteral":
  19004. return this.visitTemplateLiteral(node, state, path);
  19005. case "TaggedTemplateExpression":
  19006. return this.visitTaggedTemplateExpression(node, state, path);
  19007. case "AssignmentProperty":
  19008. return this.visitAssignmentProperty(node, state, path);
  19009. case "ObjectPattern":
  19010. return this.visitObjectPattern(node, state, path);
  19011. case "ArrayPattern":
  19012. return this.visitArrayPattern(node, state, path);
  19013. case "RestElement":
  19014. return this.visitRestElement(node, state, path);
  19015. case "AssignmentPattern":
  19016. return this.visitAssignmentPattern(node, state, path);
  19017. case "ClassExpression":
  19018. return this.visitClassExpression(node, state, path);
  19019. case "MetaProperty":
  19020. return this.visitMetaProperty(node, state, path);
  19021. case "ImportDeclaration":
  19022. return this.visitImportDeclaration(node, state, path);
  19023. case "ImportSpecifier":
  19024. return this.visitImportSpecifier(node, state, path);
  19025. case "ImportDefaultSpecifier":
  19026. return this.visitImportDefaultSpecifier(node, state, path);
  19027. case "ImportNamespaceSpecifier":
  19028. return this.visitImportNamespaceSpecifier(node, state, path);
  19029. case "ExportNamedDeclaration":
  19030. return this.visitExportNamedDeclaration(node, state, path);
  19031. case "ExportSpecifier":
  19032. return this.visitExportSpecifier(node, state, path);
  19033. case "ExportDefaultDeclaration":
  19034. return this.visitExportDefaultDeclaration(node, state, path);
  19035. case "ExportAllDeclaration":
  19036. return this.visitExportAllDeclaration(node, state, path);
  19037. case "AwaitExpression":
  19038. return this.visitAwaitExpression(node, state, path);
  19039. case "JSXMemberExpression":
  19040. return this.visitJSXMemberExpression(node, state, path);
  19041. case "JSXNamespacedName":
  19042. return this.visitJSXNamespacedName(node, state, path);
  19043. case "JSXOpeningElement":
  19044. return this.visitJSXOpeningElement(node, state, path);
  19045. case "JSXClosingElement":
  19046. return this.visitJSXClosingElement(node, state, path);
  19047. case "JSXSpreadAttribute":
  19048. return this.visitJSXSpreadAttribute(node, state, path);
  19049. case "JSXElement":
  19050. return this.visitJSXElement(node, state, path);
  19051. case "JSXFragment":
  19052. return this.visitJSXFragment(node, state, path);
  19053. case "RegExpLiteral":
  19054. return this.visitRegExpLiteral(node, state, path);
  19055. case "FunctionBody":
  19056. return this.visitFunctionBody(node, state, path);
  19057. case "FunctionDeclaration":
  19058. return this.visitFunctionDeclaration(node, state, path);
  19059. case "VariableDeclaration":
  19060. return this.visitVariableDeclaration(node, state, path);
  19061. case "ForOfStatement":
  19062. return this.visitForOfStatement(node, state, path);
  19063. case "ClassDeclaration":
  19064. return this.visitClassDeclaration(node, state, path);
  19065. case "JSXIdentifier":
  19066. return this.visitJSXIdentifier(node, state, path);
  19067. }
  19068. throw new Error("No visit function in AST visitor Visitor for:\n " + path.join(".") + "\n " + JSON.stringify(node));
  19069. };
  19070. Visitor.prototype.visitNode = function visitNode(node, state, path) {
  19071. var visitor = this;
  19072. return node;
  19073. };
  19074. Visitor.prototype.visitSourceLocation = function visitSourceLocation(node, state, path) {
  19075. var visitor = this;
  19076. // start is of types Position
  19077. node["start"] = visitor.accept(node["start"], state, path.concat(["start"]));
  19078. // end is of types Position
  19079. node["end"] = visitor.accept(node["end"], state, path.concat(["end"]));
  19080. return node;
  19081. };
  19082. Visitor.prototype.visitPosition = function visitPosition(node, state, path) {
  19083. var visitor = this;
  19084. return node;
  19085. };
  19086. Visitor.prototype.visitProgram = function visitProgram(node, state, path) {
  19087. var visitor = this;
  19088. // body is a list with types Statement, ModuleDeclaration
  19089. var newElements = [];
  19090. for (var i = 0; i < node["body"].length; i++) {
  19091. var ea = node["body"][i];
  19092. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["body", i])) : ea;
  19093. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19094. }
  19095. node["body"] = newElements;
  19096. return node;
  19097. };
  19098. Visitor.prototype.visitFunction = function visitFunction(node, state, path) {
  19099. var visitor = this;
  19100. // id is of types Identifier
  19101. if (node["id"]) {
  19102. node["id"] = visitor.accept(node["id"], state, path.concat(["id"]));
  19103. }
  19104. // params is a list with types Pattern
  19105. var newElements = [];
  19106. for (var i = 0; i < node["params"].length; i++) {
  19107. var ea = node["params"][i];
  19108. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["params", i])) : ea;
  19109. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19110. }
  19111. node["params"] = newElements;
  19112. // body is of types FunctionBody
  19113. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19114. return node;
  19115. };
  19116. Visitor.prototype.visitStatement = function visitStatement(node, state, path) {
  19117. var visitor = this;
  19118. return node;
  19119. };
  19120. Visitor.prototype.visitDirective = function visitDirective(node, state, path) {
  19121. var visitor = this;
  19122. // expression is of types Literal
  19123. node["expression"] = visitor.accept(node["expression"], state, path.concat(["expression"]));
  19124. return node;
  19125. };
  19126. Visitor.prototype.visitSwitchCase = function visitSwitchCase(node, state, path) {
  19127. var visitor = this;
  19128. // test is of types Expression
  19129. if (node["test"]) {
  19130. node["test"] = visitor.accept(node["test"], state, path.concat(["test"]));
  19131. }
  19132. // consequent is a list with types Statement
  19133. var newElements = [];
  19134. for (var i = 0; i < node["consequent"].length; i++) {
  19135. var ea = node["consequent"][i];
  19136. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["consequent", i])) : ea;
  19137. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19138. }
  19139. node["consequent"] = newElements;
  19140. return node;
  19141. };
  19142. Visitor.prototype.visitCatchClause = function visitCatchClause(node, state, path) {
  19143. var visitor = this;
  19144. // param is of types Pattern
  19145. node["param"] = visitor.accept(node["param"], state, path.concat(["param"]));
  19146. // body is of types BlockStatement
  19147. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19148. return node;
  19149. };
  19150. Visitor.prototype.visitVariableDeclarator = function visitVariableDeclarator(node, state, path) {
  19151. var visitor = this;
  19152. // id is of types Pattern
  19153. node["id"] = visitor.accept(node["id"], state, path.concat(["id"]));
  19154. // init is of types Expression
  19155. if (node["init"]) {
  19156. node["init"] = visitor.accept(node["init"], state, path.concat(["init"]));
  19157. }
  19158. return node;
  19159. };
  19160. Visitor.prototype.visitExpression = function visitExpression(node, state, path) {
  19161. var visitor = this;
  19162. return node;
  19163. };
  19164. Visitor.prototype.visitProperty = function visitProperty(node, state, path) {
  19165. var visitor = this;
  19166. // key is of types Expression
  19167. node["key"] = visitor.accept(node["key"], state, path.concat(["key"]));
  19168. // value is of types Expression
  19169. node["value"] = visitor.accept(node["value"], state, path.concat(["value"]));
  19170. return node;
  19171. };
  19172. Visitor.prototype.visitPattern = function visitPattern(node, state, path) {
  19173. var visitor = this;
  19174. return node;
  19175. };
  19176. Visitor.prototype.visitSuper = function visitSuper(node, state, path) {
  19177. var visitor = this;
  19178. return node;
  19179. };
  19180. Visitor.prototype.visitSpreadElement = function visitSpreadElement(node, state, path) {
  19181. var visitor = this;
  19182. // argument is of types Expression
  19183. node["argument"] = visitor.accept(node["argument"], state, path.concat(["argument"]));
  19184. return node;
  19185. };
  19186. Visitor.prototype.visitTemplateElement = function visitTemplateElement(node, state, path) {
  19187. var visitor = this;
  19188. return node;
  19189. };
  19190. Visitor.prototype.visitClass = function visitClass(node, state, path) {
  19191. var visitor = this;
  19192. // id is of types Identifier
  19193. if (node["id"]) {
  19194. node["id"] = visitor.accept(node["id"], state, path.concat(["id"]));
  19195. }
  19196. // superClass is of types Expression
  19197. if (node["superClass"]) {
  19198. node["superClass"] = visitor.accept(node["superClass"], state, path.concat(["superClass"]));
  19199. }
  19200. // body is of types ClassBody
  19201. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19202. return node;
  19203. };
  19204. Visitor.prototype.visitClassBody = function visitClassBody(node, state, path) {
  19205. var visitor = this;
  19206. // body is a list with types MethodDefinition
  19207. var newElements = [];
  19208. for (var i = 0; i < node["body"].length; i++) {
  19209. var ea = node["body"][i];
  19210. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["body", i])) : ea;
  19211. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19212. }
  19213. node["body"] = newElements;
  19214. return node;
  19215. };
  19216. Visitor.prototype.visitMethodDefinition = function visitMethodDefinition(node, state, path) {
  19217. var visitor = this;
  19218. // key is of types Expression
  19219. node["key"] = visitor.accept(node["key"], state, path.concat(["key"]));
  19220. // value is of types FunctionExpression
  19221. node["value"] = visitor.accept(node["value"], state, path.concat(["value"]));
  19222. return node;
  19223. };
  19224. Visitor.prototype.visitModuleDeclaration = function visitModuleDeclaration(node, state, path) {
  19225. var visitor = this;
  19226. return node;
  19227. };
  19228. Visitor.prototype.visitModuleSpecifier = function visitModuleSpecifier(node, state, path) {
  19229. var visitor = this;
  19230. // local is of types Identifier
  19231. node["local"] = visitor.accept(node["local"], state, path.concat(["local"]));
  19232. return node;
  19233. };
  19234. Visitor.prototype.visitJSXEmptyExpression = function visitJSXEmptyExpression(node, state, path) {
  19235. var visitor = this;
  19236. return node;
  19237. };
  19238. Visitor.prototype.visitJSXExpressionContainer = function visitJSXExpressionContainer(node, state, path) {
  19239. var visitor = this;
  19240. // expression is of types Expression, JSXEmptyExpression
  19241. node["expression"] = visitor.accept(node["expression"], state, path.concat(["expression"]));
  19242. return node;
  19243. };
  19244. Visitor.prototype.visitJSXSpreadChild = function visitJSXSpreadChild(node, state, path) {
  19245. var visitor = this;
  19246. // expression is of types Expression
  19247. node["expression"] = visitor.accept(node["expression"], state, path.concat(["expression"]));
  19248. return node;
  19249. };
  19250. Visitor.prototype.visitJSXBoundaryElement = function visitJSXBoundaryElement(node, state, path) {
  19251. var visitor = this;
  19252. // name is of types JSXIdentifier, JSXMemberExpression, JSXNamespacedName
  19253. node["name"] = visitor.accept(node["name"], state, path.concat(["name"]));
  19254. return node;
  19255. };
  19256. Visitor.prototype.visitJSXAttribute = function visitJSXAttribute(node, state, path) {
  19257. var visitor = this;
  19258. // name is of types JSXIdentifier, JSXNamespacedName
  19259. node["name"] = visitor.accept(node["name"], state, path.concat(["name"]));
  19260. // value is of types Literal, JSXExpressionContainer, JSXElement, JSXFragment
  19261. if (node["value"]) {
  19262. node["value"] = visitor.accept(node["value"], state, path.concat(["value"]));
  19263. }
  19264. return node;
  19265. };
  19266. Visitor.prototype.visitJSXText = function visitJSXText(node, state, path) {
  19267. var visitor = this;
  19268. return node;
  19269. };
  19270. Visitor.prototype.visitJSXOpeningFragment = function visitJSXOpeningFragment(node, state, path) {
  19271. var visitor = this;
  19272. return node;
  19273. };
  19274. Visitor.prototype.visitJSXClosingFragment = function visitJSXClosingFragment(node, state, path) {
  19275. var visitor = this;
  19276. return node;
  19277. };
  19278. Visitor.prototype.visitIdentifier = function visitIdentifier(node, state, path) {
  19279. var visitor = this;
  19280. return node;
  19281. };
  19282. Visitor.prototype.visitLiteral = function visitLiteral(node, state, path) {
  19283. var visitor = this;
  19284. return node;
  19285. };
  19286. Visitor.prototype.visitExpressionStatement = function visitExpressionStatement(node, state, path) {
  19287. var visitor = this;
  19288. // expression is of types Expression
  19289. node["expression"] = visitor.accept(node["expression"], state, path.concat(["expression"]));
  19290. return node;
  19291. };
  19292. Visitor.prototype.visitBlockStatement = function visitBlockStatement(node, state, path) {
  19293. var visitor = this;
  19294. // body is a list with types Statement
  19295. var newElements = [];
  19296. for (var i = 0; i < node["body"].length; i++) {
  19297. var ea = node["body"][i];
  19298. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["body", i])) : ea;
  19299. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19300. }
  19301. node["body"] = newElements;
  19302. return node;
  19303. };
  19304. Visitor.prototype.visitEmptyStatement = function visitEmptyStatement(node, state, path) {
  19305. var visitor = this;
  19306. return node;
  19307. };
  19308. Visitor.prototype.visitDebuggerStatement = function visitDebuggerStatement(node, state, path) {
  19309. var visitor = this;
  19310. return node;
  19311. };
  19312. Visitor.prototype.visitWithStatement = function visitWithStatement(node, state, path) {
  19313. var visitor = this;
  19314. // object is of types Expression
  19315. node["object"] = visitor.accept(node["object"], state, path.concat(["object"]));
  19316. // body is of types Statement
  19317. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19318. return node;
  19319. };
  19320. Visitor.prototype.visitReturnStatement = function visitReturnStatement(node, state, path) {
  19321. var visitor = this;
  19322. // argument is of types Expression
  19323. if (node["argument"]) {
  19324. node["argument"] = visitor.accept(node["argument"], state, path.concat(["argument"]));
  19325. }
  19326. return node;
  19327. };
  19328. Visitor.prototype.visitLabeledStatement = function visitLabeledStatement(node, state, path) {
  19329. var visitor = this;
  19330. // label is of types Identifier
  19331. node["label"] = visitor.accept(node["label"], state, path.concat(["label"]));
  19332. // body is of types Statement
  19333. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19334. return node;
  19335. };
  19336. Visitor.prototype.visitBreakStatement = function visitBreakStatement(node, state, path) {
  19337. var visitor = this;
  19338. // label is of types Identifier
  19339. if (node["label"]) {
  19340. node["label"] = visitor.accept(node["label"], state, path.concat(["label"]));
  19341. }
  19342. return node;
  19343. };
  19344. Visitor.prototype.visitContinueStatement = function visitContinueStatement(node, state, path) {
  19345. var visitor = this;
  19346. // label is of types Identifier
  19347. if (node["label"]) {
  19348. node["label"] = visitor.accept(node["label"], state, path.concat(["label"]));
  19349. }
  19350. return node;
  19351. };
  19352. Visitor.prototype.visitIfStatement = function visitIfStatement(node, state, path) {
  19353. var visitor = this;
  19354. // test is of types Expression
  19355. node["test"] = visitor.accept(node["test"], state, path.concat(["test"]));
  19356. // consequent is of types Statement
  19357. node["consequent"] = visitor.accept(node["consequent"], state, path.concat(["consequent"]));
  19358. // alternate is of types Statement
  19359. if (node["alternate"]) {
  19360. node["alternate"] = visitor.accept(node["alternate"], state, path.concat(["alternate"]));
  19361. }
  19362. return node;
  19363. };
  19364. Visitor.prototype.visitSwitchStatement = function visitSwitchStatement(node, state, path) {
  19365. var visitor = this;
  19366. // discriminant is of types Expression
  19367. node["discriminant"] = visitor.accept(node["discriminant"], state, path.concat(["discriminant"]));
  19368. // cases is a list with types SwitchCase
  19369. var newElements = [];
  19370. for (var i = 0; i < node["cases"].length; i++) {
  19371. var ea = node["cases"][i];
  19372. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["cases", i])) : ea;
  19373. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19374. }
  19375. node["cases"] = newElements;
  19376. return node;
  19377. };
  19378. Visitor.prototype.visitThrowStatement = function visitThrowStatement(node, state, path) {
  19379. var visitor = this;
  19380. // argument is of types Expression
  19381. node["argument"] = visitor.accept(node["argument"], state, path.concat(["argument"]));
  19382. return node;
  19383. };
  19384. Visitor.prototype.visitTryStatement = function visitTryStatement(node, state, path) {
  19385. var visitor = this;
  19386. // block is of types BlockStatement
  19387. node["block"] = visitor.accept(node["block"], state, path.concat(["block"]));
  19388. // handler is of types CatchClause
  19389. if (node["handler"]) {
  19390. node["handler"] = visitor.accept(node["handler"], state, path.concat(["handler"]));
  19391. }
  19392. // finalizer is of types BlockStatement
  19393. if (node["finalizer"]) {
  19394. node["finalizer"] = visitor.accept(node["finalizer"], state, path.concat(["finalizer"]));
  19395. }
  19396. return node;
  19397. };
  19398. Visitor.prototype.visitWhileStatement = function visitWhileStatement(node, state, path) {
  19399. var visitor = this;
  19400. // test is of types Expression
  19401. node["test"] = visitor.accept(node["test"], state, path.concat(["test"]));
  19402. // body is of types Statement
  19403. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19404. return node;
  19405. };
  19406. Visitor.prototype.visitDoWhileStatement = function visitDoWhileStatement(node, state, path) {
  19407. var visitor = this;
  19408. // body is of types Statement
  19409. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19410. // test is of types Expression
  19411. node["test"] = visitor.accept(node["test"], state, path.concat(["test"]));
  19412. return node;
  19413. };
  19414. Visitor.prototype.visitForStatement = function visitForStatement(node, state, path) {
  19415. var visitor = this;
  19416. // init is of types VariableDeclaration, Expression
  19417. if (node["init"]) {
  19418. node["init"] = visitor.accept(node["init"], state, path.concat(["init"]));
  19419. }
  19420. // test is of types Expression
  19421. if (node["test"]) {
  19422. node["test"] = visitor.accept(node["test"], state, path.concat(["test"]));
  19423. }
  19424. // update is of types Expression
  19425. if (node["update"]) {
  19426. node["update"] = visitor.accept(node["update"], state, path.concat(["update"]));
  19427. }
  19428. // body is of types Statement
  19429. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19430. return node;
  19431. };
  19432. Visitor.prototype.visitForInStatement = function visitForInStatement(node, state, path) {
  19433. var visitor = this;
  19434. // left is of types VariableDeclaration, Pattern
  19435. node["left"] = visitor.accept(node["left"], state, path.concat(["left"]));
  19436. // right is of types Expression
  19437. node["right"] = visitor.accept(node["right"], state, path.concat(["right"]));
  19438. // body is of types Statement
  19439. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19440. return node;
  19441. };
  19442. Visitor.prototype.visitDeclaration = function visitDeclaration(node, state, path) {
  19443. var visitor = this;
  19444. return node;
  19445. };
  19446. Visitor.prototype.visitThisExpression = function visitThisExpression(node, state, path) {
  19447. var visitor = this;
  19448. return node;
  19449. };
  19450. Visitor.prototype.visitArrayExpression = function visitArrayExpression(node, state, path) {
  19451. var visitor = this;
  19452. // elements is a list with types Expression, SpreadElement
  19453. if (node["elements"]) {
  19454. var newElements = [];
  19455. for (var i = 0; i < node["elements"].length; i++) {
  19456. var ea = node["elements"][i];
  19457. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["elements", i])) : ea;
  19458. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19459. }
  19460. node["elements"] = newElements;
  19461. }
  19462. return node;
  19463. };
  19464. Visitor.prototype.visitObjectExpression = function visitObjectExpression(node, state, path) {
  19465. var visitor = this;
  19466. // properties is a list with types Property, SpreadElement
  19467. var newElements = [];
  19468. for (var i = 0; i < node["properties"].length; i++) {
  19469. var ea = node["properties"][i];
  19470. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["properties", i])) : ea;
  19471. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19472. }
  19473. node["properties"] = newElements;
  19474. return node;
  19475. };
  19476. Visitor.prototype.visitFunctionExpression = function visitFunctionExpression(node, state, path) {
  19477. var visitor = this;
  19478. // id is of types Identifier
  19479. if (node["id"]) {
  19480. node["id"] = visitor.accept(node["id"], state, path.concat(["id"]));
  19481. }
  19482. // params is a list with types Pattern
  19483. var newElements = [];
  19484. for (var i = 0; i < node["params"].length; i++) {
  19485. var ea = node["params"][i];
  19486. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["params", i])) : ea;
  19487. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19488. }
  19489. node["params"] = newElements;
  19490. // body is of types FunctionBody
  19491. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19492. return node;
  19493. };
  19494. Visitor.prototype.visitUnaryExpression = function visitUnaryExpression(node, state, path) {
  19495. var visitor = this;
  19496. // argument is of types Expression
  19497. node["argument"] = visitor.accept(node["argument"], state, path.concat(["argument"]));
  19498. return node;
  19499. };
  19500. Visitor.prototype.visitUpdateExpression = function visitUpdateExpression(node, state, path) {
  19501. var visitor = this;
  19502. // argument is of types Expression
  19503. node["argument"] = visitor.accept(node["argument"], state, path.concat(["argument"]));
  19504. return node;
  19505. };
  19506. Visitor.prototype.visitBinaryExpression = function visitBinaryExpression(node, state, path) {
  19507. var visitor = this;
  19508. // left is of types Expression
  19509. node["left"] = visitor.accept(node["left"], state, path.concat(["left"]));
  19510. // right is of types Expression
  19511. node["right"] = visitor.accept(node["right"], state, path.concat(["right"]));
  19512. return node;
  19513. };
  19514. Visitor.prototype.visitAssignmentExpression = function visitAssignmentExpression(node, state, path) {
  19515. var visitor = this;
  19516. // left is of types Pattern
  19517. node["left"] = visitor.accept(node["left"], state, path.concat(["left"]));
  19518. // right is of types Expression
  19519. node["right"] = visitor.accept(node["right"], state, path.concat(["right"]));
  19520. return node;
  19521. };
  19522. Visitor.prototype.visitLogicalExpression = function visitLogicalExpression(node, state, path) {
  19523. var visitor = this;
  19524. // left is of types Expression
  19525. node["left"] = visitor.accept(node["left"], state, path.concat(["left"]));
  19526. // right is of types Expression
  19527. node["right"] = visitor.accept(node["right"], state, path.concat(["right"]));
  19528. return node;
  19529. };
  19530. Visitor.prototype.visitMemberExpression = function visitMemberExpression(node, state, path) {
  19531. var visitor = this;
  19532. // object is of types Expression, Super
  19533. node["object"] = visitor.accept(node["object"], state, path.concat(["object"]));
  19534. // property is of types Expression
  19535. node["property"] = visitor.accept(node["property"], state, path.concat(["property"]));
  19536. return node;
  19537. };
  19538. Visitor.prototype.visitConditionalExpression = function visitConditionalExpression(node, state, path) {
  19539. var visitor = this;
  19540. // test is of types Expression
  19541. node["test"] = visitor.accept(node["test"], state, path.concat(["test"]));
  19542. // alternate is of types Expression
  19543. node["alternate"] = visitor.accept(node["alternate"], state, path.concat(["alternate"]));
  19544. // consequent is of types Expression
  19545. node["consequent"] = visitor.accept(node["consequent"], state, path.concat(["consequent"]));
  19546. return node;
  19547. };
  19548. Visitor.prototype.visitCallExpression = function visitCallExpression(node, state, path) {
  19549. var visitor = this;
  19550. // callee is of types Expression, Super
  19551. node["callee"] = visitor.accept(node["callee"], state, path.concat(["callee"]));
  19552. // arguments is a list with types Expression, SpreadElement
  19553. var newElements = [];
  19554. for (var i = 0; i < node["arguments"].length; i++) {
  19555. var ea = node["arguments"][i];
  19556. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["arguments", i])) : ea;
  19557. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19558. }
  19559. node["arguments"] = newElements;
  19560. return node;
  19561. };
  19562. Visitor.prototype.visitNewExpression = function visitNewExpression(node, state, path) {
  19563. var visitor = this;
  19564. // callee is of types Expression
  19565. node["callee"] = visitor.accept(node["callee"], state, path.concat(["callee"]));
  19566. // arguments is a list with types Expression
  19567. var newElements = [];
  19568. for (var i = 0; i < node["arguments"].length; i++) {
  19569. var ea = node["arguments"][i];
  19570. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["arguments", i])) : ea;
  19571. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19572. }
  19573. node["arguments"] = newElements;
  19574. return node;
  19575. };
  19576. Visitor.prototype.visitSequenceExpression = function visitSequenceExpression(node, state, path) {
  19577. var visitor = this;
  19578. // expressions is a list with types Expression
  19579. var newElements = [];
  19580. for (var i = 0; i < node["expressions"].length; i++) {
  19581. var ea = node["expressions"][i];
  19582. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["expressions", i])) : ea;
  19583. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19584. }
  19585. node["expressions"] = newElements;
  19586. return node;
  19587. };
  19588. Visitor.prototype.visitArrowFunctionExpression = function visitArrowFunctionExpression(node, state, path) {
  19589. var visitor = this;
  19590. // body is of types FunctionBody, Expression
  19591. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19592. // id is of types Identifier
  19593. if (node["id"]) {
  19594. node["id"] = visitor.accept(node["id"], state, path.concat(["id"]));
  19595. }
  19596. // params is a list with types Pattern
  19597. var newElements = [];
  19598. for (var i = 0; i < node["params"].length; i++) {
  19599. var ea = node["params"][i];
  19600. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["params", i])) : ea;
  19601. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19602. }
  19603. node["params"] = newElements;
  19604. return node;
  19605. };
  19606. Visitor.prototype.visitYieldExpression = function visitYieldExpression(node, state, path) {
  19607. var visitor = this;
  19608. // argument is of types Expression
  19609. if (node["argument"]) {
  19610. node["argument"] = visitor.accept(node["argument"], state, path.concat(["argument"]));
  19611. }
  19612. return node;
  19613. };
  19614. Visitor.prototype.visitTemplateLiteral = function visitTemplateLiteral(node, state, path) {
  19615. var visitor = this;
  19616. // quasis is a list with types TemplateElement
  19617. var newElements = [];
  19618. for (var i = 0; i < node["quasis"].length; i++) {
  19619. var ea = node["quasis"][i];
  19620. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["quasis", i])) : ea;
  19621. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19622. }
  19623. node["quasis"] = newElements;
  19624. // expressions is a list with types Expression
  19625. var newElements = [];
  19626. for (var i = 0; i < node["expressions"].length; i++) {
  19627. var ea = node["expressions"][i];
  19628. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["expressions", i])) : ea;
  19629. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19630. }
  19631. node["expressions"] = newElements;
  19632. return node;
  19633. };
  19634. Visitor.prototype.visitTaggedTemplateExpression = function visitTaggedTemplateExpression(node, state, path) {
  19635. var visitor = this;
  19636. // tag is of types Expression
  19637. node["tag"] = visitor.accept(node["tag"], state, path.concat(["tag"]));
  19638. // quasi is of types TemplateLiteral
  19639. node["quasi"] = visitor.accept(node["quasi"], state, path.concat(["quasi"]));
  19640. return node;
  19641. };
  19642. Visitor.prototype.visitAssignmentProperty = function visitAssignmentProperty(node, state, path) {
  19643. var visitor = this;
  19644. // value is of types Pattern, Expression
  19645. node["value"] = visitor.accept(node["value"], state, path.concat(["value"]));
  19646. // key is of types Expression
  19647. node["key"] = visitor.accept(node["key"], state, path.concat(["key"]));
  19648. return node;
  19649. };
  19650. Visitor.prototype.visitObjectPattern = function visitObjectPattern(node, state, path) {
  19651. var visitor = this;
  19652. // properties is a list with types AssignmentProperty, RestElement
  19653. var newElements = [];
  19654. for (var i = 0; i < node["properties"].length; i++) {
  19655. var ea = node["properties"][i];
  19656. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["properties", i])) : ea;
  19657. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19658. }
  19659. node["properties"] = newElements;
  19660. return node;
  19661. };
  19662. Visitor.prototype.visitArrayPattern = function visitArrayPattern(node, state, path) {
  19663. var visitor = this;
  19664. // elements is a list with types Pattern
  19665. if (node["elements"]) {
  19666. var newElements = [];
  19667. for (var i = 0; i < node["elements"].length; i++) {
  19668. var ea = node["elements"][i];
  19669. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["elements", i])) : ea;
  19670. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19671. }
  19672. node["elements"] = newElements;
  19673. }
  19674. return node;
  19675. };
  19676. Visitor.prototype.visitRestElement = function visitRestElement(node, state, path) {
  19677. var visitor = this;
  19678. // argument is of types Pattern
  19679. node["argument"] = visitor.accept(node["argument"], state, path.concat(["argument"]));
  19680. return node;
  19681. };
  19682. Visitor.prototype.visitAssignmentPattern = function visitAssignmentPattern(node, state, path) {
  19683. var visitor = this;
  19684. // left is of types Pattern
  19685. node["left"] = visitor.accept(node["left"], state, path.concat(["left"]));
  19686. // right is of types Expression
  19687. node["right"] = visitor.accept(node["right"], state, path.concat(["right"]));
  19688. return node;
  19689. };
  19690. Visitor.prototype.visitClassExpression = function visitClassExpression(node, state, path) {
  19691. var visitor = this;
  19692. // id is of types Identifier
  19693. if (node["id"]) {
  19694. node["id"] = visitor.accept(node["id"], state, path.concat(["id"]));
  19695. }
  19696. // superClass is of types Expression
  19697. if (node["superClass"]) {
  19698. node["superClass"] = visitor.accept(node["superClass"], state, path.concat(["superClass"]));
  19699. }
  19700. // body is of types ClassBody
  19701. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19702. return node;
  19703. };
  19704. Visitor.prototype.visitMetaProperty = function visitMetaProperty(node, state, path) {
  19705. var visitor = this;
  19706. // meta is of types Identifier
  19707. node["meta"] = visitor.accept(node["meta"], state, path.concat(["meta"]));
  19708. // property is of types Identifier
  19709. node["property"] = visitor.accept(node["property"], state, path.concat(["property"]));
  19710. return node;
  19711. };
  19712. Visitor.prototype.visitImportDeclaration = function visitImportDeclaration(node, state, path) {
  19713. var visitor = this;
  19714. // specifiers is a list with types ImportSpecifier, ImportDefaultSpecifier, ImportNamespaceSpecifier
  19715. var newElements = [];
  19716. for (var i = 0; i < node["specifiers"].length; i++) {
  19717. var ea = node["specifiers"][i];
  19718. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["specifiers", i])) : ea;
  19719. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19720. }
  19721. node["specifiers"] = newElements;
  19722. // source is of types Literal
  19723. node["source"] = visitor.accept(node["source"], state, path.concat(["source"]));
  19724. return node;
  19725. };
  19726. Visitor.prototype.visitImportSpecifier = function visitImportSpecifier(node, state, path) {
  19727. var visitor = this;
  19728. // imported is of types Identifier
  19729. node["imported"] = visitor.accept(node["imported"], state, path.concat(["imported"]));
  19730. // local is of types Identifier
  19731. node["local"] = visitor.accept(node["local"], state, path.concat(["local"]));
  19732. return node;
  19733. };
  19734. Visitor.prototype.visitImportDefaultSpecifier = function visitImportDefaultSpecifier(node, state, path) {
  19735. var visitor = this;
  19736. // local is of types Identifier
  19737. node["local"] = visitor.accept(node["local"], state, path.concat(["local"]));
  19738. return node;
  19739. };
  19740. Visitor.prototype.visitImportNamespaceSpecifier = function visitImportNamespaceSpecifier(node, state, path) {
  19741. var visitor = this;
  19742. // local is of types Identifier
  19743. node["local"] = visitor.accept(node["local"], state, path.concat(["local"]));
  19744. return node;
  19745. };
  19746. Visitor.prototype.visitExportNamedDeclaration = function visitExportNamedDeclaration(node, state, path) {
  19747. var visitor = this;
  19748. // declaration is of types Declaration
  19749. if (node["declaration"]) {
  19750. node["declaration"] = visitor.accept(node["declaration"], state, path.concat(["declaration"]));
  19751. }
  19752. // specifiers is a list with types ExportSpecifier
  19753. var newElements = [];
  19754. for (var i = 0; i < node["specifiers"].length; i++) {
  19755. var ea = node["specifiers"][i];
  19756. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["specifiers", i])) : ea;
  19757. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19758. }
  19759. node["specifiers"] = newElements;
  19760. // source is of types Literal
  19761. if (node["source"]) {
  19762. node["source"] = visitor.accept(node["source"], state, path.concat(["source"]));
  19763. }
  19764. return node;
  19765. };
  19766. Visitor.prototype.visitExportSpecifier = function visitExportSpecifier(node, state, path) {
  19767. var visitor = this;
  19768. // exported is of types Identifier
  19769. node["exported"] = visitor.accept(node["exported"], state, path.concat(["exported"]));
  19770. // local is of types Identifier
  19771. node["local"] = visitor.accept(node["local"], state, path.concat(["local"]));
  19772. return node;
  19773. };
  19774. Visitor.prototype.visitExportDefaultDeclaration = function visitExportDefaultDeclaration(node, state, path) {
  19775. var visitor = this;
  19776. // declaration is of types Declaration, Expression
  19777. node["declaration"] = visitor.accept(node["declaration"], state, path.concat(["declaration"]));
  19778. return node;
  19779. };
  19780. Visitor.prototype.visitExportAllDeclaration = function visitExportAllDeclaration(node, state, path) {
  19781. var visitor = this;
  19782. // source is of types Literal
  19783. node["source"] = visitor.accept(node["source"], state, path.concat(["source"]));
  19784. return node;
  19785. };
  19786. Visitor.prototype.visitAwaitExpression = function visitAwaitExpression(node, state, path) {
  19787. var visitor = this;
  19788. // argument is of types Expression
  19789. node["argument"] = visitor.accept(node["argument"], state, path.concat(["argument"]));
  19790. return node;
  19791. };
  19792. Visitor.prototype.visitJSXMemberExpression = function visitJSXMemberExpression(node, state, path) {
  19793. var visitor = this;
  19794. // object is of types JSXMemberExpression, JSXIdentifier
  19795. node["object"] = visitor.accept(node["object"], state, path.concat(["object"]));
  19796. // property is of types JSXIdentifier
  19797. node["property"] = visitor.accept(node["property"], state, path.concat(["property"]));
  19798. return node;
  19799. };
  19800. Visitor.prototype.visitJSXNamespacedName = function visitJSXNamespacedName(node, state, path) {
  19801. var visitor = this;
  19802. // namespace is of types JSXIdentifier
  19803. node["namespace"] = visitor.accept(node["namespace"], state, path.concat(["namespace"]));
  19804. // name is of types JSXIdentifier
  19805. node["name"] = visitor.accept(node["name"], state, path.concat(["name"]));
  19806. return node;
  19807. };
  19808. Visitor.prototype.visitJSXOpeningElement = function visitJSXOpeningElement(node, state, path) {
  19809. var visitor = this;
  19810. // attributes is a list with types JSXAttribute, JSXSpreadAttribute
  19811. var newElements = [];
  19812. for (var i = 0; i < node["attributes"].length; i++) {
  19813. var ea = node["attributes"][i];
  19814. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["attributes", i])) : ea;
  19815. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19816. }
  19817. node["attributes"] = newElements;
  19818. // name is of types JSXIdentifier, JSXMemberExpression, JSXNamespacedName
  19819. node["name"] = visitor.accept(node["name"], state, path.concat(["name"]));
  19820. return node;
  19821. };
  19822. Visitor.prototype.visitJSXClosingElement = function visitJSXClosingElement(node, state, path) {
  19823. var visitor = this;
  19824. // name is of types JSXIdentifier, JSXMemberExpression, JSXNamespacedName
  19825. node["name"] = visitor.accept(node["name"], state, path.concat(["name"]));
  19826. return node;
  19827. };
  19828. Visitor.prototype.visitJSXSpreadAttribute = function visitJSXSpreadAttribute(node, state, path) {
  19829. var visitor = this;
  19830. // argument is of types Expression
  19831. node["argument"] = visitor.accept(node["argument"], state, path.concat(["argument"]));
  19832. return node;
  19833. };
  19834. Visitor.prototype.visitJSXElement = function visitJSXElement(node, state, path) {
  19835. var visitor = this;
  19836. // openingElement is of types JSXOpeningElement
  19837. node["openingElement"] = visitor.accept(node["openingElement"], state, path.concat(["openingElement"]));
  19838. // children is a list with types JSXText, JSXExpressionContainer, JSXSpreadChild, JSXElement, JSXFragment
  19839. var newElements = [];
  19840. for (var i = 0; i < node["children"].length; i++) {
  19841. var ea = node["children"][i];
  19842. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["children", i])) : ea;
  19843. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19844. }
  19845. node["children"] = newElements;
  19846. // closingElement is of types JSXClosingElement
  19847. if (node["closingElement"]) {
  19848. node["closingElement"] = visitor.accept(node["closingElement"], state, path.concat(["closingElement"]));
  19849. }
  19850. return node;
  19851. };
  19852. Visitor.prototype.visitJSXFragment = function visitJSXFragment(node, state, path) {
  19853. var visitor = this;
  19854. // openingFragment is of types JSXOpeningFragment
  19855. node["openingFragment"] = visitor.accept(node["openingFragment"], state, path.concat(["openingFragment"]));
  19856. // children is a list with types JSXText, JSXExpressionContainer, JSXSpreadChild, JSXElement, JSXFragment
  19857. var newElements = [];
  19858. for (var i = 0; i < node["children"].length; i++) {
  19859. var ea = node["children"][i];
  19860. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["children", i])) : ea;
  19861. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19862. }
  19863. node["children"] = newElements;
  19864. // closingFragment is of types JSXClosingFragment
  19865. node["closingFragment"] = visitor.accept(node["closingFragment"], state, path.concat(["closingFragment"]));
  19866. return node;
  19867. };
  19868. Visitor.prototype.visitRegExpLiteral = function visitRegExpLiteral(node, state, path) {
  19869. var visitor = this;
  19870. return node;
  19871. };
  19872. Visitor.prototype.visitFunctionBody = function visitFunctionBody(node, state, path) {
  19873. var visitor = this;
  19874. // body is a list with types Directive, Statement
  19875. var newElements = [];
  19876. for (var i = 0; i < node["body"].length; i++) {
  19877. var ea = node["body"][i];
  19878. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["body", i])) : ea;
  19879. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19880. }
  19881. node["body"] = newElements;
  19882. return node;
  19883. };
  19884. Visitor.prototype.visitFunctionDeclaration = function visitFunctionDeclaration(node, state, path) {
  19885. var visitor = this;
  19886. // id is of types Identifier
  19887. if (node["id"]) {
  19888. node["id"] = visitor.accept(node["id"], state, path.concat(["id"]));
  19889. }
  19890. // params is a list with types Pattern
  19891. var newElements = [];
  19892. for (var i = 0; i < node["params"].length; i++) {
  19893. var ea = node["params"][i];
  19894. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["params", i])) : ea;
  19895. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19896. }
  19897. node["params"] = newElements;
  19898. // body is of types FunctionBody
  19899. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19900. return node;
  19901. };
  19902. Visitor.prototype.visitVariableDeclaration = function visitVariableDeclaration(node, state, path) {
  19903. var visitor = this;
  19904. // declarations is a list with types VariableDeclarator
  19905. var newElements = [];
  19906. for (var i = 0; i < node["declarations"].length; i++) {
  19907. var ea = node["declarations"][i];
  19908. var acceptedNodes = ea ? visitor.accept(ea, state, path.concat(["declarations", i])) : ea;
  19909. if (Array.isArray(acceptedNodes)) newElements.push.apply(newElements, acceptedNodes);else newElements.push(acceptedNodes);
  19910. }
  19911. node["declarations"] = newElements;
  19912. return node;
  19913. };
  19914. Visitor.prototype.visitForOfStatement = function visitForOfStatement(node, state, path) {
  19915. var visitor = this;
  19916. // left is of types VariableDeclaration, Pattern
  19917. node["left"] = visitor.accept(node["left"], state, path.concat(["left"]));
  19918. // right is of types Expression
  19919. node["right"] = visitor.accept(node["right"], state, path.concat(["right"]));
  19920. // body is of types Statement
  19921. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19922. return node;
  19923. };
  19924. Visitor.prototype.visitClassDeclaration = function visitClassDeclaration(node, state, path) {
  19925. var visitor = this;
  19926. // id is of types Identifier
  19927. if (node["id"]) {
  19928. node["id"] = visitor.accept(node["id"], state, path.concat(["id"]));
  19929. }
  19930. // superClass is of types Expression
  19931. if (node["superClass"]) {
  19932. node["superClass"] = visitor.accept(node["superClass"], state, path.concat(["superClass"]));
  19933. }
  19934. // body is of types ClassBody
  19935. node["body"] = visitor.accept(node["body"], state, path.concat(["body"]));
  19936. return node;
  19937. };
  19938. Visitor.prototype.visitJSXIdentifier = function visitJSXIdentifier(node, state, path) {
  19939. var visitor = this;
  19940. return node;
  19941. };
  19942. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj$$1) {
  19943. return typeof obj$$1;
  19944. } : function (obj$$1) {
  19945. return obj$$1 && typeof Symbol === "function" && obj$$1.constructor === Symbol && obj$$1 !== Symbol.prototype ? "symbol" : typeof obj$$1;
  19946. };
  19947. var classCallCheck = function (instance, Constructor) {
  19948. if (!(instance instanceof Constructor)) {
  19949. throw new TypeError("Cannot call a class as a function");
  19950. }
  19951. };
  19952. var createClass = function () {
  19953. function defineProperties(target, props) {
  19954. for (var i = 0; i < props.length; i++) {
  19955. var descriptor = props[i];
  19956. descriptor.enumerable = descriptor.enumerable || false;
  19957. descriptor.configurable = true;
  19958. if ("value" in descriptor) descriptor.writable = true;
  19959. Object.defineProperty(target, descriptor.key, descriptor);
  19960. }
  19961. }
  19962. return function (Constructor, protoProps, staticProps) {
  19963. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  19964. if (staticProps) defineProperties(Constructor, staticProps);
  19965. return Constructor;
  19966. };
  19967. }();
  19968. var defineProperty = function (obj$$1, key, value) {
  19969. if (key in obj$$1) {
  19970. Object.defineProperty(obj$$1, key, {
  19971. value: value,
  19972. enumerable: true,
  19973. configurable: true,
  19974. writable: true
  19975. });
  19976. } else {
  19977. obj$$1[key] = value;
  19978. }
  19979. return obj$$1;
  19980. };
  19981. var _extends = Object.assign || function (target) {
  19982. for (var i = 1; i < arguments.length; i++) {
  19983. var source = arguments[i];
  19984. for (var key in source) {
  19985. if (Object.prototype.hasOwnProperty.call(source, key)) {
  19986. target[key] = source[key];
  19987. }
  19988. }
  19989. }
  19990. return target;
  19991. };
  19992. var get = function get(object, property, receiver) {
  19993. if (object === null) object = Function.prototype;
  19994. var desc = Object.getOwnPropertyDescriptor(object, property);
  19995. if (desc === undefined) {
  19996. var parent = Object.getPrototypeOf(object);
  19997. if (parent === null) {
  19998. return undefined;
  19999. } else {
  20000. return get(parent, property, receiver);
  20001. }
  20002. } else if ("value" in desc) {
  20003. return desc.value;
  20004. } else {
  20005. var getter = desc.get;
  20006. if (getter === undefined) {
  20007. return undefined;
  20008. }
  20009. return getter.call(receiver);
  20010. }
  20011. };
  20012. var inherits = function (subClass, superClass) {
  20013. if (typeof superClass !== "function" && superClass !== null) {
  20014. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  20015. }
  20016. subClass.prototype = Object.create(superClass && superClass.prototype, {
  20017. constructor: {
  20018. value: subClass,
  20019. enumerable: false,
  20020. writable: true,
  20021. configurable: true
  20022. }
  20023. });
  20024. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  20025. };
  20026. var possibleConstructorReturn = function (self, call) {
  20027. if (!self) {
  20028. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  20029. }
  20030. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  20031. };
  20032. var set = function set(object, property, value, receiver) {
  20033. var desc = Object.getOwnPropertyDescriptor(object, property);
  20034. if (desc === undefined) {
  20035. var parent = Object.getPrototypeOf(object);
  20036. if (parent !== null) {
  20037. set(parent, property, value, receiver);
  20038. }
  20039. } else if ("value" in desc && desc.writable) {
  20040. desc.value = value;
  20041. } else {
  20042. var setter = desc.set;
  20043. if (setter !== undefined) {
  20044. setter.call(receiver, value);
  20045. }
  20046. }
  20047. return value;
  20048. };
  20049. var slicedToArray = function () {
  20050. function sliceIterator(arr$$1, i) {
  20051. var _arr = [];
  20052. var _n = true;
  20053. var _d = false;
  20054. var _e = undefined;
  20055. try {
  20056. for (var _i = arr$$1[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  20057. _arr.push(_s.value);
  20058. if (i && _arr.length === i) break;
  20059. }
  20060. } catch (err) {
  20061. _d = true;
  20062. _e = err;
  20063. } finally {
  20064. try {
  20065. if (!_n && _i["return"]) _i["return"]();
  20066. } finally {
  20067. if (_d) throw _e;
  20068. }
  20069. }
  20070. return _arr;
  20071. }
  20072. return function (arr$$1, i) {
  20073. if (Array.isArray(arr$$1)) {
  20074. return arr$$1;
  20075. } else if (Symbol.iterator in Object(arr$$1)) {
  20076. return sliceIterator(arr$$1, i);
  20077. } else {
  20078. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  20079. }
  20080. };
  20081. }();
  20082. var toArray = function (arr$$1) {
  20083. return Array.isArray(arr$$1) ? arr$$1 : Array.from(arr$$1);
  20084. };
  20085. var toConsumableArray = function (arr$$1) {
  20086. if (Array.isArray(arr$$1)) {
  20087. for (var i = 0, arr2 = Array(arr$$1.length); i < arr$$1.length; i++) arr2[i] = arr$$1[i];
  20088. return arr2;
  20089. } else {
  20090. return Array.from(arr$$1);
  20091. }
  20092. };
  20093. /*global process, global, exports*/
  20094. var PrinterVisitor = function (_Visitor) {
  20095. inherits(PrinterVisitor, _Visitor);
  20096. function PrinterVisitor() {
  20097. classCallCheck(this, PrinterVisitor);
  20098. return possibleConstructorReturn(this, (PrinterVisitor.__proto__ || Object.getPrototypeOf(PrinterVisitor)).apply(this, arguments));
  20099. }
  20100. createClass(PrinterVisitor, [{
  20101. key: "accept",
  20102. value: function accept(node, state, path) {
  20103. var pathString = path.map(function (ea) {
  20104. return typeof ea === 'string' ? "." + ea : "[" + ea + "]";
  20105. }).join(''),
  20106. myChildren = [],
  20107. result = get(PrinterVisitor.prototype.__proto__ || Object.getPrototypeOf(PrinterVisitor.prototype), "accept", this).call(this, node, { index: state.index, tree: myChildren }, path);
  20108. state.tree.push({
  20109. node: node,
  20110. path: pathString,
  20111. index: state.index++,
  20112. children: myChildren
  20113. });
  20114. return result;
  20115. }
  20116. }]);
  20117. return PrinterVisitor;
  20118. }(Visitor);
  20119. var ComparisonVisitor = function (_Visitor2) {
  20120. inherits(ComparisonVisitor, _Visitor2);
  20121. function ComparisonVisitor() {
  20122. classCallCheck(this, ComparisonVisitor);
  20123. return possibleConstructorReturn(this, (ComparisonVisitor.__proto__ || Object.getPrototypeOf(ComparisonVisitor)).apply(this, arguments));
  20124. }
  20125. createClass(ComparisonVisitor, [{
  20126. key: "recordNotEqual",
  20127. value: function recordNotEqual(node1, node2, state, msg) {
  20128. state.comparisons.errors.push({
  20129. node1: node1, node2: node2,
  20130. path: state.completePath, msg: msg
  20131. });
  20132. }
  20133. }, {
  20134. key: "compareType",
  20135. value: function compareType(node1, node2, state) {
  20136. return this.compareField('type', node1, node2, state);
  20137. }
  20138. }, {
  20139. key: "compareField",
  20140. value: function compareField(field, node1, node2, state) {
  20141. node2 = lively.lang.Path(state.completePath.join('.')).get(node2);
  20142. if (node1 && node2 && node1[field] === node2[field]) return true;
  20143. if (node1 && node1[field] === '*' || node2 && node2[field] === '*') return true;
  20144. var fullPath = state.completePath.join('.') + '.' + field,
  20145. msg;
  20146. if (!node1) msg = "node1 on " + fullPath + " not defined";else if (!node2) msg = 'node2 not defined but node1 (' + fullPath + ') is: ' + node1[field];else msg = fullPath + ' is not equal: ' + node1[field] + ' vs. ' + node2[field];
  20147. this.recordNotEqual(node1, node2, state, msg);
  20148. return false;
  20149. }
  20150. }, {
  20151. key: "accept",
  20152. value: function accept(node1, node2, state, path) {
  20153. var patternNode = lively.lang.Path(path.join('.')).get(node2);
  20154. if (node1 === '*' || patternNode === '*') return;
  20155. var nextState = {
  20156. completePath: path,
  20157. comparisons: state.comparisons
  20158. };
  20159. if (this.compareType(node1, node2, nextState)) this['visit' + node1.type](node1, node2, nextState, path);
  20160. }
  20161. }, {
  20162. key: "visitFunction",
  20163. value: function visitFunction(node1, node2, state, path) {
  20164. // node1.generator has a specific type that is boolean
  20165. if (node1.generator) {
  20166. this.compareField("generator", node1, node2, state);
  20167. }
  20168. // node1.expression has a specific type that is boolean
  20169. if (node1.expression) {
  20170. this.compareField("expression", node1, node2, state);
  20171. }
  20172. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitFunction", this).call(this, node1, node2, state, path);
  20173. }
  20174. }, {
  20175. key: "visitSwitchStatement",
  20176. value: function visitSwitchStatement(node1, node2, state, path) {
  20177. // node1.lexical has a specific type that is boolean
  20178. if (node1.lexical) {
  20179. this.compareField("lexical", node1, node2, state);
  20180. }
  20181. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitSwitchStatement", this).call(this, node1, node2, state, path);
  20182. }
  20183. }, {
  20184. key: "visitForInStatement",
  20185. value: function visitForInStatement(node1, node2, state, path) {
  20186. // node1.each has a specific type that is boolean
  20187. if (node1.each) {
  20188. this.compareField("each", node1, node2, state);
  20189. }
  20190. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitForInStatement", this).call(this, node1, node2, state, path);
  20191. }
  20192. }, {
  20193. key: "visitFunctionDeclaration",
  20194. value: function visitFunctionDeclaration(node1, node2, state, path) {
  20195. // node1.generator has a specific type that is boolean
  20196. if (node1.generator) {
  20197. this.compareField("generator", node1, node2, state);
  20198. }
  20199. // node1.expression has a specific type that is boolean
  20200. if (node1.expression) {
  20201. this.compareField("expression", node1, node2, state);
  20202. }
  20203. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitFunctionDeclaration", this).call(this, node1, node2, state, path);
  20204. }
  20205. }, {
  20206. key: "visitVariableDeclaration",
  20207. value: function visitVariableDeclaration(node1, node2, state, path) {
  20208. // node1.kind is "var" or "let" or "const"
  20209. this.compareField("kind", node1, node2, state);
  20210. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitVariableDeclaration", this).call(this, node1, node2, state, path);
  20211. }
  20212. }, {
  20213. key: "visitUnaryExpression",
  20214. value: function visitUnaryExpression(node1, node2, state, path) {
  20215. // node1.operator is an UnaryOperator enum:
  20216. // "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"
  20217. this.compareField("operator", node1, node2, state);
  20218. // node1.prefix has a specific type that is boolean
  20219. if (node1.prefix) {
  20220. this.compareField("prefix", node1, node2, state);
  20221. }
  20222. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitUnaryExpression", this).call(this, node1, node2, state, path);
  20223. }
  20224. }, {
  20225. key: "visitBinaryExpression",
  20226. value: function visitBinaryExpression(node1, node2, state, path) {
  20227. // node1.operator is an BinaryOperator enum:
  20228. // "==" | "!=" | "===" | "!==" | | "<" | "<=" | ">" | ">=" | | "<<" | ">>" | ">>>" | | "+" | "-" | "*" | "/" | "%" | | "|" | "^" | "&" | "in" | | "instanceof" | ".."
  20229. this.compareField("operator", node1, node2, state);
  20230. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitBinaryExpression", this).call(this, node1, node2, state, path);
  20231. }
  20232. }, {
  20233. key: "visitAssignmentExpression",
  20234. value: function visitAssignmentExpression(node1, node2, state, path) {
  20235. // node1.operator is an AssignmentOperator enum:
  20236. // "=" | "+=" | "-=" | "*=" | "/=" | "%=" | | "<<=" | ">>=" | ">>>=" | | "|=" | "^=" | "&="
  20237. this.compareField("operator", node1, node2, state);
  20238. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitAssignmentExpression", this).call(this, node1, node2, state, path);
  20239. }
  20240. }, {
  20241. key: "visitUpdateExpression",
  20242. value: function visitUpdateExpression(node1, node2, state, path) {
  20243. // node1.operator is an UpdateOperator enum:
  20244. // "++" | "--"
  20245. this.compareField("operator", node1, node2, state);
  20246. // node1.prefix has a specific type that is boolean
  20247. if (node1.prefix) {
  20248. this.compareField("prefix", node1, node2, state);
  20249. }
  20250. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitUpdateExpression", this).call(this, node1, node2, state, path);
  20251. }
  20252. }, {
  20253. key: "visitLogicalExpression",
  20254. value: function visitLogicalExpression(node1, node2, state, path) {
  20255. // node1.operator is an LogicalOperator enum:
  20256. // "||" | "&&"
  20257. this.compareField("operator", node1, node2, state);
  20258. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitLogicalExpression", this).call(this, node1, node2, state, path);
  20259. }
  20260. }, {
  20261. key: "visitMemberExpression",
  20262. value: function visitMemberExpression(node1, node2, state, path) {
  20263. // node1.computed has a specific type that is boolean
  20264. if (node1.computed) {
  20265. this.compareField("computed", node1, node2, state);
  20266. }
  20267. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitMemberExpression", this).call(this, node1, node2, state, path);
  20268. }
  20269. }, {
  20270. key: "visitComprehensionBlock",
  20271. value: function visitComprehensionBlock(node1, node2, state, path) {
  20272. // node1.each has a specific type that is boolean
  20273. if (node1.each) {
  20274. this.compareField("each", node1, node2, state);
  20275. }
  20276. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitComprehensionBlock", this).call(this, node1, node2, state, path);
  20277. }
  20278. }, {
  20279. key: "visitIdentifier",
  20280. value: function visitIdentifier(node1, node2, state, path) {
  20281. // node1.name has a specific type that is string
  20282. this.compareField("name", node1, node2, state);
  20283. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitIdentifier", this).call(this, node1, node2, state, path);
  20284. }
  20285. }, {
  20286. key: "visitLiteral",
  20287. value: function visitLiteral(node1, node2, state, path) {
  20288. this.compareField("value", node1, node2, state);
  20289. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitLiteral", this).call(this, node1, node2, state, path);
  20290. }
  20291. }, {
  20292. key: "visitClassDeclaration",
  20293. value: function visitClassDeclaration(node1, node2, state, path) {
  20294. this.compareField("id", node1, node2, state);
  20295. if (node1.superClass) {
  20296. this.compareField("superClass", node1, node2, state);
  20297. }
  20298. this.compareField("body", node1, node2, state);
  20299. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitClassDeclaration", this).call(this, node1, node2, state, path);
  20300. }
  20301. }, {
  20302. key: "visitClassBody",
  20303. value: function visitClassBody(node1, node2, state, path) {
  20304. this.compareField("body", node1, node2, state);
  20305. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitClassBody", this).call(this, node1, node2, state, path);
  20306. }
  20307. }, {
  20308. key: "visitMethodDefinition",
  20309. value: function visitMethodDefinition(node1, node2, state, path) {
  20310. this.compareField("static", node1, node2, state);
  20311. this.compareField("computed", node1, node2, state);
  20312. this.compareField("kind", node1, node2, state);
  20313. this.compareField("key", node1, node2, state);
  20314. this.compareField("value", node1, node2, state);
  20315. return get(ComparisonVisitor.prototype.__proto__ || Object.getPrototypeOf(ComparisonVisitor.prototype), "visitMethodDefinition", this).call(this, node1, node2, state, path);
  20316. }
  20317. }]);
  20318. return ComparisonVisitor;
  20319. }(Visitor);
  20320. var ScopeVisitor = function (_Visitor3) {
  20321. inherits(ScopeVisitor, _Visitor3);
  20322. function ScopeVisitor() {
  20323. classCallCheck(this, ScopeVisitor);
  20324. return possibleConstructorReturn(this, (ScopeVisitor.__proto__ || Object.getPrototypeOf(ScopeVisitor)).apply(this, arguments));
  20325. }
  20326. createClass(ScopeVisitor, [{
  20327. key: "newScope",
  20328. value: function newScope(scopeNode, parentScope) {
  20329. var scope = {
  20330. node: scopeNode,
  20331. varDecls: [],
  20332. varDeclPaths: [],
  20333. funcDecls: [],
  20334. funcDeclPaths: [],
  20335. classDecls: [],
  20336. classDeclPaths: [],
  20337. classExprs: [],
  20338. classExprPaths: [],
  20339. methodDecls: [],
  20340. methodDeclPaths: [],
  20341. importSpecifiers: [],
  20342. importSpecifierPaths: [],
  20343. exportDecls: [],
  20344. exportDeclPaths: [],
  20345. refs: [],
  20346. thisRefs: [],
  20347. params: [],
  20348. catches: [],
  20349. subScopes: [],
  20350. resolvedRefMap: new Map()
  20351. };
  20352. if (parentScope) parentScope.subScopes.push(scope);
  20353. return scope;
  20354. }
  20355. }, {
  20356. key: "visitVariableDeclaration",
  20357. value: function visitVariableDeclaration(node, scope, path) {
  20358. scope.varDecls.push(node);
  20359. scope.varDeclPaths.push(path);
  20360. return get(ScopeVisitor.prototype.__proto__ || Object.getPrototypeOf(ScopeVisitor.prototype), "visitVariableDeclaration", this).call(this, node, scope, path);
  20361. }
  20362. }, {
  20363. key: "visitVariableDeclarator",
  20364. value: function visitVariableDeclarator(node, scope, path) {
  20365. var visitor = this;
  20366. // ignore id
  20367. // // id is of types Pattern
  20368. // node["id"] = visitor.accept(node["id"], scope, path.concat(["id"]));
  20369. // init is of types Expression
  20370. if (node["init"]) {
  20371. node["init"] = visitor.accept(node["init"], scope, path.concat(["init"]));
  20372. }
  20373. return node;
  20374. }
  20375. }, {
  20376. key: "visitFunction",
  20377. value: function visitFunction(node, scope, path) {
  20378. var visitor = this;
  20379. var newScope = this.newScope(node, scope);
  20380. // AssignmentPattern = default params
  20381. // only visit the right side of a default param, we track the declarations
  20382. // in newScope.params specificially
  20383. node.params.forEach(function (param, i) {
  20384. if (param.type === "AssignmentPattern") visitor.accept(param.right, newScope, path.concat("params", i, "right"));
  20385. });
  20386. newScope.params = Array.prototype.slice.call(node.params);
  20387. return newScope;
  20388. }
  20389. }, {
  20390. key: "visitFunctionDeclaration",
  20391. value: function visitFunctionDeclaration(node, scope, path) {
  20392. var newScope = this.visitFunction(node, scope, path);
  20393. scope.funcDecls.push(node);
  20394. scope.funcDeclPaths.push(path);
  20395. // don't visit id and params
  20396. var visitor = this;
  20397. if (node.defaults) {
  20398. node["defaults"] = node["defaults"].reduce(function (results, ea, i) {
  20399. var result = visitor.accept(ea, newScope, path.concat(["defaults", i]));
  20400. if (Array.isArray(result)) results.push.apply(results, result);else results.push(result);
  20401. return results;
  20402. }, []);
  20403. }
  20404. if (node.rest) {
  20405. node["rest"] = visitor.accept(node["rest"], newScope, path.concat(["rest"]));
  20406. }
  20407. node["body"] = visitor.accept(node["body"], newScope, path.concat(["body"]));
  20408. // loc is of types SourceLocation
  20409. if (node["loc"]) {
  20410. node["loc"] = visitor.accept(node["loc"], newScope, path.concat(["loc"]));
  20411. }
  20412. return node;
  20413. }
  20414. }, {
  20415. key: "visitFunctionExpression",
  20416. value: function visitFunctionExpression(node, scope, path) {
  20417. var newScope = this.visitFunction(node, scope, path);
  20418. // don't visit id and params
  20419. var visitor = this;
  20420. if (node.defaults) {
  20421. node["defaults"] = node["defaults"].reduce(function (results, ea, i) {
  20422. var result = visitor.accept(ea, newScope, path.concat(["defaults", i]));
  20423. if (Array.isArray(result)) results.push.apply(results, result);else results.push(result);
  20424. return results;
  20425. }, []);
  20426. }
  20427. if (node.rest) {
  20428. node["rest"] = visitor.accept(node["rest"], newScope, path.concat(["rest"]));
  20429. }
  20430. node["body"] = visitor.accept(node["body"], newScope, path.concat(["body"]));
  20431. // loc is of types SourceLocation
  20432. if (node["loc"]) {
  20433. node["loc"] = visitor.accept(node["loc"], newScope, path.concat(["loc"]));
  20434. }
  20435. return node;
  20436. }
  20437. }, {
  20438. key: "visitArrowFunctionExpression",
  20439. value: function visitArrowFunctionExpression(node, scope, path) {
  20440. var newScope = this.visitFunction(node, scope, path);
  20441. var visitor = this;
  20442. if (node.defaults) {
  20443. node["defaults"] = node["defaults"].reduce(function (results, ea, i) {
  20444. var result = visitor.accept(ea, newScope, path.concat(["defaults", i]));
  20445. if (Array.isArray(result)) results.push.apply(results, result);else results.push(result);
  20446. return results;
  20447. }, []);
  20448. }
  20449. if (node.rest) {
  20450. node["rest"] = visitor.accept(node["rest"], newScope, path.concat(["rest"]));
  20451. }
  20452. // body is of types BlockStatement, Expression
  20453. node["body"] = visitor.accept(node["body"], newScope, path.concat(["body"]));
  20454. // loc is of types SourceLocation
  20455. if (node["loc"]) {
  20456. node["loc"] = visitor.accept(node["loc"], newScope, path.concat(["loc"]));
  20457. }
  20458. // node.generator has a specific type that is boolean
  20459. if (node.generator) {} /*do stuff*/
  20460. // node.expression has a specific type that is boolean
  20461. if (node.expression) {/*do stuff*/}
  20462. return node;
  20463. }
  20464. }, {
  20465. key: "visitIdentifier",
  20466. value: function visitIdentifier(node, scope, path) {
  20467. scope.refs.push(node);
  20468. return get(ScopeVisitor.prototype.__proto__ || Object.getPrototypeOf(ScopeVisitor.prototype), "visitIdentifier", this).call(this, node, scope, path);
  20469. }
  20470. }, {
  20471. key: "visitMemberExpression",
  20472. value: function visitMemberExpression(node, scope, path) {
  20473. // only visit property part when prop is computed so we don't gather
  20474. // prop ids
  20475. var visitor = this;
  20476. // object is of types Expression, Super
  20477. node["object"] = visitor.accept(node["object"], scope, path.concat(["object"]));
  20478. // property is of types Expression
  20479. if (node.computed) {
  20480. node["property"] = visitor.accept(node["property"], scope, path.concat(["property"]));
  20481. }
  20482. return node;
  20483. }
  20484. }, {
  20485. key: "visitProperty",
  20486. value: function visitProperty(node, scope, path) {
  20487. var visitor = this;
  20488. // key is of types Expression
  20489. if (node.computed) node["key"] = visitor.accept(node["key"], scope, path.concat(["key"]));
  20490. // value is of types Expression
  20491. node["value"] = visitor.accept(node["value"], scope, path.concat(["value"]));
  20492. return node;
  20493. }
  20494. }, {
  20495. key: "visitThisExpression",
  20496. value: function visitThisExpression(node, scope, path) {
  20497. scope.thisRefs.push(node);
  20498. return get(ScopeVisitor.prototype.__proto__ || Object.getPrototypeOf(ScopeVisitor.prototype), "visitThisExpression", this).call(this, node, scope, path);
  20499. }
  20500. }, {
  20501. key: "visitTryStatement",
  20502. value: function visitTryStatement(node, scope, path) {
  20503. var visitor = this;
  20504. // block is of types BlockStatement
  20505. node["block"] = visitor.accept(node["block"], scope, path.concat(["block"]));
  20506. // handler is of types CatchClause
  20507. if (node["handler"]) {
  20508. node["handler"] = visitor.accept(node["handler"], scope, path.concat(["handler"]));
  20509. scope.catches.push(node.handler.param);
  20510. }
  20511. // finalizer is of types BlockStatement
  20512. if (node["finalizer"]) {
  20513. node["finalizer"] = visitor.accept(node["finalizer"], scope, path.concat(["finalizer"]));
  20514. }
  20515. return node;
  20516. }
  20517. }, {
  20518. key: "visitLabeledStatement",
  20519. value: function visitLabeledStatement(node, scope, path) {
  20520. var visitor = this;
  20521. // ignore label
  20522. // // label is of types Identifier
  20523. // node["label"] = visitor.accept(node["label"], scope, path.concat(["label"]));
  20524. // body is of types Statement
  20525. node["body"] = visitor.accept(node["body"], scope, path.concat(["body"]));
  20526. return node;
  20527. }
  20528. }, {
  20529. key: "visitClassDeclaration",
  20530. value: function visitClassDeclaration(node, scope, path) {
  20531. scope.classDecls.push(node);
  20532. scope.classDeclPaths.push(path);
  20533. var visitor = this;
  20534. // ignore id
  20535. // // id is of types Identifier
  20536. // node["id"] = visitor.accept(node["id"], scope, path.concat(["id"]));
  20537. // superClass is of types Expression
  20538. if (node["superClass"]) {
  20539. node["superClass"] = visitor.accept(node["superClass"], scope, path.concat(["superClass"]));
  20540. }
  20541. // body is of types ClassBody
  20542. node["body"] = visitor.accept(node["body"], scope, path.concat(["body"]));
  20543. return node;
  20544. }
  20545. }, {
  20546. key: "visitClassExpression",
  20547. value: function visitClassExpression(node, scope, path) {
  20548. if (node.id) {
  20549. scope.classExprs.push(node);
  20550. scope.classExprPaths.push(path);
  20551. }
  20552. var visitor = this;
  20553. // ignore id
  20554. // // id is of types Identifier
  20555. // node["id"] = visitor.accept(node["id"], scope, path.concat(["id"]));
  20556. // superClass is of types Expression
  20557. if (node["superClass"]) {
  20558. node["superClass"] = visitor.accept(node["superClass"], scope, path.concat(["superClass"]));
  20559. }
  20560. // body is of types ClassBody
  20561. node["body"] = visitor.accept(node["body"], scope, path.concat(["body"]));
  20562. return node;
  20563. }
  20564. }, {
  20565. key: "visitMethodDefinition",
  20566. value: function visitMethodDefinition(node, scope, path) {
  20567. var visitor = this;
  20568. // don't visit key Identifier for now
  20569. // // key is of types Expression
  20570. // node["key"] = visitor.accept(node["key"], scope, path.concat(["key"]));
  20571. // value is of types FunctionExpression
  20572. node["value"] = visitor.accept(node["value"], scope, path.concat(["value"]));
  20573. return node;
  20574. }
  20575. }, {
  20576. key: "visitMetaProperty",
  20577. value: function visitMetaProperty(node, scope, path) {
  20578. // this is the new.target thing
  20579. var visitor = this;
  20580. // node['meta'] = visitor.accept(node['meta'], scope, path.concat(['meta']));
  20581. // node['property'] = visitor.accept(node['property'],scope, path.concat(['property']));
  20582. return node;
  20583. }
  20584. }, {
  20585. key: "visitBreakStatement",
  20586. value: function visitBreakStatement(node, scope, path) {
  20587. return node;
  20588. }
  20589. }, {
  20590. key: "visitContinueStatement",
  20591. value: function visitContinueStatement(node, scope, path) {
  20592. return node;
  20593. }
  20594. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  20595. // es6 modules
  20596. }, {
  20597. key: "visitImportSpecifier",
  20598. value: function visitImportSpecifier(node, scope, path) {
  20599. scope.importSpecifiers.push(node.local);
  20600. scope.importSpecifierPaths.push(path);
  20601. var visitor = this;
  20602. // imported is of types Identifier
  20603. // node["imported"] = visitor.accept(node["imported"], scope, path.concat(["imported"]));
  20604. // local is of types Identifier
  20605. // node["local"] = visitor.accept(node["local"], scope, path.concat(["local"]));
  20606. return node;
  20607. }
  20608. }, {
  20609. key: "visitImportDefaultSpecifier",
  20610. value: function visitImportDefaultSpecifier(node, scope, path) {
  20611. scope.importSpecifiers.push(node.local);
  20612. scope.importSpecifierPaths.push(path);
  20613. var visitor = this;
  20614. // // local is of types Identifier
  20615. // node["local"] = visitor.accept(node["local"], scope, path.concat(["local"]));
  20616. return node;
  20617. }
  20618. }, {
  20619. key: "visitImportNamespaceSpecifier",
  20620. value: function visitImportNamespaceSpecifier(node, scope, path) {
  20621. scope.importSpecifiers.push(node.local);
  20622. scope.importSpecifierPaths.push(path);
  20623. var visitor = this;
  20624. // // local is of types Identifier
  20625. // node["local"] = visitor.accept(node["local"], scope, path.concat(["local"]));
  20626. return node;
  20627. }
  20628. }, {
  20629. key: "visitExportSpecifier",
  20630. value: function visitExportSpecifier(node, scope, path) {
  20631. var visitor = this;
  20632. // // exported is of types Identifier
  20633. // node["exported"] = visitor.accept(node["exported"], scope, path.concat(["exported"]));
  20634. // local is of types Identifier
  20635. node["local"] = visitor.accept(node["local"], scope, path.concat(["local"]));
  20636. return node;
  20637. }
  20638. }, {
  20639. key: "visitExportNamedDeclaration",
  20640. value: function visitExportNamedDeclaration(node, scope, path) {
  20641. scope.exportDecls.push(node);
  20642. scope.exportDeclPaths.push(path);
  20643. // only descend if it's not an export {...} from "..."
  20644. if (!node.source) get(ScopeVisitor.prototype.__proto__ || Object.getPrototypeOf(ScopeVisitor.prototype), "visitExportNamedDeclaration", this).call(this, node, scope, path);
  20645. return node;
  20646. }
  20647. }, {
  20648. key: "visitExportDefaultDeclaration",
  20649. value: function visitExportDefaultDeclaration(node, scope, path) {
  20650. scope.exportDecls.push(node);
  20651. scope.exportDeclPaths.push(path);
  20652. return get(ScopeVisitor.prototype.__proto__ || Object.getPrototypeOf(ScopeVisitor.prototype), "visitExportDefaultDeclaration", this).call(this, node, scope, path);
  20653. }
  20654. }, {
  20655. key: "visitExportAllDeclaration",
  20656. value: function visitExportAllDeclaration(node, scope, path) {
  20657. scope.exportDecls.push(node);
  20658. scope.exportDeclPaths.push(path);
  20659. return get(ScopeVisitor.prototype.__proto__ || Object.getPrototypeOf(ScopeVisitor.prototype), "visitExportAllDeclaration", this).call(this, node, scope, path);
  20660. }
  20661. }]);
  20662. return ScopeVisitor;
  20663. }(Visitor);
  20664. var es = escodegen.escodegen || escodegen;
  20665. function stringify(node) {
  20666. var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  20667. var optsIndent = opts && opts.format && opts.format.indent || {};
  20668. var indent = {
  20669. style: " ",
  20670. base: 0,
  20671. adjustMultilineComment: false,
  20672. optsIndent: optsIndent
  20673. };
  20674. var optsFormat = opts && opts.format || {};
  20675. var format = _extends({
  20676. indent: indent,
  20677. quotes: "double"
  20678. }, lively_lang.obj.dissoc(optsFormat, ["indent"]));
  20679. opts = _extends({
  20680. format: format,
  20681. comment: false
  20682. }, lively_lang.obj.dissoc(opts, ["format"]));
  20683. return es.generate(node, opts);
  20684. }
  20685. /*global acorn*/
  20686. var walk = acorn.walk;
  20687. var loose = acorn.loose;
  20688. // rk 2016-05-17 FIXME: the current version of acorn.walk doesn't support async
  20689. // await. We patch the walker here until it does
  20690. if (!walk.base.AwaitExpression) {
  20691. walk.base.AwaitExpression = function (node, st, c) {
  20692. if (node.argument) c(node.argument, st, 'Expression');
  20693. };
  20694. }
  20695. // FIXME, don't add to walk object, that's our own stuff!
  20696. walk.forEachNode = forEachNode;
  20697. walk.matchNodes = matchNodes;
  20698. walk.findNodesIncluding = findNodesIncluding;
  20699. walk.withParentInfo = withParentInfo;
  20700. walk.copy = copy;
  20701. walk.findSiblings = findSiblings;
  20702. walk.findNodeByAstIndex = findNodeByAstIndex;
  20703. walk.findStatementOfNode = findStatementOfNode;
  20704. walk.addAstIndex = addAstIndex;
  20705. // -=-=-=-=-=-=-=-=-=-=-=-
  20706. // from lively.ast.acorn
  20707. // -=-=-=-=-=-=-=-=-=-=-=-
  20708. function forEachNode(parsed, func, state, options) {
  20709. // note: func can get called with the same node for different
  20710. // visitor callbacks!
  20711. // func args: node, state, depth, type
  20712. options = options || {};
  20713. var traversal = options.traversal || 'preorder'; // also: postorder
  20714. var visitors = lively_lang.obj.clone(options.visitors ? options.visitors : walk.make(walk.visitors.withMemberExpression));
  20715. var iterator = traversal === 'preorder' ? function (orig, type, node, depth, cont) {
  20716. func(node, state, depth, type);return orig(node, depth + 1, cont);
  20717. } : function (orig, type, node, depth, cont) {
  20718. var result = orig(node, depth + 1, cont);func(node, state, depth, type);return result;
  20719. };
  20720. Object.keys(visitors).forEach(function (type) {
  20721. var orig = visitors[type];
  20722. visitors[type] = function (node, depth, cont) {
  20723. return iterator(orig, type, node, depth, cont);
  20724. };
  20725. });
  20726. walk.recursive(parsed, 0, null, visitors);
  20727. return parsed;
  20728. }
  20729. function matchNodes(parsed, visitor, state, options) {
  20730. function visit(node, state, depth, type) {
  20731. if (visitor[node.type]) visitor[node.type](node, state, depth, type);
  20732. }
  20733. return forEachNode(parsed, visit, state, options);
  20734. }
  20735. // findNodesIncluding: function(ast, pos, test, base) {
  20736. // var nodes = [];
  20737. // base = base || acorn.walk.make({});
  20738. // Object.keys(base).forEach(function(name) {
  20739. // var orig = base[name];
  20740. // base[name] = function(node, state, cont) {
  20741. // nodes.pushIfNotIncluded(node);
  20742. // return orig(node, state, cont);
  20743. // }
  20744. // });
  20745. // acorn.walk.findNodeAround(ast, pos, test, base);
  20746. // return nodes;
  20747. // }
  20748. function findNodesIncluding(parsed, pos, test, base) {
  20749. var nodes = [];
  20750. base = base || walk.make(walk.visitors.withMemberExpression);
  20751. Object.keys(walk.base).forEach(function (name) {
  20752. var orig = base[name];
  20753. base[name] = function (node, state, cont) {
  20754. lively_lang.arr.pushIfNotIncluded(nodes, node);
  20755. return orig(node, state, cont);
  20756. };
  20757. });
  20758. base["Property"] = function (node, st, c) {
  20759. lively_lang.arr.pushIfNotIncluded(nodes, node);
  20760. c(node.key, st, "Expression");
  20761. c(node.value, st, "Expression");
  20762. };
  20763. base["LabeledStatement"] = function (node, st, c) {
  20764. node.label && c(node.label, st, "Expression");
  20765. c(node.body, st, "Statement");
  20766. };
  20767. walk.findNodeAround(parsed, pos, test, base);
  20768. return nodes;
  20769. }
  20770. function withParentInfo(parsed, iterator, options) {
  20771. // options = {visitAllNodes: BOOL}
  20772. options = options || {};
  20773. function makeScope(parentScope) {
  20774. var scope = { id: lively_lang.string.newUUID(), parentScope: parentScope, containingScopes: [] };
  20775. parentScope && parentScope.containingScopes.push(scope);
  20776. return scope;
  20777. }
  20778. var visitors = walk.make({
  20779. Function: function Function(node, st, c) {
  20780. if (st && st.scope) st.scope = makeScope(st.scope);
  20781. c(node.body, st, "ScopeBody");
  20782. },
  20783. VariableDeclarator: function VariableDeclarator(node, st, c) {
  20784. // node.id && c(node.id, st, 'Identifier');
  20785. node.init && c(node.init, st, 'Expression');
  20786. },
  20787. VariableDeclaration: function VariableDeclaration(node, st, c) {
  20788. for (var i = 0; i < node.declarations.length; ++i) {
  20789. var decl = node.declarations[i];
  20790. if (decl) c(decl, st, "VariableDeclarator");
  20791. }
  20792. },
  20793. ObjectExpression: function ObjectExpression(node, st, c) {
  20794. for (var i = 0; i < node.properties.length; ++i) {
  20795. var prop = node.properties[i];
  20796. c(prop.key, st, "Expression");
  20797. c(prop.value, st, "Expression");
  20798. }
  20799. },
  20800. MemberExpression: function MemberExpression(node, st, c) {
  20801. c(node.object, st, "Expression");
  20802. c(node.property, st, "Expression");
  20803. }
  20804. }, walk.base);
  20805. var lastActiveProp,
  20806. getters = [];
  20807. forEachNode(parsed, function (node) {
  20808. lively_lang.arr.withoutAll(Object.keys(node), ['end', 'start', 'type', 'source', 'raw']).forEach(function (propName) {
  20809. if (node.__lookupGetter__(propName)) return; // already defined
  20810. var val = node[propName];
  20811. node.__defineGetter__(propName, function () {
  20812. lastActiveProp = propName;return val;
  20813. });
  20814. getters.push([node, propName, node[propName]]);
  20815. });
  20816. }, null, { visitors: visitors });
  20817. var result = [];
  20818. Object.keys(visitors).forEach(function (type) {
  20819. var orig = visitors[type];
  20820. visitors[type] = function (node, state, cont) {
  20821. if (type === node.type || options.visitAllNodes) {
  20822. result.push(iterator.call(null, node, { scope: state.scope, depth: state.depth, parent: state.parent, type: type, propertyInParent: lastActiveProp }));
  20823. return orig(node, { scope: state.scope, parent: node, depth: state.depth + 1 }, cont);
  20824. } else {
  20825. return orig(node, state, cont);
  20826. }
  20827. };
  20828. });
  20829. walk.recursive(parsed, { scope: makeScope(), parent: null, propertyInParent: '', depth: 0 }, null, visitors);
  20830. getters.forEach(function (nodeNameVal) {
  20831. delete nodeNameVal[0][nodeNameVal[1]];
  20832. nodeNameVal[0][nodeNameVal[1]] = nodeNameVal[2];
  20833. });
  20834. return result;
  20835. }
  20836. function copy(ast, override) {
  20837. var visitors = lively_lang.obj.extend({
  20838. Program: function Program(n, c) {
  20839. return {
  20840. start: n.start, end: n.end, type: 'Program',
  20841. body: n.body.map(c),
  20842. source: n.source, astIndex: n.astIndex
  20843. };
  20844. },
  20845. FunctionDeclaration: function FunctionDeclaration(n, c) {
  20846. return {
  20847. start: n.start, end: n.end, type: 'FunctionDeclaration',
  20848. id: c(n.id), params: n.params.map(c), body: c(n.body),
  20849. source: n.source, astIndex: n.astIndex
  20850. };
  20851. },
  20852. BlockStatement: function BlockStatement(n, c) {
  20853. return {
  20854. start: n.start, end: n.end, type: 'BlockStatement',
  20855. body: n.body.map(c),
  20856. source: n.source, astIndex: n.astIndex
  20857. };
  20858. },
  20859. ExpressionStatement: function ExpressionStatement(n, c) {
  20860. return {
  20861. start: n.start, end: n.end, type: 'ExpressionStatement',
  20862. expression: c(n.expression),
  20863. source: n.source, astIndex: n.astIndex
  20864. };
  20865. },
  20866. CallExpression: function CallExpression(n, c) {
  20867. return {
  20868. start: n.start, end: n.end, type: 'CallExpression',
  20869. callee: c(n.callee), arguments: n.arguments.map(c),
  20870. source: n.source, astIndex: n.astIndex
  20871. };
  20872. },
  20873. MemberExpression: function MemberExpression(n, c) {
  20874. return {
  20875. start: n.start, end: n.end, type: 'MemberExpression',
  20876. object: c(n.object), property: c(n.property), computed: n.computed,
  20877. source: n.source, astIndex: n.astIndex
  20878. };
  20879. },
  20880. NewExpression: function NewExpression(n, c) {
  20881. return {
  20882. start: n.start, end: n.end, type: 'NewExpression',
  20883. callee: c(n.callee), arguments: n.arguments.map(c),
  20884. source: n.source, astIndex: n.astIndex
  20885. };
  20886. },
  20887. VariableDeclaration: function VariableDeclaration(n, c) {
  20888. return {
  20889. start: n.start, end: n.end, type: 'VariableDeclaration',
  20890. declarations: n.declarations.map(c), kind: n.kind,
  20891. source: n.source, astIndex: n.astIndex
  20892. };
  20893. },
  20894. VariableDeclarator: function VariableDeclarator(n, c) {
  20895. return {
  20896. start: n.start, end: n.end, type: 'VariableDeclarator',
  20897. id: c(n.id), init: c(n.init),
  20898. source: n.source, astIndex: n.astIndex
  20899. };
  20900. },
  20901. FunctionExpression: function FunctionExpression(n, c) {
  20902. return {
  20903. start: n.start, end: n.end, type: 'FunctionExpression',
  20904. id: c(n.id), params: n.params.map(c), body: c(n.body),
  20905. source: n.source, astIndex: n.astIndex
  20906. };
  20907. },
  20908. IfStatement: function IfStatement(n, c) {
  20909. return {
  20910. start: n.start, end: n.end, type: 'IfStatement',
  20911. test: c(n.test), consequent: c(n.consequent),
  20912. alternate: c(n.alternate),
  20913. source: n.source, astIndex: n.astIndex
  20914. };
  20915. },
  20916. ConditionalExpression: function ConditionalExpression(n, c) {
  20917. return {
  20918. start: n.start, end: n.end, type: 'ConditionalExpression',
  20919. test: c(n.test), consequent: c(n.consequent),
  20920. alternate: c(n.alternate),
  20921. source: n.source, astIndex: n.astIndex
  20922. };
  20923. },
  20924. SwitchStatement: function SwitchStatement(n, c) {
  20925. return {
  20926. start: n.start, end: n.end, type: 'SwitchStatement',
  20927. discriminant: c(n.discriminant), cases: n.cases.map(c),
  20928. source: n.source, astIndex: n.astIndex
  20929. };
  20930. },
  20931. SwitchCase: function SwitchCase(n, c) {
  20932. return {
  20933. start: n.start, end: n.end, type: 'SwitchCase',
  20934. test: c(n.test), consequent: n.consequent.map(c),
  20935. source: n.source, astIndex: n.astIndex
  20936. };
  20937. },
  20938. BreakStatement: function BreakStatement(n, c) {
  20939. return {
  20940. start: n.start, end: n.end, type: 'BreakStatement',
  20941. label: n.label,
  20942. source: n.source, astIndex: n.astIndex
  20943. };
  20944. },
  20945. ContinueStatement: function ContinueStatement(n, c) {
  20946. return {
  20947. start: n.start, end: n.end, type: 'ContinueStatement',
  20948. label: n.label,
  20949. source: n.source, astIndex: n.astIndex
  20950. };
  20951. },
  20952. TryStatement: function TryStatement(n, c) {
  20953. return {
  20954. start: n.start, end: n.end, type: 'TryStatement',
  20955. block: c(n.block), handler: c(n.handler), finalizer: c(n.finalizer),
  20956. guardedHandlers: n.guardedHandlers.map(c),
  20957. source: n.source, astIndex: n.astIndex
  20958. };
  20959. },
  20960. CatchClause: function CatchClause(n, c) {
  20961. return {
  20962. start: n.start, end: n.end, type: 'CatchClause',
  20963. param: c(n.param), guard: c(n.guard), body: c(n.body),
  20964. source: n.source, astIndex: n.astIndex
  20965. };
  20966. },
  20967. ThrowStatement: function ThrowStatement(n, c) {
  20968. return {
  20969. start: n.start, end: n.end, type: 'ThrowStatement',
  20970. argument: c(n.argument),
  20971. source: n.source, astIndex: n.astIndex
  20972. };
  20973. },
  20974. ForStatement: function ForStatement(n, c) {
  20975. return {
  20976. start: n.start, end: n.end, type: 'ForStatement',
  20977. init: c(n.init), test: c(n.test), update: c(n.update),
  20978. body: c(n.body),
  20979. source: n.source, astIndex: n.astIndex
  20980. };
  20981. },
  20982. ForInStatement: function ForInStatement(n, c) {
  20983. return {
  20984. start: n.start, end: n.end, type: 'ForInStatement',
  20985. left: c(n.left), right: c(n.right), body: c(n.body),
  20986. source: n.source, astIndex: n.astIndex
  20987. };
  20988. },
  20989. WhileStatement: function WhileStatement(n, c) {
  20990. return {
  20991. start: n.start, end: n.end, type: 'WhileStatement',
  20992. test: c(n.test), body: c(n.body),
  20993. source: n.source, astIndex: n.astIndex
  20994. };
  20995. },
  20996. DoWhileStatement: function DoWhileStatement(n, c) {
  20997. return {
  20998. start: n.start, end: n.end, type: 'DoWhileStatement',
  20999. test: c(n.test), body: c(n.body),
  21000. source: n.source, astIndex: n.astIndex
  21001. };
  21002. },
  21003. WithStatement: function WithStatement(n, c) {
  21004. return {
  21005. start: n.start, end: n.end, type: 'WithStatement',
  21006. object: c(n.object), body: c(n.body),
  21007. source: n.source, astIndex: n.astIndex
  21008. };
  21009. },
  21010. UnaryExpression: function UnaryExpression(n, c) {
  21011. return {
  21012. start: n.start, end: n.end, type: 'UnaryExpression',
  21013. argument: c(n.argument), operator: n.operator, prefix: n.prefix,
  21014. source: n.source, astIndex: n.astIndex
  21015. };
  21016. },
  21017. BinaryExpression: function BinaryExpression(n, c) {
  21018. return {
  21019. start: n.start, end: n.end, type: 'BinaryExpression',
  21020. left: c(n.left), operator: n.operator, right: c(n.right),
  21021. source: n.source, astIndex: n.astIndex
  21022. };
  21023. },
  21024. LogicalExpression: function LogicalExpression(n, c) {
  21025. return {
  21026. start: n.start, end: n.end, type: 'LogicalExpression',
  21027. left: c(n.left), operator: n.operator, right: c(n.right),
  21028. source: n.source, astIndex: n.astIndex
  21029. };
  21030. },
  21031. AssignmentExpression: function AssignmentExpression(n, c) {
  21032. return {
  21033. start: n.start, end: n.end, type: 'AssignmentExpression',
  21034. left: c(n.left), operator: n.operator, right: c(n.right),
  21035. source: n.source, astIndex: n.astIndex
  21036. };
  21037. },
  21038. UpdateExpression: function UpdateExpression(n, c) {
  21039. return {
  21040. start: n.start, end: n.end, type: 'UpdateExpression',
  21041. argument: c(n.argument), operator: n.operator, prefix: n.prefix,
  21042. source: n.source, astIndex: n.astIndex
  21043. };
  21044. },
  21045. ReturnStatement: function ReturnStatement(n, c) {
  21046. return {
  21047. start: n.start, end: n.end, type: 'ReturnStatement',
  21048. argument: c(n.argument),
  21049. source: n.source, astIndex: n.astIndex
  21050. };
  21051. },
  21052. Identifier: function Identifier(n, c) {
  21053. return {
  21054. start: n.start, end: n.end, type: 'Identifier',
  21055. name: n.name,
  21056. source: n.source, astIndex: n.astIndex
  21057. };
  21058. },
  21059. Literal: function Literal(n, c) {
  21060. return {
  21061. start: n.start, end: n.end, type: 'Literal',
  21062. value: n.value, raw: n.raw /* Acorn-specific */
  21063. , source: n.source, astIndex: n.astIndex
  21064. };
  21065. },
  21066. ObjectExpression: function ObjectExpression(n, c) {
  21067. return {
  21068. start: n.start, end: n.end, type: 'ObjectExpression',
  21069. properties: n.properties.map(function (prop) {
  21070. return {
  21071. key: c(prop.key), value: c(prop.value), kind: prop.kind
  21072. };
  21073. }),
  21074. source: n.source, astIndex: n.astIndex
  21075. };
  21076. },
  21077. ArrayExpression: function ArrayExpression(n, c) {
  21078. return {
  21079. start: n.start, end: n.end, type: 'ArrayExpression',
  21080. elements: n.elements.map(c),
  21081. source: n.source, astIndex: n.astIndex
  21082. };
  21083. },
  21084. SequenceExpression: function SequenceExpression(n, c) {
  21085. return {
  21086. start: n.start, end: n.end, type: 'SequenceExpression',
  21087. expressions: n.expressions.map(c),
  21088. source: n.source, astIndex: n.astIndex
  21089. };
  21090. },
  21091. EmptyStatement: function EmptyStatement(n, c) {
  21092. return {
  21093. start: n.start, end: n.end, type: 'EmptyStatement',
  21094. source: n.source, astIndex: n.astIndex
  21095. };
  21096. },
  21097. ThisExpression: function ThisExpression(n, c) {
  21098. return {
  21099. start: n.start, end: n.end, type: 'ThisExpression',
  21100. source: n.source, astIndex: n.astIndex
  21101. };
  21102. },
  21103. DebuggerStatement: function DebuggerStatement(n, c) {
  21104. return {
  21105. start: n.start, end: n.end, type: 'DebuggerStatement',
  21106. source: n.source, astIndex: n.astIndex
  21107. };
  21108. },
  21109. LabeledStatement: function LabeledStatement(n, c) {
  21110. return {
  21111. start: n.start, end: n.end, type: 'LabeledStatement',
  21112. label: n.label, body: c(n.body),
  21113. source: n.source, astIndex: n.astIndex
  21114. };
  21115. }
  21116. }, override || {});
  21117. function c(node) {
  21118. if (node === null) return null;
  21119. return visitors[node.type](node, c);
  21120. }
  21121. return c(ast);
  21122. }
  21123. function findSiblings(parsed, node, beforeOrAfter) {
  21124. if (!node) return [];
  21125. var nodes = findNodesIncluding(parsed, node.start),
  21126. idx = nodes.indexOf(node),
  21127. parents = nodes.slice(0, idx),
  21128. parentWithBody = lively_lang.arr.detect(parents.reverse(), function (p) {
  21129. return Array.isArray(p.body);
  21130. }),
  21131. siblingsWithNode = parentWithBody.body;
  21132. if (!beforeOrAfter) return lively_lang.arr.without(siblingsWithNode, node);
  21133. var nodeIdxInSiblings = siblingsWithNode.indexOf(node);
  21134. return beforeOrAfter === 'before' ? siblingsWithNode.slice(0, nodeIdxInSiblings) : siblingsWithNode.slice(nodeIdxInSiblings + 1);
  21135. }
  21136. // // cached visitors that are used often
  21137. walk.visitors = {
  21138. stopAtFunctions: walk.make({
  21139. 'Function': function Function() {/* stop descent */}
  21140. }, walk.base),
  21141. withMemberExpression: walk.make({
  21142. MemberExpression: function MemberExpression(node, st, c) {
  21143. c(node.object, st, "Expression");
  21144. c(node.property, st, "Expression");
  21145. }
  21146. }, walk.base)
  21147. // -=-=-=-=-=-=-=-=-=-=-=-=-=-
  21148. // from lively.ast.AstHelper
  21149. // -=-=-=-=-=-=-=-=-=-=-=-=-=-
  21150. };function findNodeByAstIndex(parsed, astIndexToFind, addIndex) {
  21151. addIndex = addIndex == null ? true : !!addIndex;
  21152. if (!parsed.astIndex && addIndex) addAstIndex(parsed);
  21153. // we need to visit every node, forEachNode is highly
  21154. // inefficient, the compilled Mozilla visitors are a better fit
  21155. var found = null;
  21156. withMozillaAstDo(parsed, null, function (next, node, state) {
  21157. if (found) return;
  21158. var idx = node.astIndex;
  21159. if (idx < astIndexToFind) return;
  21160. if (node.astIndex === astIndexToFind) {
  21161. found = node;return;
  21162. }
  21163. next();
  21164. });
  21165. return found;
  21166. }
  21167. // FIXME: global (and temporary) findNodeByAstIndex is used by __getClosure and defined in Rewriting.js
  21168. // Global.findNodeByAstIndex = findNodeByAstIndex;
  21169. function findStatementOfNode(options, parsed, target) {
  21170. // DEPRECATED in favor of query.statementOf(parsed, node)
  21171. // Can also be called with just ast and target. options can be {asPath: BOOLEAN}.
  21172. // Find the statement that a target node is in. Example:
  21173. // let source be "var x = 1; x + 1;" and we are looking for the
  21174. // Identifier "x" in "x+1;". The second statement is what will be found.
  21175. if (!target) {
  21176. target = parsed;parsed = options;options = null;
  21177. }
  21178. if (!options) options = {};
  21179. if (!parsed.astIndex) addAstIndex(parsed);
  21180. var found,
  21181. targetReached = false;
  21182. var statements = [
  21183. // ES5
  21184. 'EmptyStatement', 'BlockStatement', 'ExpressionStatement', 'IfStatement', 'LabeledStatement', 'BreakStatement', 'ContinueStatement', 'WithStatement', 'SwitchStatement', 'ReturnStatement', 'ThrowStatement', 'TryStatement', 'WhileStatement', 'DoWhileStatement', 'ForStatement', 'ForInStatement', 'DebuggerStatement', 'FunctionDeclaration', 'VariableDeclaration',
  21185. // ES2015:
  21186. 'ClassDeclaration'];
  21187. withMozillaAstDo(parsed, {}, function (next, node, state, path) {
  21188. if (targetReached || node.astIndex < target.astIndex) return;
  21189. if (node === target || node.astIndex === target.astIndex) {
  21190. targetReached = true;
  21191. if (options.asPath) found = path;else {
  21192. var p = lively_lang.Path(path);
  21193. do {
  21194. found = p.get(parsed);
  21195. p = p.slice(0, p.size() - 1);
  21196. } while (statements.indexOf(found.type) == -1 && p.size() > 0);
  21197. }
  21198. }
  21199. !targetReached && next();
  21200. });
  21201. return found;
  21202. }
  21203. function addAstIndex(parsed) {
  21204. // we need to visit every node, forEachNode is highly
  21205. // inefficient, the compilled Mozilla visitors are a better fit
  21206. withMozillaAstDo(parsed, { index: 0 }, function (next, node, state) {
  21207. next();node.astIndex = state.index++;
  21208. });
  21209. return parsed;
  21210. }
  21211. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  21212. // simple ast traversing
  21213. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  21214. var AllNodesVisitor = function (_Visitor) {
  21215. inherits(AllNodesVisitor, _Visitor);
  21216. function AllNodesVisitor() {
  21217. classCallCheck(this, AllNodesVisitor);
  21218. return possibleConstructorReturn(this, (AllNodesVisitor.__proto__ || Object.getPrototypeOf(AllNodesVisitor)).apply(this, arguments));
  21219. }
  21220. createClass(AllNodesVisitor, [{
  21221. key: "accept",
  21222. value: function accept(node, state, path) {
  21223. this.doFunc(node, state, path);
  21224. return get(AllNodesVisitor.prototype.__proto__ || Object.getPrototypeOf(AllNodesVisitor.prototype), "accept", this).call(this, node, state, path);
  21225. }
  21226. }], [{
  21227. key: "run",
  21228. value: function run(parsed, doFunc, state) {
  21229. var v = new this();
  21230. v.doFunc = doFunc;
  21231. v.accept(parsed, state, []);
  21232. return state;
  21233. }
  21234. }]);
  21235. return AllNodesVisitor;
  21236. }(Visitor);
  21237. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  21238. // scoping
  21239. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  21240. var FindToplevelFuncDeclVisitor = function (_Visitor2) {
  21241. inherits(FindToplevelFuncDeclVisitor, _Visitor2);
  21242. function FindToplevelFuncDeclVisitor() {
  21243. classCallCheck(this, FindToplevelFuncDeclVisitor);
  21244. return possibleConstructorReturn(this, (FindToplevelFuncDeclVisitor.__proto__ || Object.getPrototypeOf(FindToplevelFuncDeclVisitor)).apply(this, arguments));
  21245. }
  21246. createClass(FindToplevelFuncDeclVisitor, [{
  21247. key: "accept",
  21248. value: function accept(node, funcDecls, path) {
  21249. switch (node.type) {
  21250. case "ArrowFunctionExpression":
  21251. return node;
  21252. case "FunctionExpression":
  21253. return node;
  21254. case "FunctionDeclaration":
  21255. funcDecls.unshift({ node: node, path: path });return node;
  21256. default:
  21257. return get(FindToplevelFuncDeclVisitor.prototype.__proto__ || Object.getPrototypeOf(FindToplevelFuncDeclVisitor.prototype), "accept", this).call(this, node, funcDecls, path);
  21258. }
  21259. }
  21260. }], [{
  21261. key: "run",
  21262. value: function run(parsed) {
  21263. var state = [];
  21264. new this().accept(parsed, state, []);
  21265. return state;
  21266. }
  21267. }]);
  21268. return FindToplevelFuncDeclVisitor;
  21269. }(Visitor);
  21270. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  21271. // replacement
  21272. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  21273. var canBeInlinedSym = Symbol("canBeInlined");
  21274. function blockInliner(node) {
  21275. // FIXME what about () => x kind of functions?
  21276. if (Array.isArray(node.body)) {
  21277. for (var i = node.body.length - 1; i >= 0; i--) {
  21278. var stmt = node.body[i];
  21279. if (stmt.type === "BlockStatement" && stmt[canBeInlinedSym]) {
  21280. node.body.splice.apply(node.body, [i, 1].concat(stmt.body));
  21281. }
  21282. }
  21283. }
  21284. return node;
  21285. }
  21286. function block(nodes) {
  21287. return { type: "BlockStatement", body: nodes };
  21288. }
  21289. var ReplaceManyVisitor = function (_Visitor3) {
  21290. inherits(ReplaceManyVisitor, _Visitor3);
  21291. function ReplaceManyVisitor() {
  21292. classCallCheck(this, ReplaceManyVisitor);
  21293. return possibleConstructorReturn(this, (ReplaceManyVisitor.__proto__ || Object.getPrototypeOf(ReplaceManyVisitor)).apply(this, arguments));
  21294. }
  21295. createClass(ReplaceManyVisitor, [{
  21296. key: "accept",
  21297. value: function accept(node, state, path) {
  21298. return this.replacer(get(ReplaceManyVisitor.prototype.__proto__ || Object.getPrototypeOf(ReplaceManyVisitor.prototype), "accept", this).call(this, node, state, path));
  21299. var replaced = this.replacer(get(ReplaceManyVisitor.prototype.__proto__ || Object.getPrototypeOf(ReplaceManyVisitor.prototype), "accept", this).call(this, node, state, path), path);
  21300. return !Array.isArray(replaced) ? replaced : replaced.length === 1 ? replaced[0] : Object.assign(block(replaced), defineProperty({}, canBeInlinedSym, true));
  21301. }
  21302. }, {
  21303. key: "visitBlockStatement",
  21304. value: function visitBlockStatement(node, state, path) {
  21305. return blockInliner(get(ReplaceManyVisitor.prototype.__proto__ || Object.getPrototypeOf(ReplaceManyVisitor.prototype), "visitBlockStatement", this).call(this, node, state, path));
  21306. }
  21307. }, {
  21308. key: "visitProgram",
  21309. value: function visitProgram(node, state, path) {
  21310. return blockInliner(get(ReplaceManyVisitor.prototype.__proto__ || Object.getPrototypeOf(ReplaceManyVisitor.prototype), "visitProgram", this).call(this, node, state, path));
  21311. }
  21312. }], [{
  21313. key: "run",
  21314. value: function run(parsed, replacer) {
  21315. var v = new this();
  21316. v.replacer = replacer;
  21317. return v.accept(parsed, null, []);
  21318. }
  21319. }]);
  21320. return ReplaceManyVisitor;
  21321. }(Visitor);
  21322. var ReplaceVisitor = function (_Visitor4) {
  21323. inherits(ReplaceVisitor, _Visitor4);
  21324. function ReplaceVisitor() {
  21325. classCallCheck(this, ReplaceVisitor);
  21326. return possibleConstructorReturn(this, (ReplaceVisitor.__proto__ || Object.getPrototypeOf(ReplaceVisitor)).apply(this, arguments));
  21327. }
  21328. createClass(ReplaceVisitor, [{
  21329. key: "accept",
  21330. value: function accept(node, state, path) {
  21331. return this.replacer(get(ReplaceVisitor.prototype.__proto__ || Object.getPrototypeOf(ReplaceVisitor.prototype), "accept", this).call(this, node, state, path), path);
  21332. }
  21333. }], [{
  21334. key: "run",
  21335. value: function run(parsed, replacer) {
  21336. var v = new this();
  21337. v.replacer = replacer;
  21338. return v.accept(parsed, null, []);
  21339. }
  21340. }]);
  21341. return ReplaceVisitor;
  21342. }(Visitor);
  21343. acorn.walk.addSource = addSource;
  21344. function addSource(parsed, source) {
  21345. if (typeof parsed === "string") {
  21346. source = parsed;
  21347. parsed = parse(parsed);
  21348. }
  21349. source && AllNodesVisitor.run(parsed, function (node, state, path) {
  21350. return !node.source && (node.source = source.slice(node.start, node.end));
  21351. });
  21352. return parsed;
  21353. }
  21354. function nodesAt(pos, ast) {
  21355. ast = typeof ast === 'string' ? this.parse(ast) : ast;
  21356. return findNodesIncluding(ast, pos);
  21357. }
  21358. function parseFunction(source) {
  21359. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  21360. var src = '(' + source + ')',
  21361. offset = -1,
  21362. parsed = parse(src, options);
  21363. AllNodesVisitor.run(parsed, function (node, state, path) {
  21364. if (node._positionFixed) return;
  21365. node._positionFixed = true;
  21366. if (node.start || node.start === 0) {
  21367. node.start += offset;
  21368. node.end += offset;
  21369. }
  21370. if (options.addSource && !node.source) {
  21371. node.source = source.slice(node.start, node.end);
  21372. }
  21373. });
  21374. return parsed.body[0].expression;
  21375. }
  21376. function fuzzyParse(source, options) {
  21377. // options: verbose, addSource, type
  21378. options = options || {};
  21379. options.ecmaVersion = options.ecmaVersion || 8;
  21380. options.sourceType = options.sourceType || "module";
  21381. options.plugins = options.plugins || {};
  21382. // if (options.plugins.hasOwnProperty("jsx")) options.plugins.jsx = options.plugins.jsx;
  21383. options.plugins.jsx = options.plugins.hasOwnProperty("jsx") ? options.plugins.jsx : true;
  21384. options.plugins.asyncawait = options.plugins.hasOwnProperty("asyncawait") ? options.plugins.asyncawait : { inAsyncFunction: true };
  21385. options.plugins.objectSpread = options.plugins.hasOwnProperty("objectSpread") ? options.plugins.objectSpread : true;
  21386. var ast, safeSource, err;
  21387. if (options.type === 'LabeledStatement') {
  21388. safeSource = '$={' + source + '}';
  21389. }
  21390. try {
  21391. // we only parse to find errors
  21392. ast = parse(safeSource || source, options);
  21393. if (safeSource) ast = null; // we parsed only for finding errors
  21394. else if (options.addSource) addSource(ast, source);
  21395. } catch (e) {
  21396. err = e;
  21397. }
  21398. if (err && err.raisedAt !== undefined) {
  21399. if (safeSource) {
  21400. // fix error pos
  21401. err.pos -= 3;err.raisedAt -= 3;err.loc.column -= 3;
  21402. }
  21403. var parseErrorSource = '';
  21404. parseErrorSource += source.slice(err.raisedAt - 20, err.raisedAt);
  21405. parseErrorSource += '<-error->';
  21406. parseErrorSource += source.slice(err.raisedAt, err.raisedAt + 20);
  21407. options.verbose && show('parse error: ' + parseErrorSource);
  21408. err.parseErrorSource = parseErrorSource;
  21409. } else if (err && options.verbose) {
  21410. show('' + err + err.stack);
  21411. }
  21412. if (!ast) {
  21413. ast = loose.parse_dammit(source, options);
  21414. if (options.addSource) addSource(ast, source);
  21415. ast.isFuzzy = true;
  21416. ast.parseError = err;
  21417. }
  21418. return ast;
  21419. }
  21420. function parse(source, options) {
  21421. // proxy function to acorn.parse.
  21422. // Note that we will implement useful functionality on top of the pure
  21423. // acorn interface and make it available here (such as more convenient
  21424. // comment parsing). For using the pure acorn interface use the acorn
  21425. // global.
  21426. // See https://github.com/marijnh/acorn for full acorn doc and parse options.
  21427. // options: {
  21428. // addSource: BOOL, -- add source property to each node
  21429. // addAstIndex: BOOL, -- each node gets an index number
  21430. // withComments: BOOL, -- adds comment objects to Program/BlockStatements:
  21431. // {isBlock: BOOL, text: STRING, node: NODE,
  21432. // start: INTEGER, end: INTEGER, line: INTEGER, column: INTEGER}
  21433. // ecmaVersion: 3|5|6,
  21434. // allowReturnOutsideFunction: BOOL, -- Default is false
  21435. // locations: BOOL -- Default is false
  21436. // }
  21437. options = options || {};
  21438. options.ecmaVersion = options.ecmaVersion || 8;
  21439. options.sourceType = options.sourceType || "module";
  21440. if (!options.hasOwnProperty("allowImportExportEverywhere")) options.allowImportExportEverywhere = true;
  21441. options.plugins = options.plugins || {};
  21442. options.plugins.jsx = options.plugins.hasOwnProperty("jsx") ? options.plugins.jsx : true;
  21443. options.plugins.asyncawait = options.plugins.hasOwnProperty("asyncawait") ? options.plugins.asyncawait : { inAsyncFunction: true };
  21444. options.plugins.objectSpread = options.plugins.hasOwnProperty("objectSpread") ? options.plugins.objectSpread : true;
  21445. if (options.withComments) {
  21446. // record comments
  21447. delete options.withComments;
  21448. var comments = [];
  21449. options.onComment = function (isBlock, text, start, end, line, column) {
  21450. comments.push({
  21451. isBlock: isBlock,
  21452. text: text, node: null,
  21453. start: start, end: end,
  21454. line: line, column: column
  21455. });
  21456. };
  21457. }
  21458. try {
  21459. var parsed = acorn.parse(source, options);
  21460. } catch (err) {
  21461. if (typeof SyntaxError !== "undefined" && err instanceof SyntaxError && err.loc) {
  21462. var lines = source.split("\n"),
  21463. message = err.message,
  21464. _err$loc = err.loc,
  21465. row = _err$loc.line,
  21466. column = _err$loc.column,
  21467. pos = err.pos,
  21468. line = lines[row - 1],
  21469. newMessage = "Syntax error at line " + row + " column " + column + " (index " + pos + ") \"" + message + "\"\nsource: " + line.slice(0, column) + "<--SyntaxError-->" + line.slice(column),
  21470. betterErr = new SyntaxError(newMessage);
  21471. betterErr.loc = { line: row, column: column };
  21472. betterErr.pos = pos;
  21473. throw betterErr;
  21474. } else throw err;
  21475. }
  21476. if (options.addSource) addSource(parsed, source);
  21477. if (options.addAstIndex && !parsed.hasOwnProperty('astIndex')) addAstIndex(parsed);
  21478. if (parsed && comments) attachCommentsToAST({ ast: parsed, comments: comments, nodesWithComments: [] });
  21479. return parsed;
  21480. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  21481. function attachCommentsToAST(commentData) {
  21482. // for each comment: assign the comment to a block-level AST node
  21483. commentData = mergeComments(assignCommentsToBlockNodes(commentData));
  21484. parsed.allComments = commentData.comments;
  21485. }
  21486. function assignCommentsToBlockNodes(commentData) {
  21487. comments.forEach(function (comment) {
  21488. var node = lively_lang.arr.detect(nodesAt(comment.start, parsed).reverse(), function (node) {
  21489. return node.type === 'BlockStatement' || node.type === 'Program';
  21490. });
  21491. if (!node) node = parsed;
  21492. if (!node.comments) node.comments = [];
  21493. node.comments.push(comment);
  21494. commentData.nodesWithComments.push(node);
  21495. });
  21496. return commentData;
  21497. }
  21498. function mergeComments(commentData) {
  21499. // coalesce non-block comments (multiple following lines of "// ...") into one comment.
  21500. // This only happens if line comments aren't seperated by newlines
  21501. commentData.nodesWithComments.forEach(function (blockNode) {
  21502. lively_lang.arr.clone(blockNode.comments).reduce(function (coalesceData, comment) {
  21503. if (comment.isBlock) {
  21504. coalesceData.lastComment = null;
  21505. return coalesceData;
  21506. }
  21507. if (!coalesceData.lastComment) {
  21508. coalesceData.lastComment = comment;
  21509. return coalesceData;
  21510. }
  21511. // if the comments are seperated by a statement, don't merge
  21512. var last = coalesceData.lastComment;
  21513. var nodeInbetween = lively_lang.arr.detect(blockNode.body, function (node) {
  21514. return node.start >= last.end && node.end <= comment.start;
  21515. });
  21516. if (nodeInbetween) {
  21517. coalesceData.lastComment = comment;
  21518. return coalesceData;
  21519. }
  21520. // if the comments are seperated by a newline, don't merge
  21521. var codeInBetween = source.slice(last.end, comment.start);
  21522. if (/[\n\r][\n\r]+/.test(codeInBetween)) {
  21523. coalesceData.lastComment = comment;
  21524. return coalesceData;
  21525. }
  21526. // merge comments into one
  21527. last.text += "\n" + comment.text;
  21528. last.end = comment.end;
  21529. lively_lang.arr.remove(blockNode.comments, comment);
  21530. lively_lang.arr.remove(commentData.comments, comment);
  21531. return coalesceData;
  21532. }, { lastComment: null });
  21533. });
  21534. return commentData;
  21535. }
  21536. }
  21537. /*global process, global, exports*/
  21538. var methods = {
  21539. withMozillaAstDo: function withMozillaAstDo(parsed, state, func) {
  21540. // simple interface to mozilla AST visitor. function gets passed three
  21541. // arguments:
  21542. // acceptNext, -- continue visiting
  21543. // node, -- current node being visited
  21544. // state -- state variable that is passed along
  21545. var vis = new Visitor(),
  21546. origAccept = vis.accept;
  21547. vis.accept = function (node, st, path) {
  21548. var next = function next() {
  21549. origAccept.call(vis, node, st, path);
  21550. };
  21551. state = func(next, node, st, path);
  21552. return node;
  21553. };
  21554. vis.accept(parsed, state, []);
  21555. return state;
  21556. },
  21557. printAst: function printAst(astOrSource, options) {
  21558. options = options || {};
  21559. var printSource = options.printSource || false,
  21560. printPositions = options.printPositions || false,
  21561. printIndex = options.printIndex || false,
  21562. source,
  21563. parsed,
  21564. tree$$1 = [];
  21565. if (typeof astOrSource === "string") {
  21566. source = astOrSource;
  21567. parsed = parse(astOrSource);
  21568. } else {
  21569. parsed = astOrSource;source = options.source || parsed.source;
  21570. }
  21571. if (printSource && !parsed.source) {
  21572. // ensure that nodes have source attached
  21573. if (!source) {
  21574. source = stringify(parsed);
  21575. parsed = parse(source);
  21576. }
  21577. addSource(parsed, source);
  21578. }
  21579. function printFunc(ea) {
  21580. var line = ea.path + ':' + ea.node.type,
  21581. additional = [];
  21582. if (printIndex) {
  21583. additional.push(ea.index);
  21584. }
  21585. if (printPositions) {
  21586. additional.push(ea.node.start + '-' + ea.node.end);
  21587. }
  21588. if (printSource) {
  21589. var src = ea.node.source || source.slice(ea.node.start, ea.node.end),
  21590. printed = lively_lang.string.print(src.truncate(60).replace(/\n/g, '').replace(/\s+/g, ' '));
  21591. additional.push(printed);
  21592. }
  21593. if (additional.length) {
  21594. line += '(' + additional.join(',') + ')';
  21595. }
  21596. return line;
  21597. }
  21598. new PrinterVisitor().accept(parsed, { index: 0, tree: tree$$1 }, []);
  21599. return lively_lang.string.printTree(tree$$1[0], printFunc, function (ea) {
  21600. return ea.children;
  21601. }, ' ');
  21602. },
  21603. compareAst: function compareAst(node1, node2) {
  21604. if (!node1 || !node2) throw new Error('node' + (node1 ? '1' : '2') + ' not defined');
  21605. var state = { completePath: [], comparisons: { errors: [] } };
  21606. new ComparisonVisitor().accept(node1, node2, state, []);
  21607. return !state.comparisons.errors.length ? null : state.comparisons.errors.pluck('msg');
  21608. },
  21609. pathToNode: function pathToNode(parsed, index, options) {
  21610. options = options || {};
  21611. if (!parsed.astIndex) addAstIndex(parsed);
  21612. var vis = new Visitor(),
  21613. found = null;
  21614. (vis.accept = function (node, pathToHere, state, path) {
  21615. if (found) return;
  21616. var fullPath = pathToHere.concat(path);
  21617. if (node.astIndex === index) {
  21618. var pathString = fullPath.map(function (ea) {
  21619. return typeof ea === 'string' ? '.' + ea : '[' + ea + ']';
  21620. }).join('');
  21621. found = { pathString: pathString, path: fullPath, node: node };
  21622. }
  21623. return this['visit' + node.type](node, fullPath, state, path);
  21624. }).call(vis, parsed, [], {}, []);
  21625. return found;
  21626. },
  21627. rematchAstWithSource: function rematchAstWithSource(parsed, source, addLocations, subTreePath) {
  21628. addLocations = !!addLocations;
  21629. var parsed2 = parse(source, addLocations ? { locations: true } : undefined),
  21630. visitor = new Visitor();
  21631. if (subTreePath) parsed2 = lively_lang.Path(subTreePath).get(parsed2);
  21632. visitor.accept = function (node, state, path) {
  21633. path = path || [];
  21634. var node2 = path.reduce(function (node, pathElem) {
  21635. return node[pathElem];
  21636. }, parsed);
  21637. node2.start = node.start;
  21638. node2.end = node.end;
  21639. if (addLocations) node2.loc = node.loc;
  21640. return this['visit' + node.type](node, state, path);
  21641. };
  21642. visitor.accept(parsed2);
  21643. }
  21644. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  21645. };var withMozillaAstDo = methods.withMozillaAstDo; var printAst = methods.printAst; var compareAst = methods.compareAst; var pathToNode = methods.pathToNode; var rematchAstWithSource = methods.rematchAstWithSource;
  21646. // obj.extend(ast, methods);
  21647. // FIXME! Don't extend acorn object!
  21648. // obj.extend(ast.acorn, methods);
  21649. var identifierRe = /[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/;
  21650. function isIdentifier(string$$1) {
  21651. // Note: It's not so easy...
  21652. // http://wiki.ecmascript.org/doku.php?id=strawman:identifier_identification
  21653. // https://mathiasbynens.be/notes/javascript-identifiers-es6
  21654. return identifierRe.test(string$$1) && string$$1.indexOf("-") === -1;
  21655. }
  21656. function id(name) {
  21657. return name === "this" ? { type: "ThisExpression" } : { name: String(name), type: "Identifier" };
  21658. }
  21659. function literal(value) {
  21660. return { type: "Literal", value: value };
  21661. }
  21662. function exprStmt(expression) {
  21663. return { type: "ExpressionStatement", expression: expression };
  21664. }
  21665. function returnStmt(expr) {
  21666. return { type: "ReturnStatement", argument: expr };
  21667. }
  21668. function empty() {
  21669. return { type: "EmptyStatement" };
  21670. }
  21671. function binaryExpr(left, op, right) {
  21672. return {
  21673. left: left, right: right, operator: op,
  21674. type: "BinaryExpression"
  21675. };
  21676. }
  21677. function funcExpr(_ref) {
  21678. for (var _len = arguments.length, statements = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  21679. statements[_key - 2] = arguments[_key];
  21680. }
  21681. var arrow = _ref.arrow,
  21682. funcId = _ref.id,
  21683. expression = _ref.expression,
  21684. generator = _ref.generator;
  21685. var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  21686. // lively.ast.stringify(funcExpr({id: "foo"}, ["a"], exprStmt(id("3"))))
  21687. // // => "function foo(a) { 3; }"
  21688. params = params.map(function (ea) {
  21689. return typeof ea === "string" ? id(ea) : ea;
  21690. });
  21691. return {
  21692. type: (arrow ? "Arrow" : "") + "FunctionExpression",
  21693. id: funcId ? typeof funcId === "string" ? id(funcId) : funcId : undefined,
  21694. params: params,
  21695. body: expression && statements.length === 1 ? statements[0] : { body: statements, type: "BlockStatement" },
  21696. expression: expression || false,
  21697. generator: generator || false
  21698. };
  21699. }
  21700. function funcCall(callee) {
  21701. for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  21702. args[_key2 - 1] = arguments[_key2];
  21703. }
  21704. if (typeof callee === "string") callee = id(callee);
  21705. return {
  21706. type: "CallExpression",
  21707. callee: callee,
  21708. arguments: args
  21709. };
  21710. }
  21711. function varDecl(id, init, kind) {
  21712. if (typeof id === "string") id = { name: id, type: "Identifier" };
  21713. return {
  21714. type: "VariableDeclaration", kind: kind || "var",
  21715. declarations: [{ type: "VariableDeclarator", id: id, init: init }]
  21716. };
  21717. }
  21718. function member(obj$$1, prop, computed) {
  21719. // Example:
  21720. // lively.ast.stringify(member("foo", "bar"))
  21721. // // => "foo.bar"
  21722. // lively.ast.stringify(member("foo", "b-a-r"))
  21723. // // => "foo['b-a-r']"
  21724. // lively.ast.stringify(member("foo", "zork", true))
  21725. // // => "foo['zork']"
  21726. // lively.ast.stringify(member("foo", 0))
  21727. // // => "foo[0]"
  21728. if (typeof obj$$1 === "string") obj$$1 = id(obj$$1);
  21729. if (typeof prop === "string") {
  21730. if (!computed && !isIdentifier(prop)) computed = true;
  21731. prop = computed ? literal(prop) : id(prop);
  21732. } else if (typeof prop === "number") {
  21733. prop = literal(prop);
  21734. computed = true;
  21735. } else if (prop.type === "Literal") {
  21736. computed = true;
  21737. }
  21738. return {
  21739. type: "MemberExpression",
  21740. computed: !!computed,
  21741. object: obj$$1, property: prop
  21742. };
  21743. }
  21744. function memberChain(first) {
  21745. for (var _len3 = arguments.length, rest = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
  21746. rest[_key3 - 1] = arguments[_key3];
  21747. }
  21748. // lively.ast.stringify(memberChain("foo", "bar", 0, "baz-zork"));
  21749. // // => "foo.bar[0]['baz-zork']"
  21750. return rest.reduce(function (memberExpr, key) {
  21751. return member(memberExpr, key);
  21752. }, (typeof first === "undefined" ? "undefined" : _typeof(first)) === "object" ? first : id(first));
  21753. }
  21754. function assign(left, right) {
  21755. // lively.ast.stringify(assign("a", "x"))
  21756. // // => "a = x"
  21757. // lively.ast.stringify(assign(member("a", "x"), literal(23)))
  21758. // // => "a.x = 23"
  21759. return {
  21760. type: "AssignmentExpression", operator: "=",
  21761. right: right ? typeof right === "string" ? id(right) : right : id("undefined"),
  21762. left: typeof left === "string" ? id(left) : left
  21763. };
  21764. }
  21765. function block$1() {
  21766. for (var _len4 = arguments.length, body = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  21767. body[_key4] = arguments[_key4];
  21768. }
  21769. return { body: Array.isArray(body[0]) ? body[0] : body, type: "BlockStatement" };
  21770. }
  21771. function program() {
  21772. return Object.assign(block$1.apply(undefined, arguments), { sourceType: "module", type: "Program" });
  21773. }
  21774. function tryStmt(exName, handlerBody, finalizerBody) {
  21775. for (var _len5 = arguments.length, body = Array(_len5 > 3 ? _len5 - 3 : 0), _key5 = 3; _key5 < _len5; _key5++) {
  21776. body[_key5 - 3] = arguments[_key5];
  21777. }
  21778. // Example:
  21779. // var stmt = exprStmt(binaryExpr(literal(3), "+", literal(2)));
  21780. // lively.ast.stringify(tryStmt("err", [stmt], [stmt], stmt, stmt))
  21781. // // => "try { 3 + 2; 3 + 2; } catch (err) { 3 + 2; } finally { 3 + 2; }"
  21782. if (!Array.isArray(finalizerBody)) {
  21783. body.unshift(finalizerBody);
  21784. finalizerBody = null;
  21785. }
  21786. return {
  21787. block: block$1(body),
  21788. finalizer: finalizerBody ? block$1(finalizerBody) : null,
  21789. handler: {
  21790. body: block$1(handlerBody),
  21791. param: id(exName),
  21792. type: "CatchClause"
  21793. },
  21794. type: "TryStatement"
  21795. };
  21796. }
  21797. function prop(key, value) {
  21798. return {
  21799. type: "Property",
  21800. key: key,
  21801. computed: key.type !== "Identifier",
  21802. shorthand: false,
  21803. value: value
  21804. };
  21805. }
  21806. function objectLiteral(keysAndValues) {
  21807. var props = [];
  21808. for (var i = 0; i < keysAndValues.length; i += 2) {
  21809. var key = keysAndValues[i];
  21810. if (typeof key === "string") key = id(key);
  21811. props.push(prop(key, keysAndValues[i + 1]));
  21812. }
  21813. return {
  21814. properties: props,
  21815. type: "ObjectExpression"
  21816. };
  21817. }
  21818. function ifStmt(test) {
  21819. var consequent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : block$1();
  21820. var alternate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : block$1();
  21821. return {
  21822. consequent: consequent, alternate: alternate, test: test,
  21823. type: "IfStatement"
  21824. };
  21825. }
  21826. function forIn(varDeclOrName, objExprOrName, body) {
  21827. return {
  21828. type: "ForInStatement",
  21829. left: typeof varDeclOrName === "string" ? varDecl(varDeclOrName) : varDeclOrName,
  21830. right: typeof objExprOrName === "string" ? id(objExprOrName) : objExprOrName,
  21831. body: body
  21832. };
  21833. }
  21834. function conditional(test) {
  21835. var consequent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : id("undefined");
  21836. var alternate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : id("undefined");
  21837. return {
  21838. consequent: consequent, alternate: alternate, test: test,
  21839. type: "ConditionalExpression"
  21840. };
  21841. }
  21842. function logical(op, left, right) {
  21843. return {
  21844. operator: op, left: left, right: right,
  21845. type: "LogicalExpression"
  21846. };
  21847. }
  21848. var nodes = Object.freeze({
  21849. isIdentifier: isIdentifier,
  21850. id: id,
  21851. literal: literal,
  21852. objectLiteral: objectLiteral,
  21853. prop: prop,
  21854. exprStmt: exprStmt,
  21855. returnStmt: returnStmt,
  21856. empty: empty,
  21857. binaryExpr: binaryExpr,
  21858. funcExpr: funcExpr,
  21859. funcCall: funcCall,
  21860. varDecl: varDecl,
  21861. member: member,
  21862. memberChain: memberChain,
  21863. assign: assign,
  21864. block: block$1,
  21865. program: program,
  21866. tryStmt: tryStmt,
  21867. ifStmt: ifStmt,
  21868. forIn: forIn,
  21869. conditional: conditional,
  21870. logical: logical
  21871. });
  21872. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  21873. var helpers = {
  21874. declIds: function declIds(nodes) {
  21875. var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  21876. for (var i = 0; i < nodes.length; i++) {
  21877. var node = nodes[i];
  21878. if (!node) continue;else if (node.type === "Identifier") result.push(node);else if (node.type === "RestElement") result.push(node.argument);
  21879. // AssignmentPattern: default arg like function(local = defaultVal) {}
  21880. else if (node.type === "AssignmentPattern") helpers.declIds([node.left], result);else if (node.type === "ObjectPattern") {
  21881. for (var j = 0; j < node.properties.length; j++) {
  21882. var prop = node.properties[j];
  21883. helpers.declIds([prop.value || prop], result);
  21884. }
  21885. } else if (node.type === "ArrayPattern") helpers.declIds(node.elements, result);
  21886. }
  21887. return result;
  21888. },
  21889. varDecls: function varDecls(scope) {
  21890. var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  21891. var _iteratorNormalCompletion = true;
  21892. var _didIteratorError = false;
  21893. var _iteratorError = undefined;
  21894. try {
  21895. for (var _iterator = scope.varDecls[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  21896. var varDecl = _step.value;
  21897. var _iteratorNormalCompletion2 = true;
  21898. var _didIteratorError2 = false;
  21899. var _iteratorError2 = undefined;
  21900. try {
  21901. for (var _iterator2 = varDecl.declarations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  21902. var decl = _step2.value;
  21903. var _iteratorNormalCompletion3 = true;
  21904. var _didIteratorError3 = false;
  21905. var _iteratorError3 = undefined;
  21906. try {
  21907. for (var _iterator3 = helpers.declIds([decl.id])[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
  21908. var id = _step3.value;
  21909. result.push([decl, id]);
  21910. }
  21911. } catch (err) {
  21912. _didIteratorError3 = true;
  21913. _iteratorError3 = err;
  21914. } finally {
  21915. try {
  21916. if (!_iteratorNormalCompletion3 && _iterator3.return) {
  21917. _iterator3.return();
  21918. }
  21919. } finally {
  21920. if (_didIteratorError3) {
  21921. throw _iteratorError3;
  21922. }
  21923. }
  21924. }
  21925. }
  21926. } catch (err) {
  21927. _didIteratorError2 = true;
  21928. _iteratorError2 = err;
  21929. } finally {
  21930. try {
  21931. if (!_iteratorNormalCompletion2 && _iterator2.return) {
  21932. _iterator2.return();
  21933. }
  21934. } finally {
  21935. if (_didIteratorError2) {
  21936. throw _iteratorError2;
  21937. }
  21938. }
  21939. }
  21940. }
  21941. } catch (err) {
  21942. _didIteratorError = true;
  21943. _iteratorError = err;
  21944. } finally {
  21945. try {
  21946. if (!_iteratorNormalCompletion && _iterator.return) {
  21947. _iterator.return();
  21948. }
  21949. } finally {
  21950. if (_didIteratorError) {
  21951. throw _iteratorError;
  21952. }
  21953. }
  21954. }
  21955. return result;
  21956. },
  21957. varDeclIds: function varDeclIds(scope) {
  21958. var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  21959. var _iteratorNormalCompletion4 = true;
  21960. var _didIteratorError4 = false;
  21961. var _iteratorError4 = undefined;
  21962. try {
  21963. for (var _iterator4 = scope.varDecls[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
  21964. var varDecl = _step4.value;
  21965. var _iteratorNormalCompletion5 = true;
  21966. var _didIteratorError5 = false;
  21967. var _iteratorError5 = undefined;
  21968. try {
  21969. for (var _iterator5 = varDecl.declarations[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
  21970. var decl = _step5.value;
  21971. helpers.declIds([decl.id], result);
  21972. }
  21973. } catch (err) {
  21974. _didIteratorError5 = true;
  21975. _iteratorError5 = err;
  21976. } finally {
  21977. try {
  21978. if (!_iteratorNormalCompletion5 && _iterator5.return) {
  21979. _iterator5.return();
  21980. }
  21981. } finally {
  21982. if (_didIteratorError5) {
  21983. throw _iteratorError5;
  21984. }
  21985. }
  21986. }
  21987. }
  21988. } catch (err) {
  21989. _didIteratorError4 = true;
  21990. _iteratorError4 = err;
  21991. } finally {
  21992. try {
  21993. if (!_iteratorNormalCompletion4 && _iterator4.return) {
  21994. _iterator4.return();
  21995. }
  21996. } finally {
  21997. if (_didIteratorError4) {
  21998. throw _iteratorError4;
  21999. }
  22000. }
  22001. }
  22002. return result;
  22003. },
  22004. objPropertiesAsList: function objPropertiesAsList(objExpr, path, onlyLeafs) {
  22005. var result = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  22006. // takes an obj expr like {x: 23, y: [{z: 4}]} an returns the key and value
  22007. // nodes as a list
  22008. var _iteratorNormalCompletion6 = true;
  22009. var _didIteratorError6 = false;
  22010. var _iteratorError6 = undefined;
  22011. try {
  22012. for (var _iterator6 = objExpr.properties[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
  22013. var prop = _step6.value;
  22014. var key = prop.key.name,
  22015. thisNode = { key: path.concat([key]), value: prop.value };
  22016. switch (prop.value.type) {
  22017. case "ArrayExpression":case "ArrayPattern":
  22018. if (!onlyLeafs) result.push(thisNode);
  22019. for (var i = 0; i < prop.value.elements.length; i++) {
  22020. var el = prop.value.elements[i];
  22021. helpers.objPropertiesAsList(el, path.concat([key, i]), onlyLeafs, result);
  22022. }
  22023. break;
  22024. case "ObjectExpression":case "ObjectPattern":
  22025. if (!onlyLeafs) result.push(thisNode);
  22026. helpers.objPropertiesAsList(prop.value, path.concat([key]), onlyLeafs, result);
  22027. break;
  22028. case "AssignmentPattern":
  22029. if (!onlyLeafs) result.push(thisNode);
  22030. helpers.objPropertiesAsList(prop.left, path.concat([key]), onlyLeafs, result);
  22031. break;
  22032. default:
  22033. result.push(thisNode);
  22034. }
  22035. }
  22036. } catch (err) {
  22037. _didIteratorError6 = true;
  22038. _iteratorError6 = err;
  22039. } finally {
  22040. try {
  22041. if (!_iteratorNormalCompletion6 && _iterator6.return) {
  22042. _iterator6.return();
  22043. }
  22044. } finally {
  22045. if (_didIteratorError6) {
  22046. throw _iteratorError6;
  22047. }
  22048. }
  22049. }
  22050. return result;
  22051. },
  22052. isDeclaration: function isDeclaration(node) {
  22053. return node.type === "FunctionDeclaration" || node.type === "VariableDeclaration" || node.type === "ClassDeclaration";
  22054. }
  22055. };
  22056. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  22057. var knownGlobals = ["true", "false", "null", "undefined", "arguments", "Object", "Function", "Array", "Number", "parseFloat", "parseInt", "Infinity", "NaN", "Boolean", "String", "Symbol", "Date", "Promise", "RegExp", "Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "JSON", "Math", "console", "ArrayBuffer", "Uint8Array", "Int8Array", "Uint16Array", "Int16Array", "Uint32Array", "Int32Array", "Float32Array", "Float64Array", "Uint8ClampedArray", "DataView", "Map", "Set", "WeakMap", "WeakSet", "Proxy", "Reflect", "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "escape", "unescape", "eval", "isFinite", "isNaN", "Intl", "navigator", "window", "document", "Blob", "setTimeout", "clearTimeout", "setInterval", "clearInterval", "requestAnimationFrame", "cancelAnimationFrame", "btoa", "atob", "sessionStorage", "localStorage", "$world", "lively"];
  22058. function scopes(parsed) {
  22059. var vis = new ScopeVisitor(),
  22060. scope = vis.newScope(parsed, null);
  22061. vis.accept(parsed, scope, []);
  22062. return scope;
  22063. }
  22064. function nodesAtIndex(parsed, index) {
  22065. return withMozillaAstDo(parsed, [], function (next, node, found) {
  22066. if (node.start <= index && index <= node.end) {
  22067. found.push(node);next();
  22068. }
  22069. return found;
  22070. });
  22071. }
  22072. function scopesAtIndex(parsed, index) {
  22073. return lively_lang.tree.filter(scopes(parsed), function (scope) {
  22074. var n = scope.node;
  22075. var start = n.start,
  22076. end = n.end;
  22077. if (n.type === 'FunctionDeclaration') {
  22078. start = n.params.length ? n.params[0].start : n.body.start;
  22079. end = n.body.end;
  22080. }
  22081. return start <= index && index <= end;
  22082. }, function (s) {
  22083. return s.subScopes;
  22084. });
  22085. }
  22086. function scopeAtIndex(parsed, index) {
  22087. return lively_lang.arr.last(scopesAtIndex(parsed, index));
  22088. }
  22089. function scopesAtPos(pos, parsed) {
  22090. // DEPRECATED
  22091. // FIXME "scopes" should actually not referer to a node but to a scope
  22092. // object, see exports.scopes!
  22093. return nodesAt$1(pos, parsed).filter(function (node) {
  22094. return node.type === 'Program' || node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression';
  22095. });
  22096. }
  22097. function nodesInScopeOf(node) {
  22098. // DEPRECATED
  22099. // FIXME "scopes" should actually not referer to a node but to a scope
  22100. // object, see exports.scopes!
  22101. return withMozillaAstDo(node, { root: node, result: [] }, function (next, node, state) {
  22102. state.result.push(node);
  22103. if (node !== state.root && (node.type === 'Program' || node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression')) return state;
  22104. next();
  22105. return state;
  22106. }).result;
  22107. }
  22108. function declarationsOfScope(scope, includeOuter) {
  22109. var result = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  22110. // returns Identifier nodes
  22111. if (includeOuter && scope.node.id && scope.node.id.name) result.push(scope.node.id);
  22112. helpers.declIds(scope.params, result);
  22113. for (var i = 0; i < scope.funcDecls.length; i++) {
  22114. var id = scope.funcDecls[i].id;
  22115. if (id) result.push(id);
  22116. }
  22117. helpers.varDeclIds(scope, result);
  22118. result.push.apply(result, toConsumableArray(scope.catches));
  22119. for (var i = 0; i < scope.classDecls.length; i++) {
  22120. var id = scope.classDecls[i].id;
  22121. if (id) result.push(id);
  22122. }
  22123. result.push.apply(result, toConsumableArray(scope.importSpecifiers));
  22124. return result;
  22125. }
  22126. function declarationsWithIdsOfScope(scope) {
  22127. // returns a list of pairs [(DeclarationNode,IdentifierNode)]
  22128. var bareIds = helpers.declIds(scope.params).concat(scope.catches),
  22129. declNodes = (scope.node.id && scope.node.id.name ? [scope.node] : []).concat(scope.funcDecls.filter(function (ea) {
  22130. return ea.id;
  22131. })).concat(scope.classDecls.filter(function (ea) {
  22132. return ea.id;
  22133. }));
  22134. return bareIds.map(function (ea) {
  22135. return [ea, ea];
  22136. }).concat(declNodes.map(function (ea) {
  22137. return [ea, ea.id];
  22138. })).concat(helpers.varDecls(scope)).concat(scope.importSpecifiers.map(function (im) {
  22139. return [statementOf(scope.node, im), im];
  22140. }));
  22141. }
  22142. function _declaredVarNames(scope, useComments) {
  22143. var result = [];
  22144. var _iteratorNormalCompletion7 = true;
  22145. var _didIteratorError7 = false;
  22146. var _iteratorError7 = undefined;
  22147. try {
  22148. for (var _iterator7 = declarationsOfScope(scope, true)[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
  22149. var decl = _step7.value;
  22150. result.push(decl.name);
  22151. }
  22152. } catch (err) {
  22153. _didIteratorError7 = true;
  22154. _iteratorError7 = err;
  22155. } finally {
  22156. try {
  22157. if (!_iteratorNormalCompletion7 && _iterator7.return) {
  22158. _iterator7.return();
  22159. }
  22160. } finally {
  22161. if (_didIteratorError7) {
  22162. throw _iteratorError7;
  22163. }
  22164. }
  22165. }
  22166. if (useComments) {
  22167. _findJsLintGlobalDeclarations(scope.node.type === 'Program' ? scope.node : scope.node.body, result);
  22168. }
  22169. return result;
  22170. }
  22171. var globalDeclRe = /^\s*global\s*/;
  22172. function _findJsLintGlobalDeclarations(node) {
  22173. var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  22174. if (!node || !node.comments) return result;
  22175. var _iteratorNormalCompletion8 = true;
  22176. var _didIteratorError8 = false;
  22177. var _iteratorError8 = undefined;
  22178. try {
  22179. for (var _iterator8 = node.comments[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
  22180. var comment = _step8.value;
  22181. var text = comment.text.trim();
  22182. if (!text.startsWith("global")) continue;
  22183. var _iteratorNormalCompletion9 = true;
  22184. var _didIteratorError9 = false;
  22185. var _iteratorError9 = undefined;
  22186. try {
  22187. for (var _iterator9 = text.replace(globalDeclRe, '').split(',')[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
  22188. var globalDecl = _step9.value;
  22189. result.push(globalDecl.trim());
  22190. }
  22191. } catch (err) {
  22192. _didIteratorError9 = true;
  22193. _iteratorError9 = err;
  22194. } finally {
  22195. try {
  22196. if (!_iteratorNormalCompletion9 && _iterator9.return) {
  22197. _iterator9.return();
  22198. }
  22199. } finally {
  22200. if (_didIteratorError9) {
  22201. throw _iteratorError9;
  22202. }
  22203. }
  22204. }
  22205. }
  22206. } catch (err) {
  22207. _didIteratorError8 = true;
  22208. _iteratorError8 = err;
  22209. } finally {
  22210. try {
  22211. if (!_iteratorNormalCompletion8 && _iterator8.return) {
  22212. _iterator8.return();
  22213. }
  22214. } finally {
  22215. if (_didIteratorError8) {
  22216. throw _iteratorError8;
  22217. }
  22218. }
  22219. }
  22220. return result;
  22221. }
  22222. function topLevelFuncDecls(parsed) {
  22223. return FindToplevelFuncDeclVisitor.run(parsed);
  22224. }
  22225. function resolveReference(ref, scopePath) {
  22226. if (scopePath.length == 0) return [null, null];
  22227. var _scopePath = toArray(scopePath),
  22228. scope = _scopePath[0],
  22229. outer = _scopePath.slice(1);
  22230. var decls = scope.decls || declarationsWithIdsOfScope(scope);
  22231. scope.decls = decls;
  22232. var decl = decls.find(function (_ref) {
  22233. var _ref2 = slicedToArray(_ref, 2),
  22234. _ = _ref2[0],
  22235. id = _ref2[1];
  22236. return id.name == ref;
  22237. });
  22238. return decl || resolveReference(ref, outer);
  22239. }
  22240. function resolveReferences(scope) {
  22241. function rec(scope, outerScopes) {
  22242. var path = [scope].concat(outerScopes);
  22243. scope.refs.forEach(function (ref) {
  22244. var _resolveReference = resolveReference(ref.name, path),
  22245. _resolveReference2 = slicedToArray(_resolveReference, 2),
  22246. decl = _resolveReference2[0],
  22247. id = _resolveReference2[1];
  22248. map.set(ref, { decl: decl, declId: id, ref: ref });
  22249. });
  22250. scope.subScopes.forEach(function (s) {
  22251. return rec(s, path);
  22252. });
  22253. }
  22254. if (scope.referencesResolvedSafely) return scope;
  22255. var map = scope.resolvedRefMap || (scope.resolvedRefMap = new Map());
  22256. rec(scope, []);
  22257. scope.referencesResolvedSafely = true;
  22258. return scope;
  22259. }
  22260. function refWithDeclAt(pos, scope) {
  22261. var _iteratorNormalCompletion10 = true;
  22262. var _didIteratorError10 = false;
  22263. var _iteratorError10 = undefined;
  22264. try {
  22265. for (var _iterator10 = scope.resolvedRefMap.values()[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
  22266. var ref = _step10.value;
  22267. var _ref$ref = ref.ref,
  22268. start = _ref$ref.start,
  22269. end = _ref$ref.end;
  22270. if (start <= pos && pos <= end) return ref;
  22271. }
  22272. } catch (err) {
  22273. _didIteratorError10 = true;
  22274. _iteratorError10 = err;
  22275. } finally {
  22276. try {
  22277. if (!_iteratorNormalCompletion10 && _iterator10.return) {
  22278. _iterator10.return();
  22279. }
  22280. } finally {
  22281. if (_didIteratorError10) {
  22282. throw _iteratorError10;
  22283. }
  22284. }
  22285. }
  22286. }
  22287. function topLevelDeclsAndRefs(parsed, options) {
  22288. options = options || {};
  22289. options.withComments = true;
  22290. if (typeof parsed === "string") parsed = parse(parsed, options);
  22291. var scope = scopes(parsed),
  22292. useComments = !!options.jslintGlobalComment,
  22293. declared = _declaredVarNames(scope, useComments),
  22294. refs = scope.refs.concat(lively_lang.arr.flatten(scope.subScopes.map(findUndeclaredReferences))),
  22295. undeclared = lively_lang.arr.withoutAll(refs.map(function (ea) {
  22296. return ea.name;
  22297. }), declared);
  22298. return {
  22299. scope: scope,
  22300. varDecls: scope.varDecls,
  22301. funcDecls: scope.funcDecls.filter(function (ea) {
  22302. return ea.id;
  22303. }),
  22304. classDecls: scope.classDecls.filter(function (ea) {
  22305. return ea.id;
  22306. }),
  22307. declaredNames: declared,
  22308. undeclaredNames: undeclared,
  22309. refs: refs,
  22310. thisRefs: scope.thisRefs
  22311. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  22312. };function findUndeclaredReferences(scope) {
  22313. var names = _declaredVarNames(scope, useComments);
  22314. return scope.subScopes.map(findUndeclaredReferences).reduce(function (refs, ea) {
  22315. return refs.concat(ea);
  22316. }, scope.refs).filter(function (ref) {
  22317. return names.indexOf(ref.name) === -1;
  22318. });
  22319. }
  22320. }
  22321. function findGlobalVarRefs(parsed, options) {
  22322. var topLevel = topLevelDeclsAndRefs(parsed, options),
  22323. noGlobals = topLevel.declaredNames.concat(knownGlobals);
  22324. return topLevel.refs.filter(function (ea) {
  22325. return noGlobals.indexOf(ea.name) === -1;
  22326. });
  22327. }
  22328. function findNodesIncludingLines(parsed, code, lines, options) {
  22329. if (!code && !parsed) throw new Error("Need at least ast or code");
  22330. code = code ? code : stringify(parsed);
  22331. parsed = parsed && parsed.loc ? parsed : parse(code, { locations: true });
  22332. return withMozillaAstDo(parsed, [], function (next, node, found) {
  22333. if (lines.every(function (line) {
  22334. return lively_lang.num.between(line, node.loc.start.line, node.loc.end.line);
  22335. })) {
  22336. lively_lang.arr.pushIfNotIncluded(found, node);next();
  22337. }
  22338. return found;
  22339. });
  22340. }
  22341. function __varDeclIdsFor(scope, name) {
  22342. var result = [];
  22343. var _iteratorNormalCompletion11 = true;
  22344. var _didIteratorError11 = false;
  22345. var _iteratorError11 = undefined;
  22346. try {
  22347. for (var _iterator11 = scope.params[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
  22348. var ea = _step11.value;
  22349. if (ea.name === name) result.push(ea);
  22350. }
  22351. } catch (err) {
  22352. _didIteratorError11 = true;
  22353. _iteratorError11 = err;
  22354. } finally {
  22355. try {
  22356. if (!_iteratorNormalCompletion11 && _iterator11.return) {
  22357. _iterator11.return();
  22358. }
  22359. } finally {
  22360. if (_didIteratorError11) {
  22361. throw _iteratorError11;
  22362. }
  22363. }
  22364. }
  22365. var _iteratorNormalCompletion12 = true;
  22366. var _didIteratorError12 = false;
  22367. var _iteratorError12 = undefined;
  22368. try {
  22369. for (var _iterator12 = scope.funcDecls[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
  22370. var ea = _step12.value;
  22371. if (ea.id && ea.id.name === name) result.push(ea.id);
  22372. }
  22373. } catch (err) {
  22374. _didIteratorError12 = true;
  22375. _iteratorError12 = err;
  22376. } finally {
  22377. try {
  22378. if (!_iteratorNormalCompletion12 && _iterator12.return) {
  22379. _iterator12.return();
  22380. }
  22381. } finally {
  22382. if (_didIteratorError12) {
  22383. throw _iteratorError12;
  22384. }
  22385. }
  22386. }
  22387. var _iteratorNormalCompletion13 = true;
  22388. var _didIteratorError13 = false;
  22389. var _iteratorError13 = undefined;
  22390. try {
  22391. for (var _iterator13 = scope.classDecls[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
  22392. var ea = _step13.value;
  22393. if (ea.id && ea.id.name === name) result.push(ea.id);
  22394. }
  22395. } catch (err) {
  22396. _didIteratorError13 = true;
  22397. _iteratorError13 = err;
  22398. } finally {
  22399. try {
  22400. if (!_iteratorNormalCompletion13 && _iterator13.return) {
  22401. _iterator13.return();
  22402. }
  22403. } finally {
  22404. if (_didIteratorError13) {
  22405. throw _iteratorError13;
  22406. }
  22407. }
  22408. }
  22409. var _iteratorNormalCompletion14 = true;
  22410. var _didIteratorError14 = false;
  22411. var _iteratorError14 = undefined;
  22412. try {
  22413. for (var _iterator14 = scope.importSpecifiers[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) {
  22414. var ea = _step14.value;
  22415. if (ea.name === name) result.push(ea);
  22416. }
  22417. } catch (err) {
  22418. _didIteratorError14 = true;
  22419. _iteratorError14 = err;
  22420. } finally {
  22421. try {
  22422. if (!_iteratorNormalCompletion14 && _iterator14.return) {
  22423. _iterator14.return();
  22424. }
  22425. } finally {
  22426. if (_didIteratorError14) {
  22427. throw _iteratorError14;
  22428. }
  22429. }
  22430. }
  22431. var _iteratorNormalCompletion15 = true;
  22432. var _didIteratorError15 = false;
  22433. var _iteratorError15 = undefined;
  22434. try {
  22435. for (var _iterator15 = helpers.varDeclIds(scope)[Symbol.iterator](), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) {
  22436. var ea = _step15.value;
  22437. if (ea.name === name) result.push(ea);
  22438. }
  22439. } catch (err) {
  22440. _didIteratorError15 = true;
  22441. _iteratorError15 = err;
  22442. } finally {
  22443. try {
  22444. if (!_iteratorNormalCompletion15 && _iterator15.return) {
  22445. _iterator15.return();
  22446. }
  22447. } finally {
  22448. if (_didIteratorError15) {
  22449. throw _iteratorError15;
  22450. }
  22451. }
  22452. }
  22453. return result;
  22454. }
  22455. function findReferencesAndDeclsInScope(scope, name) {
  22456. var _result$decls;
  22457. var startingScope = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  22458. var result = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { refs: [], decls: [] };
  22459. if (name === "this") {
  22460. var _result$refs;
  22461. (_result$refs = result.refs).push.apply(_result$refs, toConsumableArray(scope.thisRefs));
  22462. return result;
  22463. }
  22464. var decls = __varDeclIdsFor(scope, name);
  22465. if (!startingScope && decls.length) return result; // name shadowed in sub-scope
  22466. var _iteratorNormalCompletion16 = true;
  22467. var _didIteratorError16 = false;
  22468. var _iteratorError16 = undefined;
  22469. try {
  22470. for (var _iterator16 = scope.refs[Symbol.iterator](), _step16; !(_iteratorNormalCompletion16 = (_step16 = _iterator16.next()).done); _iteratorNormalCompletion16 = true) {
  22471. var ref = _step16.value;
  22472. if (ref.name === name) result.refs.push(ref);
  22473. }
  22474. } catch (err) {
  22475. _didIteratorError16 = true;
  22476. _iteratorError16 = err;
  22477. } finally {
  22478. try {
  22479. if (!_iteratorNormalCompletion16 && _iterator16.return) {
  22480. _iterator16.return();
  22481. }
  22482. } finally {
  22483. if (_didIteratorError16) {
  22484. throw _iteratorError16;
  22485. }
  22486. }
  22487. }
  22488. (_result$decls = result.decls).push.apply(_result$decls, toConsumableArray(decls));
  22489. var _iteratorNormalCompletion17 = true;
  22490. var _didIteratorError17 = false;
  22491. var _iteratorError17 = undefined;
  22492. try {
  22493. for (var _iterator17 = scope.subScopes[Symbol.iterator](), _step17; !(_iteratorNormalCompletion17 = (_step17 = _iterator17.next()).done); _iteratorNormalCompletion17 = true) {
  22494. var subScope = _step17.value;
  22495. findReferencesAndDeclsInScope(subScope, name, false, result);
  22496. }
  22497. } catch (err) {
  22498. _didIteratorError17 = true;
  22499. _iteratorError17 = err;
  22500. } finally {
  22501. try {
  22502. if (!_iteratorNormalCompletion17 && _iterator17.return) {
  22503. _iterator17.return();
  22504. }
  22505. } finally {
  22506. if (_didIteratorError17) {
  22507. throw _iteratorError17;
  22508. }
  22509. }
  22510. }
  22511. return result;
  22512. }
  22513. function findDeclarationClosestToIndex(parsed, name, index) {
  22514. var found = null;
  22515. lively_lang.arr.detect(scopesAtIndex(parsed, index).reverse(), function (scope) {
  22516. var decls = declarationsOfScope(scope, true),
  22517. idx = lively_lang.arr.pluck(decls, 'name').indexOf(name);
  22518. if (idx === -1) return false;
  22519. found = decls[idx];return true;
  22520. });
  22521. return found;
  22522. }
  22523. function nodesAt$1(pos, ast) {
  22524. ast = typeof ast === 'string' ? parse(ast) : ast;
  22525. return acorn.walk.findNodesIncluding(ast, pos);
  22526. }
  22527. var _stmtTypes = ["EmptyStatement", "BlockStatement", "ExpressionStatement", "IfStatement", "BreakStatement", "ContinueStatement", "WithStatement", "ReturnStatement", "ThrowStatement", "TryStatement", "WhileStatement", "DoWhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DebuggerStatement", "FunctionDeclaration", "VariableDeclaration", "ClassDeclaration", "ImportDeclaration", "ImportDeclaration", "ExportNamedDeclaration", "ExportDefaultDeclaration", "ExportAllDeclaration"];
  22528. function statementOf(parsed, node, options) {
  22529. // Find the statement that a target node is in. Example:
  22530. // let source be "var x = 1; x + 1;" and we are looking for the
  22531. // Identifier "x" in "x+1;". The second statement is what will be found.
  22532. var nodes = nodesAt$1(node.start, parsed),
  22533. found = nodes.reverse().find(function (node) {
  22534. return lively_lang.arr.include(_stmtTypes, node.type);
  22535. });
  22536. if (options && options.asPath) {
  22537. var v = new Visitor(),
  22538. foundPath = void 0;
  22539. v.accept = lively_lang.fun.wrap(v.accept, function (proceed, node, state, path) {
  22540. if (node === found) {
  22541. foundPath = path;throw new Error("stop search");
  22542. }
  22543. return proceed(node, state, path);
  22544. });
  22545. try {
  22546. v.accept(parsed, {}, []);
  22547. } catch (e) {}
  22548. return foundPath;
  22549. }
  22550. return found;
  22551. }
  22552. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  22553. // imports and exports
  22554. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  22555. function imports(scope) {
  22556. // like import "fooo";
  22557. var imports = [],
  22558. stmts = scope.node.body || [];
  22559. for (var i = 0; i < stmts.length; i++) {
  22560. var stmt = stmts[i];
  22561. if (stmt.type !== "ImportDeclaration") continue;
  22562. if (stmt.specifiers.length === 0) {
  22563. imports.push({ local: null, imported: null, fromModule: stmt.source.value, node: stmt });
  22564. continue;
  22565. }
  22566. // like import { x as y } from "fooo"; import * as x from "fooo"; import x from "fooo";
  22567. var from = stmt.source ? stmt.source.value : "unknown module";
  22568. imports.push.apply(imports, toConsumableArray(stmt.specifiers.map(function (importSpec) {
  22569. var imported;
  22570. if (importSpec.type === "ImportNamespaceSpecifier") imported = "*";else if (importSpec.type === "ImportDefaultSpecifier") imported = "default";else if (importSpec.type === "ImportSpecifier") imported = importSpec.imported.name;else imported = null;
  22571. return {
  22572. local: importSpec.local ? importSpec.local.name : null,
  22573. imported: imported,
  22574. fromModule: from,
  22575. node: stmt
  22576. };
  22577. })));
  22578. }
  22579. return imports;
  22580. }
  22581. function exports$1(scope) {
  22582. var resolve = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  22583. if (resolve) resolveReferences(scope);
  22584. var exports = [];
  22585. var _iteratorNormalCompletion18 = true;
  22586. var _didIteratorError18 = false;
  22587. var _iteratorError18 = undefined;
  22588. try {
  22589. var _loop = function _loop() {
  22590. var node = _step18.value;
  22591. exportsStmt = statementOf(scope.node, node);
  22592. if (!exportsStmt) return "continue";
  22593. from = exportsStmt.source ? exportsStmt.source.value : null;
  22594. if (exportsStmt.type === "ExportAllDeclaration") {
  22595. exports.push({
  22596. local: null,
  22597. exported: "*",
  22598. imported: "*",
  22599. fromModule: from,
  22600. node: node,
  22601. type: "all"
  22602. });
  22603. return "continue";
  22604. }
  22605. if (exportsStmt.type === "ExportDefaultDeclaration") {
  22606. if (helpers.isDeclaration(exportsStmt.declaration)) {
  22607. exports.push({
  22608. local: exportsStmt.declaration.id ? exportsStmt.declaration.id.name : null,
  22609. exported: "default",
  22610. type: exportsStmt.declaration.type === "FunctionDeclaration" ? "function" : exportsStmt.declaration.type === "ClassDeclaration" ? "class" : null,
  22611. fromModule: null,
  22612. node: node,
  22613. decl: exportsStmt.declaration,
  22614. declId: exportsStmt.declaration.id
  22615. });
  22616. return "continue";
  22617. }
  22618. if (exportsStmt.declaration.type === "Identifier") {
  22619. var _ref3 = scope.resolvedRefMap.get(exportsStmt.declaration) || {};
  22620. decl = _ref3.decl;
  22621. declId = _ref3.declId;
  22622. exports.push({
  22623. local: exportsStmt.declaration.name,
  22624. exported: "default",
  22625. fromModule: null,
  22626. node: node,
  22627. type: "id",
  22628. decl: decl,
  22629. declId: declId
  22630. });
  22631. return "continue";
  22632. }
  22633. // exportsStmt.declaration is an expression
  22634. exports.push({
  22635. local: null,
  22636. exported: "default",
  22637. fromModule: null,
  22638. node: node,
  22639. type: "expr",
  22640. decl: exportsStmt.declaration,
  22641. declId: exportsStmt.declaration
  22642. });
  22643. return "continue";
  22644. }
  22645. if (exportsStmt.specifiers && exportsStmt.specifiers.length) {
  22646. exports.push.apply(exports, toConsumableArray(exportsStmt.specifiers.map(function (exportSpec) {
  22647. var decl, declId;
  22648. if (from) {
  22649. // "export { x as y } from 'foo'" is the only case where export
  22650. // creates a (non-local) declaration itself
  22651. decl = node;declId = exportSpec.exported;
  22652. } else if (exportSpec.local) {
  22653. var resolved = scope.resolvedRefMap.get(exportSpec.local);
  22654. decl = resolved ? resolved.decl : null;
  22655. declId = resolved ? resolved.declId : null;
  22656. }
  22657. return {
  22658. local: !from && exportSpec.local ? exportSpec.local.name : null,
  22659. exported: exportSpec.exported ? exportSpec.exported.name : null,
  22660. imported: from && exportSpec.local ? exportSpec.local.name : null,
  22661. fromModule: from || null,
  22662. type: "id",
  22663. node: node,
  22664. decl: decl,
  22665. declId: declId
  22666. };
  22667. })));
  22668. return "continue";
  22669. }
  22670. if (exportsStmt.declaration && exportsStmt.declaration.declarations) {
  22671. exports.push.apply(exports, toConsumableArray(exportsStmt.declaration.declarations.map(function (decl) {
  22672. return {
  22673. local: decl.id ? decl.id.name : "default",
  22674. exported: decl.id ? decl.id.name : "default",
  22675. type: exportsStmt.declaration.kind,
  22676. fromModule: null,
  22677. node: node,
  22678. decl: decl,
  22679. declId: decl.id
  22680. };
  22681. })));
  22682. return "continue";
  22683. }
  22684. if (exportsStmt.declaration) {
  22685. exports.push({
  22686. local: exportsStmt.declaration.id ? exportsStmt.declaration.id.name : "default",
  22687. exported: exportsStmt.declaration.id ? exportsStmt.declaration.id.name : "default",
  22688. type: exportsStmt.declaration.type === "FunctionDeclaration" ? "function" : exportsStmt.declaration.type === "ClassDeclaration" ? "class" : null,
  22689. fromModule: null,
  22690. node: node,
  22691. decl: exportsStmt.declaration,
  22692. declId: exportsStmt.declaration.id
  22693. });
  22694. return "continue";
  22695. }
  22696. };
  22697. for (var _iterator18 = scope.exportDecls[Symbol.iterator](), _step18; !(_iteratorNormalCompletion18 = (_step18 = _iterator18.next()).done); _iteratorNormalCompletion18 = true) {
  22698. var exportsStmt;
  22699. var from;
  22700. var decl, declId;
  22701. var _ret = _loop();
  22702. if (_ret === "continue") continue;
  22703. }
  22704. } catch (err) {
  22705. _didIteratorError18 = true;
  22706. _iteratorError18 = err;
  22707. } finally {
  22708. try {
  22709. if (!_iteratorNormalCompletion18 && _iterator18.return) {
  22710. _iterator18.return();
  22711. }
  22712. } finally {
  22713. if (_didIteratorError18) {
  22714. throw _iteratorError18;
  22715. }
  22716. }
  22717. }
  22718. return lively_lang.arr.uniqBy(exports, function (a, b) {
  22719. return a.local == b.local && a.exported == b.exported && a.fromModule == b.fromModule;
  22720. });
  22721. }
  22722. var query = Object.freeze({
  22723. helpers: helpers,
  22724. knownGlobals: knownGlobals,
  22725. scopes: scopes,
  22726. nodesAtIndex: nodesAtIndex,
  22727. scopesAtIndex: scopesAtIndex,
  22728. scopeAtIndex: scopeAtIndex,
  22729. scopesAtPos: scopesAtPos,
  22730. nodesInScopeOf: nodesInScopeOf,
  22731. declarationsOfScope: declarationsOfScope,
  22732. _declaredVarNames: _declaredVarNames,
  22733. _findJsLintGlobalDeclarations: _findJsLintGlobalDeclarations,
  22734. topLevelDeclsAndRefs: topLevelDeclsAndRefs,
  22735. topLevelFuncDecls: topLevelFuncDecls,
  22736. findGlobalVarRefs: findGlobalVarRefs,
  22737. findNodesIncludingLines: findNodesIncludingLines,
  22738. findReferencesAndDeclsInScope: findReferencesAndDeclsInScope,
  22739. findDeclarationClosestToIndex: findDeclarationClosestToIndex,
  22740. nodesAt: nodesAt$1,
  22741. statementOf: statementOf,
  22742. resolveReferences: resolveReferences,
  22743. refWithDeclAt: refWithDeclAt,
  22744. imports: imports,
  22745. exports: exports$1
  22746. });
  22747. var ObjectSpreadTransformer = function (_Visitor) {
  22748. inherits(ObjectSpreadTransformer, _Visitor);
  22749. function ObjectSpreadTransformer() {
  22750. classCallCheck(this, ObjectSpreadTransformer);
  22751. return possibleConstructorReturn(this, (ObjectSpreadTransformer.__proto__ || Object.getPrototypeOf(ObjectSpreadTransformer)).apply(this, arguments));
  22752. }
  22753. createClass(ObjectSpreadTransformer, [{
  22754. key: "accept",
  22755. value: function accept(node, state, path) {
  22756. if (node.type === "ObjectExpression") {
  22757. node = this.transformSpreadElement(node);
  22758. }
  22759. return get(ObjectSpreadTransformer.prototype.__proto__ || Object.getPrototypeOf(ObjectSpreadTransformer.prototype), "accept", this).call(this, node, state, path);
  22760. }
  22761. }, {
  22762. key: "transformSpreadElement",
  22763. value: function transformSpreadElement(node) {
  22764. var currentGroup = [],
  22765. propGroups = [currentGroup];
  22766. node.properties.forEach(function (prop$$1) {
  22767. if (prop$$1.type !== "SpreadElement") currentGroup.push(prop$$1);else {
  22768. propGroups.push(prop$$1);
  22769. currentGroup = [];
  22770. propGroups.push(currentGroup);
  22771. }
  22772. });
  22773. if (propGroups.length === 1) return node;
  22774. if (!currentGroup.length) propGroups.pop();
  22775. return funcCall.apply(undefined, [member("Object", "assign")].concat(toConsumableArray(propGroups.map(function (group) {
  22776. return group.type === "SpreadElement" ? group.argument : {
  22777. properties: group,
  22778. type: 'ObjectExpression'
  22779. };
  22780. }))));
  22781. }
  22782. }]);
  22783. return ObjectSpreadTransformer;
  22784. }(Visitor);
  22785. function objectSpreadTransform(parsed) {
  22786. // "var x = {y, ...z}" => "var x = Object.assign({ y }, z);"
  22787. return new ObjectSpreadTransformer().accept(parsed, {}, []);
  22788. }
  22789. /*global process, global, exports*/
  22790. function _node2string(node) {
  22791. return node.source || stringify(node);
  22792. }
  22793. function _findIndentAt(s, pos) {
  22794. var bol = lively_lang.string.peekLeft(s, pos, /\s+$/),
  22795. indent = typeof bol === 'number' ? s.slice(bol, pos) : '';
  22796. if (indent[0] === '\n') indent = indent.slice(1);
  22797. return indent;
  22798. }
  22799. function _applyChanges(changes, source) {
  22800. for (var i = 0; i < changes.length; i++) {
  22801. var change = changes[i];
  22802. if (change.type === 'del') {
  22803. source = source.slice(0, change.pos) + source.slice(change.pos + change.length);
  22804. } else if (change.type === 'add') {
  22805. source = source.slice(0, change.pos) + change.string + source.slice(change.pos);
  22806. } else {
  22807. throw new Error('Unexpected change ' + lively_lang.obj.inspect(change));
  22808. }
  22809. }
  22810. return source;
  22811. }
  22812. function _compareNodesForReplacement(nodeA, nodeB) {
  22813. // equals
  22814. if (nodeA.start === nodeB.start && nodeA.end === nodeB.end) return 0;
  22815. // a "left" of b
  22816. if (nodeA.end <= nodeB.start) return -1;
  22817. // a "right" of b
  22818. if (nodeA.start >= nodeB.end) return 1;
  22819. // a contains b
  22820. if (nodeA.start <= nodeB.start && nodeA.end >= nodeB.end) return 1;
  22821. // b contains a
  22822. if (nodeB.start <= nodeA.start && nodeB.end >= nodeA.end) return -1;
  22823. throw new Error('Comparing nodes');
  22824. }
  22825. function replaceNode(target, replacementFunc, sourceOrChanges) {
  22826. // parameters:
  22827. // - target: ast node
  22828. // - replacementFunc that gets this node and its source snippet
  22829. // handed and should produce a new ast node or source code.
  22830. // - sourceOrChanges: If its a string -- the source code to rewrite
  22831. // If its and object -- {changes: ARRAY, source: STRING}
  22832. var sourceChanges = (typeof sourceOrChanges === "undefined" ? "undefined" : _typeof(sourceOrChanges)) === 'object' ? sourceOrChanges : { changes: [], source: sourceOrChanges },
  22833. insideChangedBefore = false,
  22834. pos = sourceChanges.changes.reduce(function (pos, change) {
  22835. // fixup the start and end indices of target using the del/add
  22836. // changes already applied
  22837. if (pos.end < change.pos) return pos;
  22838. var isInFront = change.pos < pos.start;
  22839. insideChangedBefore = insideChangedBefore || change.pos >= pos.start && change.pos <= pos.end;
  22840. if (change.type === 'add') return {
  22841. start: isInFront ? pos.start + change.string.length : pos.start,
  22842. end: pos.end + change.string.length
  22843. };
  22844. if (change.type === 'del') return {
  22845. start: isInFront ? pos.start - change.length : pos.start,
  22846. end: pos.end - change.length
  22847. };
  22848. throw new Error('Cannot deal with change ' + lively_lang.obj.inspect(change));
  22849. }, { start: target.start, end: target.end });
  22850. var source = sourceChanges.source,
  22851. replacement = replacementFunc(target, source.slice(pos.start, pos.end), insideChangedBefore),
  22852. replacementSource = typeof replacement === "string" ? replacement : Array.isArray(replacement) ? replacement.map(_node2string).join('\n' + _findIndentAt(source, pos.start)) : replacementSource = _node2string(replacement);
  22853. var changes = [{ type: 'del', pos: pos.start, length: pos.end - pos.start }, { type: 'add', pos: pos.start, string: replacementSource }];
  22854. return {
  22855. changes: sourceChanges.changes.concat(changes),
  22856. source: _applyChanges(changes, source)
  22857. };
  22858. }
  22859. function replaceNodes(targetAndReplacementFuncs, sourceOrChanges) {
  22860. // replace multiple AST nodes, order rewriting from inside out and
  22861. // top to bottom so that nodes to rewrite can overlap or be contained
  22862. // in each other
  22863. var sorted = targetAndReplacementFuncs.sort(function (a, b) {
  22864. return _compareNodesForReplacement(a.target, b.target);
  22865. }),
  22866. sourceChanges = (typeof sourceOrChanges === "undefined" ? "undefined" : _typeof(sourceOrChanges)) === 'object' ? sourceOrChanges : { changes: [], source: sourceOrChanges };
  22867. for (var i = 0; i < sorted.length; i++) {
  22868. var _sorted$i = sorted[i],
  22869. target = _sorted$i.target,
  22870. replacementFunc = _sorted$i.replacementFunc;
  22871. sourceChanges = replaceNode(target, replacementFunc, sourceChanges);
  22872. }
  22873. return sourceChanges;
  22874. }
  22875. function replace(astOrSource, targetNode, replacementFunc, options) {
  22876. // replaces targetNode in astOrSource with what replacementFunc returns
  22877. // (one or multiple ast nodes)
  22878. // Example:
  22879. // var ast = exports.parse('foo.bar("hello");')
  22880. // exports.transform.replace(
  22881. // ast, ast.body[0].expression,
  22882. // function(node, source) {
  22883. // return {type: "CallExpression",
  22884. // callee: {name: node.arguments[0].value, type: "Identifier"},
  22885. // arguments: [{value: "world", type: "Literal"}]
  22886. // }
  22887. // });
  22888. // => {
  22889. // source: "hello('world');",
  22890. // changes: [{pos: 0,length: 16,type: "del"},{pos: 0,string: "hello('world')",type: "add"}]
  22891. // }
  22892. var parsed = (typeof astOrSource === "undefined" ? "undefined" : _typeof(astOrSource)) === 'object' ? astOrSource : null,
  22893. source = typeof astOrSource === 'string' ? astOrSource : parsed.source || _node2string(parsed);
  22894. return replaceNode(targetNode, replacementFunc, source);
  22895. }
  22896. function __findVarDecls(scope) {
  22897. var varDecls = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  22898. varDecls.push.apply(varDecls, toConsumableArray(scope.varDecls));
  22899. var _iteratorNormalCompletion = true;
  22900. var _didIteratorError = false;
  22901. var _iteratorError = undefined;
  22902. try {
  22903. for (var _iterator = scope.subScopes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  22904. var subScope = _step.value;
  22905. __findVarDecls(subScope, varDecls);
  22906. }
  22907. } catch (err) {
  22908. _didIteratorError = true;
  22909. _iteratorError = err;
  22910. } finally {
  22911. try {
  22912. if (!_iteratorNormalCompletion && _iterator.return) {
  22913. _iterator.return();
  22914. }
  22915. } finally {
  22916. if (_didIteratorError) {
  22917. throw _iteratorError;
  22918. }
  22919. }
  22920. }
  22921. return varDecls;
  22922. }
  22923. function oneDeclaratorPerVarDecl(astOrSource) {
  22924. // exports.transform.oneDeclaratorPerVarDecl(
  22925. // "var x = 3, y = (function() { var y = 3, x = 2; })(); ").source
  22926. var parsed = (typeof astOrSource === "undefined" ? "undefined" : _typeof(astOrSource)) === 'object' ? astOrSource : parse(astOrSource),
  22927. source = typeof astOrSource === 'string' ? astOrSource : parsed.source || _node2string(parsed),
  22928. scope = scopes(parsed),
  22929. varDecls = __findVarDecls(scope);
  22930. var targetsAndReplacements = [];
  22931. var _iteratorNormalCompletion2 = true;
  22932. var _didIteratorError2 = false;
  22933. var _iteratorError2 = undefined;
  22934. try {
  22935. for (var _iterator2 = varDecls[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  22936. var decl = _step2.value;
  22937. targetsAndReplacements.push({
  22938. target: decl,
  22939. replacementFunc: function replacementFunc(declNode, s, wasChanged) {
  22940. if (wasChanged) {
  22941. // reparse node if necessary, e.g. if init was changed before like in
  22942. // var x = (function() { var y = ... })();
  22943. declNode = parse(s).body[0];
  22944. }
  22945. return declNode.declarations.map(function (ea) {
  22946. return {
  22947. type: "VariableDeclaration",
  22948. kind: "var", declarations: [ea]
  22949. };
  22950. });
  22951. }
  22952. });
  22953. }
  22954. } catch (err) {
  22955. _didIteratorError2 = true;
  22956. _iteratorError2 = err;
  22957. } finally {
  22958. try {
  22959. if (!_iteratorNormalCompletion2 && _iterator2.return) {
  22960. _iterator2.return();
  22961. }
  22962. } finally {
  22963. if (_didIteratorError2) {
  22964. throw _iteratorError2;
  22965. }
  22966. }
  22967. }
  22968. return replaceNodes(targetsAndReplacements, source);
  22969. }
  22970. function oneDeclaratorForVarsInDestructoring(astOrSource) {
  22971. var parsed = (typeof astOrSource === "undefined" ? "undefined" : _typeof(astOrSource)) === 'object' ? astOrSource : parse(astOrSource),
  22972. source = typeof astOrSource === 'string' ? astOrSource : parsed.source || _node2string(parsed),
  22973. scope = scopes(parsed),
  22974. varDecls = __findVarDecls(scope),
  22975. targetsAndReplacements = [];
  22976. var _iteratorNormalCompletion3 = true;
  22977. var _didIteratorError3 = false;
  22978. var _iteratorError3 = undefined;
  22979. try {
  22980. for (var _iterator3 = varDecls[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
  22981. var decl = _step3.value;
  22982. targetsAndReplacements.push({
  22983. target: decl,
  22984. replacementFunc: function replacementFunc(declNode, s, wasChanged) {
  22985. if (wasChanged) {
  22986. // reparse node if necessary, e.g. if init was changed before like in
  22987. // var x = (function() { var y = ... })();
  22988. declNode = parse(s).body[0];
  22989. }
  22990. var nodes = [];
  22991. var _iteratorNormalCompletion4 = true;
  22992. var _didIteratorError4 = false;
  22993. var _iteratorError4 = undefined;
  22994. try {
  22995. for (var _iterator4 = declNode.declarations[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
  22996. var _declNode = _step4.value;
  22997. var extractedId = { type: "Identifier", name: "__temp" },
  22998. extractedInit = {
  22999. type: "VariableDeclaration", kind: "var",
  23000. declarations: [{ type: "VariableDeclarator", id: extractedId, init: _declNode.init }]
  23001. };
  23002. nodes.push(extractedInit);
  23003. var _iteratorNormalCompletion5 = true;
  23004. var _didIteratorError5 = false;
  23005. var _iteratorError5 = undefined;
  23006. try {
  23007. for (var _iterator5 = helpers.objPropertiesAsList(_declNode.id, [], false)[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
  23008. var _ref2 = _step5.value;
  23009. var keyPath = _ref2.key;
  23010. nodes.push(varDecl(keyPath[keyPath.length - 2], memberChain.apply(undefined, [extractedId.name].concat(toConsumableArray(keyPath))), "var"));
  23011. }
  23012. } catch (err) {
  23013. _didIteratorError5 = true;
  23014. _iteratorError5 = err;
  23015. } finally {
  23016. try {
  23017. if (!_iteratorNormalCompletion5 && _iterator5.return) {
  23018. _iterator5.return();
  23019. }
  23020. } finally {
  23021. if (_didIteratorError5) {
  23022. throw _iteratorError5;
  23023. }
  23024. }
  23025. }
  23026. }
  23027. } catch (err) {
  23028. _didIteratorError4 = true;
  23029. _iteratorError4 = err;
  23030. } finally {
  23031. try {
  23032. if (!_iteratorNormalCompletion4 && _iterator4.return) {
  23033. _iterator4.return();
  23034. }
  23035. } finally {
  23036. if (_didIteratorError4) {
  23037. throw _iteratorError4;
  23038. }
  23039. }
  23040. }
  23041. return nodes;
  23042. }
  23043. });
  23044. }
  23045. } catch (err) {
  23046. _didIteratorError3 = true;
  23047. _iteratorError3 = err;
  23048. } finally {
  23049. try {
  23050. if (!_iteratorNormalCompletion3 && _iterator3.return) {
  23051. _iterator3.return();
  23052. }
  23053. } finally {
  23054. if (_didIteratorError3) {
  23055. throw _iteratorError3;
  23056. }
  23057. }
  23058. }
  23059. return replaceNodes(targetsAndReplacements, source);
  23060. }
  23061. function returnLastStatement(source, opts) {
  23062. opts = opts || {};
  23063. var parsed = parse(source, opts),
  23064. last = lively_lang.arr.last(parsed.body);
  23065. if (last.type !== "ExpressionStatement") return opts.asAST ? parsed : source;
  23066. parsed.body.splice(parsed.body.length - 1, 1, returnStmt(last.expression));
  23067. return opts.asAST ? parsed : stringify(parsed);
  23068. }
  23069. function wrapInFunction(code, opts) {
  23070. opts = opts || {};
  23071. var transformed = returnLastStatement(code, opts);
  23072. return opts.asAST ? program(funcExpr.apply(undefined, [{ id: opts.id || undefined }, []].concat(toConsumableArray(transformed.body)))) : "function" + (opts.id ? " " + opts.id : "") + "() {\n" + transformed + "\n}";
  23073. }
  23074. function wrapInStartEndCall(parsed, options) {
  23075. // Wraps a piece of code into two function calls: One before the first
  23076. // statement and one after the last. Also wraps the entire thing into a try /
  23077. // catch block. The end call gets the result of the last statement (if it is
  23078. // something that returns a value, i.e. an expression) passed as the second
  23079. // argument. If an error occurs the end function is called with an error as
  23080. // first parameter
  23081. // Why? This allows to easily track execution of code, especially for
  23082. // asynchronus / await code!
  23083. // Example:
  23084. // stringify(wrapInStartEndCall("var y = x + 23; y"))
  23085. // // generates code
  23086. // try {
  23087. // __start_execution();
  23088. // __lvVarRecorder.y = x + 23;
  23089. // return __end_execution(null, __lvVarRecorder.y);
  23090. // } catch (err) {
  23091. // return __end_execution(err, undefined);
  23092. // }
  23093. if (typeof parsed === "string") parsed = parse(parsed);
  23094. options = options || {};
  23095. var isProgram = parsed.type === "Program",
  23096. startFuncNode = options.startFuncNode || id("__start_execution"),
  23097. endFuncNode = options.endFuncNode || id("__end_execution"),
  23098. funcDecls = topLevelFuncDecls(parsed),
  23099. innerBody = parsed.body,
  23100. outerBody = [];
  23101. // 1. Hoist func decls outside the actual eval start - end code. The async /
  23102. // generator transforms require this!
  23103. funcDecls.forEach(function (_ref3) {
  23104. var node = _ref3.node,
  23105. path = _ref3.path;
  23106. lively_lang.Path(path).set(parsed, exprStmt(node.id));
  23107. outerBody.push(node);
  23108. });
  23109. // 2. add start-eval call
  23110. innerBody.unshift(exprStmt(funcCall(startFuncNode)));
  23111. // 3. if last statement is an expression, transform it so we can pass it to
  23112. // the end-eval call, replacing the original expression. If it's a
  23113. // non-expression we record undefined as the eval result
  23114. var last = lively_lang.arr.last(innerBody);
  23115. if (last.type === "ExpressionStatement") {
  23116. innerBody.pop();
  23117. innerBody.push(exprStmt(funcCall(endFuncNode, id("null"), last.expression)));
  23118. } else if (last.type === "VariableDeclaration" && lively_lang.arr.last(last.declarations).id.type === "Identifier") {
  23119. innerBody.push(exprStmt(funcCall(endFuncNode, id("null"), lively_lang.arr.last(last.declarations).id)));
  23120. } else {
  23121. innerBody.push(exprStmt(funcCall(endFuncNode, id("null"), id("undefined"))));
  23122. }
  23123. // 4. Wrap that stuff in a try stmt
  23124. outerBody.push(tryStmt.apply(undefined, ["err", [exprStmt(funcCall(endFuncNode, id("err"), id("undefined")))]].concat(toConsumableArray(innerBody))));
  23125. return isProgram ? program.apply(undefined, outerBody) : block$1.apply(undefined, outerBody);
  23126. }
  23127. var isProbablySingleExpressionRe = /^\s*(\{|function\s*\()/;
  23128. function transformSingleExpression(code) {
  23129. // evaling certain expressions such as single functions or object
  23130. // literals will fail or not work as intended. When the code being
  23131. // evaluated consists just out of a single expression we will wrap it in
  23132. // parens to allow for those cases
  23133. // Example:
  23134. // transformSingleExpression("{foo: 23}") // => "({foo: 23})"
  23135. if (!isProbablySingleExpressionRe.test(code) || code.split("\n").length > 30) return code;
  23136. try {
  23137. var parsed = fuzzyParse(code);
  23138. if (parsed.body.length === 1 && (parsed.body[0].type === 'FunctionDeclaration' || parsed.body[0].type === 'BlockStatement' && parsed.body[0].body[0].type === 'LabeledStatement')) {
  23139. code = '(' + code.replace(/;\s*$/, '') + ')';
  23140. }
  23141. } catch (e) {
  23142. if (typeof $world !== "undefined") $world.logError(e);else console.error("Eval preprocess error: %s", e.stack || e);
  23143. }
  23144. return code;
  23145. }
  23146. var transform = Object.freeze({
  23147. replaceNode: replaceNode,
  23148. replaceNodes: replaceNodes,
  23149. replace: replace,
  23150. _compareNodesForReplacement: _compareNodesForReplacement,
  23151. oneDeclaratorPerVarDecl: oneDeclaratorPerVarDecl,
  23152. oneDeclaratorForVarsInDestructoring: oneDeclaratorForVarsInDestructoring,
  23153. returnLastStatement: returnLastStatement,
  23154. wrapInFunction: wrapInFunction,
  23155. wrapInStartEndCall: wrapInStartEndCall,
  23156. transformSingleExpression: transformSingleExpression,
  23157. objectSpreadTransform: objectSpreadTransform
  23158. });
  23159. /*global process, global, exports*/
  23160. function getCommentPrecedingNode(parsed, node) {
  23161. var statementPath = statementOf(parsed, node, { asPath: true }),
  23162. blockPath = statementPath.slice(0, -2),
  23163. block = lively_lang.Path(blockPath).get(parsed);
  23164. return !block.comments || !block.comments.length ? null : lively_lang.chain(extractComments(parsed)).reversed().detect(function (ea) {
  23165. return ea.followingNode === node;
  23166. }).value();
  23167. }
  23168. function extractComments(astOrCode, optCode) {
  23169. var parsed = typeof astOrCode === "string" ? parse(astOrCode, { withComments: true }) : astOrCode,
  23170. code = optCode ? optCode : typeof astOrCode === "string" ? astOrCode : stringify(astOrCode),
  23171. parsedComments = lively_lang.arr.sortBy(commentsWithPathsAndNodes(parsed), function (c) {
  23172. return c.comment.start;
  23173. });
  23174. return parsedComments.map(function (c, i) {
  23175. // 1. a method comment like "x: function() {\n//foo\n ...}"?
  23176. if (isInObjectMethod(c)) {
  23177. return lively_lang.obj.merge([c, c.comment, { type: 'method', comment: c.comment.text }, methodAttributesOf(c)]);
  23178. }
  23179. if (isInComputedMethod(c)) {
  23180. return lively_lang.obj.merge([c, c.comment, { type: 'method', comment: c.comment.text }, computedMethodAttributesOf(c)]);
  23181. }
  23182. // 2. function statement comment like "function foo() {\n//foo\n ...}"?
  23183. if (isInFunctionStatement(c)) {
  23184. return lively_lang.obj.merge([c, c.comment, { type: 'function', comment: c.comment.text }, functionAttributesOf(c)]);
  23185. }
  23186. // 3. assigned method like "foo.bar = function(x) {/*comment*/};"
  23187. if (isInAssignedMethod(c)) {
  23188. return lively_lang.obj.merge([c, c.comment, { type: 'method', comment: c.comment.text }, methodAttributesOfAssignment(c)]);
  23189. }
  23190. // 4. comment preceding another node?
  23191. var followingNode = followingNodeOf(c);
  23192. if (!followingNode) return lively_lang.obj.merge([c, c.comment, { followingNode: followingNode }, unknownComment(c)]);
  23193. // is there another comment in front of the node>
  23194. var followingComment = parsedComments[i + 1];
  23195. if (followingComment && followingComment.comment.start <= followingNode.start) return lively_lang.obj.merge([c, c.comment, { followingNode: followingNode }, unknownComment(c)]);
  23196. // 3. an obj var comment like "// foo\nvar obj = {...}"?
  23197. if (isSingleObjVarDeclaration(followingNode)) {
  23198. return lively_lang.obj.merge([c, c.comment, { followingNode: followingNode }, { type: 'object', comment: c.comment.text }, objAttributesOf(followingNode)]);
  23199. }
  23200. // 4. Is it a simple var declaration like "// foo\nvar obj = 23"?
  23201. if (isSingleVarDeclaration(followingNode)) {
  23202. return lively_lang.obj.merge([c, c.comment, { followingNode: followingNode }, { type: 'var', comment: c.comment.text }, objAttributesOf(followingNode)]);
  23203. }
  23204. return lively_lang.obj.merge([c, c.comment, { followingNode: followingNode }, unknownComment(c)]);
  23205. });
  23206. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23207. function commentsWithPathsAndNodes(parsed) {
  23208. var comments = [],
  23209. v = new Visitor();
  23210. v.accept = lively_lang.fun.wrap(v.accept, function (proceed, node, state, path) {
  23211. if (node.comments) {
  23212. lively_lang.arr.pushAll(comments, node.comments.map(function (comment) {
  23213. return { path: path, comment: comment, node: node };
  23214. }));
  23215. }
  23216. return proceed(node, state, path);
  23217. });
  23218. v.accept(parsed, comments, []);
  23219. return comments;
  23220. }
  23221. function followingNodeOf(comment) {
  23222. return lively_lang.arr.detect(comment.node.body, function (node) {
  23223. return node.start > comment.comment.end;
  23224. });
  23225. }
  23226. function unknownComment(comment) {
  23227. return { type: "unknown", comment: comment.comment.text };
  23228. }
  23229. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23230. function isInFunctionStatement(comment) {
  23231. var node = lively_lang.Path(comment.path.slice(0, -1)).get(parsed);
  23232. return node && node.type === "FunctionDeclaration";
  23233. }
  23234. function functionAttributesOf(comment) {
  23235. var funcNode = lively_lang.Path(comment.path.slice(0, -1)).get(parsed),
  23236. name = funcNode.id ? funcNode.id.name : "<error: no name for function>";
  23237. return { name: name, args: lively_lang.arr.pluck(funcNode.params, "name") };
  23238. }
  23239. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23240. function isInObjectMethod(comment) {
  23241. return lively_lang.arr.equals(comment.path.slice(-2), ["value", "body"]); // obj expr
  23242. }
  23243. function isInAssignedMethod(comment) {
  23244. return lively_lang.arr.equals(comment.path.slice(-2), ["right", "body"]); // asignment
  23245. }
  23246. function methodAttributesOf(comment) {
  23247. var methodNode = lively_lang.Path(comment.path.slice(0, -2)).get(parsed),
  23248. name = methodNode.key ? methodNode.key.name : "<error: no name for method>";
  23249. // if it's someting like "var obj = {foo: function() {...}};"
  23250. var p = comment.path.slice(),
  23251. objectName = "<error: no object found for method>";
  23252. while (p.length && lively_lang.arr.last(p) !== 'init') {
  23253. p.pop();
  23254. }if (p.length) {
  23255. objectName = lively_lang.Path(p.slice(0, -1).concat(["id", "name"])).get(parsed);
  23256. }
  23257. // if it's someting like "exports.obj = {foo: function() {...}};"
  23258. if (lively_lang.string.startsWith(objectName, "<error")) {
  23259. p = comment.path.slice();
  23260. while (p.length && lively_lang.arr.last(p) !== 'right') {
  23261. p.pop();
  23262. }if (p.length) {
  23263. var assignNode = lively_lang.Path(p.slice(0, -1).concat(["left"])).get(parsed);
  23264. objectName = code.slice(assignNode.start, assignNode.end);
  23265. }
  23266. }
  23267. // if it's someting like "Object.extend(Foo.prototype, {m: function() {/*some comment*/ return 23; }})"
  23268. if (lively_lang.string.startsWith(objectName, "<error")) {
  23269. p = comment.path.slice();
  23270. var callExpr = lively_lang.Path(p.slice(0, -6)).get(parsed),
  23271. isCall = callExpr && callExpr.type === "CallExpression",
  23272. firstArg = isCall && callExpr.arguments[0];
  23273. if (firstArg) objectName = code.slice(firstArg.start, firstArg.end);
  23274. }
  23275. return {
  23276. name: name,
  23277. args: lively_lang.arr.pluck(methodNode.value.params, "name"),
  23278. objectName: objectName
  23279. };
  23280. }
  23281. function methodAttributesOfAssignment(comment) {
  23282. var node = lively_lang.Path(comment.path.slice(0, -1)).get(parsed);
  23283. if (node.type !== "FunctionExpression" && node.type !== "FunctionDeclaration") return {};
  23284. var statement = statementOf(parsed, node);
  23285. if (statement.type !== "ExpressionStatement" || statement.expression.type !== "AssignmentExpression") return {};
  23286. var objName = code.slice(statement.expression.left.object.start, statement.expression.left.object.end);
  23287. var methodName = code.slice(statement.expression.left.property.start, statement.expression.left.property.end);
  23288. return {
  23289. name: methodName,
  23290. objectName: objName,
  23291. args: lively_lang.arr.pluck(node.params, "name")
  23292. };
  23293. }
  23294. function isInComputedMethod(comment) {
  23295. var path = comment.path.slice(-5);
  23296. lively_lang.arr.removeAt(path, 1);
  23297. return lively_lang.arr.equals(path, ["properties", "value", "callee", "body"]);
  23298. }
  23299. function computedMethodAttributesOf(comment) {
  23300. var name, args, pathToProp;
  23301. pathToProp = comment.path.slice(0, -3);
  23302. var propertyNode = lively_lang.Path(pathToProp).get(parsed);
  23303. if (propertyNode && propertyNode.type === "Property") {
  23304. // if it is a function immediatelly called
  23305. args = lively_lang.arr.pluck(propertyNode.value.callee.params, "name");
  23306. name = propertyNode.key ? propertyNode.key.name : "<error: no name for method>";
  23307. }
  23308. if (!name) {
  23309. // if it is an object member function
  23310. pathToProp = comment.path.slice(0, -2);
  23311. propertyNode = lively_lang.Path(pathToProp).get(parsed);
  23312. if (propertyNode && propertyNode.type === "Property") {
  23313. args = lively_lang.arr.pluck(propertyNode.value.params, "name");
  23314. name = propertyNode.key ? propertyNode.key.name : "<error: no name for method>";
  23315. }
  23316. }
  23317. if (!name) {
  23318. name = "<error: no name for method>";
  23319. args = [];
  23320. pathToProp = comment.path;
  23321. }
  23322. // if it's someting like "var obj = {foo: function() {...}};"
  23323. var p = lively_lang.arr.clone(pathToProp);
  23324. var objectName = "<error: no object found for method>";
  23325. while (p.length && lively_lang.arr.last(p) !== 'init') {
  23326. p.pop();
  23327. }if (p.length) {
  23328. objectName = lively_lang.Path(p.slice(0, -1).concat(["id", "name"])).get(parsed);
  23329. }
  23330. // if it's someting like "exports.obj = {foo: function() {...}};"
  23331. if (lively_lang.string.startsWith(objectName, "<error")) {
  23332. var p = lively_lang.arr.clone(pathToProp);
  23333. while (p.length && lively_lang.arr.last(p) !== 'right') {
  23334. p.pop();
  23335. }if (p.length) {
  23336. var assignNode = lively_lang.Path(p.slice(0, -1).concat(["left"])).get(parsed);
  23337. objectName = code.slice(assignNode.start, assignNode.end);
  23338. }
  23339. }
  23340. // if it's someting like "Object.extend(Foo.prototype, {m: function() {/*some comment*/ return 23; }})"
  23341. if (lively_lang.string.startsWith(objectName, "<error")) {
  23342. var p = lively_lang.arr.clone(pathToProp);
  23343. var callExpr = lively_lang.Path(p.slice(0, -4)).get(parsed),
  23344. isCall = callExpr && callExpr.type === "CallExpression",
  23345. firstArg = isCall && callExpr.arguments[0];
  23346. if (firstArg) objectName = code.slice(firstArg.start, firstArg.end);
  23347. }
  23348. return { name: name, args: args, objectName: objectName };
  23349. }
  23350. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23351. // like "var foo = {/*...*/}" or "var foo = bar = {/*...*/};"
  23352. function isSingleObjVarDeclaration(node) {
  23353. // should be a var declaration with one declarator with a value
  23354. // being an JS object
  23355. return isSingleVarDeclaration(node) && (node.declarations[0].init.type === "ObjectExpression" || isObjectAssignment(node.declarations[0].init));
  23356. }
  23357. function isSingleVarDeclaration(node) {
  23358. return node && node.type === 'VariableDeclaration' && node.declarations.length === 1;
  23359. }
  23360. function objAttributesOf(node) {
  23361. return { name: node.declarations[0].id.name };
  23362. }
  23363. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23364. // like "foo = {/*...*/}"
  23365. function isObjectAssignment(node) {
  23366. if (node.type !== "AssignmentExpression") return false;
  23367. if (node.right.type === "ObjectExpression") return true;
  23368. if (node.right.type === "AssignmentExpression") return isObjectAssignment(node.right);
  23369. return false;
  23370. }
  23371. }
  23372. var comments = Object.freeze({
  23373. getCommentPrecedingNode: getCommentPrecedingNode,
  23374. extractComments: extractComments
  23375. });
  23376. /*
  23377. types found:
  23378. The def data structure:
  23379. {type, name, node, children?, parent?}
  23380. class-decl
  23381. class-constructor
  23382. class-instance-method
  23383. class-class-method
  23384. class-instance-getter
  23385. class-instance-setter
  23386. class-class-getter
  23387. class-class-setter
  23388. function-decl
  23389. var-decl
  23390. object-decl
  23391. object-method
  23392. object-property
  23393. */
  23394. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23395. // main method
  23396. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23397. function findDecls(parsed, options) {
  23398. // lively.debugNextMethodCall(lively.ast.codeCategorizer, "findDecls")
  23399. options = options || lively_lang.obj.merge({ hideOneLiners: false }, options);
  23400. if (typeof parsed === "string") parsed = parse(parsed, { addSource: true });
  23401. var topLevelNodes = parsed.type === "Program" ? parsed.body : parsed.body.body,
  23402. defs = [],
  23403. hideOneLiners = options.hideOneLiners && parsed.source;
  23404. var _iteratorNormalCompletion = true;
  23405. var _didIteratorError = false;
  23406. var _iteratorError = undefined;
  23407. try {
  23408. for (var _iterator = topLevelNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  23409. var node = _step.value;
  23410. node = unwrapExport(node);
  23411. var found = functionWrapper(node, options) || varDefs(node) || funcDef(node) || es6ClassDef(node) || someObjectExpressionCall(node);
  23412. if (!found) continue;
  23413. if (options.hideOneLiners) {
  23414. if (parsed.loc) {
  23415. found = found.filter(function (def) {
  23416. return !def.node.loc || def.node.loc.start.line !== def.node.loc.end.line;
  23417. });
  23418. } else if (parsed.source) {
  23419. var filtered = [];
  23420. var _iteratorNormalCompletion2 = true;
  23421. var _didIteratorError2 = false;
  23422. var _iteratorError2 = undefined;
  23423. try {
  23424. for (var _iterator2 = found[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  23425. var def = _step2.value;
  23426. if (def.parent && filtered.includes(def.parent) || // parent is in
  23427. (def.node.source || "").includes("\n") // more than one line
  23428. ) filtered.push(def);
  23429. }
  23430. } catch (err) {
  23431. _didIteratorError2 = true;
  23432. _iteratorError2 = err;
  23433. } finally {
  23434. try {
  23435. if (!_iteratorNormalCompletion2 && _iterator2.return) {
  23436. _iterator2.return();
  23437. }
  23438. } finally {
  23439. if (_didIteratorError2) {
  23440. throw _iteratorError2;
  23441. }
  23442. }
  23443. }
  23444. found = filtered;
  23445. }
  23446. }
  23447. defs.push.apply(defs, toConsumableArray(found));
  23448. }
  23449. } catch (err) {
  23450. _didIteratorError = true;
  23451. _iteratorError = err;
  23452. } finally {
  23453. try {
  23454. if (!_iteratorNormalCompletion && _iterator.return) {
  23455. _iterator.return();
  23456. }
  23457. } finally {
  23458. if (_didIteratorError) {
  23459. throw _iteratorError;
  23460. }
  23461. }
  23462. }
  23463. return defs;
  23464. }
  23465. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23466. // defs
  23467. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23468. function es6ClassDef(node) {
  23469. var _def$children;
  23470. if (node.type !== "ClassDeclaration") return null;
  23471. var def = {
  23472. type: "class-decl",
  23473. name: node.id.name,
  23474. node: node,
  23475. children: []
  23476. };
  23477. (_def$children = def.children).push.apply(_def$children, toConsumableArray(node.body.body.map(function (node, i) {
  23478. return es6ClassMethod(node, def, i);
  23479. }).filter(Boolean)));
  23480. return [def].concat(toConsumableArray(def.children));
  23481. }
  23482. function es6ClassMethod(node, parent, i) {
  23483. if (node.type !== "MethodDefinition") return null;
  23484. var type;
  23485. if (node.kind === "constructor") type = "class-constructor";else if (node.kind === "method") type = node.static ? "class-class-method" : "class-instance-method";else if (node.kind === "get") type = node.static ? "class-class-getter" : "class-instance-getter";else if (node.kind === "set") type = node.static ? "class-class-setter" : "class-instance-setter";
  23486. return type ? {
  23487. type: type, parent: parent, node: node,
  23488. name: node.key.name
  23489. } : null;
  23490. }
  23491. function varDefs(varDeclNode) {
  23492. if (varDeclNode.type !== "VariableDeclaration") return null;
  23493. var result = [];
  23494. var _iteratorNormalCompletion3 = true;
  23495. var _didIteratorError3 = false;
  23496. var _iteratorError3 = undefined;
  23497. try {
  23498. var _loop = function _loop() {
  23499. var _ref = _step3.value;
  23500. var id = _ref.id,
  23501. node = _ref.node;
  23502. var def = { name: id.name, node: node, type: "var-decl" };
  23503. result.push(def);
  23504. if (!def.node.init) return "continue";
  23505. var initNode = def.node.init;
  23506. while (initNode.type === "AssignmentExpression") {
  23507. initNode = initNode.right;
  23508. }if (initNode.type === "ObjectExpression") {
  23509. def.type = "object-decl";
  23510. def.children = objectKeyValsAsDefs(initNode).map(function (ea) {
  23511. return _extends({}, ea, { type: "object-" + ea.type, parent: def });
  23512. });
  23513. result.push.apply(result, toConsumableArray(def.children));
  23514. return "continue";
  23515. }
  23516. objDefs = someObjectExpressionCall(initNode, def);
  23517. if (objDefs) {
  23518. def.children = objDefs.map(function (d) {
  23519. return _extends({}, d, { parent: def });
  23520. });
  23521. result.push.apply(result, toConsumableArray(def.children));
  23522. }
  23523. };
  23524. for (var _iterator3 = withVarDeclIds(varDeclNode)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
  23525. var objDefs;
  23526. var _ret = _loop();
  23527. if (_ret === "continue") continue;
  23528. }
  23529. } catch (err) {
  23530. _didIteratorError3 = true;
  23531. _iteratorError3 = err;
  23532. } finally {
  23533. try {
  23534. if (!_iteratorNormalCompletion3 && _iterator3.return) {
  23535. _iterator3.return();
  23536. }
  23537. } finally {
  23538. if (_didIteratorError3) {
  23539. throw _iteratorError3;
  23540. }
  23541. }
  23542. }
  23543. return result;
  23544. }
  23545. function funcDef(node) {
  23546. if (node.type !== "FunctionStatement" && node.type !== "FunctionDeclaration") return null;
  23547. return [{ name: node.id.name, node: node, type: "function-decl" }];
  23548. }
  23549. function someObjectExpressionCall(node, parentDef) {
  23550. // like Foo({....})
  23551. if (node.type === "ExpressionStatement") node = node.expression;
  23552. if (node.type !== "CallExpression") return null;
  23553. var objArg = node.arguments.find(function (a) {
  23554. return a.type === "ObjectExpression";
  23555. });
  23556. if (!objArg) return null;
  23557. return objectKeyValsAsDefs(objArg, parentDef);
  23558. }
  23559. function functionWrapper(node, options) {
  23560. if (!isFunctionWrapper(node)) return null;
  23561. var decls;
  23562. // Is it a function wrapper passed as arg?
  23563. // like ;(function(run) {... })(function(exports) {...})
  23564. var argFunc = lively_lang.Path("expression.arguments.0").get(node);
  23565. if (argFunc && argFunc.type === "FunctionExpression" && lively_lang.string.lines(argFunc.source || "").length > 5) {
  23566. // lively.debugNextMethodCall(lively.ast.CodeCategorizer, "findDecls");
  23567. decls = findDecls(argFunc, options);
  23568. } else {
  23569. decls = findDecls(lively_lang.Path("expression.callee").get(node), options);
  23570. }
  23571. var parent = { node: node, name: lively_lang.Path("expression.callee.id.name").get(node) };
  23572. decls.forEach(function (decl) {
  23573. return decl.parent || (decl.parent = parent);
  23574. });
  23575. return decls;
  23576. }
  23577. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23578. // helpers
  23579. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23580. function unwrapExport(node) {
  23581. return (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") && node.declaration ? node.declaration : node;
  23582. }
  23583. function objectKeyValsAsDefs(objectExpression, parent) {
  23584. return objectExpression.properties.map(function (node) {
  23585. return {
  23586. name: node.key.name || node.key.value,
  23587. type: node.value.type === "FunctionExpression" ? "method" : "property",
  23588. node: node, parent: parent
  23589. };
  23590. });
  23591. }
  23592. function isFunctionWrapper(node) {
  23593. return lively_lang.Path("expression.type").get(node) === "CallExpression" && lively_lang.Path("expression.callee.type").get(node) === "FunctionExpression";
  23594. }
  23595. function withVarDeclIds(varNode) {
  23596. return varNode.declarations.map(function (declNode) {
  23597. if (!declNode.source && declNode.init) declNode.source = declNode.id.name + " = " + declNode.init.source;
  23598. return { node: declNode, id: declNode.id };
  23599. });
  23600. }
  23601. var codeCategorizer = Object.freeze({
  23602. findDecls: findDecls
  23603. });
  23604. // ignore-in-doc
  23605. // As defined in the Ecmascript standard (http://www.ecma-international.org/ecma-262/5.1/#sec-7.6)
  23606. // JS identifiers can consist out of several unicode character classes.
  23607. // The code below was generated using the MIT licensed CSET library, see http://inimino.org/~inimino/blog/javascript_cset
  23608. var isValidIdentifierRe = /^(?!(?:do|if|in|for|let|new|try|var|case|default|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$)[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/;
  23609. function isValidIdentifier(string$$1) {
  23610. return isValidIdentifierRe.test(string$$1);
  23611. }
  23612. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23613. // serialization extension for ast nodes
  23614. var Node = parse("").constructor;
  23615. Object.defineProperty(Node.prototype, "__serialize__", {
  23616. configurable: true,
  23617. value: function value() {
  23618. return {
  23619. __expr__: "(" + JSON.stringify(this) + ")"
  23620. };
  23621. }
  23622. });
  23623. exports.escodegen = es;
  23624. exports.acorn = acorn;
  23625. exports.query = query;
  23626. exports.transform = transform;
  23627. exports.comments = comments;
  23628. exports.categorizer = codeCategorizer;
  23629. exports.stringify = stringify;
  23630. exports.nodes = nodes;
  23631. exports.isValidIdentifier = isValidIdentifier;
  23632. exports.BaseVisitor = Visitor;
  23633. exports.withMozillaAstDo = withMozillaAstDo;
  23634. exports.printAst = printAst;
  23635. exports.compareAst = compareAst;
  23636. exports.pathToNode = pathToNode;
  23637. exports.rematchAstWithSource = rematchAstWithSource;
  23638. exports.ReplaceManyVisitor = ReplaceManyVisitor;
  23639. exports.ReplaceVisitor = ReplaceVisitor;
  23640. exports.parse = parse;
  23641. exports.parseFunction = parseFunction;
  23642. exports.fuzzyParse = fuzzyParse;
  23643. }((this.lively.ast = this.lively.ast || {}),lively.lang,GLOBAL.escodegen,acorn));
  23644. }).call(GLOBAL);
  23645. if (typeof module !== "undefined" && module.exports) module.exports = GLOBAL.lively.ast;
  23646. if (__define_suckz__) { GLOBAL.define = __define_suckz__; }
  23647. })();
  23648. // INLINED END /Users/user/git/lively.vm/node_modules/lively.ast/dist/lively.ast.js
  23649. // INLINED /Users/user/git/lively.vm/node_modules/lively.classes/dist/lively.classes.js
  23650. ;(function() {
  23651. var GLOBAL = typeof window !== "undefined" ? window :
  23652. typeof global!=="undefined" ? global :
  23653. typeof self!=="undefined" ? self : this;
  23654. if (typeof lively.lang === "undefined") GLOBAL.livey.lang = {};
  23655. })();
  23656. (function() {
  23657. var GLOBAL = typeof window !== "undefined" ? window :
  23658. typeof global!=="undefined" ? global :
  23659. typeof self!=="undefined" ? self : this;
  23660. this.lively = this.lively || {};
  23661. (function (exports,lively_lang,lively_ast) {
  23662. 'use strict';
  23663. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj$$1) {
  23664. return typeof obj$$1;
  23665. } : function (obj$$1) {
  23666. return obj$$1 && typeof Symbol === "function" && obj$$1.constructor === Symbol && obj$$1 !== Symbol.prototype ? "symbol" : typeof obj$$1;
  23667. };
  23668. var classCallCheck = function (instance, Constructor) {
  23669. if (!(instance instanceof Constructor)) {
  23670. throw new TypeError("Cannot call a class as a function");
  23671. }
  23672. };
  23673. var createClass = function () {
  23674. function defineProperties(target, props) {
  23675. for (var i = 0; i < props.length; i++) {
  23676. var descriptor = props[i];
  23677. descriptor.enumerable = descriptor.enumerable || false;
  23678. descriptor.configurable = true;
  23679. if ("value" in descriptor) descriptor.writable = true;
  23680. Object.defineProperty(target, descriptor.key, descriptor);
  23681. }
  23682. }
  23683. return function (Constructor, protoProps, staticProps) {
  23684. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  23685. if (staticProps) defineProperties(Constructor, staticProps);
  23686. return Constructor;
  23687. };
  23688. }();
  23689. var defineProperty = function (obj$$1, key, value) {
  23690. if (key in obj$$1) {
  23691. Object.defineProperty(obj$$1, key, {
  23692. value: value,
  23693. enumerable: true,
  23694. configurable: true,
  23695. writable: true
  23696. });
  23697. } else {
  23698. obj$$1[key] = value;
  23699. }
  23700. return obj$$1;
  23701. };
  23702. var _extends = Object.assign || function (target) {
  23703. for (var i = 1; i < arguments.length; i++) {
  23704. var source = arguments[i];
  23705. for (var key in source) {
  23706. if (Object.prototype.hasOwnProperty.call(source, key)) {
  23707. target[key] = source[key];
  23708. }
  23709. }
  23710. }
  23711. return target;
  23712. };
  23713. var get = function get(object, property, receiver) {
  23714. if (object === null) object = Function.prototype;
  23715. var desc = Object.getOwnPropertyDescriptor(object, property);
  23716. if (desc === undefined) {
  23717. var parent = Object.getPrototypeOf(object);
  23718. if (parent === null) {
  23719. return undefined;
  23720. } else {
  23721. return get(parent, property, receiver);
  23722. }
  23723. } else if ("value" in desc) {
  23724. return desc.value;
  23725. } else {
  23726. var getter = desc.get;
  23727. if (getter === undefined) {
  23728. return undefined;
  23729. }
  23730. return getter.call(receiver);
  23731. }
  23732. };
  23733. var inherits = function (subClass, superClass) {
  23734. if (typeof superClass !== "function" && superClass !== null) {
  23735. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  23736. }
  23737. subClass.prototype = Object.create(superClass && superClass.prototype, {
  23738. constructor: {
  23739. value: subClass,
  23740. enumerable: false,
  23741. writable: true,
  23742. configurable: true
  23743. }
  23744. });
  23745. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  23746. };
  23747. var possibleConstructorReturn = function (self, call) {
  23748. if (!self) {
  23749. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  23750. }
  23751. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  23752. };
  23753. var set = function set(object, property, value, receiver) {
  23754. var desc = Object.getOwnPropertyDescriptor(object, property);
  23755. if (desc === undefined) {
  23756. var parent = Object.getPrototypeOf(object);
  23757. if (parent !== null) {
  23758. set(parent, property, value, receiver);
  23759. }
  23760. } else if ("value" in desc && desc.writable) {
  23761. desc.value = value;
  23762. } else {
  23763. var setter = desc.set;
  23764. if (setter !== undefined) {
  23765. setter.call(receiver, value);
  23766. }
  23767. }
  23768. return value;
  23769. };
  23770. var slicedToArray = function () {
  23771. function sliceIterator(arr, i) {
  23772. var _arr = [];
  23773. var _n = true;
  23774. var _d = false;
  23775. var _e = undefined;
  23776. try {
  23777. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  23778. _arr.push(_s.value);
  23779. if (i && _arr.length === i) break;
  23780. }
  23781. } catch (err) {
  23782. _d = true;
  23783. _e = err;
  23784. } finally {
  23785. try {
  23786. if (!_n && _i["return"]) _i["return"]();
  23787. } finally {
  23788. if (_d) throw _e;
  23789. }
  23790. }
  23791. return _arr;
  23792. }
  23793. return function (arr, i) {
  23794. if (Array.isArray(arr)) {
  23795. return arr;
  23796. } else if (Symbol.iterator in Object(arr)) {
  23797. return sliceIterator(arr, i);
  23798. } else {
  23799. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  23800. }
  23801. };
  23802. }();
  23803. var toConsumableArray = function (arr) {
  23804. if (Array.isArray(arr)) {
  23805. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  23806. return arr2;
  23807. } else {
  23808. return Array.from(arr);
  23809. }
  23810. };
  23811. // compactness
  23812. // types -> fabrik
  23813. // serialization, obscure references
  23814. // debugging, more usful inspector
  23815. // change system -> synchronization, serialization, debugging
  23816. // initialization order, dependencies (ex. btn => label => submoprhs needed)
  23817. // declaratively configuring objects
  23818. // propertySettings: {
  23819. // valueStoreProperty: STRING|SYMBOL - optional, defaults to _state. This is where the
  23820. // actual values of the properties will be stored by default
  23821. // defaultGetter: FUNCTION(STRING) - default getter to be used
  23822. // defaultSetter: FUNCTION(STRING, VALUE) - default setter to be used
  23823. // }
  23824. //
  23825. // ????????????
  23826. // propertyDescriptorCacheKey: STRING|SYMBOL - where the result of
  23827. // initializeProperties() should go
  23828. // ????????????
  23829. // properties:
  23830. // {STRING: DESCRIPTOR, ...}
  23831. // properties are merged in the proto chain
  23832. //
  23833. // descriptor: {
  23834. // get: FUNCTION - optional
  23835. // set: FUNCTION - optional
  23836. // defaultValue: OBJECT - optional
  23837. // initialize: FUNCTION - optional, function that when present should
  23838. // produce a value for the property. Run after object creation
  23839. // autoSetter: BOOL - optional, true if not specified
  23840. // usePropertyStore: BOOL - optional, true if not specified.
  23841. // priority: NUMBER - optional, true if not specified.
  23842. // before: [STRING] - optional, list of property names that depend on
  23843. // the descriptor's property and that should be
  23844. // initialized / sorted / ... *after*
  23845. // it. Think of it as a constraint: "this property
  23846. // needs to run before that property"
  23847. // after: [STRING] - optional, list of property names that this property depends on
  23848. // internal: BOOL - optional, if specified marks property as meant for
  23849. // internal housekeeping. At this point this is only used
  23850. // documentation and debugging purposes, it won't affect
  23851. // how the property works
  23852. // }
  23853. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  23854. var defaultPropertiesKey = "properties";
  23855. var propertiesAndSettingsCacheSym = Symbol.for("lively.classes-properties-and-settings");
  23856. var defaultPropertySettings = {
  23857. defaultSetter: null,
  23858. defaultGetter: null,
  23859. valueStoreProperty: "_state"
  23860. };
  23861. function hasManagedProperties(klass) {
  23862. return klass.hasOwnProperty(defaultPropertiesKey);
  23863. }
  23864. function prepareClassForManagedPropertiesAfterCreation(klass) {
  23865. if (!hasManagedProperties(klass)) return;
  23866. var _propertiesAndSetting = propertiesAndSettingsInHierarchyOf(klass),
  23867. properties = _propertiesAndSetting.properties,
  23868. propertySettings = _propertiesAndSetting.propertySettings;
  23869. klass[propertiesAndSettingsCacheSym] = { properties: properties, propertySettings: propertySettings };
  23870. if (!properties || (typeof properties === "undefined" ? "undefined" : _typeof(properties)) !== "object") {
  23871. console.warn("Class " + klass.name + " indicates it has managed properties but its " + ("properties accessor (" + defaultPropertiesKey + ") does not return ") + "a valid property descriptor map");
  23872. return;
  23873. }
  23874. prepareClassForProperties(klass, propertySettings, properties);
  23875. }
  23876. function prepareClassForProperties(klass, propertySettings, properties) {
  23877. ensurePropertyInitializer(klass);
  23878. var valueStoreProperty = propertySettings.valueStoreProperty,
  23879. defaultGetter = propertySettings.defaultGetter,
  23880. defaultSetter = propertySettings.defaultSetter,
  23881. myProto = klass.prototype,
  23882. keys = Object.keys(properties);
  23883. keys.forEach(function (key) {
  23884. var descriptor = properties[key];
  23885. // ... define a getter to the property for the outside world...
  23886. var hasGetter = myProto.hasOwnProperty(key) && myProto.__lookupGetter__(key);
  23887. if (!hasGetter) {
  23888. var getter = descriptor.get || typeof defaultGetter === "function" && function () {
  23889. return defaultGetter.call(this, key);
  23890. } || function () {
  23891. return this[valueStoreProperty][key];
  23892. };
  23893. myProto.__defineGetter__(key, getter);
  23894. }
  23895. // ...define a setter if necessary
  23896. var hasSetter = myProto.hasOwnProperty(key) && myProto.__lookupSetter__(key);
  23897. if (!hasSetter) {
  23898. var descrHasSetter = descriptor.hasOwnProperty("set"),
  23899. setterNeeded = descrHasSetter || !descriptor.readOnly;
  23900. if (setterNeeded) {
  23901. var setter = descriptor.set || typeof defaultSetter === "function" && function (val) {
  23902. defaultSetter.call(this, key, val);
  23903. } || function (val) {
  23904. this[valueStoreProperty][key] = val;
  23905. };
  23906. myProto.__defineSetter__(key, setter);
  23907. }
  23908. }
  23909. });
  23910. }
  23911. function ensurePropertyInitializer(klass) {
  23912. // when we inherit from "conventional classes" those don't have an
  23913. // initializer method. We install a stub that calls the superclass function
  23914. // itself
  23915. Object.defineProperty(klass.prototype, "propertiesAndPropertySettings", {
  23916. enumerable: false,
  23917. configurable: true,
  23918. writable: true,
  23919. value: function value() {
  23920. var klass = this.constructor;
  23921. return klass[propertiesAndSettingsCacheSym] || propertiesAndSettingsInHierarchyOf(klass);
  23922. }
  23923. });
  23924. Object.defineProperty(klass.prototype, "initializeProperties", {
  23925. enumerable: false,
  23926. configurable: true,
  23927. writable: true,
  23928. value: function value(values) {
  23929. var _propertiesAndPropert = this.propertiesAndPropertySettings(),
  23930. properties = _propertiesAndPropert.properties,
  23931. propertySettings = _propertiesAndPropert.propertySettings;
  23932. prepareInstanceForProperties(this, propertySettings, properties, values);
  23933. return this;
  23934. }
  23935. });
  23936. }
  23937. function propertiesAndSettingsInHierarchyOf(klass) {
  23938. // walks class proto chain
  23939. var propertySettings = _extends({}, defaultPropertySettings),
  23940. properties = {},
  23941. allPropSettings = lively_lang.obj.valuesInPropertyHierarchy(klass, "propertySettings"),
  23942. allProps = lively_lang.obj.valuesInPropertyHierarchy(klass, "properties");
  23943. for (var i = 0; i < allPropSettings.length; i++) {
  23944. var current = allPropSettings[i];
  23945. current && (typeof current === "undefined" ? "undefined" : _typeof(current)) === "object" && Object.assign(propertySettings, current);
  23946. }
  23947. for (var i = 0; i < allProps.length; i++) {
  23948. var _current = allProps[i];
  23949. if ((typeof _current === "undefined" ? "undefined" : _typeof(_current)) !== "object") {
  23950. console.error("[initializeProperties] " + klass + " encountered property declaration " + ("that is not a JS object: " + _current));
  23951. continue;
  23952. }
  23953. // "deep" merge
  23954. for (var name in _current) {
  23955. if (!properties.hasOwnProperty(name)) properties[name] = _current[name];else Object.assign(properties[name], _current[name]);
  23956. }
  23957. }
  23958. return { properties: properties, propertySettings: propertySettings };
  23959. }
  23960. function prepareInstanceForProperties(instance, propertySettings, properties, values) {
  23961. var valueStoreProperty = propertySettings.valueStoreProperty,
  23962. sortedKeys = lively_lang.obj.sortKeysWithBeforeAndAfterConstraints(properties),
  23963. propsNeedingInitialize = [],
  23964. initActions = {};
  23965. // 1. this[valueStoreProperty] is were the actual values will be stored
  23966. if (!instance.hasOwnProperty(valueStoreProperty)) instance[valueStoreProperty] = {};
  23967. for (var i = 0; i < sortedKeys.length; i++) {
  23968. var key = sortedKeys[i],
  23969. descriptor = properties[key];
  23970. var derived = descriptor.derived,
  23971. foldable = !!descriptor.foldable,
  23972. defaultValue = descriptor.hasOwnProperty("defaultValue") ? descriptor.defaultValue : undefined;
  23973. if (Array.isArray(defaultValue)) defaultValue = defaultValue.slice();
  23974. if (!derived && !foldable) instance[valueStoreProperty][key] = defaultValue;
  23975. var initAction = void 0;
  23976. if (descriptor.hasOwnProperty("initialize")) {
  23977. initAction = initActions[key] = { initialize: defaultValue };
  23978. propsNeedingInitialize.push(key);
  23979. } else if (derived && defaultValue !== undefined) {
  23980. initAction = initActions[key] = { derived: defaultValue };
  23981. propsNeedingInitialize.push(key);
  23982. } else if (foldable && defaultValue !== undefined) {
  23983. initAction = initActions[key] = { folded: defaultValue };
  23984. propsNeedingInitialize.push(key);
  23985. }
  23986. if (values && key in values) {
  23987. if (descriptor.readOnly) {
  23988. console.warn("Trying to initialize read-only property " + key + " in " + instance + ", " + "skipping setting value");
  23989. } else {
  23990. if (!initAction) {
  23991. initAction = initActions[key] = {};
  23992. propsNeedingInitialize.push(key);
  23993. }
  23994. initAction.value = values[key];
  23995. }
  23996. }
  23997. }
  23998. // 2. Run init code for properties
  23999. // and if we have values we will initialize the properties from it. Values
  24000. // is expected to be a JS object mapping property names to property values
  24001. for (var i = 0; i < propsNeedingInitialize.length; i++) {
  24002. var _key = propsNeedingInitialize[i],
  24003. actions = initActions[_key],
  24004. hasValue = actions.hasOwnProperty("value");
  24005. // if we have an initialize function we call it either with the value from
  24006. // values or with the defaultValue
  24007. if (actions.hasOwnProperty("initialize")) {
  24008. var value = hasValue ? actions.value : actions.initialize;
  24009. properties[_key].initialize.call(instance, value);
  24010. if (hasValue) instance[_key] = actions.value;
  24011. }
  24012. // if we have a derived property we will call the setter with the default
  24013. // value or the value from values
  24014. else if (actions.hasOwnProperty("derived")) {
  24015. instance[_key] = hasValue ? actions.value : actions.derived;
  24016. } else if (actions.hasOwnProperty("folded")) {
  24017. instance[_key] = hasValue ? actions.value : actions.folded;
  24018. }
  24019. // if we only have the value from values we simply call the setter with it
  24020. else if (hasValue) {
  24021. instance[_key] = actions.value;
  24022. }
  24023. }
  24024. }
  24025. var initializeSymbol = Symbol.for("lively-instance-initialize");
  24026. var instanceRestorerSymbol = Symbol.for("lively-instance-restorer");
  24027. var superclassSymbol = Symbol.for("lively-instance-superclass");
  24028. var moduleMetaSymbol = Symbol.for("lively-module-meta");
  24029. var objMetaSymbol = Symbol.for("lively-object-meta");
  24030. var moduleSubscribeToToplevelChangesSym = Symbol.for("lively-klass-changes-subscriber");
  24031. var constructorArgMatcher = /\([^\\)]*\)/;
  24032. var defaultPropertyDescriptorForGetterSetter = {
  24033. enumerable: false,
  24034. configurable: true
  24035. };
  24036. var defaultPropertyDescriptorForValue = {
  24037. enumerable: false,
  24038. configurable: true,
  24039. writable: true
  24040. };
  24041. var setPrototypeOf = typeof Object.setPrototypeOf === "function" ? function (obj$$1, proto) {
  24042. return Object.setPrototypeOf(obj$$1, proto);
  24043. } : function (obj$$1, proto) {
  24044. return obj$$1.__proto__ = proto;
  24045. };
  24046. function adoptObject(object, newClass) {
  24047. // change the class of object to newClass
  24048. if (newClass === object.constructor) return;
  24049. object.constructor = newClass;
  24050. setPrototypeOf(object, newClass.prototype);
  24051. }
  24052. function setSuperclass(klass, superclassOrSpec) {
  24053. // define klass.prototype, klass.prototype[constructor], klass[superclassSymbol]
  24054. var superclass = !superclassOrSpec ? Object : typeof superclassOrSpec === "function" ? superclassOrSpec : superclassOrSpec.value ? superclassOrSpec.value : Object;
  24055. var existingSuperclass = klass && klass[superclassSymbol];
  24056. // set the superclass if necessary and set prototype
  24057. if (!existingSuperclass || existingSuperclass !== superclass) {
  24058. ensureInitializeStub(superclass);
  24059. klass[superclassSymbol] = superclass;
  24060. setPrototypeOf(klass.prototype, superclass.prototype);
  24061. if (superclass !== Object) setPrototypeOf(klass, superclass);
  24062. }
  24063. return superclass;
  24064. }
  24065. function installValueDescriptor(object, klass, descr) {
  24066. descr = Object.assign(descr, defaultPropertyDescriptorForValue);
  24067. descr.value.displayName = descr.key;
  24068. if (descr.needsDeclaringClass) {
  24069. var orig = descr.value.originalFunction || descr.value;
  24070. descr.value = Object.assign(function declaring_class_wrapper() /*args*/{
  24071. return orig.call.apply(orig, [this, klass].concat(Array.prototype.slice.call(arguments)));
  24072. }, {
  24073. originalFunction: orig,
  24074. toString: function toString() {
  24075. return orig.toString();
  24076. },
  24077. displayName: descr.key
  24078. });
  24079. }
  24080. Object.defineProperty(object, descr.key, descr);
  24081. }
  24082. function installGetterSetterDescriptor(klass, descr) {
  24083. descr = Object.assign(descr, defaultPropertyDescriptorForGetterSetter);
  24084. Object.defineProperty(klass, descr.key, descr);
  24085. }
  24086. function installMethods(klass, instanceMethods, classMethods) {
  24087. // install methods from two lists (static + instance) of {key, value} or
  24088. // {key, get/set} descriptors
  24089. classMethods && classMethods.forEach(function (ea) {
  24090. ea.value ? installValueDescriptor(klass, klass, ea) : installGetterSetterDescriptor(klass, ea);
  24091. });
  24092. instanceMethods && instanceMethods.forEach(function (ea) {
  24093. ea.value ? installValueDescriptor(klass.prototype, klass, ea) : installGetterSetterDescriptor(klass.prototype, ea);
  24094. });
  24095. // 4. define initializer method, in our class system the constructor is
  24096. // generic and re-directs to the initializer method. This way we can change
  24097. // the constructor without loosing the identity of the class
  24098. if (!klass.prototype[initializeSymbol]) {
  24099. Object.defineProperty(klass.prototype, initializeSymbol, {
  24100. enumerable: false,
  24101. configurable: true,
  24102. writable: true,
  24103. value: function value() {}
  24104. });
  24105. klass.prototype[initializeSymbol].isDefaultInitializer = true;
  24106. klass.prototype[initializeSymbol].displayName = "lively-initialize";
  24107. } else {
  24108. if (Object.getOwnPropertySymbols(klass.prototype).includes(initializeSymbol)) {
  24109. if (klass.prototype[initializeSymbol].isDefaultInitializer) {
  24110. if (klass[superclassSymbol].prototype[initializeSymbol]) {
  24111. delete klass.prototype[initializeSymbol];
  24112. }
  24113. }
  24114. }
  24115. }
  24116. // 5. undefine properties that were removed form class definition
  24117. var instanceMethodsInClass = instanceMethods.map(function (m) {
  24118. return m.key;
  24119. }).concat(["constructor", "arguments", "caller"]),
  24120. instanceAttributes = Object.getOwnPropertyNames(klass.prototype);
  24121. for (var i = 0; i < instanceAttributes.length; i++) {
  24122. var name = instanceAttributes[i];
  24123. if (!instanceMethodsInClass.includes(name)) delete klass.prototype[name];
  24124. }
  24125. var classMethodsInClass = classMethods.map(function (m) {
  24126. return m.key;
  24127. }).concat(["length", "name", "prototype", "arguments", "caller"]),
  24128. classAttributes = Object.getOwnPropertyNames(klass);
  24129. for (var _i = 0; _i < classAttributes.length; _i++) {
  24130. var _name = classAttributes[_i];
  24131. if (!classMethodsInClass.includes(_name)) delete klass[_name];
  24132. }
  24133. }
  24134. function ensureInitializeStub(superclass) {
  24135. // when we inherit from "conventional classes" those don't have an
  24136. // initializer method. We install a stub that calls the superclass function
  24137. // itself
  24138. if (superclass === Object || superclass.prototype[initializeSymbol]) return;
  24139. Object.defineProperty(superclass.prototype, initializeSymbol, {
  24140. enumerable: false,
  24141. configurable: true,
  24142. writable: true,
  24143. value: function value() /*args*/{
  24144. superclass.apply(this, arguments);
  24145. }
  24146. });
  24147. superclass.prototype[initializeSymbol].displayName = "lively-initialize-stub";
  24148. }
  24149. function initializeClass(constructorFunc, superclassSpec) {
  24150. var instanceMethods = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  24151. var classMethods = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  24152. var classHolder = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  24153. var currentModule = arguments[5];
  24154. var sourceLoc = arguments[6];
  24155. // Given a `classHolder` object as "environment", will try to find a "class"
  24156. // (JS constructor function) inside it. If no class is found it will create a
  24157. // new costructor function object and will attach the methods to it. If a class
  24158. // is found it will be modified.
  24159. // This is being used as the compile target for es6 class syntax by the
  24160. // lively.ast capturing / transform logic
  24161. // Example:
  24162. // var Foo = function(superclass) {
  24163. // function Foo() {}
  24164. // return initializeClass(Foo, superclass, [{key: "m", value: function m() { return 23 }}])
  24165. // }();
  24166. // new Foo().m() // => 23
  24167. // 1. create a new constructor function if necessary, re-use an exisiting if the
  24168. // classHolder object has it
  24169. var className = constructorFunc.name,
  24170. klass = className && classHolder.hasOwnProperty(className) && classHolder[className],
  24171. existingSuperclass = klass && klass[superclassSymbol];
  24172. if (!klass || typeof klass !== "function" || !existingSuperclass) klass = constructorFunc;
  24173. // 2. set the superclass if necessary and set prototype
  24174. var superclass = setSuperclass(klass, superclassSpec);
  24175. // 3. Install methods
  24176. installMethods(klass, instanceMethods, classMethods);
  24177. klass[objMetaSymbol] = sourceLoc;
  24178. // 4. If we have a `currentModule` instance (from lively.modules/src/module.js)
  24179. // then we also store some meta data about the module. This allows us to
  24180. // (de)serialize class instances in lively.serializer
  24181. if (currentModule) {
  24182. var p = currentModule.package();
  24183. var prevMeta = klass[moduleMetaSymbol];
  24184. var t = Date.now();
  24185. klass[moduleMetaSymbol] = {
  24186. package: p ? { name: p.name, version: p.version } : {},
  24187. pathInPackage: p ? currentModule.pathInPackage() : currentModule.id,
  24188. lastChange: prevMeta && prevMeta.lastChange && t <= prevMeta.lastChange ? prevMeta.lastChange + 1 : t,
  24189. lastSuperclassChange: 0
  24190. // if we have a module, we can listen to toplevel changes of it in case the
  24191. // superclass binding changes. With that we can keep our class up-to-date
  24192. // even if the superclass binding changes. This is especially useful for
  24193. // situations where modules have a circular dependency and classes in modules
  24194. // won't get defined correctly when loaded first. See
  24195. // https://github.com/LivelyKernel/lively.modules/issues/27 for more details
  24196. };if (superclassSpec && superclassSpec.referencedAs) {
  24197. if (klass.hasOwnProperty(moduleSubscribeToToplevelChangesSym)) {
  24198. currentModule.unsubscribeFromToplevelDefinitionChanges(klass[moduleSubscribeToToplevelChangesSym]);
  24199. }
  24200. klass[moduleSubscribeToToplevelChangesSym] = currentModule.subscribeToToplevelDefinitionChanges(function (name, val) {
  24201. if (name !== superclassSpec.referencedAs) return;
  24202. // console.log(`class ${className}: new superclass ${name} ${name !== superclassSpec.referencedAs ? '(' + superclassSpec.referencedAs + ')' : ''} was defined via module bindings`)
  24203. // Only run through the (expensive) updates if superclass really has changes
  24204. var superMeta = val && val[moduleMetaSymbol],
  24205. myMeta = klass[moduleMetaSymbol];
  24206. if (superMeta) {
  24207. if (superMeta.lastChange === myMeta.lastSuperclassChange) return;
  24208. myMeta.lastSuperclassChange = superMeta.lastChange;
  24209. }
  24210. setSuperclass(klass, val);
  24211. installMethods(klass, instanceMethods, classMethods);
  24212. prepareClassForManagedPropertiesAfterCreation(klass);
  24213. });
  24214. }
  24215. }
  24216. // 6. Add a toString method for the class to allows us to see its constructor arguments
  24217. klass.toString = function () {
  24218. var constructorArgs = String(this.prototype[initializeSymbol]).match(constructorArgMatcher),
  24219. className = this.name,
  24220. superclass = this[superclassSymbol];
  24221. return "class " + className + " " + (superclass ? "extends " + superclass.name : "") + " {\n" + (" constructor" + (constructorArgs ? constructorArgs[0] : "()") + " { /*...*/ }") + "\n}";
  24222. };
  24223. // 7. If the class allows managed properties (auto getters/setters etc., see
  24224. // managed-properties.js) then setup those
  24225. prepareClassForManagedPropertiesAfterCreation(klass);
  24226. return klass;
  24227. }
  24228. initializeClass._get = function _get(object, property, receiver) {
  24229. if (object === null) object = Function.prototype;
  24230. var desc = Object.getOwnPropertyDescriptor(object, property);
  24231. if (desc === undefined) {
  24232. var parent = Object.getPrototypeOf(object);
  24233. return parent === null ? undefined : _get(parent, property, receiver);
  24234. }
  24235. if ("value" in desc) return desc.value;
  24236. var getter = desc.get;
  24237. return getter === undefined ? undefined : getter.call(receiver);
  24238. };
  24239. initializeClass._set = function _set(object, property, value, receiver) {
  24240. var desc = Object.getOwnPropertyDescriptor(object, property);
  24241. if (desc === undefined) {
  24242. var parent = Object.getPrototypeOf(object);
  24243. if (parent !== null) _set(parent, property, value, receiver);
  24244. } else if ("value" in desc && desc.writable) desc.value = value;else {
  24245. var setter = desc.set;
  24246. if (setter !== undefined) setter.call(receiver, value);
  24247. }
  24248. return value;
  24249. };
  24250. var runtime = Object.freeze({
  24251. initializeSymbol: initializeSymbol,
  24252. instanceRestorerSymbol: instanceRestorerSymbol,
  24253. superclassSymbol: superclassSymbol,
  24254. moduleMetaSymbol: moduleMetaSymbol,
  24255. objMetaSymbol: objMetaSymbol,
  24256. moduleSubscribeToToplevelChangesSym: moduleSubscribeToToplevelChangesSym,
  24257. setPrototypeOf: setPrototypeOf,
  24258. adoptObject: adoptObject,
  24259. setSuperclass: setSuperclass,
  24260. initializeClass: initializeClass
  24261. });
  24262. var assign = lively_ast.nodes.assign;
  24263. var member = lively_ast.nodes.member;
  24264. var id = lively_ast.nodes.id;
  24265. var exprStmt = lively_ast.nodes.exprStmt;
  24266. var funcCall = lively_ast.nodes.funcCall;
  24267. var literal = lively_ast.nodes.literal;
  24268. var objectLiteral = lively_ast.nodes.objectLiteral;
  24269. var varDecl = lively_ast.nodes.varDecl;
  24270. var funcExpr = lively_ast.nodes.funcExpr;
  24271. var returnStmt = lively_ast.nodes.returnStmt;
  24272. var binaryExpr = lively_ast.nodes.binaryExpr;
  24273. var ifStmt = lively_ast.nodes.ifStmt;
  24274. var block = lively_ast.nodes.block;
  24275. function isFunctionNode(node) {
  24276. return node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration";
  24277. }
  24278. var firstIdRe = /^[^_a-z]/i;
  24279. var trailingIdRe = /[^_a-z0-9]/ig;
  24280. function ensureIdentifier(name) {
  24281. return name.replace(firstIdRe, "_").replace(trailingIdRe, "_");
  24282. }
  24283. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  24284. function constructorTemplate(name) {
  24285. // Creates a function like
  24286. // function CLASS() {
  24287. // var firstArg = arguments[0];
  24288. // if (firstArg && firstArg[Symbol.for("lively-instance-restorer")]) {
  24289. // // for deserializing instances just do nothing
  24290. // } else {
  24291. // // automatically call the initialize method
  24292. // this[Symbol.for("lively-instance-initialize")].apply(this, arguments);
  24293. // }
  24294. // }
  24295. return funcExpr({ id: name ? id(name) : null }, ["__first_arg__"], ifStmt(binaryExpr(id("__first_arg__"), "&&", member("__first_arg__", funcCall(member("Symbol", "for"), literal("lively-instance-restorer")), true)), block(), block(exprStmt(funcCall(member(member("this", funcCall(member("Symbol", "for"), literal("lively-instance-initialize")), true), "apply"), id("this"), id("arguments"))))));
  24296. }
  24297. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  24298. var isTransformedClassVarDeclSymbol = Symbol();
  24299. var methodKindSymbol = Symbol();
  24300. var tempLivelyClassVar = "__lively_class__";
  24301. var tempLivelyClassHolderVar = "__lively_classholder__";
  24302. var ClassReplaceVisitor = function (_Visitor) {
  24303. inherits(ClassReplaceVisitor, _Visitor);
  24304. function ClassReplaceVisitor() {
  24305. classCallCheck(this, ClassReplaceVisitor);
  24306. return possibleConstructorReturn(this, (ClassReplaceVisitor.__proto__ || Object.getPrototypeOf(ClassReplaceVisitor)).apply(this, arguments));
  24307. }
  24308. createClass(ClassReplaceVisitor, [{
  24309. key: "accept",
  24310. value: function accept(node, state, path) {
  24311. if (isFunctionNode(node)) {
  24312. state = _extends({}, state, { classHolder: objectLiteral([]),
  24313. currentMethod: node[methodKindSymbol] ? node : state.currentMethod
  24314. });
  24315. }
  24316. if (node.type === "ClassExpression" || node.type === "ClassDeclaration") node = replaceClass(node, state, path, state.options);
  24317. if (node.type === "Super") node = replaceSuper(node, state, path, state.options);
  24318. if (node.type === "MemberExpression" && node.object && node.object.type === "Super") node = replaceSuperGetter(node, state, path, state.options);
  24319. if (node.type === "AssignmentExpression" && node.left.type === "MemberExpression" && node.left.object.type === "Super") node = replaceSuperSetter(node, state, path, state.options);
  24320. if (node.type === "CallExpression" && node.callee.type === "Super") node = replaceDirectSuperCall(node, state, path, state.options);
  24321. if (node.type === "CallExpression" && node.callee.object && node.callee.object.type === "Super") node = replaceSuperMethodCall(node, state, path, state.options);
  24322. node = get(ClassReplaceVisitor.prototype.__proto__ || Object.getPrototypeOf(ClassReplaceVisitor.prototype), "accept", this).call(this, node, state, path);
  24323. if (node.type === "ExportDefaultDeclaration") return splitExportDefaultWithClass(node, state, path, state.options);
  24324. return node;
  24325. }
  24326. }], [{
  24327. key: "run",
  24328. value: function run(parsed, options) {
  24329. var v = new this(),
  24330. classHolder = options.classHolder || objectLiteral([]);
  24331. return v.accept(parsed, { options: options, classHolder: classHolder }, []);
  24332. }
  24333. }]);
  24334. return ClassReplaceVisitor;
  24335. }(lively_ast.BaseVisitor);
  24336. function replaceSuper(node, state, path, options) {
  24337. // just super
  24338. console.assert(node.type === "Super");
  24339. var currentMethod = state.currentMethod;
  24340. if (!currentMethod) {
  24341. console.warn("[lively.classes] Trying to transform es6 class but got super call outside a method! " + lively_ast.stringify(node) + " in " + path.join("."));
  24342. // return node;
  24343. }
  24344. var _path$slice = path.slice(-2),
  24345. _path$slice2 = slicedToArray(_path$slice, 2),
  24346. parentReferencedAs = _path$slice2[0],
  24347. referencedAs = _path$slice2[1];
  24348. if (parentReferencedAs === 'callee' && referencedAs === 'object' || referencedAs === 'callee') return node; // deal with this in replaceSuperCall
  24349. var methodHolder = currentMethod && currentMethod[methodKindSymbol] === "static" ? funcCall(member("Object", "getPrototypeOf"), id(tempLivelyClassVar)) : funcCall(member("Object", "getPrototypeOf"), member(id(tempLivelyClassVar), "prototype"));
  24350. return methodHolder;
  24351. }
  24352. // parse("class Foo extends Bar { get x() { return super.x; }}").body[0]
  24353. function replaceSuperMethodCall(node, state, path, options) {
  24354. // like super.foo()
  24355. console.assert(node.type === "CallExpression");
  24356. console.assert(node.callee.object.type === "Super");
  24357. return funcCall.apply(undefined, [member(funcCall(member(options.functionNode, "_get"), replaceSuper(node.callee.object, state, path.concat(["callee", "object"]), options), literal(node.callee.property.value || node.callee.property.name), id("this")), "call"), id("this")].concat(toConsumableArray(node.arguments)));
  24358. }
  24359. function replaceDirectSuperCall(node, state, path, options) {
  24360. // like super()
  24361. console.assert(node.type === "CallExpression");
  24362. console.assert(node.callee.type === "Super");
  24363. return funcCall.apply(undefined, [member(funcCall(member(options.functionNode, "_get"), replaceSuper(node.callee, state, path.concat(["callee"]), options), funcCall(member("Symbol", "for"), literal("lively-instance-initialize")), id("this")), "call"), id("this")].concat(toConsumableArray(node.arguments)));
  24364. }
  24365. function replaceSuperGetter(node, state, path, options) {
  24366. console.assert(node.type === "MemberExpression");
  24367. console.assert(node.object.type === "Super");
  24368. return funcCall(member(options.functionNode, "_get"), replaceSuper(node.object, state, path.concat(["object"]), options), literal(node.property.value || node.property.name), id("this"));
  24369. }
  24370. function replaceSuperSetter(node, state, path, options) {
  24371. console.assert(node.type === "AssignmentExpression");
  24372. console.assert(node.left.object.type === "Super");
  24373. return funcCall(member(options.functionNode, "_set"), replaceSuper(node.left.object, state, path.concat(["left", "object"]), options), literal(node.left.property.value || node.left.property.name), node.right, id("this"));
  24374. }
  24375. function replaceClass(node, state, path, options) {
  24376. console.assert(node.type === "ClassDeclaration" || node.type === "ClassExpression");
  24377. var body = node.body.body,
  24378. superClass = node.superClass,
  24379. classId = node.id,
  24380. type = node.type,
  24381. start = node.start,
  24382. end = node.end,
  24383. instanceProps = id("undefined"),
  24384. classProps = id("undefined"),
  24385. className = classId ? classId.name : "anonymous_class",
  24386. evalId = options.evalId,
  24387. sourceAccessorName = options.sourceAccessorName,
  24388. loc = node["x-lively-object-meta"] || { start: start, end: end };
  24389. if (body.length) {
  24390. var _body$reduce = body.reduce(function (props, propNode) {
  24391. var decl,
  24392. key = propNode.key,
  24393. kind = propNode.kind,
  24394. value = propNode.value,
  24395. classSide = propNode.static;
  24396. if (key.type !== "Literal" && key.type !== "Identifier") {
  24397. console.warn("Unexpected key in classToFunctionTransform! " + JSON.stringify(key));
  24398. }
  24399. if (kind === "method") {
  24400. // The name is just for debugging purposes when it appears in
  24401. // native debuggers. We have to be careful about it b/c it shadows
  24402. // outer functions / vars, something that is totally not apparent for a user
  24403. // of the class syntax. That's the reason for making it a little cryptic
  24404. var methodId = id(className + "_" + ensureIdentifier(key.name || key.value) + "_"),
  24405. _props = ["key", literal(key.name || key.value), "value", _extends({}, value, defineProperty({ id: methodId }, methodKindSymbol, classSide ? "static" : "proto"))];
  24406. decl = objectLiteral(_props);
  24407. } else if (kind === "get" || kind === "set") {
  24408. decl = objectLiteral(["key", literal(key.name || key.value), kind, Object.assign({}, value, defineProperty({ id: id(kind) }, methodKindSymbol, classSide ? "static" : "proto"))]);
  24409. } else if (kind === "constructor") {
  24410. var _props2 = ["key", funcCall(member("Symbol", "for"), literal("lively-instance-initialize")), "value", _extends({}, value, defineProperty({ id: id(className + "_initialize_") }, methodKindSymbol, "proto"))];
  24411. decl = objectLiteral(_props2);
  24412. } else {
  24413. console.warn("[lively.classes] classToFunctionTransform encountered unknown class property with kind " + kind + ", ignoring it, " + JSON.stringify(propNode));
  24414. }
  24415. (classSide ? props.clazz : props.inst).push(decl);
  24416. return props;
  24417. }, { inst: [], clazz: [] }),
  24418. inst = _body$reduce.inst,
  24419. clazz = _body$reduce.clazz;
  24420. if (inst.length) instanceProps = { type: "ArrayExpression", elements: inst };
  24421. if (clazz.length) classProps = { type: "ArrayExpression", elements: clazz };
  24422. }
  24423. var scope = options.scope,
  24424. superClassReferencedAs,
  24425. superClassRef;
  24426. if (superClass && options.currentModuleAccessor) {
  24427. if (options.classHolder === superClass.object) {
  24428. superClassRef = superClass;
  24429. superClassReferencedAs = superClass.property.name;
  24430. } else {
  24431. var found = scope && scope.resolvedRefMap && scope.resolvedRefMap.get(superClass),
  24432. isTopLevel = found && found.decl && scope.decls && scope.decls.find(function (_ref) {
  24433. var _ref2 = slicedToArray(_ref, 1),
  24434. decl = _ref2[0];
  24435. return decl === found.decl;
  24436. });
  24437. if (isTopLevel) {
  24438. superClassRef = superClass;
  24439. superClassReferencedAs = superClass.name;
  24440. }
  24441. }
  24442. }
  24443. var superClassSpec = superClassRef ? objectLiteral(["referencedAs", literal(superClassReferencedAs), "value", superClassRef]) : superClass || id("undefined");
  24444. // For persistent storage and retrieval of pre-existing classes in "classHolder" object
  24445. var useClassHolder = classId && type === "ClassDeclaration";
  24446. var locKeyVals = ["start", literal(loc.start), "end", literal(loc.end)];
  24447. if (typeof evalId !== "undefined") locKeyVals.push("evalId", literal(evalId));
  24448. if (sourceAccessorName) locKeyVals.push("moduleSource", lively_ast.nodes.id(sourceAccessorName));
  24449. var locNode = objectLiteral(locKeyVals);
  24450. var classCreator = funcCall(funcExpr({}, ["superclass"], varDecl(tempLivelyClassHolderVar, state.classHolder), varDecl(tempLivelyClassVar, useClassHolder ? {
  24451. type: "ConditionalExpression",
  24452. test: binaryExpr(funcCall(member(tempLivelyClassHolderVar, "hasOwnProperty"), literal(classId.name)), "&&", binaryExpr({
  24453. argument: member(tempLivelyClassHolderVar, classId),
  24454. operator: "typeof", prefix: true, type: "UnaryExpression"
  24455. }, "===", literal("function"))),
  24456. consequent: member(tempLivelyClassHolderVar, classId),
  24457. alternate: assign(member(tempLivelyClassHolderVar, classId), constructorTemplate(classId.name))
  24458. } : classId ? constructorTemplate(classId.name) : constructorTemplate(null)), returnStmt(funcCall(options.functionNode, id(tempLivelyClassVar), id("superclass"), instanceProps, classProps, id(tempLivelyClassHolderVar), options.currentModuleAccessor || id("undefined"), locNode))), superClassSpec);
  24459. if (type === "ClassExpression") return classCreator;
  24460. var result = classCreator;
  24461. if (options.declarationWrapper && state.classHolder === options.classHolder /*i.e. toplevel*/) result = funcCall(options.declarationWrapper, literal(classId.name), literal("class"), result, options.classHolder, locNode);
  24462. // since it is a declaration and we removed the class construct we need to add a var-decl
  24463. result = varDecl(classId, result, "var");
  24464. result[isTransformedClassVarDeclSymbol] = true;
  24465. return result;
  24466. }
  24467. function splitExportDefaultWithClass(node, classHolder, path, options) {
  24468. return !node.declaration || !node.declaration[isTransformedClassVarDeclSymbol] ? node : [node.declaration, {
  24469. declaration: node.declaration.declarations[0].id,
  24470. type: "ExportDefaultDeclaration"
  24471. }];
  24472. }
  24473. // var opts = {classHolder: {type: "Identifier", name: "_rec"}, functionNode: {type: "Identifier", name: "createOrExtendClass"}};
  24474. // stringify(classToFunctionTransform(parse("class Foo extends Bar {m() { super.m(); }}"), opts))
  24475. // stringify(classToFunctionTransform(parse("class Foo extends Bar {m() { super.m(arguments[1]); }}"), opts))
  24476. // stringify(classToFunctionTransform(parse("class Foo {constructor() {}}"), opts))
  24477. function classToFunctionTransform(sourceOrAst, options) {
  24478. // required: options = {functionNode, classHolder}
  24479. // From
  24480. // class Foo extends SuperFoo { m() { return 2 + super.m() }}
  24481. // produces something like
  24482. // createOrExtend({}, {referencedAs: "SuperFoo", value: SuperFoo}, "Foo2", [{
  24483. // key: "m",
  24484. // value: function m() {
  24485. // return 2 + this.constructor[superclassSymbol].prototype.m.call(this);
  24486. // }
  24487. // }])
  24488. // console.log(typeof sourceOrAst === "string" ? sourceOrAst : stringify(sourceOrAst))
  24489. var parsed = typeof sourceOrAst === "string" ? lively_ast.parse(sourceOrAst) : sourceOrAst;
  24490. options.scope = lively_ast.query.resolveReferences(lively_ast.query.scopes(parsed));
  24491. var replaced = ClassReplaceVisitor.run(parsed, options);
  24492. return replaced;
  24493. }
  24494. exports.runtime = runtime;
  24495. exports.classToFunctionTransform = classToFunctionTransform;
  24496. }((this.lively.classes = this.lively.classes || {}),lively.lang,lively.ast));
  24497. if (typeof module !== "undefined" && module.exports) module.exports = GLOBAL.lively.classes;
  24498. })();
  24499. // INLINED END /Users/user/git/lively.vm/node_modules/lively.classes/dist/lively.classes.js
  24500. // INLINED /Users/user/git/lively.vm/node_modules/lively.source-transform/dist/lively.source-transform.js
  24501. ;(function() {
  24502. var GLOBAL = typeof window !== "undefined" ? window :
  24503. typeof global!=="undefined" ? global :
  24504. typeof self!=="undefined" ? self : this;
  24505. if (typeof lively.lang === "undefined") GLOBAL.livey.lang = {};
  24506. })();
  24507. (function() {
  24508. var GLOBAL = typeof window !== "undefined" ? window :
  24509. typeof global!=="undefined" ? global :
  24510. typeof self!=="undefined" ? self : this;
  24511. this.lively = this.lively || {};
  24512. (function (exports,lively_lang,lively_classes,lively_ast) {
  24513. 'use strict';
  24514. var _extends = Object.assign || function (target) {
  24515. for (var i = 1; i < arguments.length; i++) {
  24516. var source = arguments[i];
  24517. for (var key in source) {
  24518. if (Object.prototype.hasOwnProperty.call(source, key)) {
  24519. target[key] = source[key];
  24520. }
  24521. }
  24522. }
  24523. return target;
  24524. };
  24525. var get = function get(object, property, receiver) {
  24526. if (object === null) object = Function.prototype;
  24527. var desc = Object.getOwnPropertyDescriptor(object, property);
  24528. if (desc === undefined) {
  24529. var parent = Object.getPrototypeOf(object);
  24530. if (parent === null) {
  24531. return undefined;
  24532. } else {
  24533. return get(parent, property, receiver);
  24534. }
  24535. } else if ("value" in desc) {
  24536. return desc.value;
  24537. } else {
  24538. var getter = desc.get;
  24539. if (getter === undefined) {
  24540. return undefined;
  24541. }
  24542. return getter.call(receiver);
  24543. }
  24544. };
  24545. var set = function set(object, property, value, receiver) {
  24546. var desc = Object.getOwnPropertyDescriptor(object, property);
  24547. if (desc === undefined) {
  24548. var parent = Object.getPrototypeOf(object);
  24549. if (parent !== null) {
  24550. set(parent, property, value, receiver);
  24551. }
  24552. } else if ("value" in desc && desc.writable) {
  24553. desc.value = value;
  24554. } else {
  24555. var setter = desc.set;
  24556. if (setter !== undefined) {
  24557. setter.call(receiver, value);
  24558. }
  24559. }
  24560. return value;
  24561. };
  24562. var toConsumableArray = function (arr$$1) {
  24563. if (Array.isArray(arr$$1)) {
  24564. for (var i = 0, arr2 = Array(arr$$1.length); i < arr$$1.length; i++) arr2[i] = arr$$1[i];
  24565. return arr2;
  24566. } else {
  24567. return Array.from(arr$$1);
  24568. }
  24569. };
  24570. var member = lively_ast.nodes.member;
  24571. var prop = lively_ast.nodes.prop;
  24572. var varDecl = lively_ast.nodes.varDecl;
  24573. var assign = lively_ast.nodes.assign;
  24574. var id = lively_ast.nodes.id;
  24575. var literal = lively_ast.nodes.literal;
  24576. var exprStmt = lively_ast.nodes.exprStmt;
  24577. var conditional = lively_ast.nodes.conditional;
  24578. var binaryExpr = lively_ast.nodes.binaryExpr;
  24579. var funcCall = lively_ast.nodes.funcCall;
  24580. var topLevelDeclsAndRefs = lively_ast.query.topLevelDeclsAndRefs;
  24581. var queryHelpers = lively_ast.query.helpers;
  24582. function rewriteToCaptureTopLevelVariables(parsed, assignToObj, options) {
  24583. /* replaces var and function declarations with assignment statements.
  24584. * Example:
  24585. stringify(
  24586. rewriteToCaptureTopLevelVariables2(
  24587. parse("var x = 3, y = 2, z = 4"),
  24588. {name: "A", type: "Identifier"}, ['z']));
  24589. // => "A.x = 3; A.y = 2; z = 4"
  24590. */
  24591. if (!assignToObj) assignToObj = { type: "Identifier", name: "__rec" };
  24592. options = _extends({
  24593. ignoreUndeclaredExcept: null,
  24594. includeRefs: null,
  24595. excludeRefs: options && options.exclude || [],
  24596. includeDecls: null,
  24597. excludeDecls: options && options.exclude || [],
  24598. recordDefRanges: false,
  24599. es6ExportFuncId: null,
  24600. es6ImportFuncId: null,
  24601. captureObj: assignToObj,
  24602. moduleExportFunc: { name: options && options.es6ExportFuncId || "_moduleExport", type: "Identifier" },
  24603. moduleImportFunc: { name: options && options.es6ImportFuncId || "_moduleImport", type: "Identifier" },
  24604. declarationWrapper: undefined,
  24605. classToFunction: options && options.hasOwnProperty("classToFunction") ? options.classToFunction : {
  24606. classHolder: assignToObj,
  24607. functionNode: { type: "Identifier", name: "_createOrExtendClass" },
  24608. declarationWrapper: options && options.declarationWrapper,
  24609. evalId: options && options.evalId,
  24610. sourceAccessorName: options && options.sourceAccessorName
  24611. }
  24612. }, options);
  24613. var rewritten = parsed;
  24614. // "ignoreUndeclaredExcept" is null if we want to capture all globals in the toplevel scope
  24615. // if it is a list of names we will capture all refs with those names
  24616. if (options.ignoreUndeclaredExcept) {
  24617. var topLevel = topLevelDeclsAndRefs(parsed);
  24618. options.excludeRefs = lively_lang.arr.withoutAll(topLevel.undeclaredNames, options.ignoreUndeclaredExcept).concat(options.excludeRefs);
  24619. options.excludeDecls = lively_lang.arr.withoutAll(topLevel.undeclaredNames, options.ignoreUndeclaredExcept).concat(options.excludeDecls);
  24620. }
  24621. options.excludeRefs = options.excludeRefs.concat(options.captureObj.name);
  24622. options.excludeDecls = options.excludeDecls.concat(options.captureObj.name);
  24623. // 1. def ranges so that we know at which source code positions the
  24624. // definitions are
  24625. var defRanges = options.recordDefRanges ? computeDefRanges(rewritten, options) : null;
  24626. // 2. find those var declarations that should not be rewritten. we
  24627. // currently ignore var declarations in for loops and the error parameter
  24628. // declaration in catch clauses. Also es6 import / export declaration need
  24629. // a special treatment
  24630. // DO NOT rewrite exports like "export { foo as bar }" => "export { _rec.foo as bar }"
  24631. // as this is not valid syntax. Instead we add a var declaration using the
  24632. // recorder as init for those exports later
  24633. options.excludeRefs = options.excludeRefs.concat(additionalIgnoredRefs(parsed, options));
  24634. options.excludeDecls = options.excludeDecls.concat(additionalIgnoredDecls(parsed, options));
  24635. rewritten = fixDefaultAsyncFunctionExportForRegeneratorBug(rewritten, options);
  24636. // 3. if the es6ExportFuncId options is defined we rewrite the es6 form into an
  24637. // obj assignment, converting es6 code to es5 using the extra
  24638. // options.moduleExportFunc and options.moduleImportFunc as capture / sources
  24639. if (options.es6ExportFuncId) {
  24640. options.excludeRefs.push(options.es6ExportFuncId);
  24641. options.excludeRefs.push(options.es6ImportFuncId);
  24642. rewritten = es6ModuleTransforms(rewritten, options);
  24643. }
  24644. // 4. make all references declared in the toplevel scope into property
  24645. // reads of captureObj
  24646. // Example "var foo = 3; 99 + foo;" -> "var foo = 3; 99 + Global.foo;"
  24647. rewritten = replaceRefs(rewritten, options);
  24648. // 5.a turn var declarations into assignments to captureObj
  24649. // Example: "var foo = 3; 99 + foo;" -> "Global.foo = 3; 99 + foo;"
  24650. // if declarationWrapper is requested:
  24651. // "var foo = 3;" -> "Global.foo = _define(3, 'foo', _rec, 'var');"
  24652. rewritten = replaceVarDecls(rewritten, options);
  24653. // 5.b record class declarations
  24654. // Example: "class Foo {}" -> "class Foo {}; Global.Foo = Foo;"
  24655. // if declarationWrapper is requested:
  24656. // "class Foo {}" -> "Global.Foo = _define(class Foo {});"
  24657. rewritten = replaceClassDecls(rewritten, options);
  24658. rewritten = splitExportDeclarations(rewritten, options);
  24659. // 6. es6 export declaration are left untouched but a capturing assignment
  24660. // is added after the export so that we get the value:
  24661. // "export var x = 23;" => "export var x = 23; Global.x = x;"
  24662. rewritten = insertCapturesForExportDeclarations(rewritten, options);
  24663. // 7. es6 import declaration are left untouched but a capturing assignment
  24664. // is added after the import so that we get the value:
  24665. // "import x from './some-es6-module.js';" =>
  24666. // "import x from './some-es6-module.js';\n_rec.x = x;"
  24667. rewritten = insertCapturesForImportDeclarations(rewritten, options);
  24668. // 8. Since variable declarations like "var x = 23" were transformed to sth
  24669. // like "_rex.x = 23" exports can't simply reference vars anymore and
  24670. // "export { _rec.x }" is invalid syntax. So in front of those exports we add
  24671. // var decls manually
  24672. rewritten = insertDeclarationsForExports(rewritten, options);
  24673. // 9. assignments for function declarations in the top level scope are
  24674. // put in front of everything else to mirror the func hoisting:
  24675. // "return bar(); function bar() { return 23 }" ->
  24676. // "Global.bar = bar; return bar(); function bar() { return 23 }"
  24677. // if declarationWrapper is requested:
  24678. // "Global.bar = _define(bar, 'bar', _rec, 'function'); function bar() {}"
  24679. rewritten = putFunctionDeclsInFront(rewritten, options);
  24680. return rewritten;
  24681. }
  24682. function rewriteToRegisterModuleToCaptureSetters(parsed, assignToObj, options) {
  24683. // for rewriting the setters part in code like
  24684. // ```js
  24685. // System.register(["a.js"], function (_export, _context) {
  24686. // var a, _rec;
  24687. // return {
  24688. // setters: [function(foo_a_js) { a = foo_a_js.x }],
  24689. // execute: function () { _rec.x = 23 + _rec.a; }
  24690. // };
  24691. // });
  24692. // ```
  24693. // This allows us to capture (and potentially re-export) imports and their
  24694. // changes without actively running the module again.
  24695. options = _extends({
  24696. captureObj: assignToObj || { type: "Identifier", name: "__rec" },
  24697. exclude: [],
  24698. declarationWrapper: undefined
  24699. }, options);
  24700. var registerCall = lively_lang.Path("body.0.expression").get(parsed);
  24701. if (registerCall.callee.object.name !== "System") throw new Error("rewriteToRegisterModuleToCaptureSetters: input doesn't seem to be a System.register call: " + lively_ast.stringify(parsed).slice(0, 300) + "...");
  24702. if (registerCall.callee.property.name !== "register") throw new Error("rewriteToRegisterModuleToCaptureSetters: input doesn't seem to be a System.register call: " + lively_ast.stringify(parsed).slice(0, 300) + "...");
  24703. var registerBody = lively_lang.Path("arguments.1.body.body").get(registerCall),
  24704. registerReturn = lively_lang.arr.last(registerBody);
  24705. if (registerReturn.type !== "ReturnStatement") throw new Error("rewriteToRegisterModuleToCaptureSetters: input doesn't seem to be a System.register call, at return statement: " + lively_ast.stringify(parsed).slice(0, 300) + "...");
  24706. var setters = registerReturn.argument.properties.find(function (prop) {
  24707. return prop.key.name === "setters";
  24708. });
  24709. if (!setters) throw new Error("rewriteToRegisterModuleToCaptureSetters: input doesn't seem to be a System.register call, at finding setters: " + lively_ast.stringify(parsed).slice(0, 300) + "...");
  24710. var execute = registerReturn.argument.properties.find(function (prop) {
  24711. return prop.key.name === "execute";
  24712. });
  24713. if (!execute) throw new Error("rewriteToRegisterModuleToCaptureSetters: input doesn't seem to be a System.register call, at finding execute: " + lively_ast.stringify(parsed).slice(0, 300) + "...");
  24714. // in each setter function: intercept the assignments to local vars and inject capture object
  24715. setters.value.elements.forEach(function (funcExpr) {
  24716. return funcExpr.body.body = funcExpr.body.body.map(function (stmt) {
  24717. if (stmt.type !== "ExpressionStatement" || stmt.expression.type !== "AssignmentExpression" || stmt.expression.left.type !== "Identifier" || lively_lang.arr.include(options.exclude, stmt.expression.left.name)) return stmt;
  24718. var id = stmt.expression.left,
  24719. rhs = options.declarationWrapper ? declarationWrapperCall(options.declarationWrapper, null, literal(id.name), literal("var"), stmt.expression, options.captureObj, options) : stmt.expression;
  24720. return exprStmt(assign(member(options.captureObj, id), rhs));
  24721. });
  24722. });
  24723. var captureInitialize = execute.value.body.body.find(function (stmt) {
  24724. return stmt.type === "ExpressionStatement" && stmt.expression.type == "AssignmentExpression" && stmt.expression.left.name === options.captureObj.name;
  24725. });
  24726. if (!captureInitialize) captureInitialize = execute.value.body.body.find(function (stmt) {
  24727. return stmt.type === "VariableDeclaration" && stmt.declarations[0].id && stmt.declarations[0].id.name === options.captureObj.name;
  24728. });
  24729. if (captureInitialize) {
  24730. lively_lang.arr.remove(execute.value.body.body, captureInitialize);
  24731. lively_lang.arr.pushAt(registerBody, captureInitialize, registerBody.length - 1);
  24732. }
  24733. if (options.sourceAccessorName) {
  24734. var origSourceInitialize = execute.value.body.body.find(function (stmt) {
  24735. return stmt.type === "ExpressionStatement" && stmt.expression.type == "AssignmentExpression" && stmt.expression.left.name === options.sourceAccessorName;
  24736. });
  24737. if (!origSourceInitialize) origSourceInitialize = execute.value.body.body.find(function (stmt) {
  24738. return stmt.type === "VariableDeclaration" && stmt.declarations[0].id && stmt.declarations[0].id.name === options.sourceAccessorName;
  24739. });
  24740. if (origSourceInitialize) {
  24741. lively_lang.arr.remove(execute.value.body.body, origSourceInitialize);
  24742. lively_lang.arr.pushAt(registerBody, origSourceInitialize, registerBody.length - 1);
  24743. }
  24744. }
  24745. return parsed;
  24746. }
  24747. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  24748. // replacement helpers
  24749. function replaceRefs(parsed, options) {
  24750. var topLevel = topLevelDeclsAndRefs(parsed),
  24751. refsToReplace = topLevel.refs.filter(function (ref) {
  24752. return shouldRefBeCaptured(ref, topLevel, options);
  24753. }),
  24754. locallyIgnored = [];
  24755. var replaced = lively_ast.ReplaceVisitor.run(parsed, function (node, path) {
  24756. // cs 2016/06/27, 1a4661
  24757. // ensure keys of shorthand properties are not renamed while capturing
  24758. if (node.type === "Property" && refsToReplace.includes(node.key) && node.shorthand) return prop(id(node.key.name), node.value);
  24759. // don't replace var refs in expressions such as "export { x }" or "export var x;"
  24760. // We make sure that those var references are defined in insertDeclarationsForExports()
  24761. if (node.type === "ExportNamedDeclaration") {
  24762. var declaration = node.declaration,
  24763. specifiers = node.specifiers;
  24764. if (declaration) {
  24765. if (declaration.id) locallyIgnored.push(declaration.id);else if (declaration.declarations) locallyIgnored.push.apply(locallyIgnored, toConsumableArray(declaration.declarations.map(function (_ref) {
  24766. var id = _ref.id;
  24767. return id;
  24768. })));
  24769. }
  24770. specifiers && specifiers.forEach(function (_ref2) {
  24771. var local = _ref2.local;
  24772. return locallyIgnored.push(local);
  24773. });
  24774. return node;
  24775. }
  24776. // declaration wrapper function for assignments
  24777. // "a = 3" => "a = _define('a', 'assignment', 3, _rec)"
  24778. if (node.type === "AssignmentExpression" && refsToReplace.includes(node.left) && options.declarationWrapper) return _extends({}, node, {
  24779. right: declarationWrapperCall(options.declarationWrapper, null, literal(node.left.name), literal("assignment"), node.right, options.captureObj, options) });
  24780. return node;
  24781. });
  24782. return lively_ast.ReplaceVisitor.run(replaced, function (node, path, parent) {
  24783. return refsToReplace.includes(node) && !locallyIgnored.includes(node) ? member(options.captureObj, node) : node;
  24784. });
  24785. }
  24786. function replaceVarDecls(parsed, options) {
  24787. // rewrites var declarations so that they can be captured by
  24788. // `options.captureObj`.
  24789. // For normal vars we will do a transform like
  24790. // "var x = 23;" => "_rec.x = 23";
  24791. // For patterns (destructuring assignments) we will create assignments for
  24792. // all properties that are being destructured, creating helper vars as needed
  24793. // "var {x: [y]} = foo" => "var _1 = foo; var _1$x = _1.x; __rec.y = _1$x[0];"
  24794. var topLevel = topLevelDeclsAndRefs(parsed);
  24795. return lively_ast.ReplaceManyVisitor.run(parsed, function (node) {
  24796. if (!topLevel.varDecls.includes(node) || node.declarations.every(function (decl) {
  24797. return !shouldDeclBeCaptured(decl, options);
  24798. })) return node;
  24799. var replaced = [];
  24800. for (var i = 0; i < node.declarations.length; i++) {
  24801. var decl = node.declarations[i];
  24802. if (!shouldDeclBeCaptured(decl, options)) {
  24803. replaced.push({ type: "VariableDeclaration", kind: node.kind || "var", declarations: [decl] });
  24804. continue;
  24805. }
  24806. var init = decl.init || {
  24807. operator: "||",
  24808. type: "LogicalExpression",
  24809. left: { computed: false, object: options.captureObj, property: decl.id, type: "MemberExpression" },
  24810. right: { name: "undefined", type: "Identifier" }
  24811. };
  24812. var initWrapped = options.declarationWrapper && decl.id.name ? declarationWrapperCall(options.declarationWrapper, decl, literal(decl.id.name), literal(node.kind), init, options.captureObj, options) : init;
  24813. // Here we create the object pattern / destructuring replacements
  24814. if (decl.id.type.includes("Pattern")) {
  24815. var declRootName = generateUniqueName(topLevel.declaredNames, "destructured_1"),
  24816. declRoot = { type: "Identifier", name: declRootName },
  24817. state = { parent: declRoot, declaredNames: topLevel.declaredNames },
  24818. extractions = transformPattern(decl.id, state).map(function (decl) {
  24819. return decl[annotationSym] && decl[annotationSym].capture ? assignExpr(options.captureObj, decl.declarations[0].id, options.declarationWrapper ? declarationWrapperCall(options.declarationWrapper, null, literal(decl.declarations[0].id.name), literal(node.kind), decl.declarations[0].init, options.captureObj, options) : decl.declarations[0].init, false) : decl;
  24820. });
  24821. topLevel.declaredNames.push(declRootName);
  24822. replaced.push.apply(replaced, toConsumableArray([varDecl(declRoot, initWrapped, node.kind)].concat(extractions)));
  24823. continue;
  24824. }
  24825. // This is rewriting normal vars
  24826. replaced.push(assignExpr(options.captureObj, decl.id, initWrapped, false));
  24827. }
  24828. return replaced;
  24829. });
  24830. }
  24831. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  24832. // naming
  24833. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  24834. function generateUniqueName(declaredNames, hint) {
  24835. var unique = hint,
  24836. n = 1;
  24837. while (declaredNames.indexOf(unique) > -1) {
  24838. if (n > 1000) throw new Error("Endless loop searching for unique variable " + unique);
  24839. unique = unique.replace(/_[0-9]+$|$/, "_" + ++n);
  24840. }
  24841. return unique;
  24842. }
  24843. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  24844. // exclude / include helpers
  24845. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  24846. function additionalIgnoredDecls(parsed, options) {
  24847. var topLevel = topLevelDeclsAndRefs(parsed),
  24848. ignoreDecls = [];
  24849. for (var i = 0; i < topLevel.scope.varDecls.length; i++) {
  24850. var decl = topLevel.scope.varDecls[i],
  24851. path = lively_lang.Path(topLevel.scope.varDeclPaths[i]),
  24852. parent = path.slice(0, -1).get(parsed);
  24853. if (parent.type === "ForStatement" || parent.type === "ForInStatement" || parent.type === "ForOfStatement" || parent.type === "ExportNamedDeclaration") ignoreDecls.push.apply(ignoreDecls, toConsumableArray(decl.declarations));
  24854. }
  24855. return topLevel.scope.catches.map(function (ea) {
  24856. return ea.name;
  24857. }).concat(ignoreDecls.map(function (ea) {
  24858. return ea.id.name;
  24859. }));
  24860. }
  24861. function additionalIgnoredRefs(parsed, options) {
  24862. // FIXME rk 2016-05-11: in shouldRefBeCaptured we now also test for import
  24863. // decls, this should somehow be consolidated with this function and with the
  24864. // fact that naming based ignores aren't good enough...
  24865. var topLevel = topLevelDeclsAndRefs(parsed);
  24866. var ignoreDecls = [];
  24867. for (var i = 0; i < topLevel.scope.varDecls.length; i++) {
  24868. var decl = topLevel.scope.varDecls[i],
  24869. path = lively_lang.Path(topLevel.scope.varDeclPaths[i]),
  24870. parent = path.slice(0, -1).get(parsed);
  24871. if (parent.type === "ForStatement" || parent.type === "ForInStatement" || parent.type === "ForOfStatement") ignoreDecls.push.apply(ignoreDecls, toConsumableArray(decl.declarations));
  24872. }
  24873. return topLevel.scope.catches.map(function (ea) {
  24874. return ea.name;
  24875. }).concat(queryHelpers.declIds(ignoreDecls.map(function (ea) {
  24876. return ea.id;
  24877. })).map(function (ea) {
  24878. return ea.name;
  24879. }));
  24880. }
  24881. function shouldDeclBeCaptured(decl, options) {
  24882. return options.excludeDecls.indexOf(decl.id.name) === -1 && (!options.includeDecls || options.includeDecls.indexOf(decl.id.name) > -1);
  24883. }
  24884. function shouldRefBeCaptured(ref, toplevel, options) {
  24885. if (toplevel.scope.importSpecifiers.includes(ref)) return false;
  24886. for (var i = 0; i < toplevel.scope.exportDecls.length; i++) {
  24887. var ea = toplevel.scope.exportDecls[i];
  24888. if (ea.declarations && ea.declarations.includes(ref)) return false;
  24889. if (ea.declaration === ref) return false;
  24890. }
  24891. if (options.excludeRefs.includes(ref.name)) return false;
  24892. if (options.includeRefs && !options.includeRefs.includes(ref.name)) return false;
  24893. return true;
  24894. }
  24895. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  24896. // capturing specific code
  24897. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  24898. function replaceClassDecls(parsed, options) {
  24899. if (options.classToFunction) return lively_classes.classToFunctionTransform(parsed, options.classToFunction);
  24900. var topLevel = topLevelDeclsAndRefs(parsed);
  24901. if (!topLevel.classDecls.length) return parsed;
  24902. for (var i = parsed.body.length - 1; i >= 0; i--) {
  24903. var stmt = parsed.body[i];
  24904. if (topLevel.classDecls.includes(stmt)) parsed.body.splice(i + 1, 0, assignExpr(options.captureObj, stmt.id, stmt.id, false));
  24905. }
  24906. return parsed;
  24907. }
  24908. function splitExportDeclarations(parsed, options) {
  24909. var stmts = parsed.body,
  24910. newNodes = parsed.body = [];
  24911. for (var i = 0; i < stmts.length; i++) {
  24912. var stmt = stmts[i];
  24913. if (stmt.type !== "ExportNamedDeclaration" || !stmt.declaration || stmt.declaration.type !== "VariableDeclaration" || stmt.declaration.declarations.length <= 1) {
  24914. newNodes.push(stmt);continue;
  24915. }
  24916. var decls = stmt.declaration.declarations;
  24917. for (var j = 0; j < decls.length; j++) {
  24918. newNodes.push({
  24919. type: "ExportNamedDeclaration",
  24920. specifiers: [],
  24921. declaration: varDecl(decls[j].id, decls[j].init, stmt.declaration.kind)
  24922. });
  24923. }
  24924. }
  24925. return parsed;
  24926. }
  24927. function insertCapturesForExportDeclarations(parsed, options) {
  24928. var body = [];
  24929. for (var i = 0; i < parsed.body.length; i++) {
  24930. var stmt = parsed.body[i];
  24931. body.push(stmt);
  24932. // ExportNamedDeclaration can have specifieres = refs, those should already
  24933. // be captured. Only focus on export declarations and only those
  24934. // declarations that are no refs, i.e.
  24935. // ignore: "export default x;"
  24936. // capture: "export default function foo () {};", "export var x = 23, y = 3;"
  24937. if (stmt.type !== "ExportNamedDeclaration" && stmt.type !== "ExportDefaultDeclaration" || !stmt.declaration) {
  24938. /*...*/
  24939. } else if (stmt.declaration.declarations) {
  24940. body.push.apply(body, toConsumableArray(stmt.declaration.declarations.map(function (decl) {
  24941. var assignVal = decl.id;
  24942. if (options.declarationWrapper) {
  24943. var alreadyWrapped = decl.init.callee && decl.init.callee.name === options.declarationWrapper.name;
  24944. if (!alreadyWrapped) assignVal = declarationWrapperCall(options.declarationWrapper, decl, literal(decl.id.name), literal("assignment"), decl.id, options.captureObj, options);
  24945. }
  24946. return assignExpr(options.captureObj, decl.id, assignVal, false);
  24947. })));
  24948. } else if (stmt.declaration.type === "FunctionDeclaration") {
  24949. /*handled by function rewriter as last step*/
  24950. } else if (stmt.declaration.type === "ClassDeclaration") {
  24951. body.push(assignExpr(options.captureObj, stmt.declaration.id, stmt.declaration.id, false));
  24952. }
  24953. }
  24954. parsed.body = body;
  24955. return parsed;
  24956. }
  24957. function insertCapturesForImportDeclarations(parsed, options) {
  24958. parsed.body = parsed.body.reduce(function (stmts, stmt) {
  24959. return stmts.concat(stmt.type !== "ImportDeclaration" || !stmt.specifiers.length ? [stmt] : [stmt].concat(stmt.specifiers.map(function (specifier) {
  24960. return assignExpr(options.captureObj, specifier.local, specifier.local, false);
  24961. })));
  24962. }, []);
  24963. return parsed;
  24964. }
  24965. function insertDeclarationsForExports(parsed, options) {
  24966. var topLevel = topLevelDeclsAndRefs(parsed),
  24967. body = [];
  24968. for (var i = 0; i < parsed.body.length; i++) {
  24969. var stmt = parsed.body[i];
  24970. if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration && stmt.declaration.type.indexOf("Declaration") === -1) {
  24971. body = body.concat([varDeclOrAssignment(parsed, {
  24972. type: "VariableDeclarator",
  24973. id: stmt.declaration,
  24974. init: member(options.captureObj, stmt.declaration)
  24975. }), stmt]);
  24976. } else if (stmt.type !== "ExportNamedDeclaration" || !stmt.specifiers.length || stmt.source) {
  24977. body.push(stmt);
  24978. } else {
  24979. body = body.concat(stmt.specifiers.map(function (specifier) {
  24980. return lively_lang.arr.include(topLevel.declaredNames, specifier.local.name) ? null : varDeclOrAssignment(parsed, {
  24981. type: "VariableDeclarator",
  24982. id: specifier.local,
  24983. init: member(options.captureObj, specifier.local)
  24984. });
  24985. }).filter(Boolean)).concat(stmt);
  24986. }
  24987. }
  24988. parsed.body = body;
  24989. return parsed;
  24990. }
  24991. function fixDefaultAsyncFunctionExportForRegeneratorBug(parsed, options) {
  24992. // rk 2016-06-02: see https://github.com/LivelyKernel/lively.modules/issues/9
  24993. // FIXME this needs to be removed as soon as the cause for the issue is fixed
  24994. var body = [];
  24995. for (var i = 0; i < parsed.body.length; i++) {
  24996. var stmt = parsed.body[i];
  24997. if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration.type === "FunctionDeclaration" && stmt.declaration.id && stmt.declaration.async) {
  24998. body.push(stmt.declaration);
  24999. stmt.declaration = { type: "Identifier", name: stmt.declaration.id.name };
  25000. }
  25001. body.push(stmt);
  25002. }
  25003. parsed.body = body;
  25004. return parsed;
  25005. }
  25006. function es6ModuleTransforms(parsed, options) {
  25007. parsed.body = parsed.body.reduce(function (stmts, stmt) {
  25008. var nodes$$1;
  25009. if (stmt.type === "ExportNamedDeclaration") {
  25010. if (stmt.source) {
  25011. var key = moduleId = stmt.source;
  25012. nodes$$1 = stmt.specifiers.map(function (specifier) {
  25013. return {
  25014. type: "ExpressionStatement",
  25015. expression: exportFromImport({ type: "Literal", value: specifier.exported.name }, { type: "Literal", value: specifier.local.name }, moduleId, options.moduleExportFunc, options.moduleImportFunc) };
  25016. });
  25017. } else if (stmt.declaration) {
  25018. var decls = stmt.declaration.declarations;
  25019. if (!decls) {
  25020. // func decl or class
  25021. nodes$$1 = [stmt.declaration].concat(exportCallStmt(options.moduleExportFunc, stmt.declaration.id.name, stmt.declaration.id));
  25022. } else {
  25023. nodes$$1 = decls.map(function (decl) {
  25024. options.excludeDecls.push(decl.id);
  25025. return varDecl(decl.id, assignExpr(options.captureObj, decl.id, options.declarationWrapper ? declarationWrapperCall(options.declarationWrapper, null, literal(decl.id.name), literal(stmt.declaration.kind), decl, options.captureObj, options) : decl.init, false), stmt.declaration.kind);
  25026. }).concat(decls.map(function (decl) {
  25027. return exportCallStmt(options.moduleExportFunc, decl.id.name, decl.id);
  25028. }));
  25029. }
  25030. } else {
  25031. nodes$$1 = stmt.specifiers.map(function (specifier) {
  25032. return exportCallStmt(options.moduleExportFunc, specifier.exported.name, shouldDeclBeCaptured({ id: specifier.local }, options) ? member(options.captureObj, specifier.local) : specifier.local);
  25033. });
  25034. }
  25035. } else if (stmt.type === "ExportDefaultDeclaration") {
  25036. if (stmt.declaration && stmt.declaration.id) {
  25037. nodes$$1 = [stmt.declaration].concat(exportCallStmt(options.moduleExportFunc, "default", stmt.declaration.id));
  25038. } else {
  25039. nodes$$1 = [exportCallStmt(options.moduleExportFunc, "default", stmt.declaration)];
  25040. }
  25041. } else if (stmt.type === "ExportAllDeclaration") {
  25042. var key = { name: options.es6ExportFuncId + "__iterator__", type: "Identifier" },
  25043. moduleId = stmt.source;
  25044. nodes$$1 = [{
  25045. type: "ForInStatement",
  25046. body: { type: "ExpressionStatement", expression: exportFromImport(key, key, moduleId, options.moduleExportFunc, options.moduleImportFunc) },
  25047. left: { type: "VariableDeclaration", kind: "var", declarations: [{ type: "VariableDeclarator", id: key, init: null }] },
  25048. right: importCall(null, moduleId, options.moduleImportFunc)
  25049. }];
  25050. options.excludeRefs.push(key.name);
  25051. options.excludeDecls.push(key.name);
  25052. } else if (stmt.type === "ImportDeclaration") {
  25053. nodes$$1 = stmt.specifiers.length ? stmt.specifiers.map(function (specifier) {
  25054. var local = specifier.local,
  25055. imported = specifier.type === "ImportSpecifier" && specifier.imported.name || specifier.type === "ImportDefaultSpecifier" && "default" || null;
  25056. return varDeclAndImportCall(parsed, local, imported || null, stmt.source, options.moduleImportFunc);
  25057. }) : importCallStmt(null, stmt.source, options.moduleImportFunc);
  25058. } else nodes$$1 = [stmt];
  25059. return stmts.concat(nodes$$1);
  25060. }, []);
  25061. return parsed;
  25062. }
  25063. function putFunctionDeclsInFront(parsed, options) {
  25064. var scope = topLevelDeclsAndRefs(parsed).scope,
  25065. funcDecls = scope.funcDecls;
  25066. if (!funcDecls.length) return parsed;
  25067. var putInFront = [];
  25068. for (var i = funcDecls.length; i--;) {
  25069. var decl = funcDecls[i];
  25070. if (!shouldDeclBeCaptured(decl, options)) continue;
  25071. var parentPath = scope.funcDeclPaths[i].slice(0, -1),
  25072. // ge the parent so we can replace the original function:
  25073. parent = lively_lang.Path(parentPath).get(scope.node),
  25074. funcId = { type: "Identifier", name: decl.id.name },
  25075. // what we capture:
  25076. init = options.declarationWrapper ? declarationWrapperCall(options.declarationWrapper, decl, literal(funcId.name), literal("function"), funcId, options.captureObj, options) : funcId,
  25077. declFront = _extends({}, decl);
  25078. if (Array.isArray(parent)) {
  25079. // If the parent is a body array we remove the original func decl from it
  25080. // and replace it with a reference to the function
  25081. parent.splice(parent.indexOf(decl), 1, exprStmt(decl.id));
  25082. } else if (parent.type === "ExportNamedDeclaration") {
  25083. // If the function is exported we change the export declaration into a reference
  25084. var parentIndexInBody = scope.node.body.indexOf(parent);
  25085. if (parentIndexInBody > -1) {
  25086. scope.node.body.splice(parentIndexInBody, 1, { type: "ExportNamedDeclaration", specifiers: [{ type: "ExportSpecifier", exported: decl.id, local: decl.id }] });
  25087. }
  25088. } else if (parent.type === "ExportDefaultDeclaration") {
  25089. parent.declaration = decl.id;
  25090. } else {}
  25091. // ??? just leave it alone...
  25092. // decl.type = "EmptyStatement";
  25093. // hoist the function to the front, also it's capture
  25094. putInFront.unshift(assignExpr(options.captureObj, funcId, init, false));
  25095. putInFront.unshift(declFront);
  25096. }
  25097. parsed.body = putInFront.concat(parsed.body);
  25098. return parsed;
  25099. }
  25100. function computeDefRanges(parsed, options) {
  25101. var topLevel = topLevelDeclsAndRefs(parsed);
  25102. return lively_lang.chain(topLevel.scope.varDecls).pluck("declarations").flatten().value().concat(topLevel.scope.funcDecls).reduce(function (defs, decl) {
  25103. if (!defs[decl.id.name]) defs[decl.id.name] = [];
  25104. defs[decl.id.name].push({ type: decl.type, start: decl.start, end: decl.end });
  25105. return defs;
  25106. }, {});
  25107. }
  25108. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  25109. // capturing oobject patters / destructuring
  25110. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  25111. var annotationSym = Symbol("lively.ast-destructuring-transform");
  25112. function transformPattern(pattern, transformState) {
  25113. // For transforming destructuring expressions into plain vars and member access.
  25114. // Takes a var or argument pattern node (of type ArrayPattern or
  25115. // ObjectPattern) and transforms it into a set of var declarations that will
  25116. // "pull out" the nested properties
  25117. // Example:
  25118. // var parsed = parse("var [{b: {c: [a]}}] = foo;");
  25119. // var state = {parent: {type: "Identifier", name: "arg"}, declaredNames: ["foo"]}
  25120. // transformPattern(parsed.body[0].declarations[0].id, state).map(stringify).join("\n");
  25121. // // => "var arg$0 = arg[0];\n"
  25122. // // + "var arg$0$b = arg$0.b;\n"
  25123. // // + "var arg$0$b$c = arg$0$b.c;\n"
  25124. // // + "var a = arg$0$b$c[0];"
  25125. return pattern.type === "ArrayPattern" ? transformArrayPattern(pattern, transformState) : pattern.type === "ObjectPattern" ? transformObjectPattern(pattern, transformState) : [];
  25126. }
  25127. function transformArrayPattern(pattern, transformState) {
  25128. var declaredNames = transformState.declaredNames,
  25129. p = annotationSym,
  25130. transformed = [];
  25131. for (var i = 0; i < pattern.elements.length; i++) {
  25132. var el = pattern.elements[i];
  25133. // like [a]
  25134. if (el.type === "Identifier") {
  25135. var decl = varDecl(el, member(transformState.parent, id(i), true));
  25136. decl[p] = { capture: true };
  25137. transformed.push(decl);
  25138. // like [...foo]
  25139. } else if (el.type === "RestElement") {
  25140. var decl = varDecl(el.argument, {
  25141. type: "CallExpression",
  25142. arguments: [{ type: "Literal", value: i }],
  25143. callee: member(transformState.parent, id("slice"), false) });
  25144. decl[p] = { capture: true };
  25145. transformed.push(decl);
  25146. } else if (el.type == "AssignmentPattern") {
  25147. // like [x = 23]
  25148. var decl = varDecl(el.left /*id*/
  25149. , conditional(binaryExpr(member(transformState.parent, id(i), true), "===", id("undefined")), el.right, member(transformState.parent, id(i), true)));
  25150. decl[p] = { capture: true };
  25151. transformed.push(decl);
  25152. // like [{x}]
  25153. } else {
  25154. var helperVarId = id(generateUniqueName(declaredNames, transformState.parent.name + "$" + i)),
  25155. helperVar = varDecl(helperVarId, member(transformState.parent, i));
  25156. // helperVar[p] = {capture: true};
  25157. declaredNames.push(helperVarId.name);
  25158. transformed.push(helperVar);
  25159. transformed.push.apply(transformed, toConsumableArray(transformPattern(el, { parent: helperVarId, declaredNames: declaredNames })));
  25160. }
  25161. }
  25162. return transformed;
  25163. }
  25164. function transformObjectPattern(pattern, transformState) {
  25165. var declaredNames = transformState.declaredNames,
  25166. p = annotationSym,
  25167. transformed = [];
  25168. for (var i = 0; i < pattern.properties.length; i++) {
  25169. var prop = pattern.properties[i];
  25170. if (prop.value.type == "Identifier") {
  25171. // like {x: y}
  25172. var decl = varDecl(prop.value, member(transformState.parent, prop.key));
  25173. decl[p] = { capture: true };
  25174. transformed.push(decl);
  25175. } else if (prop.value.type == "AssignmentPattern") {
  25176. // like {x = 23}
  25177. var decl = varDecl(prop.value.left /*id*/
  25178. , conditional(binaryExpr(member(transformState.parent, prop.key), "===", id("undefined")), prop.value.right, member(transformState.parent, prop.key)));
  25179. decl[p] = { capture: true };
  25180. transformed.push(decl);
  25181. } else {
  25182. // like {x: {z}} or {x: [a]}
  25183. var helperVarId = id(generateUniqueName(declaredNames, transformState.parent.name + "$" + prop.key.name)),
  25184. helperVar = varDecl(helperVarId, member(transformState.parent, prop.key));
  25185. helperVar[p] = { capture: false };
  25186. declaredNames.push(helperVarId.name);
  25187. transformed.push.apply(transformed, toConsumableArray([helperVar].concat(transformPattern(prop.value, { parent: helperVarId, declaredNames: declaredNames }))));
  25188. }
  25189. }
  25190. return transformed;
  25191. }
  25192. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  25193. // code generation helpers
  25194. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  25195. function varDeclOrAssignment(parsed, declarator, kind) {
  25196. var topLevel = topLevelDeclsAndRefs(parsed),
  25197. name = declarator.id.name;
  25198. return topLevel.declaredNames.indexOf(name) > -1 ?
  25199. // only create a new declaration if necessary
  25200. exprStmt(assign(declarator.id, declarator.init)) : {
  25201. declarations: [declarator],
  25202. kind: kind || "var", type: "VariableDeclaration"
  25203. };
  25204. }
  25205. function assignExpr(assignee, propId, value, computed) {
  25206. return exprStmt(assign(member(assignee, propId, computed), value || id("undefined")));
  25207. }
  25208. function exportFromImport(keyLeft, keyRight, moduleId, moduleExportFunc, moduleImportFunc) {
  25209. return exportCall(moduleExportFunc, keyLeft, importCall(keyRight, moduleId, moduleImportFunc));
  25210. }
  25211. function varDeclAndImportCall(parsed, localId, imported, moduleSource, moduleImportFunc) {
  25212. // return varDeclOrAssignment(parsed, {
  25213. // type: "VariableDeclarator",
  25214. // id: localId,
  25215. // init: importCall(imported, moduleSource, moduleImportFunc)
  25216. // });
  25217. return varDecl(localId, importCall(imported, moduleSource, moduleImportFunc));
  25218. }
  25219. function importCall(imported, moduleSource, moduleImportFunc) {
  25220. if (typeof imported === "string") imported = literal(imported);
  25221. return {
  25222. arguments: [moduleSource].concat(imported || []),
  25223. callee: moduleImportFunc, type: "CallExpression"
  25224. };
  25225. }
  25226. function importCallStmt(imported, moduleSource, moduleImportFunc) {
  25227. return exprStmt(importCall(imported, moduleSource, moduleImportFunc));
  25228. }
  25229. function exportCall(exportFunc, local, exportedObj) {
  25230. if (typeof local === "string") local = literal(local);
  25231. exportedObj = lively_lang.obj.deepCopy(exportedObj);
  25232. return funcCall(exportFunc, local, exportedObj);
  25233. }
  25234. function exportCallStmt(exportFunc, local, exportedObj) {
  25235. return exprStmt(exportCall(exportFunc, local, exportedObj));
  25236. }
  25237. function declarationWrapperCall(declarationWrapperNode, declNode, varNameLiteral, varKindLiteral, valueNode, recorder, options) {
  25238. if (declNode) {
  25239. // here we pass compile-time meta data into the runtime
  25240. var keyVals = [];
  25241. var addMeta = false;
  25242. if (declNode["x-lively-object-meta"]) {
  25243. var _declNode$xLivelyOb = declNode["x-lively-object-meta"],
  25244. start = _declNode$xLivelyOb.start,
  25245. end = _declNode$xLivelyOb.end,
  25246. evalId = _declNode$xLivelyOb.evalId,
  25247. sourceAccessorName = _declNode$xLivelyOb.sourceAccessorName;
  25248. addMeta = true;
  25249. keyVals.push("start", lively_ast.nodes.literal(start), "end", lively_ast.nodes.literal(end));
  25250. }
  25251. if (evalId === undefined && options.hasOwnProperty("evalId")) {
  25252. evalId = options.evalId;
  25253. addMeta = true;
  25254. }
  25255. if (sourceAccessorName === undefined && options.hasOwnProperty("sourceAccessorName")) {
  25256. sourceAccessorName = options.sourceAccessorName;
  25257. addMeta = true;
  25258. }
  25259. if (evalId !== undefined) keyVals.push("evalId", lively_ast.nodes.literal(evalId));
  25260. if (sourceAccessorName) keyVals.push("moduleSource", lively_ast.nodes.id(sourceAccessorName));
  25261. if (addMeta) {
  25262. return funcCall(declarationWrapperNode, varNameLiteral, varKindLiteral, valueNode, recorder, lively_ast.nodes.objectLiteral(keyVals) /*meta node*/);
  25263. }
  25264. }
  25265. return funcCall(declarationWrapperNode, varNameLiteral, varKindLiteral, valueNode, recorder);
  25266. }
  25267. var capturing = Object.freeze({
  25268. rewriteToCaptureTopLevelVariables: rewriteToCaptureTopLevelVariables,
  25269. rewriteToRegisterModuleToCaptureSetters: rewriteToRegisterModuleToCaptureSetters
  25270. });
  25271. function stringifyFunctionWithoutToplevelRecorder(funcOrSourceOrAst) {
  25272. var varRecorderName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "__lvVarRecorder";
  25273. // stringifyFunctionWithoutToplevelRecorder((x) => hello + x)
  25274. // => x => hello + x
  25275. // instead of String((x) => hello + x) // => x => __lvVarRecorder.hello + x
  25276. // when run in toplevel scope
  25277. if (typeof funcOrSourceOrAst === "function") funcOrSourceOrAst = String(funcOrSourceOrAst);
  25278. var parsed = typeof funcOrSourceOrAst === "string" ? lively_ast.parseFunction(funcOrSourceOrAst) : funcOrSourceOrAst,
  25279. replaced = lively_ast.ReplaceVisitor.run(parsed, function (node) {
  25280. var isVarRecorderMember = node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === varRecorderName;
  25281. return isVarRecorderMember ? node.property : node;
  25282. });
  25283. return lively_ast.stringify(replaced);
  25284. }
  25285. exports.capturing = capturing;
  25286. exports.stringifyFunctionWithoutToplevelRecorder = stringifyFunctionWithoutToplevelRecorder;
  25287. }((this.lively.sourceTransform = this.lively.sourceTransform || {}),lively.lang,lively.classes,lively.ast));
  25288. if (typeof module !== "undefined" && module.exports) module.exports = GLOBAL.lively.sourceTransform;
  25289. })();
  25290. // INLINED END /Users/user/git/lively.vm/node_modules/lively.source-transform/dist/lively.source-transform.js
  25291. (function() {
  25292. var GLOBAL = typeof window !== "undefined" ? window :
  25293. typeof global!=="undefined" ? global :
  25294. typeof self!=="undefined" ? self : this;
  25295. this.lively = this.lively || {};
  25296. (function (exports,lively_lang,lively_ast,lively_sourceTransform,lively_classes,lively_notifications) {
  25297. 'use strict';
  25298. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj$$1) {
  25299. return typeof obj$$1;
  25300. } : function (obj$$1) {
  25301. return obj$$1 && typeof Symbol === "function" && obj$$1.constructor === Symbol && obj$$1 !== Symbol.prototype ? "symbol" : typeof obj$$1;
  25302. };
  25303. var asyncToGenerator = function (fn) {
  25304. return function () {
  25305. var gen = fn.apply(this, arguments);
  25306. return new Promise(function (resolve, reject) {
  25307. function step(key, arg) {
  25308. try {
  25309. var info = gen[key](arg);
  25310. var value = info.value;
  25311. } catch (error) {
  25312. reject(error);
  25313. return;
  25314. }
  25315. if (info.done) {
  25316. resolve(value);
  25317. } else {
  25318. return Promise.resolve(value).then(function (value) {
  25319. step("next", value);
  25320. }, function (err) {
  25321. step("throw", err);
  25322. });
  25323. }
  25324. }
  25325. return step("next");
  25326. });
  25327. };
  25328. };
  25329. var classCallCheck = function (instance, Constructor) {
  25330. if (!(instance instanceof Constructor)) {
  25331. throw new TypeError("Cannot call a class as a function");
  25332. }
  25333. };
  25334. var createClass = function () {
  25335. function defineProperties(target, props) {
  25336. for (var i = 0; i < props.length; i++) {
  25337. var descriptor = props[i];
  25338. descriptor.enumerable = descriptor.enumerable || false;
  25339. descriptor.configurable = true;
  25340. if ("value" in descriptor) descriptor.writable = true;
  25341. Object.defineProperty(target, descriptor.key, descriptor);
  25342. }
  25343. }
  25344. return function (Constructor, protoProps, staticProps) {
  25345. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  25346. if (staticProps) defineProperties(Constructor, staticProps);
  25347. return Constructor;
  25348. };
  25349. }();
  25350. var defineProperty = function (obj$$1, key, value) {
  25351. if (key in obj$$1) {
  25352. Object.defineProperty(obj$$1, key, {
  25353. value: value,
  25354. enumerable: true,
  25355. configurable: true,
  25356. writable: true
  25357. });
  25358. } else {
  25359. obj$$1[key] = value;
  25360. }
  25361. return obj$$1;
  25362. };
  25363. var _extends = Object.assign || function (target) {
  25364. for (var i = 1; i < arguments.length; i++) {
  25365. var source = arguments[i];
  25366. for (var key in source) {
  25367. if (Object.prototype.hasOwnProperty.call(source, key)) {
  25368. target[key] = source[key];
  25369. }
  25370. }
  25371. }
  25372. return target;
  25373. };
  25374. var get$1 = function get$1(object, property, receiver) {
  25375. if (object === null) object = Function.prototype;
  25376. var desc = Object.getOwnPropertyDescriptor(object, property);
  25377. if (desc === undefined) {
  25378. var parent = Object.getPrototypeOf(object);
  25379. if (parent === null) {
  25380. return undefined;
  25381. } else {
  25382. return get$1(parent, property, receiver);
  25383. }
  25384. } else if ("value" in desc) {
  25385. return desc.value;
  25386. } else {
  25387. var getter = desc.get;
  25388. if (getter === undefined) {
  25389. return undefined;
  25390. }
  25391. return getter.call(receiver);
  25392. }
  25393. };
  25394. var inherits = function (subClass, superClass) {
  25395. if (typeof superClass !== "function" && superClass !== null) {
  25396. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  25397. }
  25398. subClass.prototype = Object.create(superClass && superClass.prototype, {
  25399. constructor: {
  25400. value: subClass,
  25401. enumerable: false,
  25402. writable: true,
  25403. configurable: true
  25404. }
  25405. });
  25406. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  25407. };
  25408. var possibleConstructorReturn = function (self, call) {
  25409. if (!self) {
  25410. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  25411. }
  25412. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  25413. };
  25414. var set = function set(object, property, value, receiver) {
  25415. var desc = Object.getOwnPropertyDescriptor(object, property);
  25416. if (desc === undefined) {
  25417. var parent = Object.getPrototypeOf(object);
  25418. if (parent !== null) {
  25419. set(parent, property, value, receiver);
  25420. }
  25421. } else if ("value" in desc && desc.writable) {
  25422. desc.value = value;
  25423. } else {
  25424. var setter = desc.set;
  25425. if (setter !== undefined) {
  25426. setter.call(receiver, value);
  25427. }
  25428. }
  25429. return value;
  25430. };
  25431. var slicedToArray = function () {
  25432. function sliceIterator(arr$$1, i) {
  25433. var _arr = [];
  25434. var _n = true;
  25435. var _d = false;
  25436. var _e = undefined;
  25437. try {
  25438. for (var _i = arr$$1[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  25439. _arr.push(_s.value);
  25440. if (i && _arr.length === i) break;
  25441. }
  25442. } catch (err) {
  25443. _d = true;
  25444. _e = err;
  25445. } finally {
  25446. try {
  25447. if (!_n && _i["return"]) _i["return"]();
  25448. } finally {
  25449. if (_d) throw _e;
  25450. }
  25451. }
  25452. return _arr;
  25453. }
  25454. return function (arr$$1, i) {
  25455. if (Array.isArray(arr$$1)) {
  25456. return arr$$1;
  25457. } else if (Symbol.iterator in Object(arr$$1)) {
  25458. return sliceIterator(arr$$1, i);
  25459. } else {
  25460. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  25461. }
  25462. };
  25463. }();
  25464. var toConsumableArray = function (arr$$1) {
  25465. if (Array.isArray(arr$$1)) {
  25466. for (var i = 0, arr2 = Array(arr$$1.length); i < arr$$1.length; i++) arr2[i] = arr$$1[i];
  25467. return arr2;
  25468. } else {
  25469. return Array.from(arr$$1);
  25470. }
  25471. };
  25472. /*global System,global,Global,self,Node,ImageData*/
  25473. function getGlobal() {
  25474. if (typeof System !== "undefined") return System.global;
  25475. if (typeof window !== "undefined") return window;
  25476. if (typeof global !== "undefined") return global;
  25477. if (typeof Global !== "undefined") return Global;
  25478. if (typeof self !== "undefined") return self;
  25479. return function () {
  25480. return this;
  25481. }();
  25482. }
  25483. function signatureOf(name, func) {
  25484. var source = String(func),
  25485. match = source.match(/function\s*[a-zA-Z0-9_$]*\s*\(([^\)]*)\)/),
  25486. params = match && match[1] || '';
  25487. return name + '(' + params + ')';
  25488. }
  25489. function pluck(list, prop) {
  25490. return list.map(function (ea) {
  25491. return ea[prop];
  25492. });
  25493. }
  25494. var knownSymbols = function () {
  25495. return Object.getOwnPropertyNames(Symbol).filter(function (ea) {
  25496. return _typeof(Symbol[ea]) === "symbol";
  25497. }).reduce(function (map, ea) {
  25498. return map.set(Symbol[ea], "Symbol." + ea);
  25499. }, new Map());
  25500. }();
  25501. var symMatcher = /^Symbol\((.*)\)$/;
  25502. function printSymbol(sym) {
  25503. if (Symbol.keyFor(sym)) return "Symbol.for(\"" + Symbol.keyFor(sym) + "\")";
  25504. if (knownSymbols.get(sym)) return knownSymbols.get(sym);
  25505. var matched = String(sym).match(symMatcher);
  25506. return String(sym);
  25507. }
  25508. function safeToString(value) {
  25509. if (!value) return String(value);
  25510. if (Array.isArray(value)) return "[" + value.map(safeToString).join(",") + "]";
  25511. if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "symbol") return printSymbol(value);
  25512. try {
  25513. return String(value);
  25514. } catch (e) {
  25515. throw new Error("Cannot print object: " + e.stack);
  25516. }
  25517. }
  25518. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  25519. function printEvalResult(evalResult) {
  25520. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  25521. var value = evalResult.value,
  25522. isError = evalResult.isError,
  25523. isPromise = evalResult.isPromise,
  25524. promisedValue = evalResult.promisedValue,
  25525. promiseStatus = evalResult.promiseStatus;
  25526. if (isError || value instanceof Error) {
  25527. var err = value,
  25528. stringified = String(err),
  25529. stack = err.stack || "";
  25530. if (stack && err.message !== err.stack) {
  25531. stack = String(stack);
  25532. var errInStackIdx = stack.indexOf(stringified);
  25533. if (errInStackIdx === 0) stack = stack.slice(stringified.length);
  25534. stringified += "\n" + stack;
  25535. }
  25536. return stringified;
  25537. }
  25538. if (isPromise) {
  25539. var status = lively_lang.string.print(promiseStatus),
  25540. printed = promiseStatus === "pending" ? undefined : printEvalResult({ value: promisedValue }, options);
  25541. return "Promise({status: " + status + ", " + (value === undefined ? "" : "value: " + printed) + "})";
  25542. }
  25543. if (value instanceof Promise) return 'Promise({status: "unknown"})';
  25544. if (options.inspect) return printInspectEvalValue(value, options.inspectDepth || 2);
  25545. // options.asString
  25546. return String(value);
  25547. }
  25548. var printInspectEvalValue = function () {
  25549. var itSym = typeof Symbol !== "undefined" && Symbol.iterator,
  25550. maxIterLength = 10,
  25551. maxStringLength = 100,
  25552. maxNumberOfKeys = 100,
  25553. maxNumberOfLines = 1000;
  25554. return printInspect;
  25555. function printInspect(object, maxDepth) {
  25556. if ((typeof maxDepth === "undefined" ? "undefined" : _typeof(maxDepth)) === "object") maxDepth = maxDepth.maxDepth || 2;
  25557. if (!object) return String(object);
  25558. if (typeof object === "string") {
  25559. var mark = object.includes("\n") ? "`" : '"';
  25560. object = object.split('\n').slice(0, maxNumberOfLines).join('\n');
  25561. return mark + object + mark;
  25562. }
  25563. if (object instanceof Error) return object.stack || safeToString(object);
  25564. if (!lively_lang.obj.isObject(object)) return safeToString(object);
  25565. try {
  25566. var inspected = lively_lang.obj.inspect(object, {
  25567. customPrinter: inspectPrinter, maxNumberOfKeys: maxNumberOfKeys,
  25568. maxDepth: maxDepth, printFunctionSource: true
  25569. });
  25570. } catch (e) {}
  25571. // return inspected;
  25572. return inspected === "{}" ? safeToString(object) : inspected;
  25573. }
  25574. function printIterable(val, ignore) {
  25575. var isIterable = typeof val !== "string" && !Array.isArray(val) && itSym && typeof val[itSym] === "function";
  25576. if (!isIterable) return ignore;
  25577. var hasEntries = typeof val.entries === "function",
  25578. it = hasEntries ? val.entries() : val[itSym](),
  25579. values = [],
  25580. open = hasEntries ? "{" : "[",
  25581. close = hasEntries ? "}" : "]",
  25582. name = val.constructor && val.constructor.name || "Iterable";
  25583. for (var i = 0, next; i < maxIterLength; i++) {
  25584. next = it.next();
  25585. if (next.done) break;
  25586. values.push(next.value);
  25587. }
  25588. var printed = values.map(function (ea) {
  25589. return hasEntries ? String(ea[0]) + ": " + String(ea[1]) : printInspect(ea, 2);
  25590. }).join(", ");
  25591. return name + "(" + open + printed + close + ")";
  25592. }
  25593. function inspectPrinter(val, ignore, continueInspectFn) {
  25594. if (!val) return ignore;
  25595. if ((typeof val === "undefined" ? "undefined" : _typeof(val)) === "symbol") return printSymbol(val);
  25596. if (typeof val === "string") return lively_lang.string.print(lively_lang.string.truncate(val, maxStringLength));
  25597. if (val.isMorph) return safeToString(val);
  25598. if (val instanceof Promise) return "Promise()";
  25599. if (typeof Node !== "undefined" && val instanceof Node) return safeToString(val);
  25600. if (typeof ImageData !== "undefined" && val instanceof ImageData) return safeToString(val);
  25601. var length = val.length || val.byteLength;
  25602. if (length !== undefined && length > maxIterLength && val.slice) {
  25603. var printed = typeof val === "string" || val.byteLength ? safeToString(val.slice(0, maxIterLength)) : val.slice(0, maxIterLength).map(continueInspectFn);
  25604. return "[" + printed + ",...]";
  25605. }
  25606. var iterablePrinted = printIterable(val, ignore);
  25607. if (iterablePrinted !== ignore) return iterablePrinted;
  25608. return ignore;
  25609. }
  25610. }();
  25611. /*global require, __dirname*/
  25612. // helper
  25613. function getObjectForCompletion(evalFunc, stringToEval) {
  25614. var startLetters = '';
  25615. return Promise.resolve().then(function () {
  25616. // thenDo = function(err, obj, startLetters)
  25617. var idx = stringToEval.lastIndexOf('.');
  25618. if (idx >= 0) {
  25619. startLetters = stringToEval.slice(idx + 1);
  25620. stringToEval = stringToEval.slice(0, idx);
  25621. } else {
  25622. startLetters = stringToEval;
  25623. stringToEval = '(typeof window === "undefined" ? global : window)';
  25624. }
  25625. return evalFunc(stringToEval);
  25626. }).then(function (evalResult) {
  25627. return {
  25628. evalResult: evalResult,
  25629. startLetters: startLetters,
  25630. code: stringToEval
  25631. };
  25632. });
  25633. }
  25634. function propertyExtract(excludes, obj$$1, extractor) {
  25635. return Object.getOwnPropertyNames(obj$$1).concat(Object.getOwnPropertySymbols(obj$$1).map(printSymbol)).filter(function (key) {
  25636. return excludes.indexOf(key) === -1;
  25637. }).map(extractor).filter(function (ea) {
  25638. return !!ea;
  25639. }).sort(function (a, b) {
  25640. return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
  25641. });
  25642. }
  25643. function getMethodsOf(excludes, obj$$1) {
  25644. return propertyExtract(excludes, obj$$1, function (key) {
  25645. if (obj$$1.__lookupGetter__ && obj$$1.__lookupGetter__(key) || typeof obj$$1[key] !== 'function') return null;
  25646. return { name: key, completion: signatureOf(key, obj$$1[key]) };
  25647. });
  25648. }
  25649. function getAttributesOf(excludes, obj$$1) {
  25650. return propertyExtract(excludes, obj$$1, function (key) {
  25651. if (obj$$1.__lookupGetter__ && !obj$$1.__lookupGetter__(key) && typeof obj$$1[key] === 'function') return null;
  25652. return { name: key, completion: key };
  25653. });
  25654. }
  25655. function getProtoChain(obj$$1) {
  25656. var protos = [],
  25657. proto = obj$$1;
  25658. while (obj$$1) {
  25659. protos.push(obj$$1);obj$$1 = obj$$1.__proto__;
  25660. }
  25661. return protos;
  25662. }
  25663. function getDescriptorOf(originalObj, proto) {
  25664. function shorten(s, len) {
  25665. if (s.length > len) s = s.slice(0, len) + '...';
  25666. return s.replace(/\n/g, '').replace(/\s+/g, ' ');
  25667. }
  25668. if (originalObj === proto) {
  25669. if (typeof originalObj !== 'function') return shorten(safeToString(originalObj), 50);
  25670. var funcString = originalObj.toString(),
  25671. body = shorten(funcString.slice(funcString.indexOf('{') + 1, funcString.lastIndexOf('}')), 50);
  25672. return signatureOf(originalObj.displayName || originalObj.name || 'function', originalObj) + ' {' + body + '}';
  25673. }
  25674. var klass = proto.hasOwnProperty('constructor') && proto.constructor;
  25675. if (!klass) return 'prototype';
  25676. if (typeof klass.type === 'string' && klass.type.length) return shorten(klass.type, 50);
  25677. if (typeof klass.name === 'string' && klass.name.length) return shorten(klass.name, 50);
  25678. return "anonymous class";
  25679. }
  25680. function descriptorsOfObjAndProtoProperties(obj$$1) {
  25681. var excludes = [],
  25682. completions = getProtoChain(obj$$1).map(function (proto) {
  25683. var descr = getDescriptorOf(obj$$1, proto),
  25684. methodsAndAttributes = getMethodsOf(excludes, proto).concat(getAttributesOf(excludes, proto));
  25685. excludes = excludes.concat(pluck(methodsAndAttributes, 'name'));
  25686. return [descr, pluck(methodsAndAttributes, 'completion')];
  25687. });
  25688. return completions;
  25689. }
  25690. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  25691. // the main deal
  25692. function getCompletions(evalFunc, string$$1, thenDo) {
  25693. // thendo = function(err, completions/*ARRAY*/)
  25694. // eval string and for the resulting object find attributes and methods,
  25695. // grouped by its prototype / class chain
  25696. // if string is something like "foo().bar.baz" then treat "baz" as start
  25697. // letters = filter for properties of foo().bar
  25698. // ("foo().bar.baz." for props of the result of the complete string)
  25699. var promise$$1 = getObjectForCompletion(evalFunc, string$$1).then(function (evalResultAndStartLetters) {
  25700. var evalResult = evalResultAndStartLetters.evalResult,
  25701. value = evalResult && evalResult.isEvalResult ? evalResult.value : evalResult,
  25702. result = {
  25703. completions: descriptorsOfObjAndProtoProperties(value),
  25704. startLetters: evalResultAndStartLetters.startLetters,
  25705. code: evalResultAndStartLetters.code
  25706. };
  25707. if (evalResult && evalResult.isPromise) {
  25708. if (evalResult.promiseStatus === "fulfilled") result.promiseResolvedCompletions = descriptorsOfObjAndProtoProperties(evalResult.promisedValue);else if (evalResult.promiseStatus === "rejected") result.promiseRejectedCompletions = descriptorsOfObjAndProtoProperties(evalResult.promisedValue);
  25709. }
  25710. return result;
  25711. });
  25712. if (typeof thenDo === "function") {
  25713. promise$$1.then(function (result) {
  25714. return thenDo(null, result);
  25715. }).catch(function (err) {
  25716. return thenDo(err);
  25717. });
  25718. }
  25719. return promise$$1;
  25720. }
  25721. var completions = Object.freeze({
  25722. getObjectForCompletion: getObjectForCompletion,
  25723. getCompletions: getCompletions
  25724. });
  25725. var id = lively_ast.nodes.id;
  25726. var literal = lively_ast.nodes.literal;
  25727. var member = lively_ast.nodes.member;
  25728. var defaultDeclarationWrapperName = "lively.capturing-declaration-wrapper";
  25729. var defaultClassToFunctionConverterName = "initializeES6ClassForLively";
  25730. function processInlineCodeTransformOptions(parsed, options) {
  25731. if (!parsed.comments) return options;
  25732. var livelyComment = parsed.comments.find(function (ea) {
  25733. return ea.text.startsWith("lively.vm ");
  25734. });
  25735. if (!livelyComment) return options;
  25736. try {
  25737. var inlineOptions = eval("inlineOptions = {" + livelyComment.text.slice("lively.vm ".length) + "};");
  25738. return Object.assign(options, inlineOptions);
  25739. } catch (err) {
  25740. return options;
  25741. }
  25742. }
  25743. function evalCodeTransform(code, options) {
  25744. // variable declaration and references in the the source code get
  25745. // transformed so that they are bound to `varRecorderName` aren't local
  25746. // state. THis makes it possible to capture eval results, e.g. for
  25747. // inspection, watching and recording changes, workspace vars, and
  25748. // incrementally evaluating var declarations and having values bound later.
  25749. // 1. Allow evaluation of function expressions and object literals
  25750. code = lively_ast.transform.transformSingleExpression(code);
  25751. var parsed = lively_ast.parse(code, { withComments: true });
  25752. options = processInlineCodeTransformOptions(parsed, options);
  25753. // 2. Annotate definitions with code location. This is being used by the
  25754. // function-wrapper-source transform.
  25755. var _query$topLevelDeclsA = lively_ast.query.topLevelDeclsAndRefs(parsed),
  25756. classDecls = _query$topLevelDeclsA.classDecls,
  25757. funcDecls = _query$topLevelDeclsA.funcDecls,
  25758. varDecls = _query$topLevelDeclsA.varDecls,
  25759. annotation = {};
  25760. if (options.hasOwnProperty("evalId")) annotation.evalId = options.evalId;
  25761. if (options.sourceAccessorName) annotation.sourceAccessorName = options.sourceAccessorName;
  25762. [].concat(toConsumableArray(classDecls), toConsumableArray(funcDecls)).forEach(function (node) {
  25763. return node["x-lively-object-meta"] = _extends({}, annotation, { start: node.start, end: node.end });
  25764. });
  25765. varDecls.forEach(function (node) {
  25766. return node.declarations.forEach(function (decl) {
  25767. return decl["x-lively-object-meta"] = _extends({}, annotation, { start: decl.start, end: decl.end });
  25768. });
  25769. });
  25770. // transforming experimental ES features into accepted es6 form...
  25771. parsed = lively_ast.transform.objectSpreadTransform(parsed);
  25772. // 3. capture top level vars into topLevelVarRecorder "environment"
  25773. if (!options.topLevelVarRecorder && options.topLevelVarRecorderName) {
  25774. var G = getGlobal();
  25775. if (options.topLevelVarRecorderName === "GLOBAL") {
  25776. // "magic"
  25777. options.topLevelVarRecorder = getGlobal();
  25778. } else {
  25779. options.topLevelVarRecorder = lively_lang.Path(options.topLevelVarRecorderName).get(G);
  25780. }
  25781. }
  25782. if (options.topLevelVarRecorder) {
  25783. // capture and wrap logic
  25784. var blacklist = (options.dontTransform || []).concat(["arguments"]),
  25785. undeclaredToTransform = !!options.recordGlobals ? null /*all*/ : lively_lang.arr.withoutAll(Object.keys(options.topLevelVarRecorder), blacklist),
  25786. varRecorder = id(options.varRecorderName || '__lvVarRecorder'),
  25787. es6ClassToFunctionOptions = undefined;
  25788. if (options.declarationWrapperName || typeof options.declarationCallback === "function") {
  25789. // 2.1 declare a function that wraps all definitions, i.e. all var
  25790. // decls, functions, classes etc that get captured will be wrapped in this
  25791. // function. This allows to define some behavior that is run whenever
  25792. // variables get initialized or changed as well as transform values.
  25793. // The parameters passed are:
  25794. // name, kind, value, recorder
  25795. // Note that the return value of declarationCallback is used as the
  25796. // actual value in the code being executed. This allows to transform the
  25797. // value as necessary but also means that declarationCallback needs to
  25798. // return sth meaningful!
  25799. var declarationWrapperName = options.declarationWrapperName || defaultDeclarationWrapperName;
  25800. options.declarationWrapper = member(id(options.varRecorderName || '__lvVarRecorder'), literal(declarationWrapperName), true);
  25801. if (options.declarationCallback) options.topLevelVarRecorder[declarationWrapperName] = options.declarationCallback;
  25802. }
  25803. var transformES6Classes = options.hasOwnProperty("transformES6Classes") ? options.transformES6Classes : true;
  25804. if (transformES6Classes) {
  25805. // Class declarations and expressions are converted into a function call
  25806. // to `createOrExtendClass`, a helper that will produce (or extend an
  25807. // existing) constructor function in a way that allows us to redefine
  25808. // methods and properties of the class while keeping the class object
  25809. // identical
  25810. if (!(defaultClassToFunctionConverterName in options.topLevelVarRecorder)) options.topLevelVarRecorder[defaultClassToFunctionConverterName] = lively_classes.runtime.initializeClass;
  25811. es6ClassToFunctionOptions = {
  25812. currentModuleAccessor: options.currentModuleAccessor,
  25813. classHolder: varRecorder,
  25814. functionNode: member(varRecorder, defaultClassToFunctionConverterName),
  25815. declarationWrapper: options.declarationWrapper,
  25816. evalId: options.evalId,
  25817. sourceAccessorName: options.sourceAccessorName
  25818. };
  25819. }
  25820. // 3.2 Here we call out to the actual code transformation that installs the captured top level vars
  25821. parsed = lively_sourceTransform.capturing.rewriteToCaptureTopLevelVariables(parsed, varRecorder, {
  25822. es6ImportFuncId: options.es6ImportFuncId,
  25823. es6ExportFuncId: options.es6ExportFuncId,
  25824. ignoreUndeclaredExcept: undeclaredToTransform,
  25825. exclude: blacklist,
  25826. declarationWrapper: options.declarationWrapper || undefined,
  25827. classToFunction: es6ClassToFunctionOptions,
  25828. evalId: options.evalId,
  25829. sourceAccessorName: options.sourceAccessorName,
  25830. keepTopLevelVarDecls: options.keepTopLevelVarDecls
  25831. });
  25832. }
  25833. if (options.wrapInStartEndCall) {
  25834. parsed = lively_ast.transform.wrapInStartEndCall(parsed, {
  25835. startFuncNode: options.startFuncNode,
  25836. endFuncNode: options.endFuncNode
  25837. });
  25838. }
  25839. var result = lively_ast.stringify(parsed);
  25840. if (options.sourceURL) result += "\n//# sourceURL=" + options.sourceURL.replace(/\s/g, "_");
  25841. return result;
  25842. }
  25843. function evalCodeTransformOfSystemRegisterSetters(code) {
  25844. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  25845. if (!options.topLevelVarRecorder) return code;
  25846. if (typeof options.declarationCallback === "function" || options.declarationWrapperName) {
  25847. var declarationWrapperName = options.declarationWrapperName || defaultDeclarationWrapperName;
  25848. options.declarationWrapper = member(id(options.varRecorderName), literal(declarationWrapperName), true);
  25849. if (options.declarationCallback) options.topLevelVarRecorder[declarationWrapperName] = options.declarationCallback;
  25850. }
  25851. var parsed = lively_ast.parse(code),
  25852. blacklist = (options.dontTransform || []).concat(["arguments"]),
  25853. undeclaredToTransform = !!options.recordGlobals ? null /*all*/ : lively_lang.arr.withoutAll(Object.keys(options.topLevelVarRecorder), blacklist),
  25854. result = lively_sourceTransform.capturing.rewriteToRegisterModuleToCaptureSetters(parsed, id(options.varRecorderName || '__lvVarRecorder'), _extends({ exclude: blacklist }, options));
  25855. return lively_ast.stringify(result);
  25856. }
  25857. /*global: global, System*/
  25858. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  25859. // options
  25860. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  25861. var defaultTopLevelVarRecorderName = '__lvVarRecorder';
  25862. var startEvalFunctionName = "lively.vm-on-eval-start";
  25863. var endEvalFunctionName = "lively.vm-on-eval-end";
  25864. function _normalizeEvalOptions(opts) {
  25865. if (!opts) opts = {};
  25866. opts = _extends({
  25867. targetModule: null,
  25868. sourceURL: opts.targetModule,
  25869. runtime: null,
  25870. context: getGlobal(),
  25871. varRecorderName: defaultTopLevelVarRecorderName,
  25872. dontTransform: [], // blacklist vars
  25873. recordGlobals: null,
  25874. returnPromise: true,
  25875. promiseTimeout: 200,
  25876. waitForPromise: true,
  25877. wrapInStartEndCall: false,
  25878. onStartEval: null,
  25879. onEndEval: null
  25880. }, opts);
  25881. if (opts.targetModule) {
  25882. var moduleEnv = opts.runtime && opts.runtime.modules && opts.runtime.modules[opts.targetModule];
  25883. if (moduleEnv) opts = Object.assign(opts, moduleEnv);
  25884. }
  25885. if (opts.wrapInStartEndCall) {
  25886. opts.startFuncNode = {
  25887. type: "MemberExpression",
  25888. object: { type: "Identifier", name: opts.varRecorderName },
  25889. property: { type: "Literal", value: startEvalFunctionName },
  25890. computed: true
  25891. };
  25892. opts.endFuncNode = {
  25893. type: "MemberExpression",
  25894. object: { type: "Identifier", name: opts.varRecorderName },
  25895. property: { type: "Literal", value: endEvalFunctionName },
  25896. computed: true
  25897. };
  25898. }
  25899. return opts;
  25900. }
  25901. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  25902. // eval
  25903. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  25904. function _eval(__lvEvalStatement, __lvVarRecorder /*needed as arg for capturing*/, __lvOriginalCode) {
  25905. return eval(__lvEvalStatement);
  25906. }
  25907. function runEval$1(code, options, thenDo) {
  25908. // The main function where all eval options are configured.
  25909. // options can be: {
  25910. // runtime: {
  25911. // modules: {[MODULENAME: PerModuleOptions]}
  25912. // }
  25913. // }
  25914. // or directly, PerModuleOptions = {
  25915. // varRecorderName: STRING, // default is '__lvVarRecorder'
  25916. // topLevelVarRecorder: OBJECT,
  25917. // context: OBJECT,
  25918. // sourceURL: STRING,
  25919. // recordGlobals: BOOLEAN, // also transform free vars? default is false
  25920. // transpiler: FUNCTION(source, options) // for transforming the source after the lively xfm
  25921. // wrapInStartEndCall: BOOLEAN
  25922. // onStartEval: FUNCTION()?,
  25923. // onEndEval: FUNCTION(err, value)? // note: we pass in the value of last expr, not EvalResult!
  25924. // }
  25925. if (typeof options === 'function' && arguments.length === 2) {
  25926. thenDo = options;options = null;
  25927. }
  25928. var result = new EvalResult(),
  25929. returnedError,
  25930. returnedValue,
  25931. onEvalEndError,
  25932. onEvalEndValue,
  25933. onEvalStartCalled = false,
  25934. onEvalEndCalled = false;
  25935. options = _normalizeEvalOptions(options);
  25936. // 1. In case we rewrite the code with on-start and on-end calls we prepare
  25937. // the environment with actual function handlers that will get called once
  25938. // the code is evaluated
  25939. var evalDone = lively_lang.promise.deferred(),
  25940. recorder = options.topLevelVarRecorder || getGlobal(),
  25941. originalSource = code;
  25942. if (options.wrapInStartEndCall) {
  25943. if (recorder[startEvalFunctionName]) console.warn(result.addWarning("startEvalFunctionName " + startEvalFunctionName + " already exists in recorder!"));
  25944. if (recorder[endEvalFunctionName]) console.warn(result.addWarning("endEvalFunctionName " + endEvalFunctionName + " already exists in recorder!"));
  25945. recorder[startEvalFunctionName] = function () {
  25946. if (onEvalStartCalled) {
  25947. console.warn(result.addWarning("onEvalStartCalled multiple times!"));return;
  25948. }
  25949. onEvalStartCalled = true;
  25950. if (typeof options.onStartEval === "function") options.onStartEval();
  25951. };
  25952. recorder[endEvalFunctionName] = function (err, value) {
  25953. if (onEvalEndCalled) {
  25954. console.warn(result.addWarning("onEvalEndCalled multiple times!"));return;
  25955. }
  25956. onEvalEndCalled = true;
  25957. finishEval(err, value, result, options, recorder, evalDone, thenDo);
  25958. };
  25959. }
  25960. // 2. Transform the code to capture top-level variables, inject function calls, ...
  25961. try {
  25962. code = evalCodeTransform(code, options);
  25963. if (options.header) code = options.header + code;
  25964. if (options.footer) code = code + options.footer;
  25965. if (options.transpiler) code = options.transpiler(code, options.transpilerOptions);
  25966. // console.log(code);
  25967. } catch (e) {
  25968. console.warn(result.addWarning("lively.vm evalCodeTransform not working: " + e));
  25969. }
  25970. // 3. Now really run eval!
  25971. try {
  25972. typeof $world !== "undefined" && $world.get('log') && ($world.get('log').textString = code);
  25973. returnedValue = _eval.call(options.context, code, options.topLevelVarRecorder, options.originalSource || originalSource);
  25974. } catch (e) {
  25975. returnedError = e;
  25976. }
  25977. // 4. Wrapping up: if we inject a on-eval-end call we let it handle the
  25978. // wrap-up, otherwise we firectly call finishEval()
  25979. if (options.wrapInStartEndCall) {
  25980. if (returnedError && !onEvalEndCalled) recorder[endEvalFunctionName](returnedError, undefined);
  25981. } else {
  25982. finishEval(returnedError, returnedError || returnedValue, result, options, recorder, evalDone, thenDo);
  25983. }
  25984. return options.sync ? result : evalDone.promise;
  25985. }
  25986. function finishEval(err, value, result, options, recorder, evalDone, thenDo) {
  25987. // 5. Here we end the evaluation. Note that if we are in sync mode we cannot
  25988. // use any Promise since promises always run on next tick. That's why we have
  25989. // to slightly duplicate the finish logic...
  25990. if (options.wrapInStartEndCall) {
  25991. delete recorder[startEvalFunctionName];
  25992. delete recorder[endEvalFunctionName];
  25993. }
  25994. if (err) {
  25995. result.isError = true;result.value = err;
  25996. } else result.value = value;
  25997. if (result.value instanceof Promise) result.isPromise = true;
  25998. if (options.sync) {
  25999. result.processSync(options);
  26000. if (typeof options.onEndEval === "function") options.onEndEval(err, value);
  26001. } else {
  26002. result.process(options).then(function () {
  26003. typeof thenDo === "function" && thenDo(null, result);
  26004. typeof options.onEndEval === "function" && options.onEndEval(err, value);
  26005. return result;
  26006. }, function (err) {
  26007. typeof thenDo === "function" && thenDo(err, undefined);
  26008. typeof options.onEndEval === "function" && options.onEndEval(err, undefined);
  26009. return result;
  26010. }).then(evalDone.resolve, evalDone.reject);
  26011. }
  26012. }
  26013. function syncEval$1(string$$1, options) {
  26014. // See #runEval for options.
  26015. // Although the defaul eval is synchronous we assume that the general
  26016. // evaluation might not return immediatelly. This makes is possible to
  26017. // change the evaluation backend, e.g. to be a remotely attached runtime
  26018. options = Object.assign(options || {}, { sync: true });
  26019. return runEval$1(string$$1, options);
  26020. }
  26021. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  26022. // EvalResult
  26023. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  26024. var EvalResult = function () {
  26025. function EvalResult() {
  26026. classCallCheck(this, EvalResult);
  26027. this.isEvalResult = true;
  26028. this.value = undefined;
  26029. this.warnings = [];
  26030. this.isError = false;
  26031. this.isPromise = false;
  26032. this.promisedValue = undefined;
  26033. this.promiseStatus = "unknown";
  26034. }
  26035. createClass(EvalResult, [{
  26036. key: "addWarning",
  26037. value: function addWarning(warn) {
  26038. this.warnings.push(warn);return warn;
  26039. }
  26040. }, {
  26041. key: "printed",
  26042. value: function printed() {
  26043. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  26044. this.value = printEvalResult(this, options);
  26045. }
  26046. }, {
  26047. key: "processSync",
  26048. value: function processSync(options) {
  26049. if (options.inspect || options.asString) this.value = this.print(this.value, options);
  26050. return this;
  26051. }
  26052. }, {
  26053. key: "process",
  26054. value: function process(options) {
  26055. var result = this;
  26056. if (result.isPromise && options.waitForPromise) {
  26057. return tryToWaitForPromise(result, options.promiseTimeout).then(function () {
  26058. if (options.inspect || options.asString) result.printed(options);
  26059. return result;
  26060. });
  26061. }
  26062. if (options.inspect || options.asString) result.printed(options);
  26063. return Promise.resolve(result);
  26064. }
  26065. }]);
  26066. return EvalResult;
  26067. }();
  26068. function tryToWaitForPromise(evalResult, timeoutMs) {
  26069. console.assert(evalResult.isPromise, "no promise in tryToWaitForPromise???");
  26070. var timeout = {},
  26071. timeoutP = new Promise(function (resolve) {
  26072. return setTimeout(resolve, timeoutMs, timeout);
  26073. });
  26074. return Promise.race([timeoutP, evalResult.value]).then(function (resolved) {
  26075. return Object.assign(evalResult, resolved !== timeout ? { promiseStatus: "fulfilled", promisedValue: resolved } : { promiseStatus: "pending" });
  26076. }).catch(function (rejected) {
  26077. return Object.assign(evalResult, { promiseStatus: "rejected", promisedValue: rejected });
  26078. });
  26079. }
  26080. var funcCall = lively_ast.nodes.funcCall;
  26081. var member$1 = lively_ast.nodes.member;
  26082. var literal$1 = lively_ast.nodes.literal;
  26083. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  26084. // load support
  26085. function ensureImportsAreImported(System, code, parentModule) {
  26086. // FIXME do we have to do a reparse? We should be able to get the ast from
  26087. // the rewriter...
  26088. var body = lively_ast.parse(code).body,
  26089. imports = body.filter(function (node) {
  26090. return node.type === "ImportDeclaration";
  26091. });
  26092. return Promise.all(imports.map(function (node) {
  26093. return System.normalize(node.source.value, parentModule).then(function (fullName) {
  26094. return System.get(fullName) || System.import(fullName);
  26095. });
  26096. })).catch(function (err) {
  26097. console.error("Error ensuring imports: " + err.message);throw err;
  26098. });
  26099. }
  26100. function hasUnimportedImports(System, code, parentModule) {
  26101. var body = lively.ast.parse(code).body,
  26102. imports = body.filter(function (node) {
  26103. return node.type === "ImportDeclaration";
  26104. }),
  26105. importedModules = lively_lang.arr.uniq(imports.map(function (ea) {
  26106. return ea.source.value;
  26107. })).filter(Boolean),
  26108. unloadedImports = importedModules.filter(function (ea) {
  26109. return !System.get(System.decanonicalize(ea, parentModule));
  26110. });
  26111. return unloadedImports.length > 0;
  26112. }
  26113. // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  26114. // transpiler to make es next work
  26115. function babelTranspilerForAsyncAwaitCode(System, babel, filename, env) {
  26116. // The function wrapper is needed b/c we need toplevel awaits and babel
  26117. // converts "this" => "undefined" for modules
  26118. return function (source, options) {
  26119. options = Object.assign({
  26120. sourceMap: undefined, // 'inline' || true || false
  26121. inputSourceMap: undefined,
  26122. filename: filename,
  26123. code: true,
  26124. ast: false
  26125. }, options);
  26126. var sourceForBabel = "(async function(__rec) {\n" + source + "\n}).call(this);",
  26127. transpiled = babel.transform(sourceForBabel, options).code;
  26128. transpiled = transpiled.replace(/\}\)\.call\(undefined\);$/, "}).call(this)");
  26129. return transpiled;
  26130. };
  26131. }
  26132. function babelPluginTranspilerForAsyncAwaitCode(System, babelWrapper, filename, env) {
  26133. // The function wrapper is needed b/c we need toplevel awaits and babel
  26134. // converts "this" => "undefined" for modules
  26135. return function (source, options) {
  26136. var babelOptions = System.babelOptions || {},
  26137. presets = [];
  26138. presets.push(babelWrapper.presetES2015);
  26139. if (babelOptions.stage3) presets.push({ plugins: babelWrapper.pluginsStage3 });
  26140. if (babelOptions.stage2) presets.push({ plugins: babelWrapper.pluginsStage2 });
  26141. if (babelOptions.stage1) presets.push({ plugins: babelWrapper.pluginsStage1 });
  26142. options = Object.assign({
  26143. sourceMap: undefined, // 'inline' || true || false
  26144. inputSourceMap: undefined,
  26145. filename: filename,
  26146. babelrc: false,
  26147. // plugins: plugins,
  26148. presets: presets,
  26149. moduleIds: false,
  26150. code: true,
  26151. ast: false
  26152. }, options);
  26153. var sourceForBabel = "(async function(__rec) {\n" + source + "\n}).call(this);",
  26154. transpiled = babelWrapper.babel.transform(sourceForBabel, options).code;
  26155. transpiled = transpiled.replace(/\}\)\.call\(undefined\);$/, "}).call(this)");
  26156. return transpiled;
  26157. };
  26158. }
  26159. function getEs6Transpiler(System, options, env) {
  26160. if (options.transpiler) return options.transpiler;
  26161. if (!options.es6Transpile) return null;
  26162. if (System.transpiler === "babel") {
  26163. var babel = System.global[System.transpiler] || System.get(System.decanonicalize(System.transpiler));
  26164. return babel ? babelTranspilerForAsyncAwaitCode(System, babel, options.targetModule, env) : System.import(System.transpiler).then(function (babel) {
  26165. return babelTranspilerForAsyncAwaitCode(System, babel, options.targetModule, env);
  26166. });
  26167. }
  26168. if (System.transpiler === "plugin-babel") {
  26169. var babelPluginPath = System.decanonicalize("plugin-babel"),
  26170. babelPath = babelPluginPath.split("/").slice(0, -1).concat("systemjs-babel-browser.js").join("/"),
  26171. babelPlugin = System.get(babelPath);
  26172. return babelPlugin ? babelPluginTranspilerForAsyncAwaitCode(System, babelPlugin, options.targetModule, env) : System.import(babelPath).then(function (babelPlugin) {
  26173. return babelPluginTranspilerForAsyncAwaitCode(System, babelPlugin, options.targetModule, env);
  26174. });
  26175. }
  26176. if (System.transpiler === "lively.transpiler") {
  26177. var Transpiler = System.get(System.decanonicalize("lively.transpiler")).default,
  26178. transpiler = new Transpiler(System, options.targetModule, env);
  26179. return function (source, options) {
  26180. return transpiler.transpileDoit(source, options);
  26181. };
  26182. }
  26183. throw new Error("Sorry, currently only babel is supported as es6 transpiler for runEval!");
  26184. }
  26185. function runEval$2(System, code, options) {
  26186. options = _extends({
  26187. targetModule: null, parentModule: null,
  26188. es6Transpile: true,
  26189. transpiler: null, // function with params: source, options
  26190. transpilerOptions: null,
  26191. format: "esm"
  26192. }, options);
  26193. var defaultSourceAccessorName = "__lvOriginalCode";
  26194. var originalSource = code;
  26195. System.debug && console.log("[lively.module] runEval: " + code.slice(0, 100).replace(/\n/mg, " ") + "...");
  26196. var _options = options,
  26197. format = _options.format,
  26198. targetModule = _options.targetModule,
  26199. parentModule = _options.parentModule;
  26200. targetModule = System.decanonicalize(targetModule || "*scratch*", parentModule);
  26201. options.targetModule = targetModule;
  26202. if (format) {
  26203. var meta = System.getConfig().meta[targetModule];
  26204. if (!meta) meta = {};
  26205. if (!meta[targetModule]) meta[targetModule] = {};
  26206. if (!meta[targetModule].format) {
  26207. meta[targetModule].format = format;
  26208. System.config(meta);
  26209. }
  26210. }
  26211. var module = System.get("@lively-env").moduleEnv(targetModule),
  26212. recorder = module.recorder,
  26213. recorderName = module.recorderName,
  26214. dontTransform = module.dontTransform,
  26215. transpiler = getEs6Transpiler(System, options, module),
  26216. header = "var _moduleExport = " + recorderName + "._moduleExport,\n" + (" _moduleImport = " + recorderName + "._moduleImport;\n");
  26217. options = _extends({
  26218. waitForPromise: true,
  26219. sync: false,
  26220. evalId: options.evalId || module.nextEvalId(),
  26221. sourceAccessorName: (options.hasOwnProperty("embedOriginalCode") ? options.embedOriginalCode : true) ? defaultSourceAccessorName : undefined,
  26222. originalSource: originalSource
  26223. }, options, {
  26224. header: header,
  26225. recordGlobals: true,
  26226. dontTransform: dontTransform,
  26227. varRecorderName: recorderName,
  26228. topLevelVarRecorder: recorder,
  26229. sourceURL: options.sourceURL || options.targetModule,
  26230. context: options.context || recorder,
  26231. wrapInStartEndCall: true, // for async / await eval support
  26232. es6ExportFuncId: "_moduleExport",
  26233. es6ImportFuncId: "_moduleImport",
  26234. transpiler: transpiler,
  26235. declarationWrapperName: module.varDefinitionCallbackName,
  26236. currentModuleAccessor: funcCall(member$1(funcCall(member$1(member$1("__lvVarRecorder", "System"), "get"), literal$1("@lively-env")), "moduleEnv"), literal$1(options.targetModule))
  26237. });
  26238. // delay eval to ensure imports
  26239. if (!options.sync && !options.importsEnsured && hasUnimportedImports(System, code, targetModule)) {
  26240. return ensureImportsAreImported(System, code, targetModule).then(function () {
  26241. return runEval$2(System, originalSource, _extends({}, options, { importsEnsured: true }));
  26242. });
  26243. }
  26244. // delay eval to ensure SystemJS module record
  26245. if (!module.record()) {
  26246. if (!options.sync && !options._moduleImported) return System.import(targetModule).catch(function (err) {
  26247. return null;
  26248. }).then(function () {
  26249. return runEval$2(System, originalSource, _extends({}, options, { _moduleImported: true }));
  26250. });
  26251. module.ensureRecord(); // so we can record dependent modules
  26252. }
  26253. // delay eval to ensure transpiler is loaded
  26254. if (options.es6Transpile && options.transpiler instanceof Promise) {
  26255. if (!options.sync && !options._transpilerLoaded) {
  26256. return options.transpiler.catch(function (err) {
  26257. return console.error(err);
  26258. }).then(function (transpiler) {
  26259. return runEval$2(System, originalSource, _extends({}, options, { transpiler: transpiler, _transpilerLoaded: true }));
  26260. });
  26261. } else {
  26262. console.warn("[lively.vm] sync eval requested but transpiler is not yet loaded, will continue without transpilation!");
  26263. options.transpiler = null;
  26264. }
  26265. }
  26266. System.debug && console.log("[lively.module] runEval in module " + targetModule + " started");
  26267. lively_notifications.emit("lively.vm/doitrequest", {
  26268. code: originalSource,
  26269. waitForPromise: options.waitForPromise,
  26270. targetModule: options.targetModule
  26271. }, Date.now(), System);
  26272. System.get("@lively-env").evaluationStart(targetModule);
  26273. var result = runEval$1(code, options);
  26274. return options.sync ? evalEnd(System, originalSource, options, result) : Promise.resolve(result).then(function (result) {
  26275. return evalEnd(System, originalSource, options, result);
  26276. });
  26277. }
  26278. function evalEnd(System, code, options, result) {
  26279. System.get("@lively-env").evaluationEnd(options.targetModule);
  26280. System.debug && console.log("[lively.module] runEval in module " + options.targetModule + " done");
  26281. lively_notifications.emit("lively.vm/doitresult", {
  26282. code: code, result: result,
  26283. waitForPromise: options.waitForPromise,
  26284. targetModule: options.targetModule
  26285. }, Date.now(), System);
  26286. return result;
  26287. }
  26288. /*global System,location*/
  26289. var EvalStrategy = function () {
  26290. function EvalStrategy() {
  26291. classCallCheck(this, EvalStrategy);
  26292. }
  26293. createClass(EvalStrategy, [{
  26294. key: "runEval",
  26295. value: function () {
  26296. var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(source, options) {
  26297. return regeneratorRuntime.wrap(function _callee$(_context) {
  26298. while (1) {
  26299. switch (_context.prev = _context.next) {
  26300. case 0:
  26301. return _context.abrupt("return", Promise.reject("runEval(source, options) not yet implemented for " + this.constructor.name));
  26302. case 1:
  26303. case "end":
  26304. return _context.stop();
  26305. }
  26306. }
  26307. }, _callee, this);
  26308. }));
  26309. function runEval(_x, _x2) {
  26310. return _ref.apply(this, arguments);
  26311. }
  26312. return runEval;
  26313. }()
  26314. }, {
  26315. key: "keysOfObject",
  26316. value: function () {
  26317. var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(prefix, options) {
  26318. return regeneratorRuntime.wrap(function _callee2$(_context2) {
  26319. while (1) {
  26320. switch (_context2.prev = _context2.next) {
  26321. case 0:
  26322. return _context2.abrupt("return", Promise.reject("keysOfObject(prefix, options) not yet implemented for " + this.constructor.name));
  26323. case 1:
  26324. case "end":
  26325. return _context2.stop();
  26326. }
  26327. }
  26328. }, _callee2, this);
  26329. }));
  26330. function keysOfObject(_x3, _x4) {
  26331. return _ref2.apply(this, arguments);
  26332. }
  26333. return keysOfObject;
  26334. }()
  26335. }]);
  26336. return EvalStrategy;
  26337. }();
  26338. var SimpleEvalStrategy = function (_EvalStrategy) {
  26339. inherits(SimpleEvalStrategy, _EvalStrategy);
  26340. function SimpleEvalStrategy() {
  26341. classCallCheck(this, SimpleEvalStrategy);
  26342. return possibleConstructorReturn(this, (SimpleEvalStrategy.__proto__ || Object.getPrototypeOf(SimpleEvalStrategy)).apply(this, arguments));
  26343. }
  26344. createClass(SimpleEvalStrategy, [{
  26345. key: "runEval",
  26346. value: function () {
  26347. var _ref3 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(source, options) {
  26348. return regeneratorRuntime.wrap(function _callee3$(_context3) {
  26349. while (1) {
  26350. switch (_context3.prev = _context3.next) {
  26351. case 0:
  26352. return _context3.abrupt("return", Promise.resolve().then(function () {
  26353. try {
  26354. return Promise.resolve({ value: eval(source) });
  26355. } catch (err) {
  26356. return { isError: true, value: err };
  26357. }
  26358. }));
  26359. case 1:
  26360. case "end":
  26361. return _context3.stop();
  26362. }
  26363. }
  26364. }, _callee3, this);
  26365. }));
  26366. function runEval(_x5, _x6) {
  26367. return _ref3.apply(this, arguments);
  26368. }
  26369. return runEval;
  26370. }()
  26371. }, {
  26372. key: "keysOfObject",
  26373. value: function () {
  26374. var _ref4 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(prefix, options) {
  26375. var _this2 = this;
  26376. var result;
  26377. return regeneratorRuntime.wrap(function _callee4$(_context4) {
  26378. while (1) {
  26379. switch (_context4.prev = _context4.next) {
  26380. case 0:
  26381. _context4.next = 2;
  26382. return lively.vm.completions.getCompletions(function (code) {
  26383. return _this2.runEval(code, options);
  26384. }, prefix);
  26385. case 2:
  26386. result = _context4.sent;
  26387. return _context4.abrupt("return", { completions: result.completions, prefix: result.startLetters });
  26388. case 4:
  26389. case "end":
  26390. return _context4.stop();
  26391. }
  26392. }
  26393. }, _callee4, this);
  26394. }));
  26395. function keysOfObject(_x7, _x8) {
  26396. return _ref4.apply(this, arguments);
  26397. }
  26398. return keysOfObject;
  26399. }()
  26400. }]);
  26401. return SimpleEvalStrategy;
  26402. }(EvalStrategy);
  26403. var LivelyVmEvalStrategy = function (_EvalStrategy2) {
  26404. inherits(LivelyVmEvalStrategy, _EvalStrategy2);
  26405. function LivelyVmEvalStrategy() {
  26406. classCallCheck(this, LivelyVmEvalStrategy);
  26407. return possibleConstructorReturn(this, (LivelyVmEvalStrategy.__proto__ || Object.getPrototypeOf(LivelyVmEvalStrategy)).apply(this, arguments));
  26408. }
  26409. createClass(LivelyVmEvalStrategy, [{
  26410. key: "normalizeOptions",
  26411. value: function normalizeOptions(options) {
  26412. if (!options.targetModule) throw new Error("runEval called but options.targetModule not specified!");
  26413. return Object.assign({
  26414. sourceURL: options.targetModule + "_doit_" + Date.now()
  26415. }, options);
  26416. }
  26417. }, {
  26418. key: "runEval",
  26419. value: function () {
  26420. var _ref5 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(source, options) {
  26421. var System;
  26422. return regeneratorRuntime.wrap(function _callee5$(_context5) {
  26423. while (1) {
  26424. switch (_context5.prev = _context5.next) {
  26425. case 0:
  26426. options = this.normalizeOptions(options);
  26427. System = options.System || lively.modules.System;
  26428. System.config({ meta: defineProperty({}, options.targetModule, { format: "esm" }) });
  26429. return _context5.abrupt("return", lively.vm.runEval(source, options));
  26430. case 4:
  26431. case "end":
  26432. return _context5.stop();
  26433. }
  26434. }
  26435. }, _callee5, this);
  26436. }));
  26437. function runEval(_x9, _x10) {
  26438. return _ref5.apply(this, arguments);
  26439. }
  26440. return runEval;
  26441. }()
  26442. }, {
  26443. key: "keysOfObject",
  26444. value: function () {
  26445. var _ref6 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(prefix, options) {
  26446. var result;
  26447. return regeneratorRuntime.wrap(function _callee6$(_context6) {
  26448. while (1) {
  26449. switch (_context6.prev = _context6.next) {
  26450. case 0:
  26451. _context6.next = 2;
  26452. return lively.vm.completions.getCompletions(function (code) {
  26453. return lively.vm.runEval(code, options);
  26454. }, prefix);
  26455. case 2:
  26456. result = _context6.sent;
  26457. return _context6.abrupt("return", { completions: result.completions, prefix: result.startLetters });
  26458. case 4:
  26459. case "end":
  26460. return _context6.stop();
  26461. }
  26462. }
  26463. }, _callee6, this);
  26464. }));
  26465. function keysOfObject(_x11, _x12) {
  26466. return _ref6.apply(this, arguments);
  26467. }
  26468. return keysOfObject;
  26469. }()
  26470. }]);
  26471. return LivelyVmEvalStrategy;
  26472. }(EvalStrategy);
  26473. var RemoteEvalStrategy = function (_LivelyVmEvalStrategy) {
  26474. inherits(RemoteEvalStrategy, _LivelyVmEvalStrategy);
  26475. function RemoteEvalStrategy() {
  26476. classCallCheck(this, RemoteEvalStrategy);
  26477. return possibleConstructorReturn(this, (RemoteEvalStrategy.__proto__ || Object.getPrototypeOf(RemoteEvalStrategy)).apply(this, arguments));
  26478. }
  26479. createClass(RemoteEvalStrategy, [{
  26480. key: "sourceForRemote",
  26481. value: function sourceForRemote(action, arg, options) {
  26482. var contextFetch = lively_lang.obj.isString(options.context) ? options.context : false;
  26483. options = lively_lang.obj.dissoc(options, ["systemInterface", "System", "context"]);
  26484. return "\n(function() {\n var arg = " + JSON.stringify(arg) + ",\n options = " + JSON.stringify(options) + ";\n if (typeof lively === \"undefined\" || !lively.vm) {\n return Promise.resolve({\n isEvalResult: true,\n isError: true,\n value: 'lively.vm not available!'\n });\n }\n var hasSystem = typeof System !== \"undefined\"\n options.context = " + contextFetch + "\n if (!options.context) {\n options.context = hasSystem\n ? System.global\n : typeof window !== \"undefined\"\n ? window\n : typeof global !== \"undefined\"\n ? global\n : typeof self !== \"undefined\" ? self : this;\n }\n function evalFunction(source, options) {\n if (hasSystem) {\n var conf = {meta: {}}; conf.meta[options.targetModule] = {format: \"esm\"};\n System.config(conf);\n } else {\n options = Object.assign({topLevelVarRecorderName: \"GLOBAL\"}, options);\n delete options.targetModule;\n }\n return lively.vm.runEval(source, options);\n }\n function keysOfObjectFunction(prefix, options) {\n return lively.vm.completions.getCompletions(code => evalFunction(code, options), prefix)\n .then(result => ({isEvalResult: true, completions: result.completions, prefix: result.startLetters}));\n }\n return " + (action === "eval" ? "evalFunction" : "keysOfObjectFunction") + "(arg, options)\n .catch(err => ({isEvalResult: true, isError: true, value: String(err.stack || err)}));\n})();\n";
  26485. }
  26486. }, {
  26487. key: "runEval",
  26488. value: function () {
  26489. var _ref7 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(source, options) {
  26490. return regeneratorRuntime.wrap(function _callee7$(_context7) {
  26491. while (1) {
  26492. switch (_context7.prev = _context7.next) {
  26493. case 0:
  26494. return _context7.abrupt("return", this.remoteEval(this.sourceForRemote("eval", source, options), options));
  26495. case 1:
  26496. case "end":
  26497. return _context7.stop();
  26498. }
  26499. }
  26500. }, _callee7, this);
  26501. }));
  26502. function runEval(_x13, _x14) {
  26503. return _ref7.apply(this, arguments);
  26504. }
  26505. return runEval;
  26506. }()
  26507. }, {
  26508. key: "keysOfObject",
  26509. value: function () {
  26510. var _ref8 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(prefix, options) {
  26511. return regeneratorRuntime.wrap(function _callee8$(_context8) {
  26512. while (1) {
  26513. switch (_context8.prev = _context8.next) {
  26514. case 0:
  26515. return _context8.abrupt("return", this.remoteEval(this.sourceForRemote("keysOfObject", prefix, options), options));
  26516. case 1:
  26517. case "end":
  26518. return _context8.stop();
  26519. }
  26520. }
  26521. }, _callee8, this);
  26522. }));
  26523. function keysOfObject(_x15, _x16) {
  26524. return _ref8.apply(this, arguments);
  26525. }
  26526. return keysOfObject;
  26527. }()
  26528. }, {
  26529. key: "remoteEval",
  26530. value: function () {
  26531. var _ref9 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(source, options) {
  26532. var result;
  26533. return regeneratorRuntime.wrap(function _callee9$(_context9) {
  26534. while (1) {
  26535. switch (_context9.prev = _context9.next) {
  26536. case 0:
  26537. _context9.prev = 0;
  26538. _context9.next = 3;
  26539. return this.basicRemoteEval(source, options);
  26540. case 3:
  26541. result = _context9.sent;
  26542. return _context9.abrupt("return", typeof result === "string" ? JSON.parse(result) : result);
  26543. case 7:
  26544. _context9.prev = 7;
  26545. _context9.t0 = _context9["catch"](0);
  26546. return _context9.abrupt("return", { isError: true, value: "Remote eval failed: " + (result || _context9.t0) });
  26547. case 10:
  26548. case "end":
  26549. return _context9.stop();
  26550. }
  26551. }
  26552. }, _callee9, this, [[0, 7]]);
  26553. }));
  26554. function remoteEval(_x17, _x18) {
  26555. return _ref9.apply(this, arguments);
  26556. }
  26557. return remoteEval;
  26558. }()
  26559. }, {
  26560. key: "basicRemoteEval",
  26561. value: function () {
  26562. var _ref10 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee10(source, options) {
  26563. return regeneratorRuntime.wrap(function _callee10$(_context10) {
  26564. while (1) {
  26565. switch (_context10.prev = _context10.next) {
  26566. case 0:
  26567. throw new Error("Not yet implemented");
  26568. case 1:
  26569. case "end":
  26570. return _context10.stop();
  26571. }
  26572. }
  26573. }, _callee10, this);
  26574. }));
  26575. function basicRemoteEval(_x19, _x20) {
  26576. return _ref10.apply(this, arguments);
  26577. }
  26578. return basicRemoteEval;
  26579. }()
  26580. }]);
  26581. return RemoteEvalStrategy;
  26582. }(LivelyVmEvalStrategy);
  26583. var HttpEvalStrategy = function (_RemoteEvalStrategy) {
  26584. inherits(HttpEvalStrategy, _RemoteEvalStrategy);
  26585. createClass(HttpEvalStrategy, null, [{
  26586. key: "defaultURL",
  26587. get: function get() {
  26588. return "http://localhost:3000/lively";
  26589. }
  26590. }]);
  26591. function HttpEvalStrategy(url) {
  26592. classCallCheck(this, HttpEvalStrategy);
  26593. var _this5 = possibleConstructorReturn(this, (HttpEvalStrategy.__proto__ || Object.getPrototypeOf(HttpEvalStrategy)).call(this));
  26594. _this5.url = url || _this5.constructor.defaultURL;
  26595. return _this5;
  26596. }
  26597. createClass(HttpEvalStrategy, [{
  26598. key: "normalizeOptions",
  26599. value: function normalizeOptions(options) {
  26600. options = get$1(HttpEvalStrategy.prototype.__proto__ || Object.getPrototypeOf(HttpEvalStrategy.prototype), "normalizeOptions", this).call(this, options);
  26601. return Object.assign({ serverEvalURL: this.url }, options, { context: null });
  26602. }
  26603. }, {
  26604. key: "basicRemoteEval",
  26605. value: function () {
  26606. var _ref11 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee11(source, options) {
  26607. var method;
  26608. return regeneratorRuntime.wrap(function _callee11$(_context11) {
  26609. while (1) {
  26610. switch (_context11.prev = _context11.next) {
  26611. case 0:
  26612. options = this.normalizeOptions(options);
  26613. method = "basicRemoteEval_" + (System.get("@system-env").node ? "node" : "web");
  26614. _context11.next = 4;
  26615. return this[method]({ method: "POST", body: source }, options.serverEvalURL);
  26616. case 4:
  26617. return _context11.abrupt("return", _context11.sent);
  26618. case 5:
  26619. case "end":
  26620. return _context11.stop();
  26621. }
  26622. }
  26623. }, _callee11, this);
  26624. }));
  26625. function basicRemoteEval(_x21, _x22) {
  26626. return _ref11.apply(this, arguments);
  26627. }
  26628. return basicRemoteEval;
  26629. }()
  26630. }, {
  26631. key: "basicRemoteEval_web",
  26632. value: function () {
  26633. var _ref12 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee12(payload, url) {
  26634. var _ref13, _ref14, domain, loc, crossDomain, res;
  26635. return regeneratorRuntime.wrap(function _callee12$(_context12) {
  26636. while (1) {
  26637. switch (_context12.prev = _context12.next) {
  26638. case 0:
  26639. _ref13 = url.match(/[^:]+:\/\/[^\/]+/) || [url], _ref14 = slicedToArray(_ref13, 1), domain = _ref14[0], loc = void 0, crossDomain = void 0;
  26640. // fixme: this should be replaced by accessing the location
  26641. // in a canonical way
  26642. if (System.get("@system-env").worker) loc = window.location;else {
  26643. loc = document.location;
  26644. }
  26645. crossDomain = loc.origin !== domain;
  26646. if (crossDomain) {
  26647. // use lively.server proxy plugin
  26648. payload.headers = _extends({}, payload.headers, {
  26649. 'pragma': 'no-cache',
  26650. 'cache-control': 'no-cache',
  26651. "x-lively-proxy-request": url
  26652. });
  26653. url = loc.origin;
  26654. }
  26655. _context12.prev = 4;
  26656. _context12.next = 7;
  26657. return window.fetch(url, payload);
  26658. case 7:
  26659. res = _context12.sent;
  26660. _context12.next = 13;
  26661. break;
  26662. case 10:
  26663. _context12.prev = 10;
  26664. _context12.t0 = _context12["catch"](4);
  26665. throw new Error("Cannot reach server at " + url + ": " + _context12.t0.message);
  26666. case 13:
  26667. if (res.ok) {
  26668. _context12.next = 15;
  26669. break;
  26670. }
  26671. throw new Error("Server at " + url + ": " + res.statusText);
  26672. case 15:
  26673. return _context12.abrupt("return", res.text());
  26674. case 16:
  26675. case "end":
  26676. return _context12.stop();
  26677. }
  26678. }
  26679. }, _callee12, this, [[4, 10]]);
  26680. }));
  26681. function basicRemoteEval_web(_x23, _x24) {
  26682. return _ref12.apply(this, arguments);
  26683. }
  26684. return basicRemoteEval_web;
  26685. }()
  26686. }, {
  26687. key: "basicRemoteEval_node",
  26688. value: function () {
  26689. var _ref15 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee13(payload, url) {
  26690. var urlParse, http, opts;
  26691. return regeneratorRuntime.wrap(function _callee13$(_context13) {
  26692. while (1) {
  26693. switch (_context13.prev = _context13.next) {
  26694. case 0:
  26695. urlParse = System._nodeRequire("url").parse, http = System._nodeRequire(url.startsWith("https:") ? "https" : "http"), opts = Object.assign({ method: payload.method || "GET" }, urlParse(url));
  26696. return _context13.abrupt("return", new Promise(function (resolve, reject) {
  26697. var request = http.request(opts, function (res) {
  26698. res.setEncoding('utf8');
  26699. var data = "";
  26700. res.on('data', function (chunk) {
  26701. return data += chunk;
  26702. });
  26703. res.on('end', function () {
  26704. return resolve(data);
  26705. });
  26706. res.on('error', function (err) {
  26707. return reject(err);
  26708. });
  26709. });
  26710. request.on('error', function (err) {
  26711. return reject(err);
  26712. });
  26713. request.end(payload.body);
  26714. }));
  26715. case 2:
  26716. case "end":
  26717. return _context13.stop();
  26718. }
  26719. }
  26720. }, _callee13, this);
  26721. }));
  26722. function basicRemoteEval_node(_x25, _x26) {
  26723. return _ref15.apply(this, arguments);
  26724. }
  26725. return basicRemoteEval_node;
  26726. }()
  26727. }]);
  26728. return HttpEvalStrategy;
  26729. }(RemoteEvalStrategy);
  26730. var L2LEvalStrategy = function (_RemoteEvalStrategy2) {
  26731. inherits(L2LEvalStrategy, _RemoteEvalStrategy2);
  26732. function L2LEvalStrategy(l2lClient, targetId) {
  26733. classCallCheck(this, L2LEvalStrategy);
  26734. var _this6 = possibleConstructorReturn(this, (L2LEvalStrategy.__proto__ || Object.getPrototypeOf(L2LEvalStrategy)).call(this));
  26735. _this6.l2lClient = l2lClient;
  26736. _this6.targetId = targetId;
  26737. return _this6;
  26738. }
  26739. createClass(L2LEvalStrategy, [{
  26740. key: "basicRemoteEval",
  26741. value: function () {
  26742. var _ref16 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee14(source, options) {
  26743. var l2lClient, targetId, _ref17, evalResult;
  26744. return regeneratorRuntime.wrap(function _callee14$(_context14) {
  26745. while (1) {
  26746. switch (_context14.prev = _context14.next) {
  26747. case 0:
  26748. l2lClient = this.l2lClient;
  26749. targetId = this.targetId;
  26750. _context14.next = 4;
  26751. return new Promise(function (resolve, reject) {
  26752. return l2lClient.sendTo(targetId, "remote-eval", { source: source }, resolve);
  26753. });
  26754. case 4:
  26755. _ref17 = _context14.sent;
  26756. evalResult = _ref17.data;
  26757. if (evalResult && evalResult.value && evalResult.value.isEvalResult) evalResult = evalResult.value;
  26758. return _context14.abrupt("return", evalResult);
  26759. case 8:
  26760. case "end":
  26761. return _context14.stop();
  26762. }
  26763. }
  26764. }, _callee14, this);
  26765. }));
  26766. function basicRemoteEval(_x27, _x28) {
  26767. return _ref16.apply(this, arguments);
  26768. }
  26769. return basicRemoteEval;
  26770. }()
  26771. }]);
  26772. return L2LEvalStrategy;
  26773. }(RemoteEvalStrategy);
  26774. var evalStrategies = Object.freeze({
  26775. RemoteEvalStrategy: RemoteEvalStrategy,
  26776. EvalStrategy: EvalStrategy,
  26777. SimpleEvalStrategy: SimpleEvalStrategy,
  26778. LivelyVmEvalStrategy: LivelyVmEvalStrategy,
  26779. HttpEvalStrategy: HttpEvalStrategy,
  26780. L2LEvalStrategy: L2LEvalStrategy
  26781. });
  26782. function runEval$$1(code, options) {
  26783. var _options = options = _extends({
  26784. format: "esm",
  26785. System: null,
  26786. targetModule: null
  26787. }, options),
  26788. format = _options.format,
  26789. S = _options.System,
  26790. targetModule = _options.targetModule;
  26791. if (!S && typeof System !== "undefined") S = System;
  26792. if (!S && targetModule) {
  26793. return Promise.reject(new Error("options to runEval have targetModule but cannot find system loader!"));
  26794. }
  26795. return targetModule && ["esm", "es6", "register"].includes(format) ? runEval$2(S, code, options) : runEval$1(code, options);
  26796. }
  26797. function syncEval$$1(code, options) {
  26798. return syncEval$1(code, options);
  26799. }
  26800. exports.completions = completions;
  26801. exports.runEval = runEval$$1;
  26802. exports.syncEval = syncEval$$1;
  26803. exports.evalStrategies = evalStrategies;
  26804. exports.defaultTopLevelVarRecorderName = defaultTopLevelVarRecorderName;
  26805. exports.defaultClassToFunctionConverterName = defaultClassToFunctionConverterName;
  26806. exports.evalCodeTransform = evalCodeTransform;
  26807. exports.evalCodeTransformOfSystemRegisterSetters = evalCodeTransformOfSystemRegisterSetters;
  26808. }((this.lively.vm = this.lively.vm || {}),lively.lang,lively.ast,lively.sourceTransform,lively.classes,lively.notifications));
  26809. if (typeof module !== "undefined" && module.exports) module.exports = GLOBAL.lively.vm;
  26810. })();