r.js 1012 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959
  1. /**
  2. * @license r.js 2.3.2 Copyright jQuery Foundation and other contributors.
  3. * Released under MIT license, http://github.com/requirejs/r.js/LICENSE
  4. */
  5. /*
  6. * This is a bootstrap script to allow running RequireJS in the command line
  7. * in either a Java/Rhino or Node environment. It is modified by the top-level
  8. * dist.js file to inject other files to completely enable this file. It is
  9. * the shell of the r.js file.
  10. */
  11. /*jslint evil: true, nomen: true, sloppy: true */
  12. /*global readFile: true, process: false, Packages: false, print: false,
  13. console: false, java: false, module: false, requirejsVars, navigator,
  14. document, importScripts, self, location, Components, FileUtils */
  15. var requirejs, require, define, xpcUtil;
  16. (function (console, args, readFileFunc) {
  17. var fileName, env, fs, vm, path, exec, rhinoContext, dir, nodeRequire,
  18. nodeDefine, exists, reqMain, loadedOptimizedLib, existsForNode, Cc, Ci,
  19. version = '2.3.2',
  20. jsSuffixRegExp = /\.js$/,
  21. commandOption = '',
  22. useLibLoaded = {},
  23. //Used by jslib/rhino/args.js
  24. rhinoArgs = args,
  25. //Used by jslib/xpconnect/args.js
  26. xpconnectArgs = args,
  27. readFile = typeof readFileFunc !== 'undefined' ? readFileFunc : null;
  28. function showHelp() {
  29. console.log('See https://github.com/requirejs/r.js for usage.');
  30. }
  31. if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
  32. env = 'node';
  33. //Get the fs module via Node's require before it
  34. //gets replaced. Used in require/node.js
  35. fs = require('fs');
  36. vm = require('vm');
  37. path = require('path');
  38. //In Node 0.7+ existsSync is on fs.
  39. existsForNode = fs.existsSync || path.existsSync;
  40. nodeRequire = require;
  41. nodeDefine = define;
  42. reqMain = require.main;
  43. //Temporarily hide require and define to allow require.js to define
  44. //them.
  45. require = undefined;
  46. define = undefined;
  47. readFile = function (path) {
  48. return fs.readFileSync(path, 'utf8');
  49. };
  50. exec = function (string, name) {
  51. return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string),
  52. name ? fs.realpathSync(name) : '');
  53. };
  54. exists = function (fileName) {
  55. return existsForNode(fileName);
  56. };
  57. fileName = process.argv[2];
  58. if (fileName && fileName.indexOf('-') === 0) {
  59. commandOption = fileName.substring(1);
  60. fileName = process.argv[3];
  61. }
  62. } else if (typeof Packages !== 'undefined') {
  63. env = 'rhino';
  64. fileName = args[0];
  65. if (fileName && fileName.indexOf('-') === 0) {
  66. commandOption = fileName.substring(1);
  67. fileName = args[1];
  68. }
  69. //Exec/readFile differs between Rhino and Nashorn. Rhino has an
  70. //importPackage where Nashorn does not, so branch on that. This is a
  71. //coarser check -- detecting readFile existence might also be enough for
  72. //this spot. However, sticking with importPackage to keep it the same
  73. //as other Rhino/Nashorn detection branches.
  74. if (typeof importPackage !== 'undefined') {
  75. rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext();
  76. exec = function (string, name) {
  77. return rhinoContext.evaluateString(this, string, name, 0, null);
  78. };
  79. } else {
  80. exec = function (string, name) {
  81. load({ script: string, name: name});
  82. };
  83. readFile = readFully;
  84. }
  85. exists = function (fileName) {
  86. return (new java.io.File(fileName)).exists();
  87. };
  88. //Define a console.log for easier logging. Don't
  89. //get fancy though.
  90. if (typeof console === 'undefined') {
  91. console = {
  92. log: function () {
  93. print.apply(undefined, arguments);
  94. }
  95. };
  96. }
  97. } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
  98. (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
  99. env = 'browser';
  100. readFile = function (path) {
  101. return fs.readFileSync(path, 'utf8');
  102. };
  103. exec = function (string) {
  104. return eval(string);
  105. };
  106. exists = function () {
  107. console.log('x.js exists not applicable in browser env');
  108. return false;
  109. };
  110. } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
  111. env = 'xpconnect';
  112. Components.utils['import']('resource://gre/modules/FileUtils.jsm');
  113. Cc = Components.classes;
  114. Ci = Components.interfaces;
  115. fileName = args[0];
  116. if (fileName && fileName.indexOf('-') === 0) {
  117. commandOption = fileName.substring(1);
  118. fileName = args[1];
  119. }
  120. xpcUtil = {
  121. isWindows: ('@mozilla.org/windows-registry-key;1' in Cc),
  122. cwd: function () {
  123. return FileUtils.getFile("CurWorkD", []).path;
  124. },
  125. //Remove . and .. from paths, normalize on front slashes
  126. normalize: function (path) {
  127. //There has to be an easier way to do this.
  128. var i, part, ary,
  129. firstChar = path.charAt(0);
  130. if (firstChar !== '/' &&
  131. firstChar !== '\\' &&
  132. path.indexOf(':') === -1) {
  133. //A relative path. Use the current working directory.
  134. path = xpcUtil.cwd() + '/' + path;
  135. }
  136. ary = path.replace(/\\/g, '/').split('/');
  137. for (i = 0; i < ary.length; i += 1) {
  138. part = ary[i];
  139. if (part === '.') {
  140. ary.splice(i, 1);
  141. i -= 1;
  142. } else if (part === '..') {
  143. ary.splice(i - 1, 2);
  144. i -= 2;
  145. }
  146. }
  147. return ary.join('/');
  148. },
  149. xpfile: function (path) {
  150. var fullPath;
  151. try {
  152. fullPath = xpcUtil.normalize(path);
  153. if (xpcUtil.isWindows) {
  154. fullPath = fullPath.replace(/\//g, '\\');
  155. }
  156. return new FileUtils.File(fullPath);
  157. } catch (e) {
  158. throw new Error((fullPath || path) + ' failed: ' + e);
  159. }
  160. },
  161. readFile: function (/*String*/path, /*String?*/encoding) {
  162. //A file read function that can deal with BOMs
  163. encoding = encoding || "utf-8";
  164. var inStream, convertStream,
  165. readData = {},
  166. fileObj = xpcUtil.xpfile(path);
  167. //XPCOM, you so crazy
  168. try {
  169. inStream = Cc['@mozilla.org/network/file-input-stream;1']
  170. .createInstance(Ci.nsIFileInputStream);
  171. inStream.init(fileObj, 1, 0, false);
  172. convertStream = Cc['@mozilla.org/intl/converter-input-stream;1']
  173. .createInstance(Ci.nsIConverterInputStream);
  174. convertStream.init(inStream, encoding, inStream.available(),
  175. Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
  176. convertStream.readString(inStream.available(), readData);
  177. return readData.value;
  178. } catch (e) {
  179. throw new Error((fileObj && fileObj.path || '') + ': ' + e);
  180. } finally {
  181. if (convertStream) {
  182. convertStream.close();
  183. }
  184. if (inStream) {
  185. inStream.close();
  186. }
  187. }
  188. }
  189. };
  190. readFile = xpcUtil.readFile;
  191. exec = function (string) {
  192. return eval(string);
  193. };
  194. exists = function (fileName) {
  195. return xpcUtil.xpfile(fileName).exists();
  196. };
  197. //Define a console.log for easier logging. Don't
  198. //get fancy though.
  199. if (typeof console === 'undefined') {
  200. console = {
  201. log: function () {
  202. print.apply(undefined, arguments);
  203. }
  204. };
  205. }
  206. }
  207. /** vim: et:ts=4:sw=4:sts=4
  208. * @license RequireJS 2.3.2 Copyright jQuery Foundation and other contributors.
  209. * Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE
  210. */
  211. //Not using strict: uneven strict support in browsers, #392, and causes
  212. //problems with requirejs.exec()/transpiler plugins that may not be strict.
  213. /*jslint regexp: true, nomen: true, sloppy: true */
  214. /*global window, navigator, document, importScripts, setTimeout, opera */
  215. (function (global, setTimeout) {
  216. var req, s, head, baseElement, dataMain, src,
  217. interactiveScript, currentlyAddingScript, mainScript, subPath,
  218. version = '2.3.2',
  219. commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg,
  220. cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
  221. jsSuffixRegExp = /\.js$/,
  222. currDirRegExp = /^\.\//,
  223. op = Object.prototype,
  224. ostring = op.toString,
  225. hasOwn = op.hasOwnProperty,
  226. isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
  227. isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
  228. //PS3 indicates loaded and complete, but need to wait for complete
  229. //specifically. Sequence is 'loading', 'loaded', execution,
  230. // then 'complete'. The UA check is unfortunate, but not sure how
  231. //to feature test w/o causing perf issues.
  232. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
  233. /^complete$/ : /^(complete|loaded)$/,
  234. defContextName = '_',
  235. //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
  236. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
  237. contexts = {},
  238. cfg = {},
  239. globalDefQueue = [],
  240. useInteractive = false;
  241. //Could match something like ')//comment', do not lose the prefix to comment.
  242. function commentReplace(match, singlePrefix) {
  243. return singlePrefix || '';
  244. }
  245. function isFunction(it) {
  246. return ostring.call(it) === '[object Function]';
  247. }
  248. function isArray(it) {
  249. return ostring.call(it) === '[object Array]';
  250. }
  251. /**
  252. * Helper function for iterating over an array. If the func returns
  253. * a true value, it will break out of the loop.
  254. */
  255. function each(ary, func) {
  256. if (ary) {
  257. var i;
  258. for (i = 0; i < ary.length; i += 1) {
  259. if (ary[i] && func(ary[i], i, ary)) {
  260. break;
  261. }
  262. }
  263. }
  264. }
  265. /**
  266. * Helper function for iterating over an array backwards. If the func
  267. * returns a true value, it will break out of the loop.
  268. */
  269. function eachReverse(ary, func) {
  270. if (ary) {
  271. var i;
  272. for (i = ary.length - 1; i > -1; i -= 1) {
  273. if (ary[i] && func(ary[i], i, ary)) {
  274. break;
  275. }
  276. }
  277. }
  278. }
  279. function hasProp(obj, prop) {
  280. return hasOwn.call(obj, prop);
  281. }
  282. function getOwn(obj, prop) {
  283. return hasProp(obj, prop) && obj[prop];
  284. }
  285. /**
  286. * Cycles over properties in an object and calls a function for each
  287. * property value. If the function returns a truthy value, then the
  288. * iteration is stopped.
  289. */
  290. function eachProp(obj, func) {
  291. var prop;
  292. for (prop in obj) {
  293. if (hasProp(obj, prop)) {
  294. if (func(obj[prop], prop)) {
  295. break;
  296. }
  297. }
  298. }
  299. }
  300. /**
  301. * Simple function to mix in properties from source into target,
  302. * but only if target does not already have a property of the same name.
  303. */
  304. function mixin(target, source, force, deepStringMixin) {
  305. if (source) {
  306. eachProp(source, function (value, prop) {
  307. if (force || !hasProp(target, prop)) {
  308. if (deepStringMixin && typeof value === 'object' && value &&
  309. !isArray(value) && !isFunction(value) &&
  310. !(value instanceof RegExp)) {
  311. if (!target[prop]) {
  312. target[prop] = {};
  313. }
  314. mixin(target[prop], value, force, deepStringMixin);
  315. } else {
  316. target[prop] = value;
  317. }
  318. }
  319. });
  320. }
  321. return target;
  322. }
  323. //Similar to Function.prototype.bind, but the 'this' object is specified
  324. //first, since it is easier to read/figure out what 'this' will be.
  325. function bind(obj, fn) {
  326. return function () {
  327. return fn.apply(obj, arguments);
  328. };
  329. }
  330. function scripts() {
  331. return document.getElementsByTagName('script');
  332. }
  333. function defaultOnError(err) {
  334. throw err;
  335. }
  336. //Allow getting a global that is expressed in
  337. //dot notation, like 'a.b.c'.
  338. function getGlobal(value) {
  339. if (!value) {
  340. return value;
  341. }
  342. var g = global;
  343. each(value.split('.'), function (part) {
  344. g = g[part];
  345. });
  346. return g;
  347. }
  348. /**
  349. * Constructs an error with a pointer to an URL with more information.
  350. * @param {String} id the error ID that maps to an ID on a web page.
  351. * @param {String} message human readable error.
  352. * @param {Error} [err] the original error, if there is one.
  353. *
  354. * @returns {Error}
  355. */
  356. function makeError(id, msg, err, requireModules) {
  357. var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
  358. e.requireType = id;
  359. e.requireModules = requireModules;
  360. if (err) {
  361. e.originalError = err;
  362. }
  363. return e;
  364. }
  365. if (typeof define !== 'undefined') {
  366. //If a define is already in play via another AMD loader,
  367. //do not overwrite.
  368. return;
  369. }
  370. if (typeof requirejs !== 'undefined') {
  371. if (isFunction(requirejs)) {
  372. //Do not overwrite an existing requirejs instance.
  373. return;
  374. }
  375. cfg = requirejs;
  376. requirejs = undefined;
  377. }
  378. //Allow for a require config object
  379. if (typeof require !== 'undefined' && !isFunction(require)) {
  380. //assume it is a config object.
  381. cfg = require;
  382. require = undefined;
  383. }
  384. function newContext(contextName) {
  385. var inCheckLoaded, Module, context, handlers,
  386. checkLoadedTimeoutId,
  387. config = {
  388. //Defaults. Do not set a default for map
  389. //config to speed up normalize(), which
  390. //will run faster if there is no default.
  391. waitSeconds: 7,
  392. baseUrl: './',
  393. paths: {},
  394. bundles: {},
  395. pkgs: {},
  396. shim: {},
  397. config: {}
  398. },
  399. registry = {},
  400. //registry of just enabled modules, to speed
  401. //cycle breaking code when lots of modules
  402. //are registered, but not activated.
  403. enabledRegistry = {},
  404. undefEvents = {},
  405. defQueue = [],
  406. defined = {},
  407. urlFetched = {},
  408. bundlesMap = {},
  409. requireCounter = 1,
  410. unnormalizedCounter = 1;
  411. /**
  412. * Trims the . and .. from an array of path segments.
  413. * It will keep a leading path segment if a .. will become
  414. * the first path segment, to help with module name lookups,
  415. * which act like paths, but can be remapped. But the end result,
  416. * all paths that use this function should look normalized.
  417. * NOTE: this method MODIFIES the input array.
  418. * @param {Array} ary the array of path segments.
  419. */
  420. function trimDots(ary) {
  421. var i, part;
  422. for (i = 0; i < ary.length; i++) {
  423. part = ary[i];
  424. if (part === '.') {
  425. ary.splice(i, 1);
  426. i -= 1;
  427. } else if (part === '..') {
  428. // If at the start, or previous value is still ..,
  429. // keep them so that when converted to a path it may
  430. // still work when converted to a path, even though
  431. // as an ID it is less than ideal. In larger point
  432. // releases, may be better to just kick out an error.
  433. if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
  434. continue;
  435. } else if (i > 0) {
  436. ary.splice(i - 1, 2);
  437. i -= 2;
  438. }
  439. }
  440. }
  441. }
  442. /**
  443. * Given a relative module name, like ./something, normalize it to
  444. * a real name that can be mapped to a path.
  445. * @param {String} name the relative name
  446. * @param {String} baseName a real name that the name arg is relative
  447. * to.
  448. * @param {Boolean} applyMap apply the map config to the value. Should
  449. * only be done if this normalization is for a dependency ID.
  450. * @returns {String} normalized name
  451. */
  452. function normalize(name, baseName, applyMap) {
  453. var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
  454. foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
  455. baseParts = (baseName && baseName.split('/')),
  456. map = config.map,
  457. starMap = map && map['*'];
  458. //Adjust any relative paths.
  459. if (name) {
  460. name = name.split('/');
  461. lastIndex = name.length - 1;
  462. // If wanting node ID compatibility, strip .js from end
  463. // of IDs. Have to do this here, and not in nameToUrl
  464. // because node allows either .js or non .js to map
  465. // to same file.
  466. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
  467. name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
  468. }
  469. // Starts with a '.' so need the baseName
  470. if (name[0].charAt(0) === '.' && baseParts) {
  471. //Convert baseName to array, and lop off the last part,
  472. //so that . matches that 'directory' and not name of the baseName's
  473. //module. For instance, baseName of 'one/two/three', maps to
  474. //'one/two/three.js', but we want the directory, 'one/two' for
  475. //this normalization.
  476. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
  477. name = normalizedBaseParts.concat(name);
  478. }
  479. trimDots(name);
  480. name = name.join('/');
  481. }
  482. //Apply map config if available.
  483. if (applyMap && map && (baseParts || starMap)) {
  484. nameParts = name.split('/');
  485. outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
  486. nameSegment = nameParts.slice(0, i).join('/');
  487. if (baseParts) {
  488. //Find the longest baseName segment match in the config.
  489. //So, do joins on the biggest to smallest lengths of baseParts.
  490. for (j = baseParts.length; j > 0; j -= 1) {
  491. mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
  492. //baseName segment has config, find if it has one for
  493. //this name.
  494. if (mapValue) {
  495. mapValue = getOwn(mapValue, nameSegment);
  496. if (mapValue) {
  497. //Match, update name to the new value.
  498. foundMap = mapValue;
  499. foundI = i;
  500. break outerLoop;
  501. }
  502. }
  503. }
  504. }
  505. //Check for a star map match, but just hold on to it,
  506. //if there is a shorter segment match later in a matching
  507. //config, then favor over this star map.
  508. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
  509. foundStarMap = getOwn(starMap, nameSegment);
  510. starI = i;
  511. }
  512. }
  513. if (!foundMap && foundStarMap) {
  514. foundMap = foundStarMap;
  515. foundI = starI;
  516. }
  517. if (foundMap) {
  518. nameParts.splice(0, foundI, foundMap);
  519. name = nameParts.join('/');
  520. }
  521. }
  522. // If the name points to a package's name, use
  523. // the package main instead.
  524. pkgMain = getOwn(config.pkgs, name);
  525. return pkgMain ? pkgMain : name;
  526. }
  527. function removeScript(name) {
  528. if (isBrowser) {
  529. each(scripts(), function (scriptNode) {
  530. if (scriptNode.getAttribute('data-requiremodule') === name &&
  531. scriptNode.getAttribute('data-requirecontext') === context.contextName) {
  532. scriptNode.parentNode.removeChild(scriptNode);
  533. return true;
  534. }
  535. });
  536. }
  537. }
  538. function hasPathFallback(id) {
  539. var pathConfig = getOwn(config.paths, id);
  540. if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
  541. //Pop off the first array value, since it failed, and
  542. //retry
  543. pathConfig.shift();
  544. context.require.undef(id);
  545. //Custom require that does not do map translation, since
  546. //ID is "absolute", already mapped/resolved.
  547. context.makeRequire(null, {
  548. skipMap: true
  549. })([id]);
  550. return true;
  551. }
  552. }
  553. //Turns a plugin!resource to [plugin, resource]
  554. //with the plugin being undefined if the name
  555. //did not have a plugin prefix.
  556. function splitPrefix(name) {
  557. var prefix,
  558. index = name ? name.indexOf('!') : -1;
  559. if (index > -1) {
  560. prefix = name.substring(0, index);
  561. name = name.substring(index + 1, name.length);
  562. }
  563. return [prefix, name];
  564. }
  565. /**
  566. * Creates a module mapping that includes plugin prefix, module
  567. * name, and path. If parentModuleMap is provided it will
  568. * also normalize the name via require.normalize()
  569. *
  570. * @param {String} name the module name
  571. * @param {String} [parentModuleMap] parent module map
  572. * for the module name, used to resolve relative names.
  573. * @param {Boolean} isNormalized: is the ID already normalized.
  574. * This is true if this call is done for a define() module ID.
  575. * @param {Boolean} applyMap: apply the map config to the ID.
  576. * Should only be true if this map is for a dependency.
  577. *
  578. * @returns {Object}
  579. */
  580. function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
  581. var url, pluginModule, suffix, nameParts,
  582. prefix = null,
  583. parentName = parentModuleMap ? parentModuleMap.name : null,
  584. originalName = name,
  585. isDefine = true,
  586. normalizedName = '';
  587. //If no name, then it means it is a require call, generate an
  588. //internal name.
  589. if (!name) {
  590. isDefine = false;
  591. name = '_@r' + (requireCounter += 1);
  592. }
  593. nameParts = splitPrefix(name);
  594. prefix = nameParts[0];
  595. name = nameParts[1];
  596. if (prefix) {
  597. prefix = normalize(prefix, parentName, applyMap);
  598. pluginModule = getOwn(defined, prefix);
  599. }
  600. //Account for relative paths if there is a base name.
  601. if (name) {
  602. if (prefix) {
  603. if (pluginModule && pluginModule.normalize) {
  604. //Plugin is loaded, use its normalize method.
  605. normalizedName = pluginModule.normalize(name, function (name) {
  606. return normalize(name, parentName, applyMap);
  607. });
  608. } else {
  609. // If nested plugin references, then do not try to
  610. // normalize, as it will not normalize correctly. This
  611. // places a restriction on resourceIds, and the longer
  612. // term solution is not to normalize until plugins are
  613. // loaded and all normalizations to allow for async
  614. // loading of a loader plugin. But for now, fixes the
  615. // common uses. Details in #1131
  616. normalizedName = name.indexOf('!') === -1 ?
  617. normalize(name, parentName, applyMap) :
  618. name;
  619. }
  620. } else {
  621. //A regular module.
  622. normalizedName = normalize(name, parentName, applyMap);
  623. //Normalized name may be a plugin ID due to map config
  624. //application in normalize. The map config values must
  625. //already be normalized, so do not need to redo that part.
  626. nameParts = splitPrefix(normalizedName);
  627. prefix = nameParts[0];
  628. normalizedName = nameParts[1];
  629. isNormalized = true;
  630. url = context.nameToUrl(normalizedName);
  631. }
  632. }
  633. //If the id is a plugin id that cannot be determined if it needs
  634. //normalization, stamp it with a unique ID so two matching relative
  635. //ids that may conflict can be separate.
  636. suffix = prefix && !pluginModule && !isNormalized ?
  637. '_unnormalized' + (unnormalizedCounter += 1) :
  638. '';
  639. return {
  640. prefix: prefix,
  641. name: normalizedName,
  642. parentMap: parentModuleMap,
  643. unnormalized: !!suffix,
  644. url: url,
  645. originalName: originalName,
  646. isDefine: isDefine,
  647. id: (prefix ?
  648. prefix + '!' + normalizedName :
  649. normalizedName) + suffix
  650. };
  651. }
  652. function getModule(depMap) {
  653. var id = depMap.id,
  654. mod = getOwn(registry, id);
  655. if (!mod) {
  656. mod = registry[id] = new context.Module(depMap);
  657. }
  658. return mod;
  659. }
  660. function on(depMap, name, fn) {
  661. var id = depMap.id,
  662. mod = getOwn(registry, id);
  663. if (hasProp(defined, id) &&
  664. (!mod || mod.defineEmitComplete)) {
  665. if (name === 'defined') {
  666. fn(defined[id]);
  667. }
  668. } else {
  669. mod = getModule(depMap);
  670. if (mod.error && name === 'error') {
  671. fn(mod.error);
  672. } else {
  673. mod.on(name, fn);
  674. }
  675. }
  676. }
  677. function onError(err, errback) {
  678. var ids = err.requireModules,
  679. notified = false;
  680. if (errback) {
  681. errback(err);
  682. } else {
  683. each(ids, function (id) {
  684. var mod = getOwn(registry, id);
  685. if (mod) {
  686. //Set error on module, so it skips timeout checks.
  687. mod.error = err;
  688. if (mod.events.error) {
  689. notified = true;
  690. mod.emit('error', err);
  691. }
  692. }
  693. });
  694. if (!notified) {
  695. req.onError(err);
  696. }
  697. }
  698. }
  699. /**
  700. * Internal method to transfer globalQueue items to this context's
  701. * defQueue.
  702. */
  703. function takeGlobalQueue() {
  704. //Push all the globalDefQueue items into the context's defQueue
  705. if (globalDefQueue.length) {
  706. each(globalDefQueue, function(queueItem) {
  707. var id = queueItem[0];
  708. if (typeof id === 'string') {
  709. context.defQueueMap[id] = true;
  710. }
  711. defQueue.push(queueItem);
  712. });
  713. globalDefQueue = [];
  714. }
  715. }
  716. handlers = {
  717. 'require': function (mod) {
  718. if (mod.require) {
  719. return mod.require;
  720. } else {
  721. return (mod.require = context.makeRequire(mod.map));
  722. }
  723. },
  724. 'exports': function (mod) {
  725. mod.usingExports = true;
  726. if (mod.map.isDefine) {
  727. if (mod.exports) {
  728. return (defined[mod.map.id] = mod.exports);
  729. } else {
  730. return (mod.exports = defined[mod.map.id] = {});
  731. }
  732. }
  733. },
  734. 'module': function (mod) {
  735. if (mod.module) {
  736. return mod.module;
  737. } else {
  738. return (mod.module = {
  739. id: mod.map.id,
  740. uri: mod.map.url,
  741. config: function () {
  742. return getOwn(config.config, mod.map.id) || {};
  743. },
  744. exports: mod.exports || (mod.exports = {})
  745. });
  746. }
  747. }
  748. };
  749. function cleanRegistry(id) {
  750. //Clean up machinery used for waiting modules.
  751. delete registry[id];
  752. delete enabledRegistry[id];
  753. }
  754. function breakCycle(mod, traced, processed) {
  755. var id = mod.map.id;
  756. if (mod.error) {
  757. mod.emit('error', mod.error);
  758. } else {
  759. traced[id] = true;
  760. each(mod.depMaps, function (depMap, i) {
  761. var depId = depMap.id,
  762. dep = getOwn(registry, depId);
  763. //Only force things that have not completed
  764. //being defined, so still in the registry,
  765. //and only if it has not been matched up
  766. //in the module already.
  767. if (dep && !mod.depMatched[i] && !processed[depId]) {
  768. if (getOwn(traced, depId)) {
  769. mod.defineDep(i, defined[depId]);
  770. mod.check(); //pass false?
  771. } else {
  772. breakCycle(dep, traced, processed);
  773. }
  774. }
  775. });
  776. processed[id] = true;
  777. }
  778. }
  779. function checkLoaded() {
  780. var err, usingPathFallback,
  781. waitInterval = config.waitSeconds * 1000,
  782. //It is possible to disable the wait interval by using waitSeconds of 0.
  783. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
  784. noLoads = [],
  785. reqCalls = [],
  786. stillLoading = false,
  787. needCycleCheck = true;
  788. //Do not bother if this call was a result of a cycle break.
  789. if (inCheckLoaded) {
  790. return;
  791. }
  792. inCheckLoaded = true;
  793. //Figure out the state of all the modules.
  794. eachProp(enabledRegistry, function (mod) {
  795. var map = mod.map,
  796. modId = map.id;
  797. //Skip things that are not enabled or in error state.
  798. if (!mod.enabled) {
  799. return;
  800. }
  801. if (!map.isDefine) {
  802. reqCalls.push(mod);
  803. }
  804. if (!mod.error) {
  805. //If the module should be executed, and it has not
  806. //been inited and time is up, remember it.
  807. if (!mod.inited && expired) {
  808. if (hasPathFallback(modId)) {
  809. usingPathFallback = true;
  810. stillLoading = true;
  811. } else {
  812. noLoads.push(modId);
  813. removeScript(modId);
  814. }
  815. } else if (!mod.inited && mod.fetched && map.isDefine) {
  816. stillLoading = true;
  817. if (!map.prefix) {
  818. //No reason to keep looking for unfinished
  819. //loading. If the only stillLoading is a
  820. //plugin resource though, keep going,
  821. //because it may be that a plugin resource
  822. //is waiting on a non-plugin cycle.
  823. return (needCycleCheck = false);
  824. }
  825. }
  826. }
  827. });
  828. if (expired && noLoads.length) {
  829. //If wait time expired, throw error of unloaded modules.
  830. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
  831. err.contextName = context.contextName;
  832. return onError(err);
  833. }
  834. //Not expired, check for a cycle.
  835. if (needCycleCheck) {
  836. each(reqCalls, function (mod) {
  837. breakCycle(mod, {}, {});
  838. });
  839. }
  840. //If still waiting on loads, and the waiting load is something
  841. //other than a plugin resource, or there are still outstanding
  842. //scripts, then just try back later.
  843. if ((!expired || usingPathFallback) && stillLoading) {
  844. //Something is still waiting to load. Wait for it, but only
  845. //if a timeout is not already in effect.
  846. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
  847. checkLoadedTimeoutId = setTimeout(function () {
  848. checkLoadedTimeoutId = 0;
  849. checkLoaded();
  850. }, 50);
  851. }
  852. }
  853. inCheckLoaded = false;
  854. }
  855. Module = function (map) {
  856. this.events = getOwn(undefEvents, map.id) || {};
  857. this.map = map;
  858. this.shim = getOwn(config.shim, map.id);
  859. this.depExports = [];
  860. this.depMaps = [];
  861. this.depMatched = [];
  862. this.pluginMaps = {};
  863. this.depCount = 0;
  864. /* this.exports this.factory
  865. this.depMaps = [],
  866. this.enabled, this.fetched
  867. */
  868. };
  869. Module.prototype = {
  870. init: function (depMaps, factory, errback, options) {
  871. options = options || {};
  872. //Do not do more inits if already done. Can happen if there
  873. //are multiple define calls for the same module. That is not
  874. //a normal, common case, but it is also not unexpected.
  875. if (this.inited) {
  876. return;
  877. }
  878. this.factory = factory;
  879. if (errback) {
  880. //Register for errors on this module.
  881. this.on('error', errback);
  882. } else if (this.events.error) {
  883. //If no errback already, but there are error listeners
  884. //on this module, set up an errback to pass to the deps.
  885. errback = bind(this, function (err) {
  886. this.emit('error', err);
  887. });
  888. }
  889. //Do a copy of the dependency array, so that
  890. //source inputs are not modified. For example
  891. //"shim" deps are passed in here directly, and
  892. //doing a direct modification of the depMaps array
  893. //would affect that config.
  894. this.depMaps = depMaps && depMaps.slice(0);
  895. this.errback = errback;
  896. //Indicate this module has be initialized
  897. this.inited = true;
  898. this.ignore = options.ignore;
  899. //Could have option to init this module in enabled mode,
  900. //or could have been previously marked as enabled. However,
  901. //the dependencies are not known until init is called. So
  902. //if enabled previously, now trigger dependencies as enabled.
  903. if (options.enabled || this.enabled) {
  904. //Enable this module and dependencies.
  905. //Will call this.check()
  906. this.enable();
  907. } else {
  908. this.check();
  909. }
  910. },
  911. defineDep: function (i, depExports) {
  912. //Because of cycles, defined callback for a given
  913. //export can be called more than once.
  914. if (!this.depMatched[i]) {
  915. this.depMatched[i] = true;
  916. this.depCount -= 1;
  917. this.depExports[i] = depExports;
  918. }
  919. },
  920. fetch: function () {
  921. if (this.fetched) {
  922. return;
  923. }
  924. this.fetched = true;
  925. context.startTime = (new Date()).getTime();
  926. var map = this.map;
  927. //If the manager is for a plugin managed resource,
  928. //ask the plugin to load it now.
  929. if (this.shim) {
  930. context.makeRequire(this.map, {
  931. enableBuildCallback: true
  932. })(this.shim.deps || [], bind(this, function () {
  933. return map.prefix ? this.callPlugin() : this.load();
  934. }));
  935. } else {
  936. //Regular dependency.
  937. return map.prefix ? this.callPlugin() : this.load();
  938. }
  939. },
  940. load: function () {
  941. var url = this.map.url;
  942. //Regular dependency.
  943. if (!urlFetched[url]) {
  944. urlFetched[url] = true;
  945. context.load(this.map.id, url);
  946. }
  947. },
  948. /**
  949. * Checks if the module is ready to define itself, and if so,
  950. * define it.
  951. */
  952. check: function () {
  953. if (!this.enabled || this.enabling) {
  954. return;
  955. }
  956. var err, cjsModule,
  957. id = this.map.id,
  958. depExports = this.depExports,
  959. exports = this.exports,
  960. factory = this.factory;
  961. if (!this.inited) {
  962. // Only fetch if not already in the defQueue.
  963. if (!hasProp(context.defQueueMap, id)) {
  964. this.fetch();
  965. }
  966. } else if (this.error) {
  967. this.emit('error', this.error);
  968. } else if (!this.defining) {
  969. //The factory could trigger another require call
  970. //that would result in checking this module to
  971. //define itself again. If already in the process
  972. //of doing that, skip this work.
  973. this.defining = true;
  974. if (this.depCount < 1 && !this.defined) {
  975. if (isFunction(factory)) {
  976. //If there is an error listener, favor passing
  977. //to that instead of throwing an error. However,
  978. //only do it for define()'d modules. require
  979. //errbacks should not be called for failures in
  980. //their callbacks (#699). However if a global
  981. //onError is set, use that.
  982. if ((this.events.error && this.map.isDefine) ||
  983. req.onError !== defaultOnError) {
  984. try {
  985. exports = context.execCb(id, factory, depExports, exports);
  986. } catch (e) {
  987. err = e;
  988. }
  989. } else {
  990. exports = context.execCb(id, factory, depExports, exports);
  991. }
  992. // Favor return value over exports. If node/cjs in play,
  993. // then will not have a return value anyway. Favor
  994. // module.exports assignment over exports object.
  995. if (this.map.isDefine && exports === undefined) {
  996. cjsModule = this.module;
  997. if (cjsModule) {
  998. exports = cjsModule.exports;
  999. } else if (this.usingExports) {
  1000. //exports already set the defined value.
  1001. exports = this.exports;
  1002. }
  1003. }
  1004. if (err) {
  1005. err.requireMap = this.map;
  1006. err.requireModules = this.map.isDefine ? [this.map.id] : null;
  1007. err.requireType = this.map.isDefine ? 'define' : 'require';
  1008. return onError((this.error = err));
  1009. }
  1010. } else {
  1011. //Just a literal value
  1012. exports = factory;
  1013. }
  1014. this.exports = exports;
  1015. if (this.map.isDefine && !this.ignore) {
  1016. defined[id] = exports;
  1017. if (req.onResourceLoad) {
  1018. var resLoadMaps = [];
  1019. each(this.depMaps, function (depMap) {
  1020. resLoadMaps.push(depMap.normalizedMap || depMap);
  1021. });
  1022. req.onResourceLoad(context, this.map, resLoadMaps);
  1023. }
  1024. }
  1025. //Clean up
  1026. cleanRegistry(id);
  1027. this.defined = true;
  1028. }
  1029. //Finished the define stage. Allow calling check again
  1030. //to allow define notifications below in the case of a
  1031. //cycle.
  1032. this.defining = false;
  1033. if (this.defined && !this.defineEmitted) {
  1034. this.defineEmitted = true;
  1035. this.emit('defined', this.exports);
  1036. this.defineEmitComplete = true;
  1037. }
  1038. }
  1039. },
  1040. callPlugin: function () {
  1041. var map = this.map,
  1042. id = map.id,
  1043. //Map already normalized the prefix.
  1044. pluginMap = makeModuleMap(map.prefix);
  1045. //Mark this as a dependency for this plugin, so it
  1046. //can be traced for cycles.
  1047. this.depMaps.push(pluginMap);
  1048. on(pluginMap, 'defined', bind(this, function (plugin) {
  1049. var load, normalizedMap, normalizedMod,
  1050. bundleId = getOwn(bundlesMap, this.map.id),
  1051. name = this.map.name,
  1052. parentName = this.map.parentMap ? this.map.parentMap.name : null,
  1053. localRequire = context.makeRequire(map.parentMap, {
  1054. enableBuildCallback: true
  1055. });
  1056. //If current map is not normalized, wait for that
  1057. //normalized name to load instead of continuing.
  1058. if (this.map.unnormalized) {
  1059. //Normalize the ID if the plugin allows it.
  1060. if (plugin.normalize) {
  1061. name = plugin.normalize(name, function (name) {
  1062. return normalize(name, parentName, true);
  1063. }) || '';
  1064. }
  1065. //prefix and name should already be normalized, no need
  1066. //for applying map config again either.
  1067. normalizedMap = makeModuleMap(map.prefix + '!' + name,
  1068. this.map.parentMap);
  1069. on(normalizedMap,
  1070. 'defined', bind(this, function (value) {
  1071. this.map.normalizedMap = normalizedMap;
  1072. this.init([], function () { return value; }, null, {
  1073. enabled: true,
  1074. ignore: true
  1075. });
  1076. }));
  1077. normalizedMod = getOwn(registry, normalizedMap.id);
  1078. if (normalizedMod) {
  1079. //Mark this as a dependency for this plugin, so it
  1080. //can be traced for cycles.
  1081. this.depMaps.push(normalizedMap);
  1082. if (this.events.error) {
  1083. normalizedMod.on('error', bind(this, function (err) {
  1084. this.emit('error', err);
  1085. }));
  1086. }
  1087. normalizedMod.enable();
  1088. }
  1089. return;
  1090. }
  1091. //If a paths config, then just load that file instead to
  1092. //resolve the plugin, as it is built into that paths layerobj.
  1093. if (bundleId) {
  1094. this.map.url = context.nameToUrl(bundleId);
  1095. this.load();
  1096. return;
  1097. }
  1098. load = bind(this, function (value) {
  1099. this.init([], function () { return value; }, null, {
  1100. enabled: true
  1101. });
  1102. });
  1103. load.error = bind(this, function (err) {
  1104. this.inited = true;
  1105. this.error = err;
  1106. err.requireModules = [id];
  1107. //Remove temp unnormalized modules for this module,
  1108. //since they will never be resolved otherwise now.
  1109. eachProp(registry, function (mod) {
  1110. if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
  1111. cleanRegistry(mod.map.id);
  1112. }
  1113. });
  1114. onError(err);
  1115. });
  1116. //Allow plugins to load other code without having to know the
  1117. //context or how to 'complete' the load.
  1118. load.fromText = bind(this, function (text, textAlt) {
  1119. /*jslint evil: true */
  1120. var moduleName = map.name,
  1121. moduleMap = makeModuleMap(moduleName),
  1122. hasInteractive = useInteractive;
  1123. //As of 2.1.0, support just passing the text, to reinforce
  1124. //fromText only being called once per resource. Still
  1125. //support old style of passing moduleName but discard
  1126. //that moduleName in favor of the internal ref.
  1127. if (textAlt) {
  1128. text = textAlt;
  1129. }
  1130. //Turn off interactive script matching for IE for any define
  1131. //calls in the text, then turn it back on at the end.
  1132. if (hasInteractive) {
  1133. useInteractive = false;
  1134. }
  1135. //Prime the system by creating a module instance for
  1136. //it.
  1137. getModule(moduleMap);
  1138. //Transfer any config to this other module.
  1139. if (hasProp(config.config, id)) {
  1140. config.config[moduleName] = config.config[id];
  1141. }
  1142. try {
  1143. req.exec(text);
  1144. } catch (e) {
  1145. return onError(makeError('fromtexteval',
  1146. 'fromText eval for ' + id +
  1147. ' failed: ' + e,
  1148. e,
  1149. [id]));
  1150. }
  1151. if (hasInteractive) {
  1152. useInteractive = true;
  1153. }
  1154. //Mark this as a dependency for the plugin
  1155. //resource
  1156. this.depMaps.push(moduleMap);
  1157. //Support anonymous modules.
  1158. context.completeLoad(moduleName);
  1159. //Bind the value of that module to the value for this
  1160. //resource ID.
  1161. localRequire([moduleName], load);
  1162. });
  1163. //Use parentName here since the plugin's name is not reliable,
  1164. //could be some weird string with no path that actually wants to
  1165. //reference the parentName's path.
  1166. plugin.load(map.name, localRequire, load, config);
  1167. }));
  1168. context.enable(pluginMap, this);
  1169. this.pluginMaps[pluginMap.id] = pluginMap;
  1170. },
  1171. enable: function () {
  1172. enabledRegistry[this.map.id] = this;
  1173. this.enabled = true;
  1174. //Set flag mentioning that the module is enabling,
  1175. //so that immediate calls to the defined callbacks
  1176. //for dependencies do not trigger inadvertent load
  1177. //with the depCount still being zero.
  1178. this.enabling = true;
  1179. //Enable each dependency
  1180. each(this.depMaps, bind(this, function (depMap, i) {
  1181. var id, mod, handler;
  1182. if (typeof depMap === 'string') {
  1183. //Dependency needs to be converted to a depMap
  1184. //and wired up to this module.
  1185. depMap = makeModuleMap(depMap,
  1186. (this.map.isDefine ? this.map : this.map.parentMap),
  1187. false,
  1188. !this.skipMap);
  1189. this.depMaps[i] = depMap;
  1190. handler = getOwn(handlers, depMap.id);
  1191. if (handler) {
  1192. this.depExports[i] = handler(this);
  1193. return;
  1194. }
  1195. this.depCount += 1;
  1196. on(depMap, 'defined', bind(this, function (depExports) {
  1197. if (this.undefed) {
  1198. return;
  1199. }
  1200. this.defineDep(i, depExports);
  1201. this.check();
  1202. }));
  1203. if (this.errback) {
  1204. on(depMap, 'error', bind(this, this.errback));
  1205. } else if (this.events.error) {
  1206. // No direct errback on this module, but something
  1207. // else is listening for errors, so be sure to
  1208. // propagate the error correctly.
  1209. on(depMap, 'error', bind(this, function(err) {
  1210. this.emit('error', err);
  1211. }));
  1212. }
  1213. }
  1214. id = depMap.id;
  1215. mod = registry[id];
  1216. //Skip special modules like 'require', 'exports', 'module'
  1217. //Also, don't call enable if it is already enabled,
  1218. //important in circular dependency cases.
  1219. if (!hasProp(handlers, id) && mod && !mod.enabled) {
  1220. context.enable(depMap, this);
  1221. }
  1222. }));
  1223. //Enable each plugin that is used in
  1224. //a dependency
  1225. eachProp(this.pluginMaps, bind(this, function (pluginMap) {
  1226. var mod = getOwn(registry, pluginMap.id);
  1227. if (mod && !mod.enabled) {
  1228. context.enable(pluginMap, this);
  1229. }
  1230. }));
  1231. this.enabling = false;
  1232. this.check();
  1233. },
  1234. on: function (name, cb) {
  1235. var cbs = this.events[name];
  1236. if (!cbs) {
  1237. cbs = this.events[name] = [];
  1238. }
  1239. cbs.push(cb);
  1240. },
  1241. emit: function (name, evt) {
  1242. each(this.events[name], function (cb) {
  1243. cb(evt);
  1244. });
  1245. if (name === 'error') {
  1246. //Now that the error handler was triggered, remove
  1247. //the listeners, since this broken Module instance
  1248. //can stay around for a while in the registry.
  1249. delete this.events[name];
  1250. }
  1251. }
  1252. };
  1253. function callGetModule(args) {
  1254. //Skip modules already defined.
  1255. if (!hasProp(defined, args[0])) {
  1256. getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
  1257. }
  1258. }
  1259. function removeListener(node, func, name, ieName) {
  1260. //Favor detachEvent because of IE9
  1261. //issue, see attachEvent/addEventListener comment elsewhere
  1262. //in this file.
  1263. if (node.detachEvent && !isOpera) {
  1264. //Probably IE. If not it will throw an error, which will be
  1265. //useful to know.
  1266. if (ieName) {
  1267. node.detachEvent(ieName, func);
  1268. }
  1269. } else {
  1270. node.removeEventListener(name, func, false);
  1271. }
  1272. }
  1273. /**
  1274. * Given an event from a script node, get the requirejs info from it,
  1275. * and then removes the event listeners on the node.
  1276. * @param {Event} evt
  1277. * @returns {Object}
  1278. */
  1279. function getScriptData(evt) {
  1280. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1281. //all old browsers will be supported, but this one was easy enough
  1282. //to support and still makes sense.
  1283. var node = evt.currentTarget || evt.srcElement;
  1284. //Remove the listeners once here.
  1285. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
  1286. removeListener(node, context.onScriptError, 'error');
  1287. return {
  1288. node: node,
  1289. id: node && node.getAttribute('data-requiremodule')
  1290. };
  1291. }
  1292. function intakeDefines() {
  1293. var args;
  1294. //Any defined modules in the global queue, intake them now.
  1295. takeGlobalQueue();
  1296. //Make sure any remaining defQueue items get properly processed.
  1297. while (defQueue.length) {
  1298. args = defQueue.shift();
  1299. if (args[0] === null) {
  1300. return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' +
  1301. args[args.length - 1]));
  1302. } else {
  1303. //args are id, deps, factory. Should be normalized by the
  1304. //define() function.
  1305. callGetModule(args);
  1306. }
  1307. }
  1308. context.defQueueMap = {};
  1309. }
  1310. context = {
  1311. config: config,
  1312. contextName: contextName,
  1313. registry: registry,
  1314. defined: defined,
  1315. urlFetched: urlFetched,
  1316. defQueue: defQueue,
  1317. defQueueMap: {},
  1318. Module: Module,
  1319. makeModuleMap: makeModuleMap,
  1320. nextTick: req.nextTick,
  1321. onError: onError,
  1322. /**
  1323. * Set a configuration for the context.
  1324. * @param {Object} cfg config object to integrate.
  1325. */
  1326. configure: function (cfg) {
  1327. //Make sure the baseUrl ends in a slash.
  1328. if (cfg.baseUrl) {
  1329. if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
  1330. cfg.baseUrl += '/';
  1331. }
  1332. }
  1333. // Convert old style urlArgs string to a function.
  1334. if (typeof cfg.urlArgs === 'string') {
  1335. var urlArgs = cfg.urlArgs;
  1336. cfg.urlArgs = function(id, url) {
  1337. return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs;
  1338. };
  1339. }
  1340. //Save off the paths since they require special processing,
  1341. //they are additive.
  1342. var shim = config.shim,
  1343. objs = {
  1344. paths: true,
  1345. bundles: true,
  1346. config: true,
  1347. map: true
  1348. };
  1349. eachProp(cfg, function (value, prop) {
  1350. if (objs[prop]) {
  1351. if (!config[prop]) {
  1352. config[prop] = {};
  1353. }
  1354. mixin(config[prop], value, true, true);
  1355. } else {
  1356. config[prop] = value;
  1357. }
  1358. });
  1359. //Reverse map the bundles
  1360. if (cfg.bundles) {
  1361. eachProp(cfg.bundles, function (value, prop) {
  1362. each(value, function (v) {
  1363. if (v !== prop) {
  1364. bundlesMap[v] = prop;
  1365. }
  1366. });
  1367. });
  1368. }
  1369. //Merge shim
  1370. if (cfg.shim) {
  1371. eachProp(cfg.shim, function (value, id) {
  1372. //Normalize the structure
  1373. if (isArray(value)) {
  1374. value = {
  1375. deps: value
  1376. };
  1377. }
  1378. if ((value.exports || value.init) && !value.exportsFn) {
  1379. value.exportsFn = context.makeShimExports(value);
  1380. }
  1381. shim[id] = value;
  1382. });
  1383. config.shim = shim;
  1384. }
  1385. //Adjust packages if necessary.
  1386. if (cfg.packages) {
  1387. each(cfg.packages, function (pkgObj) {
  1388. var location, name;
  1389. pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj;
  1390. name = pkgObj.name;
  1391. location = pkgObj.location;
  1392. if (location) {
  1393. config.paths[name] = pkgObj.location;
  1394. }
  1395. //Save pointer to main module ID for pkg name.
  1396. //Remove leading dot in main, so main paths are normalized,
  1397. //and remove any trailing .js, since different package
  1398. //envs have different conventions: some use a module name,
  1399. //some use a file name.
  1400. config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
  1401. .replace(currDirRegExp, '')
  1402. .replace(jsSuffixRegExp, '');
  1403. });
  1404. }
  1405. //If there are any "waiting to execute" modules in the registry,
  1406. //update the maps for them, since their info, like URLs to load,
  1407. //may have changed.
  1408. eachProp(registry, function (mod, id) {
  1409. //If module already has init called, since it is too
  1410. //late to modify them, and ignore unnormalized ones
  1411. //since they are transient.
  1412. if (!mod.inited && !mod.map.unnormalized) {
  1413. mod.map = makeModuleMap(id, null, true);
  1414. }
  1415. });
  1416. //If a deps array or a config callback is specified, then call
  1417. //require with those args. This is useful when require is defined as a
  1418. //config object before require.js is loaded.
  1419. if (cfg.deps || cfg.callback) {
  1420. context.require(cfg.deps || [], cfg.callback);
  1421. }
  1422. },
  1423. makeShimExports: function (value) {
  1424. function fn() {
  1425. var ret;
  1426. if (value.init) {
  1427. ret = value.init.apply(global, arguments);
  1428. }
  1429. return ret || (value.exports && getGlobal(value.exports));
  1430. }
  1431. return fn;
  1432. },
  1433. makeRequire: function (relMap, options) {
  1434. options = options || {};
  1435. function localRequire(deps, callback, errback) {
  1436. var id, map, requireMod;
  1437. if (options.enableBuildCallback && callback && isFunction(callback)) {
  1438. callback.__requireJsBuild = true;
  1439. }
  1440. if (typeof deps === 'string') {
  1441. if (isFunction(callback)) {
  1442. //Invalid call
  1443. return onError(makeError('requireargs', 'Invalid require call'), errback);
  1444. }
  1445. //If require|exports|module are requested, get the
  1446. //value for them from the special handlers. Caveat:
  1447. //this only works while module is being defined.
  1448. if (relMap && hasProp(handlers, deps)) {
  1449. return handlers[deps](registry[relMap.id]);
  1450. }
  1451. //Synchronous access to one module. If require.get is
  1452. //available (as in the Node adapter), prefer that.
  1453. if (req.get) {
  1454. return req.get(context, deps, relMap, localRequire);
  1455. }
  1456. //Normalize module name, if it contains . or ..
  1457. map = makeModuleMap(deps, relMap, false, true);
  1458. id = map.id;
  1459. if (!hasProp(defined, id)) {
  1460. return onError(makeError('notloaded', 'Module name "' +
  1461. id +
  1462. '" has not been loaded yet for context: ' +
  1463. contextName +
  1464. (relMap ? '' : '. Use require([])')));
  1465. }
  1466. return defined[id];
  1467. }
  1468. //Grab defines waiting in the global queue.
  1469. intakeDefines();
  1470. //Mark all the dependencies as needing to be loaded.
  1471. context.nextTick(function () {
  1472. //Some defines could have been added since the
  1473. //require call, collect them.
  1474. intakeDefines();
  1475. requireMod = getModule(makeModuleMap(null, relMap));
  1476. //Store if map config should be applied to this require
  1477. //call for dependencies.
  1478. requireMod.skipMap = options.skipMap;
  1479. requireMod.init(deps, callback, errback, {
  1480. enabled: true
  1481. });
  1482. checkLoaded();
  1483. });
  1484. return localRequire;
  1485. }
  1486. mixin(localRequire, {
  1487. isBrowser: isBrowser,
  1488. /**
  1489. * Converts a module name + .extension into an URL path.
  1490. * *Requires* the use of a module name. It does not support using
  1491. * plain URLs like nameToUrl.
  1492. */
  1493. toUrl: function (moduleNamePlusExt) {
  1494. var ext,
  1495. index = moduleNamePlusExt.lastIndexOf('.'),
  1496. segment = moduleNamePlusExt.split('/')[0],
  1497. isRelative = segment === '.' || segment === '..';
  1498. //Have a file extension alias, and it is not the
  1499. //dots from a relative path.
  1500. if (index !== -1 && (!isRelative || index > 1)) {
  1501. ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
  1502. moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
  1503. }
  1504. return context.nameToUrl(normalize(moduleNamePlusExt,
  1505. relMap && relMap.id, true), ext, true);
  1506. },
  1507. defined: function (id) {
  1508. return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
  1509. },
  1510. specified: function (id) {
  1511. id = makeModuleMap(id, relMap, false, true).id;
  1512. return hasProp(defined, id) || hasProp(registry, id);
  1513. }
  1514. });
  1515. //Only allow undef on top level require calls
  1516. if (!relMap) {
  1517. localRequire.undef = function (id) {
  1518. //Bind any waiting define() calls to this context,
  1519. //fix for #408
  1520. takeGlobalQueue();
  1521. var map = makeModuleMap(id, relMap, true),
  1522. mod = getOwn(registry, id);
  1523. mod.undefed = true;
  1524. removeScript(id);
  1525. delete defined[id];
  1526. delete urlFetched[map.url];
  1527. delete undefEvents[id];
  1528. //Clean queued defines too. Go backwards
  1529. //in array so that the splices do not
  1530. //mess up the iteration.
  1531. eachReverse(defQueue, function(args, i) {
  1532. if (args[0] === id) {
  1533. defQueue.splice(i, 1);
  1534. }
  1535. });
  1536. delete context.defQueueMap[id];
  1537. if (mod) {
  1538. //Hold on to listeners in case the
  1539. //module will be attempted to be reloaded
  1540. //using a different config.
  1541. if (mod.events.defined) {
  1542. undefEvents[id] = mod.events;
  1543. }
  1544. cleanRegistry(id);
  1545. }
  1546. };
  1547. }
  1548. return localRequire;
  1549. },
  1550. /**
  1551. * Called to enable a module if it is still in the registry
  1552. * awaiting enablement. A second arg, parent, the parent module,
  1553. * is passed in for context, when this method is overridden by
  1554. * the optimizer. Not shown here to keep code compact.
  1555. */
  1556. enable: function (depMap) {
  1557. var mod = getOwn(registry, depMap.id);
  1558. if (mod) {
  1559. getModule(depMap).enable();
  1560. }
  1561. },
  1562. /**
  1563. * Internal method used by environment adapters to complete a load event.
  1564. * A load event could be a script load or just a load pass from a synchronous
  1565. * load call.
  1566. * @param {String} moduleName the name of the module to potentially complete.
  1567. */
  1568. completeLoad: function (moduleName) {
  1569. var found, args, mod,
  1570. shim = getOwn(config.shim, moduleName) || {},
  1571. shExports = shim.exports;
  1572. takeGlobalQueue();
  1573. while (defQueue.length) {
  1574. args = defQueue.shift();
  1575. if (args[0] === null) {
  1576. args[0] = moduleName;
  1577. //If already found an anonymous module and bound it
  1578. //to this name, then this is some other anon module
  1579. //waiting for its completeLoad to fire.
  1580. if (found) {
  1581. break;
  1582. }
  1583. found = true;
  1584. } else if (args[0] === moduleName) {
  1585. //Found matching define call for this script!
  1586. found = true;
  1587. }
  1588. callGetModule(args);
  1589. }
  1590. context.defQueueMap = {};
  1591. //Do this after the cycle of callGetModule in case the result
  1592. //of those calls/init calls changes the registry.
  1593. mod = getOwn(registry, moduleName);
  1594. if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
  1595. if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
  1596. if (hasPathFallback(moduleName)) {
  1597. return;
  1598. } else {
  1599. return onError(makeError('nodefine',
  1600. 'No define call for ' + moduleName,
  1601. null,
  1602. [moduleName]));
  1603. }
  1604. } else {
  1605. //A script that does not call define(), so just simulate
  1606. //the call for it.
  1607. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
  1608. }
  1609. }
  1610. checkLoaded();
  1611. },
  1612. /**
  1613. * Converts a module name to a file path. Supports cases where
  1614. * moduleName may actually be just an URL.
  1615. * Note that it **does not** call normalize on the moduleName,
  1616. * it is assumed to have already been normalized. This is an
  1617. * internal API, not a public one. Use toUrl for the public API.
  1618. */
  1619. nameToUrl: function (moduleName, ext, skipExt) {
  1620. var paths, syms, i, parentModule, url,
  1621. parentPath, bundleId,
  1622. pkgMain = getOwn(config.pkgs, moduleName);
  1623. if (pkgMain) {
  1624. moduleName = pkgMain;
  1625. }
  1626. bundleId = getOwn(bundlesMap, moduleName);
  1627. if (bundleId) {
  1628. return context.nameToUrl(bundleId, ext, skipExt);
  1629. }
  1630. //If a colon is in the URL, it indicates a protocol is used and it is just
  1631. //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
  1632. //or ends with .js, then assume the user meant to use an url and not a module id.
  1633. //The slash is important for protocol-less URLs as well as full paths.
  1634. if (req.jsExtRegExp.test(moduleName)) {
  1635. //Just a plain path, not module name lookup, so just return it.
  1636. //Add extension if it is included. This is a bit wonky, only non-.js things pass
  1637. //an extension, this method probably needs to be reworked.
  1638. url = moduleName + (ext || '');
  1639. } else {
  1640. //A module that needs to be converted to a path.
  1641. paths = config.paths;
  1642. syms = moduleName.split('/');
  1643. //For each module name segment, see if there is a path
  1644. //registered for it. Start with most specific name
  1645. //and work up from it.
  1646. for (i = syms.length; i > 0; i -= 1) {
  1647. parentModule = syms.slice(0, i).join('/');
  1648. parentPath = getOwn(paths, parentModule);
  1649. if (parentPath) {
  1650. //If an array, it means there are a few choices,
  1651. //Choose the one that is desired
  1652. if (isArray(parentPath)) {
  1653. parentPath = parentPath[0];
  1654. }
  1655. syms.splice(0, i, parentPath);
  1656. break;
  1657. }
  1658. }
  1659. //Join the path parts together, then figure out if baseUrl is needed.
  1660. url = syms.join('/');
  1661. url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js'));
  1662. url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
  1663. }
  1664. return config.urlArgs && !/^blob\:/.test(url) ?
  1665. url + config.urlArgs(moduleName, url) : url;
  1666. },
  1667. //Delegates to req.load. Broken out as a separate function to
  1668. //allow overriding in the optimizer.
  1669. load: function (id, url) {
  1670. req.load(context, id, url);
  1671. },
  1672. /**
  1673. * Executes a module callback function. Broken out as a separate function
  1674. * solely to allow the build system to sequence the files in the built
  1675. * layerobj in the right sequence.
  1676. *
  1677. * @private
  1678. */
  1679. execCb: function (name, callback, args, exports) {
  1680. return callback.apply(exports, args);
  1681. },
  1682. /**
  1683. * callback for script loads, used to check status of loading.
  1684. *
  1685. * @param {Event} evt the event from the browser for the script
  1686. * that was loaded.
  1687. */
  1688. onScriptLoad: function (evt) {
  1689. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1690. //all old browsers will be supported, but this one was easy enough
  1691. //to support and still makes sense.
  1692. if (evt.type === 'load' ||
  1693. (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
  1694. //Reset interactive script so a script node is not held onto for
  1695. //to long.
  1696. interactiveScript = null;
  1697. //Pull out the name of the module and the context.
  1698. var data = getScriptData(evt);
  1699. context.completeLoad(data.id);
  1700. }
  1701. },
  1702. /**
  1703. * Callback for script errors.
  1704. */
  1705. onScriptError: function (evt) {
  1706. var data = getScriptData(evt);
  1707. if (!hasPathFallback(data.id)) {
  1708. var parents = [];
  1709. eachProp(registry, function(value, key) {
  1710. if (key.indexOf('_@r') !== 0) {
  1711. each(value.depMaps, function(depMap) {
  1712. if (depMap.id === data.id) {
  1713. parents.push(key);
  1714. return true;
  1715. }
  1716. });
  1717. }
  1718. });
  1719. return onError(makeError('scripterror', 'Script error for "' + data.id +
  1720. (parents.length ?
  1721. '", needed by: ' + parents.join(', ') :
  1722. '"'), evt, [data.id]));
  1723. }
  1724. }
  1725. };
  1726. context.require = context.makeRequire();
  1727. return context;
  1728. }
  1729. /**
  1730. * Main entry point.
  1731. *
  1732. * If the only argument to require is a string, then the module that
  1733. * is represented by that string is fetched for the appropriate context.
  1734. *
  1735. * If the first argument is an array, then it will be treated as an array
  1736. * of dependency string names to fetch. An optional function callback can
  1737. * be specified to execute when all of those dependencies are available.
  1738. *
  1739. * Make a local req variable to help Caja compliance (it assumes things
  1740. * on a require that are not standardized), and to give a short
  1741. * name for minification/local scope use.
  1742. */
  1743. req = requirejs = function (deps, callback, errback, optional) {
  1744. //Find the right context, use default
  1745. var context, config,
  1746. contextName = defContextName;
  1747. // Determine if have config object in the call.
  1748. if (!isArray(deps) && typeof deps !== 'string') {
  1749. // deps is a config object
  1750. config = deps;
  1751. if (isArray(callback)) {
  1752. // Adjust args if there are dependencies
  1753. deps = callback;
  1754. callback = errback;
  1755. errback = optional;
  1756. } else {
  1757. deps = [];
  1758. }
  1759. }
  1760. if (config && config.context) {
  1761. contextName = config.context;
  1762. }
  1763. context = getOwn(contexts, contextName);
  1764. if (!context) {
  1765. context = contexts[contextName] = req.s.newContext(contextName);
  1766. }
  1767. if (config) {
  1768. context.configure(config);
  1769. }
  1770. return context.require(deps, callback, errback);
  1771. };
  1772. /**
  1773. * Support require.config() to make it easier to cooperate with other
  1774. * AMD loaders on globally agreed names.
  1775. */
  1776. req.config = function (config) {
  1777. return req(config);
  1778. };
  1779. /**
  1780. * Execute something after the current tick
  1781. * of the event loop. Override for other envs
  1782. * that have a better solution than setTimeout.
  1783. * @param {Function} fn function to execute later.
  1784. */
  1785. req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
  1786. setTimeout(fn, 4);
  1787. } : function (fn) { fn(); };
  1788. /**
  1789. * Export require as a global, but only if it does not already exist.
  1790. */
  1791. if (!require) {
  1792. require = req;
  1793. }
  1794. req.version = version;
  1795. //Used to filter out dependencies that are already paths.
  1796. req.jsExtRegExp = /^\/|:|\?|\.js$/;
  1797. req.isBrowser = isBrowser;
  1798. s = req.s = {
  1799. contexts: contexts,
  1800. newContext: newContext
  1801. };
  1802. //Create default context.
  1803. req({});
  1804. //Exports some context-sensitive methods on global require.
  1805. each([
  1806. 'toUrl',
  1807. 'undef',
  1808. 'defined',
  1809. 'specified'
  1810. ], function (prop) {
  1811. //Reference from contexts instead of early binding to default context,
  1812. //so that during builds, the latest instance of the default context
  1813. //with its config gets used.
  1814. req[prop] = function () {
  1815. var ctx = contexts[defContextName];
  1816. return ctx.require[prop].apply(ctx, arguments);
  1817. };
  1818. });
  1819. if (isBrowser) {
  1820. head = s.head = document.getElementsByTagName('head')[0];
  1821. //If BASE tag is in play, using appendChild is a problem for IE6.
  1822. //When that browser dies, this can be removed. Details in this jQuery bug:
  1823. //http://dev.jquery.com/ticket/2709
  1824. baseElement = document.getElementsByTagName('base')[0];
  1825. if (baseElement) {
  1826. head = s.head = baseElement.parentNode;
  1827. }
  1828. }
  1829. /**
  1830. * Any errors that require explicitly generates will be passed to this
  1831. * function. Intercept/override it if you want custom error handling.
  1832. * @param {Error} err the error object.
  1833. */
  1834. req.onError = defaultOnError;
  1835. /**
  1836. * Creates the node for the load command. Only used in browser envs.
  1837. */
  1838. req.createNode = function (config, moduleName, url) {
  1839. var node = config.xhtml ?
  1840. document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
  1841. document.createElement('script');
  1842. node.type = config.scriptType || 'text/javascript';
  1843. node.charset = 'utf-8';
  1844. node.async = true;
  1845. return node;
  1846. };
  1847. /**
  1848. * Does the request to load a module for the browser case.
  1849. * Make this a separate function to allow other environments
  1850. * to override it.
  1851. *
  1852. * @param {Object} context the require context to find state.
  1853. * @param {String} moduleName the name of the module.
  1854. * @param {Object} url the URL to the module.
  1855. */
  1856. req.load = function (context, moduleName, url) {
  1857. var config = (context && context.config) || {},
  1858. node;
  1859. if (isBrowser) {
  1860. //In the browser so use a script tag
  1861. node = req.createNode(config, moduleName, url);
  1862. node.setAttribute('data-requirecontext', context.contextName);
  1863. node.setAttribute('data-requiremodule', moduleName);
  1864. //Set up load listener. Test attachEvent first because IE9 has
  1865. //a subtle issue in its addEventListener and script onload firings
  1866. //that do not match the behavior of all other browsers with
  1867. //addEventListener support, which fire the onload event for a
  1868. //script right after the script execution. See:
  1869. //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
  1870. //UNFORTUNATELY Opera implements attachEvent but does not follow the script
  1871. //script execution mode.
  1872. if (node.attachEvent &&
  1873. //Check if node.attachEvent is artificially added by custom script or
  1874. //natively supported by browser
  1875. //read https://github.com/requirejs/requirejs/issues/187
  1876. //if we can NOT find [native code] then it must NOT natively supported.
  1877. //in IE8, node.attachEvent does not have toString()
  1878. //Note the test for "[native code" with no closing brace, see:
  1879. //https://github.com/requirejs/requirejs/issues/273
  1880. !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
  1881. !isOpera) {
  1882. //Probably IE. IE (at least 6-8) do not fire
  1883. //script onload right after executing the script, so
  1884. //we cannot tie the anonymous define call to a name.
  1885. //However, IE reports the script as being in 'interactive'
  1886. //readyState at the time of the define call.
  1887. useInteractive = true;
  1888. node.attachEvent('onreadystatechange', context.onScriptLoad);
  1889. //It would be great to add an error handler here to catch
  1890. //404s in IE9+. However, onreadystatechange will fire before
  1891. //the error handler, so that does not help. If addEventListener
  1892. //is used, then IE will fire error before load, but we cannot
  1893. //use that pathway given the connect.microsoft.com issue
  1894. //mentioned above about not doing the 'script execute,
  1895. //then fire the script load event listener before execute
  1896. //next script' that other browsers do.
  1897. //Best hope: IE10 fixes the issues,
  1898. //and then destroys all installs of IE 6-9.
  1899. //node.attachEvent('onerror', context.onScriptError);
  1900. } else {
  1901. node.addEventListener('load', context.onScriptLoad, false);
  1902. node.addEventListener('error', context.onScriptError, false);
  1903. }
  1904. node.src = url;
  1905. //Calling onNodeCreated after all properties on the node have been
  1906. //set, but before it is placed in the DOM.
  1907. if (config.onNodeCreated) {
  1908. config.onNodeCreated(node, config, moduleName, url);
  1909. }
  1910. //For some cache cases in IE 6-8, the script executes before the end
  1911. //of the appendChild execution, so to tie an anonymous define
  1912. //call to the module name (which is stored on the node), hold on
  1913. //to a reference to this node, but clear after the DOM insertion.
  1914. currentlyAddingScript = node;
  1915. if (baseElement) {
  1916. head.insertBefore(node, baseElement);
  1917. } else {
  1918. head.appendChild(node);
  1919. }
  1920. currentlyAddingScript = null;
  1921. return node;
  1922. } else if (isWebWorker) {
  1923. try {
  1924. //In a web worker, use importScripts. This is not a very
  1925. //efficient use of importScripts, importScripts will block until
  1926. //its script is downloaded and evaluated. However, if web workers
  1927. //are in play, the expectation is that a build has been done so
  1928. //that only one script needs to be loaded anyway. This may need
  1929. //to be reevaluated if other use cases become common.
  1930. // Post a task to the event loop to work around a bug in WebKit
  1931. // where the worker gets garbage-collected after calling
  1932. // importScripts(): https://webkit.org/b/153317
  1933. setTimeout(function() {}, 0);
  1934. importScripts(url);
  1935. //Account for anonymous modules
  1936. context.completeLoad(moduleName);
  1937. } catch (e) {
  1938. context.onError(makeError('importscripts',
  1939. 'importScripts failed for ' +
  1940. moduleName + ' at ' + url,
  1941. e,
  1942. [moduleName]));
  1943. }
  1944. }
  1945. };
  1946. function getInteractiveScript() {
  1947. if (interactiveScript && interactiveScript.readyState === 'interactive') {
  1948. return interactiveScript;
  1949. }
  1950. eachReverse(scripts(), function (script) {
  1951. if (script.readyState === 'interactive') {
  1952. return (interactiveScript = script);
  1953. }
  1954. });
  1955. return interactiveScript;
  1956. }
  1957. //Look for a data-main script attribute, which could also adjust the baseUrl.
  1958. if (isBrowser && !cfg.skipDataMain) {
  1959. //Figure out baseUrl. Get it from the script tag with require.js in it.
  1960. eachReverse(scripts(), function (script) {
  1961. //Set the 'head' where we can append children by
  1962. //using the script's parent.
  1963. if (!head) {
  1964. head = script.parentNode;
  1965. }
  1966. //Look for a data-main attribute to set main script for the page
  1967. //to load. If it is there, the path to data main becomes the
  1968. //baseUrl, if it is not already set.
  1969. dataMain = script.getAttribute('data-main');
  1970. if (dataMain) {
  1971. //Preserve dataMain in case it is a path (i.e. contains '?')
  1972. mainScript = dataMain;
  1973. //Set final baseUrl if there is not already an explicit one,
  1974. //but only do so if the data-main value is not a loader plugin
  1975. //module ID.
  1976. if (!cfg.baseUrl && mainScript.indexOf('!') === -1) {
  1977. //Pull off the directory of data-main for use as the
  1978. //baseUrl.
  1979. src = mainScript.split('/');
  1980. mainScript = src.pop();
  1981. subPath = src.length ? src.join('/') + '/' : './';
  1982. cfg.baseUrl = subPath;
  1983. }
  1984. //Strip off any trailing .js since mainScript is now
  1985. //like a module name.
  1986. mainScript = mainScript.replace(jsSuffixRegExp, '');
  1987. //If mainScript is still a path, fall back to dataMain
  1988. if (req.jsExtRegExp.test(mainScript)) {
  1989. mainScript = dataMain;
  1990. }
  1991. //Put the data-main script in the files to load.
  1992. cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
  1993. return true;
  1994. }
  1995. });
  1996. }
  1997. /**
  1998. * The function that handles definitions of modules. Differs from
  1999. * require() in that a string for the module should be the first argument,
  2000. * and the function to execute after dependencies are loaded should
  2001. * return a value to define the module corresponding to the first argument's
  2002. * name.
  2003. */
  2004. define = function (name, deps, callback) {
  2005. var node, context;
  2006. //Allow for anonymous modules
  2007. if (typeof name !== 'string') {
  2008. //Adjust args appropriately
  2009. callback = deps;
  2010. deps = name;
  2011. name = null;
  2012. }
  2013. //This module may not have dependencies
  2014. if (!isArray(deps)) {
  2015. callback = deps;
  2016. deps = null;
  2017. }
  2018. //If no name, and callback is a function, then figure out if it a
  2019. //CommonJS thing with dependencies.
  2020. if (!deps && isFunction(callback)) {
  2021. deps = [];
  2022. //Remove comments from the callback string,
  2023. //look for require calls, and pull them into the dependencies,
  2024. //but only if there are function args.
  2025. if (callback.length) {
  2026. callback
  2027. .toString()
  2028. .replace(commentRegExp, commentReplace)
  2029. .replace(cjsRequireRegExp, function (match, dep) {
  2030. deps.push(dep);
  2031. });
  2032. //May be a CommonJS thing even without require calls, but still
  2033. //could use exports, and module. Avoid doing exports and module
  2034. //work though if it just needs require.
  2035. //REQUIRES the function to expect the CommonJS variables in the
  2036. //order listed below.
  2037. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
  2038. }
  2039. }
  2040. //If in IE 6-8 and hit an anonymous define() call, do the interactive
  2041. //work.
  2042. if (useInteractive) {
  2043. node = currentlyAddingScript || getInteractiveScript();
  2044. if (node) {
  2045. if (!name) {
  2046. name = node.getAttribute('data-requiremodule');
  2047. }
  2048. context = contexts[node.getAttribute('data-requirecontext')];
  2049. }
  2050. }
  2051. //Always save off evaluating the def call until the script onload handler.
  2052. //This allows multiple modules to be in a file without prematurely
  2053. //tracing dependencies, and allows for anonymous module support,
  2054. //where the module name is not known until the script onload event
  2055. //occurs. If no context, use the global queue, and get it processed
  2056. //in the onscript load callback.
  2057. if (context) {
  2058. context.defQueue.push([name, deps, callback]);
  2059. context.defQueueMap[name] = true;
  2060. } else {
  2061. globalDefQueue.push([name, deps, callback]);
  2062. }
  2063. };
  2064. define.amd = {
  2065. jQuery: true
  2066. };
  2067. /**
  2068. * Executes the text. Normally just uses eval, but can be modified
  2069. * to use a better, environment-specific call. Only used for transpiling
  2070. * loader plugins, not for plain JS modules.
  2071. * @param {String} text the text to execute/evaluate.
  2072. */
  2073. req.exec = function (text) {
  2074. /*jslint evil: true */
  2075. return eval(text);
  2076. };
  2077. //Set up with config info.
  2078. req(cfg);
  2079. }(this, (typeof setTimeout === 'undefined' ? undefined : setTimeout)));
  2080. this.requirejsVars = {
  2081. require: require,
  2082. requirejs: require,
  2083. define: define
  2084. };
  2085. if (env === 'browser') {
  2086. //sloppy since eval enclosed with use strict causes problems if the source
  2087. //text is not strict-compliant.
  2088. /*jslint sloppy: true, evil: true */
  2089. /*global require, XMLHttpRequest */
  2090. (function () {
  2091. // Separate function to avoid eval pollution, same with arguments use.
  2092. function exec() {
  2093. eval(arguments[0]);
  2094. }
  2095. require.load = function (context, moduleName, url) {
  2096. var xhr = new XMLHttpRequest();
  2097. xhr.open('GET', url, true);
  2098. xhr.send();
  2099. xhr.onreadystatechange = function () {
  2100. if (xhr.readyState === 4) {
  2101. exec(xhr.responseText);
  2102. //Support anonymous modules.
  2103. context.completeLoad(moduleName);
  2104. }
  2105. };
  2106. };
  2107. }());
  2108. } else if (env === 'rhino') {
  2109. /*global require: false, java: false, load: false */
  2110. (function () {
  2111. 'use strict';
  2112. require.load = function (context, moduleName, url) {
  2113. load(url);
  2114. //Support anonymous modules.
  2115. context.completeLoad(moduleName);
  2116. };
  2117. }());
  2118. } else if (env === 'node') {
  2119. this.requirejsVars.nodeRequire = nodeRequire;
  2120. require.nodeRequire = nodeRequire;
  2121. //Explicity not strict since this file contains an eval call, and do not want
  2122. //to enforce strict on code evaluated that way. See
  2123. //https://github.com/requirejs/r.js/issues/774
  2124. /*jslint regexp: false, sloppy: true*/
  2125. /*global require: false, define: false, requirejsVars: false, process: false */
  2126. /**
  2127. * This adapter assumes that x.js has loaded it and set up
  2128. * some variables. This adapter just allows limited RequireJS
  2129. * usage from within the requirejs directory. The general
  2130. * node adapater is r.js.
  2131. */
  2132. (function () {
  2133. var nodeReq = requirejsVars.nodeRequire,
  2134. req = requirejsVars.require,
  2135. def = requirejsVars.define,
  2136. fs = nodeReq('fs'),
  2137. path = nodeReq('path'),
  2138. vm = nodeReq('vm'),
  2139. //In Node 0.7+ existsSync is on fs.
  2140. exists = fs.existsSync || path.existsSync,
  2141. hasOwn = Object.prototype.hasOwnProperty;
  2142. function hasProp(obj, prop) {
  2143. return hasOwn.call(obj, prop);
  2144. }
  2145. function syncTick(fn) {
  2146. fn();
  2147. }
  2148. function makeError(message, moduleName) {
  2149. var err = new Error(message);
  2150. err.requireModules = [moduleName];
  2151. return err;
  2152. }
  2153. //Supply an implementation that allows synchronous get of a module.
  2154. req.get = function (context, moduleName, relModuleMap, localRequire) {
  2155. if (moduleName === "require" || moduleName === "exports" || moduleName === "module") {
  2156. context.onError(makeError("Explicit require of " + moduleName + " is not allowed.", moduleName));
  2157. }
  2158. var ret, oldTick,
  2159. moduleMap = context.makeModuleMap(moduleName, relModuleMap, false, true);
  2160. //Normalize module name, if it contains . or ..
  2161. moduleName = moduleMap.id;
  2162. if (hasProp(context.defined, moduleName)) {
  2163. ret = context.defined[moduleName];
  2164. } else {
  2165. if (ret === undefined) {
  2166. //Make sure nextTick for this type of call is sync-based.
  2167. oldTick = context.nextTick;
  2168. context.nextTick = syncTick;
  2169. try {
  2170. if (moduleMap.prefix) {
  2171. //A plugin, call requirejs to handle it. Now that
  2172. //nextTick is syncTick, the require will complete
  2173. //synchronously.
  2174. localRequire([moduleMap.originalName]);
  2175. //Now that plugin is loaded, can regenerate the moduleMap
  2176. //to get the final, normalized ID.
  2177. moduleMap = context.makeModuleMap(moduleMap.originalName, relModuleMap, false, true);
  2178. moduleName = moduleMap.id;
  2179. } else {
  2180. //Try to dynamically fetch it.
  2181. req.load(context, moduleName, moduleMap.url);
  2182. //Enable the module
  2183. context.enable(moduleMap, relModuleMap);
  2184. }
  2185. //Break any cycles by requiring it normally, but this will
  2186. //finish synchronously
  2187. context.require([moduleName]);
  2188. //The above calls are sync, so can do the next thing safely.
  2189. ret = context.defined[moduleName];
  2190. } finally {
  2191. context.nextTick = oldTick;
  2192. }
  2193. }
  2194. }
  2195. return ret;
  2196. };
  2197. req.nextTick = function (fn) {
  2198. process.nextTick(fn);
  2199. };
  2200. //Add wrapper around the code so that it gets the requirejs
  2201. //API instead of the Node API, and it is done lexically so
  2202. //that it survives later execution.
  2203. req.makeNodeWrapper = function (contents) {
  2204. return '(function (require, requirejs, define) { ' +
  2205. contents +
  2206. '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));';
  2207. };
  2208. req.load = function (context, moduleName, url) {
  2209. var contents, err,
  2210. config = context.config;
  2211. if (config.shim[moduleName] && (!config.suppress || !config.suppress.nodeShim)) {
  2212. console.warn('Shim config not supported in Node, may or may not work. Detected ' +
  2213. 'for module: ' + moduleName);
  2214. }
  2215. if (exists(url)) {
  2216. contents = fs.readFileSync(url, 'utf8');
  2217. contents = req.makeNodeWrapper(contents);
  2218. try {
  2219. vm.runInThisContext(contents, fs.realpathSync(url));
  2220. } catch (e) {
  2221. err = new Error('Evaluating ' + url + ' as module "' +
  2222. moduleName + '" failed with error: ' + e);
  2223. err.originalError = e;
  2224. err.moduleName = moduleName;
  2225. err.requireModules = [moduleName];
  2226. err.fileName = url;
  2227. return context.onError(err);
  2228. }
  2229. } else {
  2230. def(moduleName, function () {
  2231. //Get the original name, since relative requires may be
  2232. //resolved differently in node (issue #202). Also, if relative,
  2233. //make it relative to the URL of the item requesting it
  2234. //(issue #393)
  2235. var dirName,
  2236. map = hasProp(context.registry, moduleName) &&
  2237. context.registry[moduleName].map,
  2238. parentMap = map && map.parentMap,
  2239. originalName = map && map.originalName;
  2240. if (originalName.charAt(0) === '.' && parentMap) {
  2241. dirName = parentMap.url.split('/');
  2242. dirName.pop();
  2243. originalName = dirName.join('/') + '/' + originalName;
  2244. }
  2245. try {
  2246. return (context.config.nodeRequire || req.nodeRequire)(originalName);
  2247. } catch (e) {
  2248. err = new Error('Tried loading "' + moduleName + '" at ' +
  2249. url + ' then tried node\'s require("' +
  2250. originalName + '") and it failed ' +
  2251. 'with error: ' + e);
  2252. err.originalError = e;
  2253. err.moduleName = originalName;
  2254. err.requireModules = [moduleName];
  2255. throw err;
  2256. }
  2257. });
  2258. }
  2259. //Support anonymous modules.
  2260. context.completeLoad(moduleName);
  2261. };
  2262. //Override to provide the function wrapper for define/require.
  2263. req.exec = function (text) {
  2264. /*jslint evil: true */
  2265. text = req.makeNodeWrapper(text);
  2266. return eval(text);
  2267. };
  2268. }());
  2269. } else if (env === 'xpconnect') {
  2270. /*jslint */
  2271. /*global require, load */
  2272. (function () {
  2273. 'use strict';
  2274. require.load = function (context, moduleName, url) {
  2275. load(url);
  2276. //Support anonymous modules.
  2277. context.completeLoad(moduleName);
  2278. };
  2279. }());
  2280. }
  2281. //Support a default file name to execute. Useful for hosted envs
  2282. //like Joyent where it defaults to a server.js as the only executed
  2283. //script. But only do it if this is not an optimization run.
  2284. if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) {
  2285. fileName = 'main.js';
  2286. }
  2287. /**
  2288. * Loads the library files that can be used for the optimizer, or for other
  2289. * tasks.
  2290. */
  2291. function loadLib() {
  2292. /*jslint strict: false */
  2293. /*global Packages: false, process: false, window: false, navigator: false,
  2294. document: false, define: false */
  2295. /**
  2296. * A plugin that modifies any /env/ path to be the right path based on
  2297. * the host environment. Right now only works for Node, Rhino and browser.
  2298. */
  2299. (function () {
  2300. var pathRegExp = /(\/|^)env\/|\{env\}/,
  2301. env = 'unknown';
  2302. if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
  2303. env = 'node';
  2304. } else if (typeof Packages !== 'undefined') {
  2305. env = 'rhino';
  2306. } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
  2307. (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
  2308. env = 'browser';
  2309. } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
  2310. env = 'xpconnect';
  2311. }
  2312. define('env', {
  2313. get: function () {
  2314. return env;
  2315. },
  2316. load: function (name, req, load, config) {
  2317. //Allow override in the config.
  2318. if (config.env) {
  2319. env = config.env;
  2320. }
  2321. name = name.replace(pathRegExp, function (match, prefix) {
  2322. if (match.indexOf('{') === -1) {
  2323. return prefix + env + '/';
  2324. } else {
  2325. return env;
  2326. }
  2327. });
  2328. req([name], function (mod) {
  2329. load(mod);
  2330. });
  2331. }
  2332. });
  2333. }());
  2334. /*jslint plusplus: true */
  2335. /*global define, java */
  2336. define('lang', function () {
  2337. 'use strict';
  2338. var lang, isJavaObj,
  2339. hasOwn = Object.prototype.hasOwnProperty;
  2340. function hasProp(obj, prop) {
  2341. return hasOwn.call(obj, prop);
  2342. }
  2343. isJavaObj = function () {
  2344. return false;
  2345. };
  2346. //Rhino, but not Nashorn (detected by importPackage not existing)
  2347. //Can have some strange foreign objects.
  2348. if (typeof java !== 'undefined' && java.lang && java.lang.Object && typeof importPackage !== 'undefined') {
  2349. isJavaObj = function (obj) {
  2350. return obj instanceof java.lang.Object;
  2351. };
  2352. }
  2353. lang = {
  2354. backSlashRegExp: /\\/g,
  2355. ostring: Object.prototype.toString,
  2356. isArray: Array.isArray || function (it) {
  2357. return lang.ostring.call(it) === "[object Array]";
  2358. },
  2359. isFunction: function(it) {
  2360. return lang.ostring.call(it) === "[object Function]";
  2361. },
  2362. isRegExp: function(it) {
  2363. return it && it instanceof RegExp;
  2364. },
  2365. hasProp: hasProp,
  2366. //returns true if the object does not have an own property prop,
  2367. //or if it does, it is a falsy value.
  2368. falseProp: function (obj, prop) {
  2369. return !hasProp(obj, prop) || !obj[prop];
  2370. },
  2371. //gets own property value for given prop on object
  2372. getOwn: function (obj, prop) {
  2373. return hasProp(obj, prop) && obj[prop];
  2374. },
  2375. _mixin: function(dest, source, override){
  2376. var name;
  2377. for (name in source) {
  2378. if(source.hasOwnProperty(name) &&
  2379. (override || !dest.hasOwnProperty(name))) {
  2380. dest[name] = source[name];
  2381. }
  2382. }
  2383. return dest; // Object
  2384. },
  2385. /**
  2386. * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean,
  2387. * then the source objects properties are force copied over to dest.
  2388. */
  2389. mixin: function(dest){
  2390. var parameters = Array.prototype.slice.call(arguments),
  2391. override, i, l;
  2392. if (!dest) { dest = {}; }
  2393. if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') {
  2394. override = parameters.pop();
  2395. }
  2396. for (i = 1, l = parameters.length; i < l; i++) {
  2397. lang._mixin(dest, parameters[i], override);
  2398. }
  2399. return dest; // Object
  2400. },
  2401. /**
  2402. * Does a deep mix of source into dest, where source values override
  2403. * dest values if a winner is needed.
  2404. * @param {Object} dest destination object that receives the mixed
  2405. * values.
  2406. * @param {Object} source source object contributing properties to mix
  2407. * in.
  2408. * @return {[Object]} returns dest object with the modification.
  2409. */
  2410. deepMix: function(dest, source) {
  2411. lang.eachProp(source, function (value, prop) {
  2412. if (typeof value === 'object' && value &&
  2413. !lang.isArray(value) && !lang.isFunction(value) &&
  2414. !(value instanceof RegExp)) {
  2415. if (!dest[prop]) {
  2416. dest[prop] = {};
  2417. }
  2418. lang.deepMix(dest[prop], value);
  2419. } else {
  2420. dest[prop] = value;
  2421. }
  2422. });
  2423. return dest;
  2424. },
  2425. /**
  2426. * Does a type of deep copy. Do not give it anything fancy, best
  2427. * for basic object copies of objects that also work well as
  2428. * JSON-serialized things, or has properties pointing to functions.
  2429. * For non-array/object values, just returns the same object.
  2430. * @param {Object} obj copy properties from this object
  2431. * @param {Object} [ignoredProps] optional object whose own properties
  2432. * are keys that should be ignored.
  2433. * @return {Object}
  2434. */
  2435. deeplikeCopy: function (obj, ignoredProps) {
  2436. var type, result;
  2437. if (lang.isArray(obj)) {
  2438. result = [];
  2439. obj.forEach(function(value) {
  2440. result.push(lang.deeplikeCopy(value, ignoredProps));
  2441. });
  2442. return result;
  2443. }
  2444. type = typeof obj;
  2445. if (obj === null || obj === undefined || type === 'boolean' ||
  2446. type === 'string' || type === 'number' || lang.isFunction(obj) ||
  2447. lang.isRegExp(obj)|| isJavaObj(obj)) {
  2448. return obj;
  2449. }
  2450. //Anything else is an object, hopefully.
  2451. result = {};
  2452. lang.eachProp(obj, function(value, key) {
  2453. if (!ignoredProps || !hasProp(ignoredProps, key)) {
  2454. result[key] = lang.deeplikeCopy(value, ignoredProps);
  2455. }
  2456. });
  2457. return result;
  2458. },
  2459. delegate: (function () {
  2460. // boodman/crockford delegation w/ cornford optimization
  2461. function TMP() {}
  2462. return function (obj, props) {
  2463. TMP.prototype = obj;
  2464. var tmp = new TMP();
  2465. TMP.prototype = null;
  2466. if (props) {
  2467. lang.mixin(tmp, props);
  2468. }
  2469. return tmp; // Object
  2470. };
  2471. }()),
  2472. /**
  2473. * Helper function for iterating over an array. If the func returns
  2474. * a true value, it will break out of the loop.
  2475. */
  2476. each: function each(ary, func) {
  2477. if (ary) {
  2478. var i;
  2479. for (i = 0; i < ary.length; i += 1) {
  2480. if (func(ary[i], i, ary)) {
  2481. break;
  2482. }
  2483. }
  2484. }
  2485. },
  2486. /**
  2487. * Cycles over properties in an object and calls a function for each
  2488. * property value. If the function returns a truthy value, then the
  2489. * iteration is stopped.
  2490. */
  2491. eachProp: function eachProp(obj, func) {
  2492. var prop;
  2493. for (prop in obj) {
  2494. if (hasProp(obj, prop)) {
  2495. if (func(obj[prop], prop)) {
  2496. break;
  2497. }
  2498. }
  2499. }
  2500. },
  2501. //Similar to Function.prototype.bind, but the "this" object is specified
  2502. //first, since it is easier to read/figure out what "this" will be.
  2503. bind: function bind(obj, fn) {
  2504. return function () {
  2505. return fn.apply(obj, arguments);
  2506. };
  2507. },
  2508. //Escapes a content string to be be a string that has characters escaped
  2509. //for inclusion as part of a JS string.
  2510. jsEscape: function (content) {
  2511. return content.replace(/(["'\\])/g, '\\$1')
  2512. .replace(/[\f]/g, "\\f")
  2513. .replace(/[\b]/g, "\\b")
  2514. .replace(/[\n]/g, "\\n")
  2515. .replace(/[\t]/g, "\\t")
  2516. .replace(/[\r]/g, "\\r");
  2517. }
  2518. };
  2519. return lang;
  2520. });
  2521. /**
  2522. * prim 0.0.1 Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2523. * Available via the MIT or new BSD license.
  2524. * see: http://github.com/requirejs/prim for details
  2525. */
  2526. /*global setImmediate, process, setTimeout, define, module */
  2527. //Set prime.hideResolutionConflict = true to allow "resolution-races"
  2528. //in promise-tests to pass.
  2529. //Since the goal of prim is to be a small impl for trusted code, it is
  2530. //more important to normally throw in this case so that we can find
  2531. //logic errors quicker.
  2532. var prim;
  2533. (function () {
  2534. 'use strict';
  2535. var op = Object.prototype,
  2536. hasOwn = op.hasOwnProperty;
  2537. function hasProp(obj, prop) {
  2538. return hasOwn.call(obj, prop);
  2539. }
  2540. /**
  2541. * Helper function for iterating over an array. If the func returns
  2542. * a true value, it will break out of the loop.
  2543. */
  2544. function each(ary, func) {
  2545. if (ary) {
  2546. var i;
  2547. for (i = 0; i < ary.length; i += 1) {
  2548. if (ary[i]) {
  2549. func(ary[i], i, ary);
  2550. }
  2551. }
  2552. }
  2553. }
  2554. function check(p) {
  2555. if (hasProp(p, 'e') || hasProp(p, 'v')) {
  2556. if (!prim.hideResolutionConflict) {
  2557. throw new Error('Prim promise already resolved: ' +
  2558. JSON.stringify(p));
  2559. }
  2560. return false;
  2561. }
  2562. return true;
  2563. }
  2564. function notify(ary, value) {
  2565. prim.nextTick(function () {
  2566. each(ary, function (item) {
  2567. item(value);
  2568. });
  2569. });
  2570. }
  2571. prim = function prim() {
  2572. var p,
  2573. ok = [],
  2574. fail = [];
  2575. return (p = {
  2576. callback: function (yes, no) {
  2577. if (no) {
  2578. p.errback(no);
  2579. }
  2580. if (hasProp(p, 'v')) {
  2581. prim.nextTick(function () {
  2582. yes(p.v);
  2583. });
  2584. } else {
  2585. ok.push(yes);
  2586. }
  2587. },
  2588. errback: function (no) {
  2589. if (hasProp(p, 'e')) {
  2590. prim.nextTick(function () {
  2591. no(p.e);
  2592. });
  2593. } else {
  2594. fail.push(no);
  2595. }
  2596. },
  2597. finished: function () {
  2598. return hasProp(p, 'e') || hasProp(p, 'v');
  2599. },
  2600. rejected: function () {
  2601. return hasProp(p, 'e');
  2602. },
  2603. resolve: function (v) {
  2604. if (check(p)) {
  2605. p.v = v;
  2606. notify(ok, v);
  2607. }
  2608. return p;
  2609. },
  2610. reject: function (e) {
  2611. if (check(p)) {
  2612. p.e = e;
  2613. notify(fail, e);
  2614. }
  2615. return p;
  2616. },
  2617. start: function (fn) {
  2618. p.resolve();
  2619. return p.promise.then(fn);
  2620. },
  2621. promise: {
  2622. then: function (yes, no) {
  2623. var next = prim();
  2624. p.callback(function (v) {
  2625. try {
  2626. if (yes && typeof yes === 'function') {
  2627. v = yes(v);
  2628. }
  2629. if (v && v.then) {
  2630. v.then(next.resolve, next.reject);
  2631. } else {
  2632. next.resolve(v);
  2633. }
  2634. } catch (e) {
  2635. next.reject(e);
  2636. }
  2637. }, function (e) {
  2638. var err;
  2639. try {
  2640. if (!no || typeof no !== 'function') {
  2641. next.reject(e);
  2642. } else {
  2643. err = no(e);
  2644. if (err && err.then) {
  2645. err.then(next.resolve, next.reject);
  2646. } else {
  2647. next.resolve(err);
  2648. }
  2649. }
  2650. } catch (e2) {
  2651. next.reject(e2);
  2652. }
  2653. });
  2654. return next.promise;
  2655. },
  2656. fail: function (no) {
  2657. return p.promise.then(null, no);
  2658. },
  2659. end: function () {
  2660. p.errback(function (e) {
  2661. throw e;
  2662. });
  2663. }
  2664. }
  2665. });
  2666. };
  2667. prim.serial = function (ary) {
  2668. var result = prim().resolve().promise;
  2669. each(ary, function (item) {
  2670. result = result.then(function () {
  2671. return item();
  2672. });
  2673. });
  2674. return result;
  2675. };
  2676. prim.nextTick = typeof setImmediate === 'function' ? setImmediate :
  2677. (typeof process !== 'undefined' && process.nextTick ?
  2678. process.nextTick : (typeof setTimeout !== 'undefined' ?
  2679. function (fn) {
  2680. setTimeout(fn, 0);
  2681. } : function (fn) {
  2682. fn();
  2683. }));
  2684. if (typeof define === 'function' && define.amd) {
  2685. define('prim', function () { return prim; });
  2686. } else if (typeof module !== 'undefined' && module.exports) {
  2687. module.exports = prim;
  2688. }
  2689. }());
  2690. if(env === 'browser') {
  2691. /*jslint strict: false */
  2692. /*global define: false, load: false */
  2693. //Just a stub for use with uglify's consolidator.js
  2694. define('browser/assert', function () {
  2695. return {};
  2696. });
  2697. }
  2698. if(env === 'node') {
  2699. /*jslint strict: false */
  2700. /*global define: false, load: false */
  2701. //Needed so that rhino/assert can return a stub for uglify's consolidator.js
  2702. define('node/assert', ['assert'], function (assert) {
  2703. return assert;
  2704. });
  2705. }
  2706. if(env === 'rhino') {
  2707. /*jslint strict: false */
  2708. /*global define: false, load: false */
  2709. //Just a stub for use with uglify's consolidator.js
  2710. define('rhino/assert', function () {
  2711. return {};
  2712. });
  2713. }
  2714. if(env === 'xpconnect') {
  2715. /*jslint strict: false */
  2716. /*global define: false, load: false */
  2717. //Just a stub for use with uglify's consolidator.js
  2718. define('xpconnect/assert', function () {
  2719. return {};
  2720. });
  2721. }
  2722. if(env === 'browser') {
  2723. /*jslint strict: false */
  2724. /*global define: false, process: false */
  2725. define('browser/args', function () {
  2726. //Always expect config via an API call
  2727. return [];
  2728. });
  2729. }
  2730. if(env === 'node') {
  2731. /*jslint strict: false */
  2732. /*global define: false, process: false */
  2733. define('node/args', function () {
  2734. //Do not return the "node" or "r.js" arguments
  2735. var args = process.argv.slice(2);
  2736. //Ignore any command option used for main x.js branching
  2737. if (args[0] && args[0].indexOf('-') === 0) {
  2738. args = args.slice(1);
  2739. }
  2740. return args;
  2741. });
  2742. }
  2743. if(env === 'rhino') {
  2744. /*jslint strict: false */
  2745. /*global define: false, process: false */
  2746. var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2747. define('rhino/args', function () {
  2748. var args = jsLibRhinoArgs;
  2749. //Ignore any command option used for main x.js branching
  2750. if (args[0] && args[0].indexOf('-') === 0) {
  2751. args = args.slice(1);
  2752. }
  2753. return args;
  2754. });
  2755. }
  2756. if(env === 'xpconnect') {
  2757. /*jslint strict: false */
  2758. /*global define, xpconnectArgs */
  2759. var jsLibXpConnectArgs = (typeof xpconnectArgs !== 'undefined' && xpconnectArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2760. define('xpconnect/args', function () {
  2761. var args = jsLibXpConnectArgs;
  2762. //Ignore any command option used for main x.js branching
  2763. if (args[0] && args[0].indexOf('-') === 0) {
  2764. args = args.slice(1);
  2765. }
  2766. return args;
  2767. });
  2768. }
  2769. if(env === 'browser') {
  2770. /*jslint strict: false */
  2771. /*global define: false, console: false */
  2772. define('browser/load', ['./file'], function (file) {
  2773. function load(fileName) {
  2774. eval(file.readFile(fileName));
  2775. }
  2776. return load;
  2777. });
  2778. }
  2779. if(env === 'node') {
  2780. /*jslint strict: false */
  2781. /*global define: false, console: false */
  2782. define('node/load', ['fs'], function (fs) {
  2783. function load(fileName) {
  2784. var contents = fs.readFileSync(fileName, 'utf8');
  2785. process.compile(contents, fileName);
  2786. }
  2787. return load;
  2788. });
  2789. }
  2790. if(env === 'rhino') {
  2791. /*jslint strict: false */
  2792. /*global define: false, load: false */
  2793. define('rhino/load', function () {
  2794. return load;
  2795. });
  2796. }
  2797. if(env === 'xpconnect') {
  2798. /*jslint strict: false */
  2799. /*global define: false, load: false */
  2800. define('xpconnect/load', function () {
  2801. return load;
  2802. });
  2803. }
  2804. if(env === 'browser') {
  2805. /*jslint sloppy: true, nomen: true */
  2806. /*global require, define, console, XMLHttpRequest, requirejs, location */
  2807. define('browser/file', ['prim'], function (prim) {
  2808. var file,
  2809. currDirRegExp = /^\.(\/|$)/;
  2810. function frontSlash(path) {
  2811. return path.replace(/\\/g, '/');
  2812. }
  2813. function exists(path) {
  2814. var status, xhr = new XMLHttpRequest();
  2815. //Oh yeah, that is right SYNC IO. Behold its glory
  2816. //and horrible blocking behavior.
  2817. xhr.open('HEAD', path, false);
  2818. xhr.send();
  2819. status = xhr.status;
  2820. return status === 200 || status === 304;
  2821. }
  2822. function mkDir(dir) {
  2823. console.log('mkDir is no-op in browser');
  2824. }
  2825. function mkFullDir(dir) {
  2826. console.log('mkFullDir is no-op in browser');
  2827. }
  2828. file = {
  2829. backSlashRegExp: /\\/g,
  2830. exclusionRegExp: /^\./,
  2831. getLineSeparator: function () {
  2832. return '/';
  2833. },
  2834. exists: function (fileName) {
  2835. return exists(fileName);
  2836. },
  2837. parent: function (fileName) {
  2838. var parts = fileName.split('/');
  2839. parts.pop();
  2840. return parts.join('/');
  2841. },
  2842. /**
  2843. * Gets the absolute file path as a string, normalized
  2844. * to using front slashes for path separators.
  2845. * @param {String} fileName
  2846. */
  2847. absPath: function (fileName) {
  2848. var dir;
  2849. if (currDirRegExp.test(fileName)) {
  2850. dir = frontSlash(location.href);
  2851. if (dir.indexOf('/') !== -1) {
  2852. dir = dir.split('/');
  2853. //Pull off protocol and host, just want
  2854. //to allow paths (other build parts, like
  2855. //require._isSupportedBuildUrl do not support
  2856. //full URLs), but a full path from
  2857. //the root.
  2858. dir.splice(0, 3);
  2859. dir.pop();
  2860. dir = '/' + dir.join('/');
  2861. }
  2862. fileName = dir + fileName.substring(1);
  2863. }
  2864. return fileName;
  2865. },
  2866. normalize: function (fileName) {
  2867. return fileName;
  2868. },
  2869. isFile: function (path) {
  2870. return true;
  2871. },
  2872. isDirectory: function (path) {
  2873. return false;
  2874. },
  2875. getFilteredFileList: function (startDir, regExpFilters, makeUnixPaths) {
  2876. console.log('file.getFilteredFileList is no-op in browser');
  2877. },
  2878. copyDir: function (srcDir, destDir, regExpFilter, onlyCopyNew) {
  2879. console.log('file.copyDir is no-op in browser');
  2880. },
  2881. copyFile: function (srcFileName, destFileName, onlyCopyNew) {
  2882. console.log('file.copyFile is no-op in browser');
  2883. },
  2884. /**
  2885. * Renames a file. May fail if "to" already exists or is on another drive.
  2886. */
  2887. renameFile: function (from, to) {
  2888. console.log('file.renameFile is no-op in browser');
  2889. },
  2890. /**
  2891. * Reads a *text* file.
  2892. */
  2893. readFile: function (path, encoding) {
  2894. var xhr = new XMLHttpRequest();
  2895. //Oh yeah, that is right SYNC IO. Behold its glory
  2896. //and horrible blocking behavior.
  2897. xhr.open('GET', path, false);
  2898. xhr.send();
  2899. return xhr.responseText;
  2900. },
  2901. readFileAsync: function (path, encoding) {
  2902. var xhr = new XMLHttpRequest(),
  2903. d = prim();
  2904. xhr.open('GET', path, true);
  2905. xhr.send();
  2906. xhr.onreadystatechange = function () {
  2907. if (xhr.readyState === 4) {
  2908. if (xhr.status > 400) {
  2909. d.reject(new Error('Status: ' + xhr.status + ': ' + xhr.statusText));
  2910. } else {
  2911. d.resolve(xhr.responseText);
  2912. }
  2913. }
  2914. };
  2915. return d.promise;
  2916. },
  2917. saveUtf8File: function (fileName, fileContents) {
  2918. //summary: saves a *text* file using UTF-8 encoding.
  2919. file.saveFile(fileName, fileContents, "utf8");
  2920. },
  2921. saveFile: function (fileName, fileContents, encoding) {
  2922. requirejs.browser.saveFile(fileName, fileContents, encoding);
  2923. },
  2924. deleteFile: function (fileName) {
  2925. console.log('file.deleteFile is no-op in browser');
  2926. },
  2927. /**
  2928. * Deletes any empty directories under the given directory.
  2929. */
  2930. deleteEmptyDirs: function (startDir) {
  2931. console.log('file.deleteEmptyDirs is no-op in browser');
  2932. }
  2933. };
  2934. return file;
  2935. });
  2936. }
  2937. if(env === 'node') {
  2938. /*jslint plusplus: false, octal:false, strict: false */
  2939. /*global define: false, process: false */
  2940. define('node/file', ['fs', 'path', 'prim'], function (fs, path, prim) {
  2941. var isWindows = process.platform === 'win32',
  2942. windowsDriveRegExp = /^[a-zA-Z]\:\/$/,
  2943. file;
  2944. function frontSlash(path) {
  2945. return path.replace(/\\/g, '/');
  2946. }
  2947. function exists(path) {
  2948. if (isWindows && path.charAt(path.length - 1) === '/' &&
  2949. path.charAt(path.length - 2) !== ':') {
  2950. path = path.substring(0, path.length - 1);
  2951. }
  2952. try {
  2953. fs.statSync(path);
  2954. return true;
  2955. } catch (e) {
  2956. return false;
  2957. }
  2958. }
  2959. function mkDir(dir) {
  2960. if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) {
  2961. fs.mkdirSync(dir, 511);
  2962. }
  2963. }
  2964. function mkFullDir(dir) {
  2965. var parts = dir.split('/'),
  2966. currDir = '',
  2967. first = true;
  2968. parts.forEach(function (part) {
  2969. //First part may be empty string if path starts with a slash.
  2970. currDir += part + '/';
  2971. first = false;
  2972. if (part) {
  2973. mkDir(currDir);
  2974. }
  2975. });
  2976. }
  2977. file = {
  2978. backSlashRegExp: /\\/g,
  2979. exclusionRegExp: /^\./,
  2980. getLineSeparator: function () {
  2981. return '/';
  2982. },
  2983. exists: function (fileName) {
  2984. return exists(fileName);
  2985. },
  2986. parent: function (fileName) {
  2987. var parts = fileName.split('/');
  2988. parts.pop();
  2989. return parts.join('/');
  2990. },
  2991. /**
  2992. * Gets the absolute file path as a string, normalized
  2993. * to using front slashes for path separators.
  2994. * @param {String} fileName
  2995. */
  2996. absPath: function (fileName) {
  2997. return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName))));
  2998. },
  2999. normalize: function (fileName) {
  3000. return frontSlash(path.normalize(fileName));
  3001. },
  3002. isFile: function (path) {
  3003. return fs.statSync(path).isFile();
  3004. },
  3005. isDirectory: function (path) {
  3006. return fs.statSync(path).isDirectory();
  3007. },
  3008. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) {
  3009. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3010. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3011. //and it will be treated as the "include" case.
  3012. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3013. //is set to another value.
  3014. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3015. i, stat, filePath, ok, dirFiles, fileName;
  3016. topDir = startDir;
  3017. regExpInclude = regExpFilters.include || regExpFilters;
  3018. regExpExclude = regExpFilters.exclude || null;
  3019. if (file.exists(topDir)) {
  3020. dirFileArray = fs.readdirSync(topDir);
  3021. for (i = 0; i < dirFileArray.length; i++) {
  3022. fileName = dirFileArray[i];
  3023. filePath = path.join(topDir, fileName);
  3024. stat = fs.statSync(filePath);
  3025. if (stat.isFile()) {
  3026. if (makeUnixPaths) {
  3027. //Make sure we have a JS string.
  3028. if (filePath.indexOf("/") === -1) {
  3029. filePath = frontSlash(filePath);
  3030. }
  3031. }
  3032. ok = true;
  3033. if (regExpInclude) {
  3034. ok = filePath.match(regExpInclude);
  3035. }
  3036. if (ok && regExpExclude) {
  3037. ok = !filePath.match(regExpExclude);
  3038. }
  3039. if (ok && (!file.exclusionRegExp ||
  3040. !file.exclusionRegExp.test(fileName))) {
  3041. files.push(filePath);
  3042. }
  3043. } else if (stat.isDirectory() &&
  3044. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) {
  3045. dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths);
  3046. //Do not use push.apply for dir listings, can hit limit of max number
  3047. //of arguments to a function call, #921.
  3048. dirFiles.forEach(function (dirFile) {
  3049. files.push(dirFile);
  3050. });
  3051. }
  3052. }
  3053. }
  3054. return files; //Array
  3055. },
  3056. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3057. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3058. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3059. regExpFilter = regExpFilter || /\w/;
  3060. //Normalize th directory names, but keep front slashes.
  3061. //path module on windows now returns backslashed paths.
  3062. srcDir = frontSlash(path.normalize(srcDir));
  3063. destDir = frontSlash(path.normalize(destDir));
  3064. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3065. copiedFiles = [], i, srcFileName, destFileName;
  3066. for (i = 0; i < fileNames.length; i++) {
  3067. srcFileName = fileNames[i];
  3068. destFileName = srcFileName.replace(srcDir, destDir);
  3069. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3070. copiedFiles.push(destFileName);
  3071. }
  3072. }
  3073. return copiedFiles.length ? copiedFiles : null; //Array or null
  3074. },
  3075. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3076. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3077. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3078. var parentDir;
  3079. //logger.trace("Src filename: " + srcFileName);
  3080. //logger.trace("Dest filename: " + destFileName);
  3081. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3082. //than dest.
  3083. if (onlyCopyNew) {
  3084. if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) {
  3085. return false; //Boolean
  3086. }
  3087. }
  3088. //Make sure destination dir exists.
  3089. parentDir = path.dirname(destFileName);
  3090. if (!file.exists(parentDir)) {
  3091. mkFullDir(parentDir);
  3092. }
  3093. fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary');
  3094. return true; //Boolean
  3095. },
  3096. /**
  3097. * Renames a file. May fail if "to" already exists or is on another drive.
  3098. */
  3099. renameFile: function (from, to) {
  3100. return fs.renameSync(from, to);
  3101. },
  3102. /**
  3103. * Reads a *text* file.
  3104. */
  3105. readFile: function (/*String*/path, /*String?*/encoding) {
  3106. if (encoding === 'utf-8') {
  3107. encoding = 'utf8';
  3108. }
  3109. if (!encoding) {
  3110. encoding = 'utf8';
  3111. }
  3112. var text = fs.readFileSync(path, encoding);
  3113. //Hmm, would not expect to get A BOM, but it seems to happen,
  3114. //remove it just in case.
  3115. if (text.indexOf('\uFEFF') === 0) {
  3116. text = text.substring(1, text.length);
  3117. }
  3118. return text;
  3119. },
  3120. readFileAsync: function (path, encoding) {
  3121. var d = prim();
  3122. try {
  3123. d.resolve(file.readFile(path, encoding));
  3124. } catch (e) {
  3125. d.reject(e);
  3126. }
  3127. return d.promise;
  3128. },
  3129. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3130. //summary: saves a *text* file using UTF-8 encoding.
  3131. file.saveFile(fileName, fileContents, "utf8");
  3132. },
  3133. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3134. //summary: saves a *text* file.
  3135. var parentDir;
  3136. if (encoding === 'utf-8') {
  3137. encoding = 'utf8';
  3138. }
  3139. if (!encoding) {
  3140. encoding = 'utf8';
  3141. }
  3142. //Make sure destination directories exist.
  3143. parentDir = path.dirname(fileName);
  3144. if (!file.exists(parentDir)) {
  3145. mkFullDir(parentDir);
  3146. }
  3147. fs.writeFileSync(fileName, fileContents, encoding);
  3148. },
  3149. deleteFile: function (/*String*/fileName) {
  3150. //summary: deletes a file or directory if it exists.
  3151. var files, i, stat;
  3152. if (file.exists(fileName)) {
  3153. stat = fs.lstatSync(fileName);
  3154. if (stat.isDirectory()) {
  3155. files = fs.readdirSync(fileName);
  3156. for (i = 0; i < files.length; i++) {
  3157. this.deleteFile(path.join(fileName, files[i]));
  3158. }
  3159. fs.rmdirSync(fileName);
  3160. } else {
  3161. fs.unlinkSync(fileName);
  3162. }
  3163. }
  3164. },
  3165. /**
  3166. * Deletes any empty directories under the given directory.
  3167. */
  3168. deleteEmptyDirs: function (startDir) {
  3169. var dirFileArray, i, fileName, filePath, stat;
  3170. if (file.exists(startDir)) {
  3171. dirFileArray = fs.readdirSync(startDir);
  3172. for (i = 0; i < dirFileArray.length; i++) {
  3173. fileName = dirFileArray[i];
  3174. filePath = path.join(startDir, fileName);
  3175. stat = fs.lstatSync(filePath);
  3176. if (stat.isDirectory()) {
  3177. file.deleteEmptyDirs(filePath);
  3178. }
  3179. }
  3180. //If directory is now empty, remove it.
  3181. if (fs.readdirSync(startDir).length === 0) {
  3182. file.deleteFile(startDir);
  3183. }
  3184. }
  3185. }
  3186. };
  3187. return file;
  3188. });
  3189. }
  3190. if(env === 'rhino') {
  3191. //Helper functions to deal with file I/O.
  3192. /*jslint plusplus: false */
  3193. /*global java: false, define: false */
  3194. define('rhino/file', ['prim'], function (prim) {
  3195. var file = {
  3196. backSlashRegExp: /\\/g,
  3197. exclusionRegExp: /^\./,
  3198. getLineSeparator: function () {
  3199. return file.lineSeparator;
  3200. },
  3201. lineSeparator: java.lang.System.getProperty("line.separator"), //Java String
  3202. exists: function (fileName) {
  3203. return (new java.io.File(fileName)).exists();
  3204. },
  3205. parent: function (fileName) {
  3206. return file.absPath((new java.io.File(fileName)).getParentFile());
  3207. },
  3208. normalize: function (fileName) {
  3209. return file.absPath(fileName);
  3210. },
  3211. isFile: function (path) {
  3212. return (new java.io.File(path)).isFile();
  3213. },
  3214. isDirectory: function (path) {
  3215. return (new java.io.File(path)).isDirectory();
  3216. },
  3217. /**
  3218. * Gets the absolute file path as a string, normalized
  3219. * to using front slashes for path separators.
  3220. * @param {java.io.File||String} file
  3221. */
  3222. absPath: function (fileObj) {
  3223. if (typeof fileObj === "string") {
  3224. fileObj = new java.io.File(fileObj);
  3225. }
  3226. return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/");
  3227. },
  3228. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) {
  3229. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3230. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3231. //and it will be treated as the "include" case.
  3232. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3233. //is set to another value.
  3234. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3235. i, fileObj, filePath, ok, dirFiles;
  3236. topDir = startDir;
  3237. if (!startDirIsJavaObject) {
  3238. topDir = new java.io.File(startDir);
  3239. }
  3240. regExpInclude = regExpFilters.include || regExpFilters;
  3241. regExpExclude = regExpFilters.exclude || null;
  3242. if (topDir.exists()) {
  3243. dirFileArray = topDir.listFiles();
  3244. for (i = 0; i < dirFileArray.length; i++) {
  3245. fileObj = dirFileArray[i];
  3246. if (fileObj.isFile()) {
  3247. filePath = fileObj.getPath();
  3248. if (makeUnixPaths) {
  3249. //Make sure we have a JS string.
  3250. filePath = String(filePath);
  3251. if (filePath.indexOf("/") === -1) {
  3252. filePath = filePath.replace(/\\/g, "/");
  3253. }
  3254. }
  3255. ok = true;
  3256. if (regExpInclude) {
  3257. ok = filePath.match(regExpInclude);
  3258. }
  3259. if (ok && regExpExclude) {
  3260. ok = !filePath.match(regExpExclude);
  3261. }
  3262. if (ok && (!file.exclusionRegExp ||
  3263. !file.exclusionRegExp.test(fileObj.getName()))) {
  3264. files.push(filePath);
  3265. }
  3266. } else if (fileObj.isDirectory() &&
  3267. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) {
  3268. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3269. //Do not use push.apply for dir listings, can hit limit of max number
  3270. //of arguments to a function call, #921.
  3271. dirFiles.forEach(function (dirFile) {
  3272. files.push(dirFile);
  3273. });
  3274. }
  3275. }
  3276. }
  3277. return files; //Array
  3278. },
  3279. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3280. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3281. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3282. regExpFilter = regExpFilter || /\w/;
  3283. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3284. copiedFiles = [], i, srcFileName, destFileName;
  3285. for (i = 0; i < fileNames.length; i++) {
  3286. srcFileName = fileNames[i];
  3287. destFileName = srcFileName.replace(srcDir, destDir);
  3288. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3289. copiedFiles.push(destFileName);
  3290. }
  3291. }
  3292. return copiedFiles.length ? copiedFiles : null; //Array or null
  3293. },
  3294. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3295. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3296. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3297. var destFile = new java.io.File(destFileName), srcFile, parentDir,
  3298. srcChannel, destChannel;
  3299. //logger.trace("Src filename: " + srcFileName);
  3300. //logger.trace("Dest filename: " + destFileName);
  3301. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3302. //than dest.
  3303. if (onlyCopyNew) {
  3304. srcFile = new java.io.File(srcFileName);
  3305. if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) {
  3306. return false; //Boolean
  3307. }
  3308. }
  3309. //Make sure destination dir exists.
  3310. parentDir = destFile.getParentFile();
  3311. if (!parentDir.exists()) {
  3312. if (!parentDir.mkdirs()) {
  3313. throw "Could not create directory: " + parentDir.getCanonicalPath();
  3314. }
  3315. }
  3316. //Java's version of copy file.
  3317. srcChannel = new java.io.FileInputStream(srcFileName).getChannel();
  3318. destChannel = new java.io.FileOutputStream(destFileName).getChannel();
  3319. destChannel.transferFrom(srcChannel, 0, srcChannel.size());
  3320. srcChannel.close();
  3321. destChannel.close();
  3322. return true; //Boolean
  3323. },
  3324. /**
  3325. * Renames a file. May fail if "to" already exists or is on another drive.
  3326. */
  3327. renameFile: function (from, to) {
  3328. return (new java.io.File(from)).renameTo((new java.io.File(to)));
  3329. },
  3330. readFile: function (/*String*/path, /*String?*/encoding) {
  3331. //A file read function that can deal with BOMs
  3332. encoding = encoding || "utf-8";
  3333. var fileObj = new java.io.File(path),
  3334. input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)),
  3335. stringBuffer, line;
  3336. try {
  3337. stringBuffer = new java.lang.StringBuffer();
  3338. line = input.readLine();
  3339. // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
  3340. // http://www.unicode.org/faq/utf_bom.html
  3341. // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
  3342. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
  3343. if (line && line.length() && line.charAt(0) === 0xfeff) {
  3344. // Eat the BOM, since we've already found the encoding on this file,
  3345. // and we plan to concatenating this buffer with others; the BOM should
  3346. // only appear at the top of a file.
  3347. line = line.substring(1);
  3348. }
  3349. while (line !== null) {
  3350. stringBuffer.append(line);
  3351. stringBuffer.append(file.lineSeparator);
  3352. line = input.readLine();
  3353. }
  3354. //Make sure we return a JavaScript string and not a Java string.
  3355. return String(stringBuffer.toString()); //String
  3356. } finally {
  3357. input.close();
  3358. }
  3359. },
  3360. readFileAsync: function (path, encoding) {
  3361. var d = prim();
  3362. try {
  3363. d.resolve(file.readFile(path, encoding));
  3364. } catch (e) {
  3365. d.reject(e);
  3366. }
  3367. return d.promise;
  3368. },
  3369. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3370. //summary: saves a file using UTF-8 encoding.
  3371. file.saveFile(fileName, fileContents, "utf-8");
  3372. },
  3373. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3374. //summary: saves a file.
  3375. var outFile = new java.io.File(fileName), outWriter, parentDir, os;
  3376. parentDir = outFile.getAbsoluteFile().getParentFile();
  3377. if (!parentDir.exists()) {
  3378. if (!parentDir.mkdirs()) {
  3379. throw "Could not create directory: " + parentDir.getAbsolutePath();
  3380. }
  3381. }
  3382. if (encoding) {
  3383. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  3384. } else {
  3385. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  3386. }
  3387. os = new java.io.BufferedWriter(outWriter);
  3388. try {
  3389. //If in Nashorn, need to coerce the JS string to a Java string so that
  3390. //writer.write method dispatch correctly detects the type.
  3391. if (typeof importPackage !== 'undefined') {
  3392. os.write(fileContents);
  3393. } else {
  3394. os.write(new java.lang.String(fileContents));
  3395. }
  3396. } finally {
  3397. os.close();
  3398. }
  3399. },
  3400. deleteFile: function (/*String*/fileName) {
  3401. //summary: deletes a file or directory if it exists.
  3402. var fileObj = new java.io.File(fileName), files, i;
  3403. if (fileObj.exists()) {
  3404. if (fileObj.isDirectory()) {
  3405. files = fileObj.listFiles();
  3406. for (i = 0; i < files.length; i++) {
  3407. this.deleteFile(files[i]);
  3408. }
  3409. }
  3410. fileObj["delete"]();
  3411. }
  3412. },
  3413. /**
  3414. * Deletes any empty directories under the given directory.
  3415. * The startDirIsJavaObject is private to this implementation's
  3416. * recursion needs.
  3417. */
  3418. deleteEmptyDirs: function (startDir, startDirIsJavaObject) {
  3419. var topDir = startDir,
  3420. dirFileArray, i, fileObj;
  3421. if (!startDirIsJavaObject) {
  3422. topDir = new java.io.File(startDir);
  3423. }
  3424. if (topDir.exists()) {
  3425. dirFileArray = topDir.listFiles();
  3426. for (i = 0; i < dirFileArray.length; i++) {
  3427. fileObj = dirFileArray[i];
  3428. if (fileObj.isDirectory()) {
  3429. file.deleteEmptyDirs(fileObj, true);
  3430. }
  3431. }
  3432. //If the directory is empty now, delete it.
  3433. if (topDir.listFiles().length === 0) {
  3434. file.deleteFile(String(topDir.getPath()));
  3435. }
  3436. }
  3437. }
  3438. };
  3439. return file;
  3440. });
  3441. }
  3442. if(env === 'xpconnect') {
  3443. //Helper functions to deal with file I/O.
  3444. /*jslint plusplus: false */
  3445. /*global define, Components, xpcUtil */
  3446. define('xpconnect/file', ['prim'], function (prim) {
  3447. var file,
  3448. Cc = Components.classes,
  3449. Ci = Components.interfaces,
  3450. //Depends on xpcUtil which is set up in x.js
  3451. xpfile = xpcUtil.xpfile;
  3452. function mkFullDir(dirObj) {
  3453. //1 is DIRECTORY_TYPE, 511 is 0777 permissions
  3454. if (!dirObj.exists()) {
  3455. dirObj.create(1, 511);
  3456. }
  3457. }
  3458. file = {
  3459. backSlashRegExp: /\\/g,
  3460. exclusionRegExp: /^\./,
  3461. getLineSeparator: function () {
  3462. return file.lineSeparator;
  3463. },
  3464. lineSeparator: ('@mozilla.org/windows-registry-key;1' in Cc) ?
  3465. '\r\n' : '\n',
  3466. exists: function (fileName) {
  3467. return xpfile(fileName).exists();
  3468. },
  3469. parent: function (fileName) {
  3470. return xpfile(fileName).parent;
  3471. },
  3472. normalize: function (fileName) {
  3473. return file.absPath(fileName);
  3474. },
  3475. isFile: function (path) {
  3476. return xpfile(path).isFile();
  3477. },
  3478. isDirectory: function (path) {
  3479. return xpfile(path).isDirectory();
  3480. },
  3481. /**
  3482. * Gets the absolute file path as a string, normalized
  3483. * to using front slashes for path separators.
  3484. * @param {java.io.File||String} file
  3485. */
  3486. absPath: function (fileObj) {
  3487. if (typeof fileObj === "string") {
  3488. fileObj = xpfile(fileObj);
  3489. }
  3490. return fileObj.path;
  3491. },
  3492. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsObject) {
  3493. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3494. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3495. //and it will be treated as the "include" case.
  3496. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3497. //is set to another value.
  3498. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3499. fileObj, filePath, ok, dirFiles;
  3500. topDir = startDir;
  3501. if (!startDirIsObject) {
  3502. topDir = xpfile(startDir);
  3503. }
  3504. regExpInclude = regExpFilters.include || regExpFilters;
  3505. regExpExclude = regExpFilters.exclude || null;
  3506. if (topDir.exists()) {
  3507. dirFileArray = topDir.directoryEntries;
  3508. while (dirFileArray.hasMoreElements()) {
  3509. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3510. if (fileObj.isFile()) {
  3511. filePath = fileObj.path;
  3512. if (makeUnixPaths) {
  3513. if (filePath.indexOf("/") === -1) {
  3514. filePath = filePath.replace(/\\/g, "/");
  3515. }
  3516. }
  3517. ok = true;
  3518. if (regExpInclude) {
  3519. ok = filePath.match(regExpInclude);
  3520. }
  3521. if (ok && regExpExclude) {
  3522. ok = !filePath.match(regExpExclude);
  3523. }
  3524. if (ok && (!file.exclusionRegExp ||
  3525. !file.exclusionRegExp.test(fileObj.leafName))) {
  3526. files.push(filePath);
  3527. }
  3528. } else if (fileObj.isDirectory() &&
  3529. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) {
  3530. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3531. //Do not use push.apply for dir listings, can hit limit of max number
  3532. //of arguments to a function call, #921.
  3533. dirFiles.forEach(function (dirFile) {
  3534. files.push(dirFile);
  3535. });
  3536. }
  3537. }
  3538. }
  3539. return files; //Array
  3540. },
  3541. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3542. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3543. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3544. regExpFilter = regExpFilter || /\w/;
  3545. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3546. copiedFiles = [], i, srcFileName, destFileName;
  3547. for (i = 0; i < fileNames.length; i += 1) {
  3548. srcFileName = fileNames[i];
  3549. destFileName = srcFileName.replace(srcDir, destDir);
  3550. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3551. copiedFiles.push(destFileName);
  3552. }
  3553. }
  3554. return copiedFiles.length ? copiedFiles : null; //Array or null
  3555. },
  3556. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3557. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3558. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3559. var destFile = xpfile(destFileName),
  3560. srcFile = xpfile(srcFileName);
  3561. //logger.trace("Src filename: " + srcFileName);
  3562. //logger.trace("Dest filename: " + destFileName);
  3563. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3564. //than dest.
  3565. if (onlyCopyNew) {
  3566. if (destFile.exists() && destFile.lastModifiedTime >= srcFile.lastModifiedTime) {
  3567. return false; //Boolean
  3568. }
  3569. }
  3570. srcFile.copyTo(destFile.parent, destFile.leafName);
  3571. return true; //Boolean
  3572. },
  3573. /**
  3574. * Renames a file. May fail if "to" already exists or is on another drive.
  3575. */
  3576. renameFile: function (from, to) {
  3577. var toFile = xpfile(to);
  3578. return xpfile(from).moveTo(toFile.parent, toFile.leafName);
  3579. },
  3580. readFile: xpcUtil.readFile,
  3581. readFileAsync: function (path, encoding) {
  3582. var d = prim();
  3583. try {
  3584. d.resolve(file.readFile(path, encoding));
  3585. } catch (e) {
  3586. d.reject(e);
  3587. }
  3588. return d.promise;
  3589. },
  3590. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3591. //summary: saves a file using UTF-8 encoding.
  3592. file.saveFile(fileName, fileContents, "utf-8");
  3593. },
  3594. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3595. var outStream, convertStream,
  3596. fileObj = xpfile(fileName);
  3597. mkFullDir(fileObj.parent);
  3598. try {
  3599. outStream = Cc['@mozilla.org/network/file-output-stream;1']
  3600. .createInstance(Ci.nsIFileOutputStream);
  3601. //438 is decimal for 0777
  3602. outStream.init(fileObj, 0x02 | 0x08 | 0x20, 511, 0);
  3603. convertStream = Cc['@mozilla.org/intl/converter-output-stream;1']
  3604. .createInstance(Ci.nsIConverterOutputStream);
  3605. convertStream.init(outStream, encoding, 0, 0);
  3606. convertStream.writeString(fileContents);
  3607. } catch (e) {
  3608. throw new Error((fileObj && fileObj.path || '') + ': ' + e);
  3609. } finally {
  3610. if (convertStream) {
  3611. convertStream.close();
  3612. }
  3613. if (outStream) {
  3614. outStream.close();
  3615. }
  3616. }
  3617. },
  3618. deleteFile: function (/*String*/fileName) {
  3619. //summary: deletes a file or directory if it exists.
  3620. var fileObj = xpfile(fileName);
  3621. if (fileObj.exists()) {
  3622. fileObj.remove(true);
  3623. }
  3624. },
  3625. /**
  3626. * Deletes any empty directories under the given directory.
  3627. * The startDirIsJavaObject is private to this implementation's
  3628. * recursion needs.
  3629. */
  3630. deleteEmptyDirs: function (startDir, startDirIsObject) {
  3631. var topDir = startDir,
  3632. dirFileArray, fileObj;
  3633. if (!startDirIsObject) {
  3634. topDir = xpfile(startDir);
  3635. }
  3636. if (topDir.exists()) {
  3637. dirFileArray = topDir.directoryEntries;
  3638. while (dirFileArray.hasMoreElements()) {
  3639. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3640. if (fileObj.isDirectory()) {
  3641. file.deleteEmptyDirs(fileObj, true);
  3642. }
  3643. }
  3644. //If the directory is empty now, delete it.
  3645. dirFileArray = topDir.directoryEntries;
  3646. if (!dirFileArray.hasMoreElements()) {
  3647. file.deleteFile(topDir.path);
  3648. }
  3649. }
  3650. }
  3651. };
  3652. return file;
  3653. });
  3654. }
  3655. if(env === 'browser') {
  3656. /*global process */
  3657. define('browser/quit', function () {
  3658. 'use strict';
  3659. return function (code) {
  3660. };
  3661. });
  3662. }
  3663. if(env === 'node') {
  3664. /*global process */
  3665. define('node/quit', function () {
  3666. 'use strict';
  3667. return function (code) {
  3668. var draining = 0;
  3669. var exit = function () {
  3670. if (draining === 0) {
  3671. process.exit(code);
  3672. } else {
  3673. draining -= 1;
  3674. }
  3675. };
  3676. if (process.stdout.bufferSize) {
  3677. draining += 1;
  3678. process.stdout.once('drain', exit);
  3679. }
  3680. if (process.stderr.bufferSize) {
  3681. draining += 1;
  3682. process.stderr.once('drain', exit);
  3683. }
  3684. exit();
  3685. };
  3686. });
  3687. }
  3688. if(env === 'rhino') {
  3689. /*global quit */
  3690. define('rhino/quit', function () {
  3691. 'use strict';
  3692. return function (code) {
  3693. return quit(code);
  3694. };
  3695. });
  3696. }
  3697. if(env === 'xpconnect') {
  3698. /*global quit */
  3699. define('xpconnect/quit', function () {
  3700. 'use strict';
  3701. return function (code) {
  3702. return quit(code);
  3703. };
  3704. });
  3705. }
  3706. if(env === 'browser') {
  3707. /*jslint strict: false */
  3708. /*global define: false, console: false */
  3709. define('browser/print', function () {
  3710. function print(msg) {
  3711. console.log(msg);
  3712. }
  3713. return print;
  3714. });
  3715. }
  3716. if(env === 'node') {
  3717. /*jslint strict: false */
  3718. /*global define: false, console: false */
  3719. define('node/print', function () {
  3720. function print(msg) {
  3721. console.log(msg);
  3722. }
  3723. return print;
  3724. });
  3725. }
  3726. if(env === 'rhino') {
  3727. /*jslint strict: false */
  3728. /*global define: false, print: false */
  3729. define('rhino/print', function () {
  3730. return print;
  3731. });
  3732. }
  3733. if(env === 'xpconnect') {
  3734. /*jslint strict: false */
  3735. /*global define: false, print: false */
  3736. define('xpconnect/print', function () {
  3737. return print;
  3738. });
  3739. }
  3740. /*jslint nomen: false, strict: false */
  3741. /*global define: false */
  3742. define('logger', ['env!env/print'], function (print) {
  3743. var logger = {
  3744. TRACE: 0,
  3745. INFO: 1,
  3746. WARN: 2,
  3747. ERROR: 3,
  3748. SILENT: 4,
  3749. level: 0,
  3750. logPrefix: "",
  3751. logLevel: function( level ) {
  3752. this.level = level;
  3753. },
  3754. trace: function (message) {
  3755. if (this.level <= this.TRACE) {
  3756. this._print(message);
  3757. }
  3758. },
  3759. info: function (message) {
  3760. if (this.level <= this.INFO) {
  3761. this._print(message);
  3762. }
  3763. },
  3764. warn: function (message) {
  3765. if (this.level <= this.WARN) {
  3766. this._print(message);
  3767. }
  3768. },
  3769. error: function (message) {
  3770. if (this.level <= this.ERROR) {
  3771. this._print(message);
  3772. }
  3773. },
  3774. _print: function (message) {
  3775. this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message);
  3776. },
  3777. _sysPrint: function (message) {
  3778. print(message);
  3779. }
  3780. };
  3781. return logger;
  3782. });
  3783. //Just a blank file to use when building the optimizer with the optimizer,
  3784. //so that the build does not attempt to inline some env modules,
  3785. //like Node's fs and path.
  3786. /*
  3787. Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
  3788. Redistribution and use in source and binary forms, with or without
  3789. modification, are permitted provided that the following conditions are met:
  3790. * Redistributions of source code must retain the above copyright
  3791. notice, this list of conditions and the following disclaimer.
  3792. * Redistributions in binary form must reproduce the above copyright
  3793. notice, this list of conditions and the following disclaimer in the
  3794. documentation and/or other materials provided with the distribution.
  3795. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  3796. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  3797. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  3798. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  3799. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  3800. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  3801. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  3802. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  3803. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  3804. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3805. */
  3806. (function (root, factory) {
  3807. 'use strict';
  3808. // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
  3809. // Rhino, and plain browser loading.
  3810. /* istanbul ignore next */
  3811. if (typeof define === 'function' && define.amd) {
  3812. define('esprima', ['exports'], factory);
  3813. } else if (typeof exports !== 'undefined') {
  3814. factory(exports);
  3815. } else {
  3816. factory((root.esprima = {}));
  3817. }
  3818. }(this, function (exports) {
  3819. 'use strict';
  3820. var Token,
  3821. TokenName,
  3822. FnExprTokens,
  3823. Syntax,
  3824. PlaceHolders,
  3825. Messages,
  3826. Regex,
  3827. source,
  3828. strict,
  3829. index,
  3830. lineNumber,
  3831. lineStart,
  3832. hasLineTerminator,
  3833. lastIndex,
  3834. lastLineNumber,
  3835. lastLineStart,
  3836. startIndex,
  3837. startLineNumber,
  3838. startLineStart,
  3839. scanning,
  3840. length,
  3841. lookahead,
  3842. state,
  3843. extra,
  3844. isBindingElement,
  3845. isAssignmentTarget,
  3846. firstCoverInitializedNameError;
  3847. Token = {
  3848. BooleanLiteral: 1,
  3849. EOF: 2,
  3850. Identifier: 3,
  3851. Keyword: 4,
  3852. NullLiteral: 5,
  3853. NumericLiteral: 6,
  3854. Punctuator: 7,
  3855. StringLiteral: 8,
  3856. RegularExpression: 9,
  3857. Template: 10
  3858. };
  3859. TokenName = {};
  3860. TokenName[Token.BooleanLiteral] = 'Boolean';
  3861. TokenName[Token.EOF] = '<end>';
  3862. TokenName[Token.Identifier] = 'Identifier';
  3863. TokenName[Token.Keyword] = 'Keyword';
  3864. TokenName[Token.NullLiteral] = 'Null';
  3865. TokenName[Token.NumericLiteral] = 'Numeric';
  3866. TokenName[Token.Punctuator] = 'Punctuator';
  3867. TokenName[Token.StringLiteral] = 'String';
  3868. TokenName[Token.RegularExpression] = 'RegularExpression';
  3869. TokenName[Token.Template] = 'Template';
  3870. // A function following one of those tokens is an expression.
  3871. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
  3872. 'return', 'case', 'delete', 'throw', 'void',
  3873. // assignment operators
  3874. '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
  3875. '&=', '|=', '^=', ',',
  3876. // binary/unary operators
  3877. '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
  3878. '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
  3879. '<=', '<', '>', '!=', '!=='];
  3880. Syntax = {
  3881. AssignmentExpression: 'AssignmentExpression',
  3882. AssignmentPattern: 'AssignmentPattern',
  3883. ArrayExpression: 'ArrayExpression',
  3884. ArrayPattern: 'ArrayPattern',
  3885. ArrowFunctionExpression: 'ArrowFunctionExpression',
  3886. BlockStatement: 'BlockStatement',
  3887. BinaryExpression: 'BinaryExpression',
  3888. BreakStatement: 'BreakStatement',
  3889. CallExpression: 'CallExpression',
  3890. CatchClause: 'CatchClause',
  3891. ClassBody: 'ClassBody',
  3892. ClassDeclaration: 'ClassDeclaration',
  3893. ClassExpression: 'ClassExpression',
  3894. ConditionalExpression: 'ConditionalExpression',
  3895. ContinueStatement: 'ContinueStatement',
  3896. DoWhileStatement: 'DoWhileStatement',
  3897. DebuggerStatement: 'DebuggerStatement',
  3898. EmptyStatement: 'EmptyStatement',
  3899. ExportAllDeclaration: 'ExportAllDeclaration',
  3900. ExportDefaultDeclaration: 'ExportDefaultDeclaration',
  3901. ExportNamedDeclaration: 'ExportNamedDeclaration',
  3902. ExportSpecifier: 'ExportSpecifier',
  3903. ExpressionStatement: 'ExpressionStatement',
  3904. ForStatement: 'ForStatement',
  3905. ForOfStatement: 'ForOfStatement',
  3906. ForInStatement: 'ForInStatement',
  3907. FunctionDeclaration: 'FunctionDeclaration',
  3908. FunctionExpression: 'FunctionExpression',
  3909. Identifier: 'Identifier',
  3910. IfStatement: 'IfStatement',
  3911. ImportDeclaration: 'ImportDeclaration',
  3912. ImportDefaultSpecifier: 'ImportDefaultSpecifier',
  3913. ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
  3914. ImportSpecifier: 'ImportSpecifier',
  3915. Literal: 'Literal',
  3916. LabeledStatement: 'LabeledStatement',
  3917. LogicalExpression: 'LogicalExpression',
  3918. MemberExpression: 'MemberExpression',
  3919. MetaProperty: 'MetaProperty',
  3920. MethodDefinition: 'MethodDefinition',
  3921. NewExpression: 'NewExpression',
  3922. ObjectExpression: 'ObjectExpression',
  3923. ObjectPattern: 'ObjectPattern',
  3924. Program: 'Program',
  3925. Property: 'Property',
  3926. RestElement: 'RestElement',
  3927. ReturnStatement: 'ReturnStatement',
  3928. SequenceExpression: 'SequenceExpression',
  3929. SpreadElement: 'SpreadElement',
  3930. Super: 'Super',
  3931. SwitchCase: 'SwitchCase',
  3932. SwitchStatement: 'SwitchStatement',
  3933. TaggedTemplateExpression: 'TaggedTemplateExpression',
  3934. TemplateElement: 'TemplateElement',
  3935. TemplateLiteral: 'TemplateLiteral',
  3936. ThisExpression: 'ThisExpression',
  3937. ThrowStatement: 'ThrowStatement',
  3938. TryStatement: 'TryStatement',
  3939. UnaryExpression: 'UnaryExpression',
  3940. UpdateExpression: 'UpdateExpression',
  3941. VariableDeclaration: 'VariableDeclaration',
  3942. VariableDeclarator: 'VariableDeclarator',
  3943. WhileStatement: 'WhileStatement',
  3944. WithStatement: 'WithStatement',
  3945. YieldExpression: 'YieldExpression'
  3946. };
  3947. PlaceHolders = {
  3948. ArrowParameterPlaceHolder: 'ArrowParameterPlaceHolder'
  3949. };
  3950. // Error messages should be identical to V8.
  3951. Messages = {
  3952. UnexpectedToken: 'Unexpected token %0',
  3953. UnexpectedNumber: 'Unexpected number',
  3954. UnexpectedString: 'Unexpected string',
  3955. UnexpectedIdentifier: 'Unexpected identifier',
  3956. UnexpectedReserved: 'Unexpected reserved word',
  3957. UnexpectedTemplate: 'Unexpected quasi %0',
  3958. UnexpectedEOS: 'Unexpected end of input',
  3959. NewlineAfterThrow: 'Illegal newline after throw',
  3960. InvalidRegExp: 'Invalid regular expression',
  3961. UnterminatedRegExp: 'Invalid regular expression: missing /',
  3962. InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
  3963. InvalidLHSInForIn: 'Invalid left-hand side in for-in',
  3964. InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
  3965. MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
  3966. NoCatchOrFinally: 'Missing catch or finally after try',
  3967. UnknownLabel: 'Undefined label \'%0\'',
  3968. Redeclaration: '%0 \'%1\' has already been declared',
  3969. IllegalContinue: 'Illegal continue statement',
  3970. IllegalBreak: 'Illegal break statement',
  3971. IllegalReturn: 'Illegal return statement',
  3972. StrictModeWith: 'Strict mode code may not include a with statement',
  3973. StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
  3974. StrictVarName: 'Variable name may not be eval or arguments in strict mode',
  3975. StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
  3976. StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
  3977. StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
  3978. StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
  3979. StrictDelete: 'Delete of an unqualified identifier in strict mode.',
  3980. StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
  3981. StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
  3982. StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
  3983. StrictReservedWord: 'Use of future reserved word in strict mode',
  3984. TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
  3985. ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
  3986. DefaultRestParameter: 'Unexpected token =',
  3987. ObjectPatternAsRestParameter: 'Unexpected token {',
  3988. DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
  3989. ConstructorSpecialMethod: 'Class constructor may not be an accessor',
  3990. DuplicateConstructor: 'A class may only have one constructor',
  3991. StaticPrototype: 'Classes may not have static property named prototype',
  3992. MissingFromClause: 'Unexpected token',
  3993. NoAsAfterImportNamespace: 'Unexpected token',
  3994. InvalidModuleSpecifier: 'Unexpected token',
  3995. IllegalImportDeclaration: 'Unexpected token',
  3996. IllegalExportDeclaration: 'Unexpected token',
  3997. DuplicateBinding: 'Duplicate binding %0'
  3998. };
  3999. // See also tools/generate-unicode-regex.js.
  4000. Regex = {
  4001. // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart:
  4002. 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]/,
  4003. // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart:
  4004. 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]/
  4005. };
  4006. // Ensure the condition is true, otherwise throw an error.
  4007. // This is only to have a better contract semantic, i.e. another safety net
  4008. // to catch a logic error. The condition shall be fulfilled in normal case.
  4009. // Do NOT use this to enforce a certain condition on any user input.
  4010. function assert(condition, message) {
  4011. /* istanbul ignore if */
  4012. if (!condition) {
  4013. throw new Error('ASSERT: ' + message);
  4014. }
  4015. }
  4016. function isDecimalDigit(ch) {
  4017. return (ch >= 0x30 && ch <= 0x39); // 0..9
  4018. }
  4019. function isHexDigit(ch) {
  4020. return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
  4021. }
  4022. function isOctalDigit(ch) {
  4023. return '01234567'.indexOf(ch) >= 0;
  4024. }
  4025. function octalToDecimal(ch) {
  4026. // \0 is not octal escape sequence
  4027. var octal = (ch !== '0'), code = '01234567'.indexOf(ch);
  4028. if (index < length && isOctalDigit(source[index])) {
  4029. octal = true;
  4030. code = code * 8 + '01234567'.indexOf(source[index++]);
  4031. // 3 digits are only allowed when string starts
  4032. // with 0, 1, 2, 3
  4033. if ('0123'.indexOf(ch) >= 0 &&
  4034. index < length &&
  4035. isOctalDigit(source[index])) {
  4036. code = code * 8 + '01234567'.indexOf(source[index++]);
  4037. }
  4038. }
  4039. return {
  4040. code: code,
  4041. octal: octal
  4042. };
  4043. }
  4044. // ECMA-262 11.2 White Space
  4045. function isWhiteSpace(ch) {
  4046. return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
  4047. (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
  4048. }
  4049. // ECMA-262 11.3 Line Terminators
  4050. function isLineTerminator(ch) {
  4051. return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
  4052. }
  4053. // ECMA-262 11.6 Identifier Names and Identifiers
  4054. function fromCodePoint(cp) {
  4055. return (cp < 0x10000) ? String.fromCharCode(cp) :
  4056. String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
  4057. String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
  4058. }
  4059. function isIdentifierStart(ch) {
  4060. return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
  4061. (ch >= 0x41 && ch <= 0x5A) || // A..Z
  4062. (ch >= 0x61 && ch <= 0x7A) || // a..z
  4063. (ch === 0x5C) || // \ (backslash)
  4064. ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)));
  4065. }
  4066. function isIdentifierPart(ch) {
  4067. return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
  4068. (ch >= 0x41 && ch <= 0x5A) || // A..Z
  4069. (ch >= 0x61 && ch <= 0x7A) || // a..z
  4070. (ch >= 0x30 && ch <= 0x39) || // 0..9
  4071. (ch === 0x5C) || // \ (backslash)
  4072. ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)));
  4073. }
  4074. // ECMA-262 11.6.2.2 Future Reserved Words
  4075. function isFutureReservedWord(id) {
  4076. switch (id) {
  4077. case 'enum':
  4078. case 'export':
  4079. case 'import':
  4080. case 'super':
  4081. return true;
  4082. default:
  4083. return false;
  4084. }
  4085. }
  4086. function isStrictModeReservedWord(id) {
  4087. switch (id) {
  4088. case 'implements':
  4089. case 'interface':
  4090. case 'package':
  4091. case 'private':
  4092. case 'protected':
  4093. case 'public':
  4094. case 'static':
  4095. case 'yield':
  4096. case 'let':
  4097. return true;
  4098. default:
  4099. return false;
  4100. }
  4101. }
  4102. function isRestrictedWord(id) {
  4103. return id === 'eval' || id === 'arguments';
  4104. }
  4105. // ECMA-262 11.6.2.1 Keywords
  4106. function isKeyword(id) {
  4107. switch (id.length) {
  4108. case 2:
  4109. return (id === 'if') || (id === 'in') || (id === 'do');
  4110. case 3:
  4111. return (id === 'var') || (id === 'for') || (id === 'new') ||
  4112. (id === 'try') || (id === 'let');
  4113. case 4:
  4114. return (id === 'this') || (id === 'else') || (id === 'case') ||
  4115. (id === 'void') || (id === 'with') || (id === 'enum');
  4116. case 5:
  4117. return (id === 'while') || (id === 'break') || (id === 'catch') ||
  4118. (id === 'throw') || (id === 'const') || (id === 'yield') ||
  4119. (id === 'class') || (id === 'super');
  4120. case 6:
  4121. return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
  4122. (id === 'switch') || (id === 'export') || (id === 'import');
  4123. case 7:
  4124. return (id === 'default') || (id === 'finally') || (id === 'extends');
  4125. case 8:
  4126. return (id === 'function') || (id === 'continue') || (id === 'debugger');
  4127. case 10:
  4128. return (id === 'instanceof');
  4129. default:
  4130. return false;
  4131. }
  4132. }
  4133. // ECMA-262 11.4 Comments
  4134. function addComment(type, value, start, end, loc) {
  4135. var comment;
  4136. assert(typeof start === 'number', 'Comment must have valid position');
  4137. state.lastCommentStart = start;
  4138. comment = {
  4139. type: type,
  4140. value: value
  4141. };
  4142. if (extra.range) {
  4143. comment.range = [start, end];
  4144. }
  4145. if (extra.loc) {
  4146. comment.loc = loc;
  4147. }
  4148. extra.comments.push(comment);
  4149. if (extra.attachComment) {
  4150. extra.leadingComments.push(comment);
  4151. extra.trailingComments.push(comment);
  4152. }
  4153. if (extra.tokenize) {
  4154. comment.type = comment.type + 'Comment';
  4155. if (extra.delegate) {
  4156. comment = extra.delegate(comment);
  4157. }
  4158. extra.tokens.push(comment);
  4159. }
  4160. }
  4161. function skipSingleLineComment(offset) {
  4162. var start, loc, ch, comment;
  4163. start = index - offset;
  4164. loc = {
  4165. start: {
  4166. line: lineNumber,
  4167. column: index - lineStart - offset
  4168. }
  4169. };
  4170. while (index < length) {
  4171. ch = source.charCodeAt(index);
  4172. ++index;
  4173. if (isLineTerminator(ch)) {
  4174. hasLineTerminator = true;
  4175. if (extra.comments) {
  4176. comment = source.slice(start + offset, index - 1);
  4177. loc.end = {
  4178. line: lineNumber,
  4179. column: index - lineStart - 1
  4180. };
  4181. addComment('Line', comment, start, index - 1, loc);
  4182. }
  4183. if (ch === 13 && source.charCodeAt(index) === 10) {
  4184. ++index;
  4185. }
  4186. ++lineNumber;
  4187. lineStart = index;
  4188. return;
  4189. }
  4190. }
  4191. if (extra.comments) {
  4192. comment = source.slice(start + offset, index);
  4193. loc.end = {
  4194. line: lineNumber,
  4195. column: index - lineStart
  4196. };
  4197. addComment('Line', comment, start, index, loc);
  4198. }
  4199. }
  4200. function skipMultiLineComment() {
  4201. var start, loc, ch, comment;
  4202. if (extra.comments) {
  4203. start = index - 2;
  4204. loc = {
  4205. start: {
  4206. line: lineNumber,
  4207. column: index - lineStart - 2
  4208. }
  4209. };
  4210. }
  4211. while (index < length) {
  4212. ch = source.charCodeAt(index);
  4213. if (isLineTerminator(ch)) {
  4214. if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
  4215. ++index;
  4216. }
  4217. hasLineTerminator = true;
  4218. ++lineNumber;
  4219. ++index;
  4220. lineStart = index;
  4221. } else if (ch === 0x2A) {
  4222. // Block comment ends with '*/'.
  4223. if (source.charCodeAt(index + 1) === 0x2F) {
  4224. ++index;
  4225. ++index;
  4226. if (extra.comments) {
  4227. comment = source.slice(start + 2, index - 2);
  4228. loc.end = {
  4229. line: lineNumber,
  4230. column: index - lineStart
  4231. };
  4232. addComment('Block', comment, start, index, loc);
  4233. }
  4234. return;
  4235. }
  4236. ++index;
  4237. } else {
  4238. ++index;
  4239. }
  4240. }
  4241. // Ran off the end of the file - the whole thing is a comment
  4242. if (extra.comments) {
  4243. loc.end = {
  4244. line: lineNumber,
  4245. column: index - lineStart
  4246. };
  4247. comment = source.slice(start + 2, index);
  4248. addComment('Block', comment, start, index, loc);
  4249. }
  4250. tolerateUnexpectedToken();
  4251. }
  4252. function skipComment() {
  4253. var ch, start;
  4254. hasLineTerminator = false;
  4255. start = (index === 0);
  4256. while (index < length) {
  4257. ch = source.charCodeAt(index);
  4258. if (isWhiteSpace(ch)) {
  4259. ++index;
  4260. } else if (isLineTerminator(ch)) {
  4261. hasLineTerminator = true;
  4262. ++index;
  4263. if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
  4264. ++index;
  4265. }
  4266. ++lineNumber;
  4267. lineStart = index;
  4268. start = true;
  4269. } else if (ch === 0x2F) { // U+002F is '/'
  4270. ch = source.charCodeAt(index + 1);
  4271. if (ch === 0x2F) {
  4272. ++index;
  4273. ++index;
  4274. skipSingleLineComment(2);
  4275. start = true;
  4276. } else if (ch === 0x2A) { // U+002A is '*'
  4277. ++index;
  4278. ++index;
  4279. skipMultiLineComment();
  4280. } else {
  4281. break;
  4282. }
  4283. } else if (start && ch === 0x2D) { // U+002D is '-'
  4284. // U+003E is '>'
  4285. if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
  4286. // '-->' is a single-line comment
  4287. index += 3;
  4288. skipSingleLineComment(3);
  4289. } else {
  4290. break;
  4291. }
  4292. } else if (ch === 0x3C) { // U+003C is '<'
  4293. if (source.slice(index + 1, index + 4) === '!--') {
  4294. ++index; // `<`
  4295. ++index; // `!`
  4296. ++index; // `-`
  4297. ++index; // `-`
  4298. skipSingleLineComment(4);
  4299. } else {
  4300. break;
  4301. }
  4302. } else {
  4303. break;
  4304. }
  4305. }
  4306. }
  4307. function scanHexEscape(prefix) {
  4308. var i, len, ch, code = 0;
  4309. len = (prefix === 'u') ? 4 : 2;
  4310. for (i = 0; i < len; ++i) {
  4311. if (index < length && isHexDigit(source[index])) {
  4312. ch = source[index++];
  4313. code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  4314. } else {
  4315. return '';
  4316. }
  4317. }
  4318. return String.fromCharCode(code);
  4319. }
  4320. function scanUnicodeCodePointEscape() {
  4321. var ch, code;
  4322. ch = source[index];
  4323. code = 0;
  4324. // At least, one hex digit is required.
  4325. if (ch === '}') {
  4326. throwUnexpectedToken();
  4327. }
  4328. while (index < length) {
  4329. ch = source[index++];
  4330. if (!isHexDigit(ch)) {
  4331. break;
  4332. }
  4333. code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
  4334. }
  4335. if (code > 0x10FFFF || ch !== '}') {
  4336. throwUnexpectedToken();
  4337. }
  4338. return fromCodePoint(code);
  4339. }
  4340. function codePointAt(i) {
  4341. var cp, first, second;
  4342. cp = source.charCodeAt(i);
  4343. if (cp >= 0xD800 && cp <= 0xDBFF) {
  4344. second = source.charCodeAt(i + 1);
  4345. if (second >= 0xDC00 && second <= 0xDFFF) {
  4346. first = cp;
  4347. cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  4348. }
  4349. }
  4350. return cp;
  4351. }
  4352. function getComplexIdentifier() {
  4353. var cp, ch, id;
  4354. cp = codePointAt(index);
  4355. id = fromCodePoint(cp);
  4356. index += id.length;
  4357. // '\u' (U+005C, U+0075) denotes an escaped character.
  4358. if (cp === 0x5C) {
  4359. if (source.charCodeAt(index) !== 0x75) {
  4360. throwUnexpectedToken();
  4361. }
  4362. ++index;
  4363. if (source[index] === '{') {
  4364. ++index;
  4365. ch = scanUnicodeCodePointEscape();
  4366. } else {
  4367. ch = scanHexEscape('u');
  4368. cp = ch.charCodeAt(0);
  4369. if (!ch || ch === '\\' || !isIdentifierStart(cp)) {
  4370. throwUnexpectedToken();
  4371. }
  4372. }
  4373. id = ch;
  4374. }
  4375. while (index < length) {
  4376. cp = codePointAt(index);
  4377. if (!isIdentifierPart(cp)) {
  4378. break;
  4379. }
  4380. ch = fromCodePoint(cp);
  4381. id += ch;
  4382. index += ch.length;
  4383. // '\u' (U+005C, U+0075) denotes an escaped character.
  4384. if (cp === 0x5C) {
  4385. id = id.substr(0, id.length - 1);
  4386. if (source.charCodeAt(index) !== 0x75) {
  4387. throwUnexpectedToken();
  4388. }
  4389. ++index;
  4390. if (source[index] === '{') {
  4391. ++index;
  4392. ch = scanUnicodeCodePointEscape();
  4393. } else {
  4394. ch = scanHexEscape('u');
  4395. cp = ch.charCodeAt(0);
  4396. if (!ch || ch === '\\' || !isIdentifierPart(cp)) {
  4397. throwUnexpectedToken();
  4398. }
  4399. }
  4400. id += ch;
  4401. }
  4402. }
  4403. return id;
  4404. }
  4405. function getIdentifier() {
  4406. var start, ch;
  4407. start = index++;
  4408. while (index < length) {
  4409. ch = source.charCodeAt(index);
  4410. if (ch === 0x5C) {
  4411. // Blackslash (U+005C) marks Unicode escape sequence.
  4412. index = start;
  4413. return getComplexIdentifier();
  4414. } else if (ch >= 0xD800 && ch < 0xDFFF) {
  4415. // Need to handle surrogate pairs.
  4416. index = start;
  4417. return getComplexIdentifier();
  4418. }
  4419. if (isIdentifierPart(ch)) {
  4420. ++index;
  4421. } else {
  4422. break;
  4423. }
  4424. }
  4425. return source.slice(start, index);
  4426. }
  4427. function scanIdentifier() {
  4428. var start, id, type;
  4429. start = index;
  4430. // Backslash (U+005C) starts an escaped character.
  4431. id = (source.charCodeAt(index) === 0x5C) ? getComplexIdentifier() : getIdentifier();
  4432. // There is no keyword or literal with only one character.
  4433. // Thus, it must be an identifier.
  4434. if (id.length === 1) {
  4435. type = Token.Identifier;
  4436. } else if (isKeyword(id)) {
  4437. type = Token.Keyword;
  4438. } else if (id === 'null') {
  4439. type = Token.NullLiteral;
  4440. } else if (id === 'true' || id === 'false') {
  4441. type = Token.BooleanLiteral;
  4442. } else {
  4443. type = Token.Identifier;
  4444. }
  4445. return {
  4446. type: type,
  4447. value: id,
  4448. lineNumber: lineNumber,
  4449. lineStart: lineStart,
  4450. start: start,
  4451. end: index
  4452. };
  4453. }
  4454. // ECMA-262 11.7 Punctuators
  4455. function scanPunctuator() {
  4456. var token, str;
  4457. token = {
  4458. type: Token.Punctuator,
  4459. value: '',
  4460. lineNumber: lineNumber,
  4461. lineStart: lineStart,
  4462. start: index,
  4463. end: index
  4464. };
  4465. // Check for most common single-character punctuators.
  4466. str = source[index];
  4467. switch (str) {
  4468. case '(':
  4469. if (extra.tokenize) {
  4470. extra.openParenToken = extra.tokenValues.length;
  4471. }
  4472. ++index;
  4473. break;
  4474. case '{':
  4475. if (extra.tokenize) {
  4476. extra.openCurlyToken = extra.tokenValues.length;
  4477. }
  4478. state.curlyStack.push('{');
  4479. ++index;
  4480. break;
  4481. case '.':
  4482. ++index;
  4483. if (source[index] === '.' && source[index + 1] === '.') {
  4484. // Spread operator: ...
  4485. index += 2;
  4486. str = '...';
  4487. }
  4488. break;
  4489. case '}':
  4490. ++index;
  4491. state.curlyStack.pop();
  4492. break;
  4493. case ')':
  4494. case ';':
  4495. case ',':
  4496. case '[':
  4497. case ']':
  4498. case ':':
  4499. case '?':
  4500. case '~':
  4501. ++index;
  4502. break;
  4503. default:
  4504. // 4-character punctuator.
  4505. str = source.substr(index, 4);
  4506. if (str === '>>>=') {
  4507. index += 4;
  4508. } else {
  4509. // 3-character punctuators.
  4510. str = str.substr(0, 3);
  4511. if (str === '===' || str === '!==' || str === '>>>' ||
  4512. str === '<<=' || str === '>>=') {
  4513. index += 3;
  4514. } else {
  4515. // 2-character punctuators.
  4516. str = str.substr(0, 2);
  4517. if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
  4518. str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
  4519. str === '++' || str === '--' || str === '<<' || str === '>>' ||
  4520. str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
  4521. str === '<=' || str === '>=' || str === '=>') {
  4522. index += 2;
  4523. } else {
  4524. // 1-character punctuators.
  4525. str = source[index];
  4526. if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
  4527. ++index;
  4528. }
  4529. }
  4530. }
  4531. }
  4532. }
  4533. if (index === token.start) {
  4534. throwUnexpectedToken();
  4535. }
  4536. token.end = index;
  4537. token.value = str;
  4538. return token;
  4539. }
  4540. // ECMA-262 11.8.3 Numeric Literals
  4541. function scanHexLiteral(start) {
  4542. var number = '';
  4543. while (index < length) {
  4544. if (!isHexDigit(source[index])) {
  4545. break;
  4546. }
  4547. number += source[index++];
  4548. }
  4549. if (number.length === 0) {
  4550. throwUnexpectedToken();
  4551. }
  4552. if (isIdentifierStart(source.charCodeAt(index))) {
  4553. throwUnexpectedToken();
  4554. }
  4555. return {
  4556. type: Token.NumericLiteral,
  4557. value: parseInt('0x' + number, 16),
  4558. lineNumber: lineNumber,
  4559. lineStart: lineStart,
  4560. start: start,
  4561. end: index
  4562. };
  4563. }
  4564. function scanBinaryLiteral(start) {
  4565. var ch, number;
  4566. number = '';
  4567. while (index < length) {
  4568. ch = source[index];
  4569. if (ch !== '0' && ch !== '1') {
  4570. break;
  4571. }
  4572. number += source[index++];
  4573. }
  4574. if (number.length === 0) {
  4575. // only 0b or 0B
  4576. throwUnexpectedToken();
  4577. }
  4578. if (index < length) {
  4579. ch = source.charCodeAt(index);
  4580. /* istanbul ignore else */
  4581. if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
  4582. throwUnexpectedToken();
  4583. }
  4584. }
  4585. return {
  4586. type: Token.NumericLiteral,
  4587. value: parseInt(number, 2),
  4588. lineNumber: lineNumber,
  4589. lineStart: lineStart,
  4590. start: start,
  4591. end: index
  4592. };
  4593. }
  4594. function scanOctalLiteral(prefix, start) {
  4595. var number, octal;
  4596. if (isOctalDigit(prefix)) {
  4597. octal = true;
  4598. number = '0' + source[index++];
  4599. } else {
  4600. octal = false;
  4601. ++index;
  4602. number = '';
  4603. }
  4604. while (index < length) {
  4605. if (!isOctalDigit(source[index])) {
  4606. break;
  4607. }
  4608. number += source[index++];
  4609. }
  4610. if (!octal && number.length === 0) {
  4611. // only 0o or 0O
  4612. throwUnexpectedToken();
  4613. }
  4614. if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
  4615. throwUnexpectedToken();
  4616. }
  4617. return {
  4618. type: Token.NumericLiteral,
  4619. value: parseInt(number, 8),
  4620. octal: octal,
  4621. lineNumber: lineNumber,
  4622. lineStart: lineStart,
  4623. start: start,
  4624. end: index
  4625. };
  4626. }
  4627. function isImplicitOctalLiteral() {
  4628. var i, ch;
  4629. // Implicit octal, unless there is a non-octal digit.
  4630. // (Annex B.1.1 on Numeric Literals)
  4631. for (i = index + 1; i < length; ++i) {
  4632. ch = source[i];
  4633. if (ch === '8' || ch === '9') {
  4634. return false;
  4635. }
  4636. if (!isOctalDigit(ch)) {
  4637. return true;
  4638. }
  4639. }
  4640. return true;
  4641. }
  4642. function scanNumericLiteral() {
  4643. var number, start, ch;
  4644. ch = source[index];
  4645. assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
  4646. 'Numeric literal must start with a decimal digit or a decimal point');
  4647. start = index;
  4648. number = '';
  4649. if (ch !== '.') {
  4650. number = source[index++];
  4651. ch = source[index];
  4652. // Hex number starts with '0x'.
  4653. // Octal number starts with '0'.
  4654. // Octal number in ES6 starts with '0o'.
  4655. // Binary number in ES6 starts with '0b'.
  4656. if (number === '0') {
  4657. if (ch === 'x' || ch === 'X') {
  4658. ++index;
  4659. return scanHexLiteral(start);
  4660. }
  4661. if (ch === 'b' || ch === 'B') {
  4662. ++index;
  4663. return scanBinaryLiteral(start);
  4664. }
  4665. if (ch === 'o' || ch === 'O') {
  4666. return scanOctalLiteral(ch, start);
  4667. }
  4668. if (isOctalDigit(ch)) {
  4669. if (isImplicitOctalLiteral()) {
  4670. return scanOctalLiteral(ch, start);
  4671. }
  4672. }
  4673. }
  4674. while (isDecimalDigit(source.charCodeAt(index))) {
  4675. number += source[index++];
  4676. }
  4677. ch = source[index];
  4678. }
  4679. if (ch === '.') {
  4680. number += source[index++];
  4681. while (isDecimalDigit(source.charCodeAt(index))) {
  4682. number += source[index++];
  4683. }
  4684. ch = source[index];
  4685. }
  4686. if (ch === 'e' || ch === 'E') {
  4687. number += source[index++];
  4688. ch = source[index];
  4689. if (ch === '+' || ch === '-') {
  4690. number += source[index++];
  4691. }
  4692. if (isDecimalDigit(source.charCodeAt(index))) {
  4693. while (isDecimalDigit(source.charCodeAt(index))) {
  4694. number += source[index++];
  4695. }
  4696. } else {
  4697. throwUnexpectedToken();
  4698. }
  4699. }
  4700. if (isIdentifierStart(source.charCodeAt(index))) {
  4701. throwUnexpectedToken();
  4702. }
  4703. return {
  4704. type: Token.NumericLiteral,
  4705. value: parseFloat(number),
  4706. lineNumber: lineNumber,
  4707. lineStart: lineStart,
  4708. start: start,
  4709. end: index
  4710. };
  4711. }
  4712. // ECMA-262 11.8.4 String Literals
  4713. function scanStringLiteral() {
  4714. var str = '', quote, start, ch, unescaped, octToDec, octal = false;
  4715. quote = source[index];
  4716. assert((quote === '\'' || quote === '"'),
  4717. 'String literal must starts with a quote');
  4718. start = index;
  4719. ++index;
  4720. while (index < length) {
  4721. ch = source[index++];
  4722. if (ch === quote) {
  4723. quote = '';
  4724. break;
  4725. } else if (ch === '\\') {
  4726. ch = source[index++];
  4727. if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
  4728. switch (ch) {
  4729. case 'u':
  4730. case 'x':
  4731. if (source[index] === '{') {
  4732. ++index;
  4733. str += scanUnicodeCodePointEscape();
  4734. } else {
  4735. unescaped = scanHexEscape(ch);
  4736. if (!unescaped) {
  4737. throw throwUnexpectedToken();
  4738. }
  4739. str += unescaped;
  4740. }
  4741. break;
  4742. case 'n':
  4743. str += '\n';
  4744. break;
  4745. case 'r':
  4746. str += '\r';
  4747. break;
  4748. case 't':
  4749. str += '\t';
  4750. break;
  4751. case 'b':
  4752. str += '\b';
  4753. break;
  4754. case 'f':
  4755. str += '\f';
  4756. break;
  4757. case 'v':
  4758. str += '\x0B';
  4759. break;
  4760. case '8':
  4761. case '9':
  4762. str += ch;
  4763. tolerateUnexpectedToken();
  4764. break;
  4765. default:
  4766. if (isOctalDigit(ch)) {
  4767. octToDec = octalToDecimal(ch);
  4768. octal = octToDec.octal || octal;
  4769. str += String.fromCharCode(octToDec.code);
  4770. } else {
  4771. str += ch;
  4772. }
  4773. break;
  4774. }
  4775. } else {
  4776. ++lineNumber;
  4777. if (ch === '\r' && source[index] === '\n') {
  4778. ++index;
  4779. }
  4780. lineStart = index;
  4781. }
  4782. } else if (isLineTerminator(ch.charCodeAt(0))) {
  4783. break;
  4784. } else {
  4785. str += ch;
  4786. }
  4787. }
  4788. if (quote !== '') {
  4789. index = start;
  4790. throwUnexpectedToken();
  4791. }
  4792. return {
  4793. type: Token.StringLiteral,
  4794. value: str,
  4795. octal: octal,
  4796. lineNumber: startLineNumber,
  4797. lineStart: startLineStart,
  4798. start: start,
  4799. end: index
  4800. };
  4801. }
  4802. // ECMA-262 11.8.6 Template Literal Lexical Components
  4803. function scanTemplate() {
  4804. var cooked = '', ch, start, rawOffset, terminated, head, tail, restore, unescaped;
  4805. terminated = false;
  4806. tail = false;
  4807. start = index;
  4808. head = (source[index] === '`');
  4809. rawOffset = 2;
  4810. ++index;
  4811. while (index < length) {
  4812. ch = source[index++];
  4813. if (ch === '`') {
  4814. rawOffset = 1;
  4815. tail = true;
  4816. terminated = true;
  4817. break;
  4818. } else if (ch === '$') {
  4819. if (source[index] === '{') {
  4820. state.curlyStack.push('${');
  4821. ++index;
  4822. terminated = true;
  4823. break;
  4824. }
  4825. cooked += ch;
  4826. } else if (ch === '\\') {
  4827. ch = source[index++];
  4828. if (!isLineTerminator(ch.charCodeAt(0))) {
  4829. switch (ch) {
  4830. case 'n':
  4831. cooked += '\n';
  4832. break;
  4833. case 'r':
  4834. cooked += '\r';
  4835. break;
  4836. case 't':
  4837. cooked += '\t';
  4838. break;
  4839. case 'u':
  4840. case 'x':
  4841. if (source[index] === '{') {
  4842. ++index;
  4843. cooked += scanUnicodeCodePointEscape();
  4844. } else {
  4845. restore = index;
  4846. unescaped = scanHexEscape(ch);
  4847. if (unescaped) {
  4848. cooked += unescaped;
  4849. } else {
  4850. index = restore;
  4851. cooked += ch;
  4852. }
  4853. }
  4854. break;
  4855. case 'b':
  4856. cooked += '\b';
  4857. break;
  4858. case 'f':
  4859. cooked += '\f';
  4860. break;
  4861. case 'v':
  4862. cooked += '\v';
  4863. break;
  4864. default:
  4865. if (ch === '0') {
  4866. if (isDecimalDigit(source.charCodeAt(index))) {
  4867. // Illegal: \01 \02 and so on
  4868. throwError(Messages.TemplateOctalLiteral);
  4869. }
  4870. cooked += '\0';
  4871. } else if (isOctalDigit(ch)) {
  4872. // Illegal: \1 \2
  4873. throwError(Messages.TemplateOctalLiteral);
  4874. } else {
  4875. cooked += ch;
  4876. }
  4877. break;
  4878. }
  4879. } else {
  4880. ++lineNumber;
  4881. if (ch === '\r' && source[index] === '\n') {
  4882. ++index;
  4883. }
  4884. lineStart = index;
  4885. }
  4886. } else if (isLineTerminator(ch.charCodeAt(0))) {
  4887. ++lineNumber;
  4888. if (ch === '\r' && source[index] === '\n') {
  4889. ++index;
  4890. }
  4891. lineStart = index;
  4892. cooked += '\n';
  4893. } else {
  4894. cooked += ch;
  4895. }
  4896. }
  4897. if (!terminated) {
  4898. throwUnexpectedToken();
  4899. }
  4900. if (!head) {
  4901. state.curlyStack.pop();
  4902. }
  4903. return {
  4904. type: Token.Template,
  4905. value: {
  4906. cooked: cooked,
  4907. raw: source.slice(start + 1, index - rawOffset)
  4908. },
  4909. head: head,
  4910. tail: tail,
  4911. lineNumber: lineNumber,
  4912. lineStart: lineStart,
  4913. start: start,
  4914. end: index
  4915. };
  4916. }
  4917. // ECMA-262 11.8.5 Regular Expression Literals
  4918. function testRegExp(pattern, flags) {
  4919. // The BMP character to use as a replacement for astral symbols when
  4920. // translating an ES6 "u"-flagged pattern to an ES5-compatible
  4921. // approximation.
  4922. // Note: replacing with '\uFFFF' enables false positives in unlikely
  4923. // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
  4924. // pattern that would not be detected by this substitution.
  4925. var astralSubstitute = '\uFFFF',
  4926. tmp = pattern;
  4927. if (flags.indexOf('u') >= 0) {
  4928. tmp = tmp
  4929. // Replace every Unicode escape sequence with the equivalent
  4930. // BMP character or a constant ASCII code point in the case of
  4931. // astral symbols. (See the above note on `astralSubstitute`
  4932. // for more information.)
  4933. .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
  4934. var codePoint = parseInt($1 || $2, 16);
  4935. if (codePoint > 0x10FFFF) {
  4936. throwUnexpectedToken(null, Messages.InvalidRegExp);
  4937. }
  4938. if (codePoint <= 0xFFFF) {
  4939. return String.fromCharCode(codePoint);
  4940. }
  4941. return astralSubstitute;
  4942. })
  4943. // Replace each paired surrogate with a single ASCII symbol to
  4944. // avoid throwing on regular expressions that are only valid in
  4945. // combination with the "u" flag.
  4946. .replace(
  4947. /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  4948. astralSubstitute
  4949. );
  4950. }
  4951. // First, detect invalid regular expressions.
  4952. try {
  4953. RegExp(tmp);
  4954. } catch (e) {
  4955. throwUnexpectedToken(null, Messages.InvalidRegExp);
  4956. }
  4957. // Return a regular expression object for this pattern-flag pair, or
  4958. // `null` in case the current environment doesn't support the flags it
  4959. // uses.
  4960. try {
  4961. return new RegExp(pattern, flags);
  4962. } catch (exception) {
  4963. /* istanbul ignore next */
  4964. return null;
  4965. }
  4966. }
  4967. function scanRegExpBody() {
  4968. var ch, str, classMarker, terminated, body;
  4969. ch = source[index];
  4970. assert(ch === '/', 'Regular expression literal must start with a slash');
  4971. str = source[index++];
  4972. classMarker = false;
  4973. terminated = false;
  4974. while (index < length) {
  4975. ch = source[index++];
  4976. str += ch;
  4977. if (ch === '\\') {
  4978. ch = source[index++];
  4979. // ECMA-262 7.8.5
  4980. if (isLineTerminator(ch.charCodeAt(0))) {
  4981. throwUnexpectedToken(null, Messages.UnterminatedRegExp);
  4982. }
  4983. str += ch;
  4984. } else if (isLineTerminator(ch.charCodeAt(0))) {
  4985. throwUnexpectedToken(null, Messages.UnterminatedRegExp);
  4986. } else if (classMarker) {
  4987. if (ch === ']') {
  4988. classMarker = false;
  4989. }
  4990. } else {
  4991. if (ch === '/') {
  4992. terminated = true;
  4993. break;
  4994. } else if (ch === '[') {
  4995. classMarker = true;
  4996. }
  4997. }
  4998. }
  4999. if (!terminated) {
  5000. throwUnexpectedToken(null, Messages.UnterminatedRegExp);
  5001. }
  5002. // Exclude leading and trailing slash.
  5003. body = str.substr(1, str.length - 2);
  5004. return {
  5005. value: body,
  5006. literal: str
  5007. };
  5008. }
  5009. function scanRegExpFlags() {
  5010. var ch, str, flags, restore;
  5011. str = '';
  5012. flags = '';
  5013. while (index < length) {
  5014. ch = source[index];
  5015. if (!isIdentifierPart(ch.charCodeAt(0))) {
  5016. break;
  5017. }
  5018. ++index;
  5019. if (ch === '\\' && index < length) {
  5020. ch = source[index];
  5021. if (ch === 'u') {
  5022. ++index;
  5023. restore = index;
  5024. ch = scanHexEscape('u');
  5025. if (ch) {
  5026. flags += ch;
  5027. for (str += '\\u'; restore < index; ++restore) {
  5028. str += source[restore];
  5029. }
  5030. } else {
  5031. index = restore;
  5032. flags += 'u';
  5033. str += '\\u';
  5034. }
  5035. tolerateUnexpectedToken();
  5036. } else {
  5037. str += '\\';
  5038. tolerateUnexpectedToken();
  5039. }
  5040. } else {
  5041. flags += ch;
  5042. str += ch;
  5043. }
  5044. }
  5045. return {
  5046. value: flags,
  5047. literal: str
  5048. };
  5049. }
  5050. function scanRegExp() {
  5051. var start, body, flags, value;
  5052. scanning = true;
  5053. lookahead = null;
  5054. skipComment();
  5055. start = index;
  5056. body = scanRegExpBody();
  5057. flags = scanRegExpFlags();
  5058. value = testRegExp(body.value, flags.value);
  5059. scanning = false;
  5060. if (extra.tokenize) {
  5061. return {
  5062. type: Token.RegularExpression,
  5063. value: value,
  5064. regex: {
  5065. pattern: body.value,
  5066. flags: flags.value
  5067. },
  5068. lineNumber: lineNumber,
  5069. lineStart: lineStart,
  5070. start: start,
  5071. end: index
  5072. };
  5073. }
  5074. return {
  5075. literal: body.literal + flags.literal,
  5076. value: value,
  5077. regex: {
  5078. pattern: body.value,
  5079. flags: flags.value
  5080. },
  5081. start: start,
  5082. end: index
  5083. };
  5084. }
  5085. function collectRegex() {
  5086. var pos, loc, regex, token;
  5087. skipComment();
  5088. pos = index;
  5089. loc = {
  5090. start: {
  5091. line: lineNumber,
  5092. column: index - lineStart
  5093. }
  5094. };
  5095. regex = scanRegExp();
  5096. loc.end = {
  5097. line: lineNumber,
  5098. column: index - lineStart
  5099. };
  5100. /* istanbul ignore next */
  5101. if (!extra.tokenize) {
  5102. // Pop the previous token, which is likely '/' or '/='
  5103. if (extra.tokens.length > 0) {
  5104. token = extra.tokens[extra.tokens.length - 1];
  5105. if (token.range[0] === pos && token.type === 'Punctuator') {
  5106. if (token.value === '/' || token.value === '/=') {
  5107. extra.tokens.pop();
  5108. }
  5109. }
  5110. }
  5111. extra.tokens.push({
  5112. type: 'RegularExpression',
  5113. value: regex.literal,
  5114. regex: regex.regex,
  5115. range: [pos, index],
  5116. loc: loc
  5117. });
  5118. }
  5119. return regex;
  5120. }
  5121. function isIdentifierName(token) {
  5122. return token.type === Token.Identifier ||
  5123. token.type === Token.Keyword ||
  5124. token.type === Token.BooleanLiteral ||
  5125. token.type === Token.NullLiteral;
  5126. }
  5127. // Using the following algorithm:
  5128. // https://github.com/mozilla/sweet.js/wiki/design
  5129. function advanceSlash() {
  5130. var regex, previous, check;
  5131. function testKeyword(value) {
  5132. return value && (value.length > 1) && (value[0] >= 'a') && (value[0] <= 'z');
  5133. }
  5134. previous = extra.tokenValues[extra.tokenValues.length - 1];
  5135. regex = (previous !== null);
  5136. switch (previous) {
  5137. case 'this':
  5138. case ']':
  5139. regex = false;
  5140. break;
  5141. case ')':
  5142. check = extra.tokenValues[extra.openParenToken - 1];
  5143. regex = (check === 'if' || check === 'while' || check === 'for' || check === 'with');
  5144. break;
  5145. case '}':
  5146. // Dividing a function by anything makes little sense,
  5147. // but we have to check for that.
  5148. regex = false;
  5149. if (testKeyword(extra.tokenValues[extra.openCurlyToken - 3])) {
  5150. // Anonymous function, e.g. function(){} /42
  5151. check = extra.tokenValues[extra.openCurlyToken - 4];
  5152. regex = check ? (FnExprTokens.indexOf(check) < 0) : false;
  5153. } else if (testKeyword(extra.tokenValues[extra.openCurlyToken - 4])) {
  5154. // Named function, e.g. function f(){} /42/
  5155. check = extra.tokenValues[extra.openCurlyToken - 5];
  5156. regex = check ? (FnExprTokens.indexOf(check) < 0) : true;
  5157. }
  5158. }
  5159. return regex ? collectRegex() : scanPunctuator();
  5160. }
  5161. function advance() {
  5162. var cp, token;
  5163. if (index >= length) {
  5164. return {
  5165. type: Token.EOF,
  5166. lineNumber: lineNumber,
  5167. lineStart: lineStart,
  5168. start: index,
  5169. end: index
  5170. };
  5171. }
  5172. cp = source.charCodeAt(index);
  5173. if (isIdentifierStart(cp)) {
  5174. token = scanIdentifier();
  5175. if (strict && isStrictModeReservedWord(token.value)) {
  5176. token.type = Token.Keyword;
  5177. }
  5178. return token;
  5179. }
  5180. // Very common: ( and ) and ;
  5181. if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
  5182. return scanPunctuator();
  5183. }
  5184. // String literal starts with single quote (U+0027) or double quote (U+0022).
  5185. if (cp === 0x27 || cp === 0x22) {
  5186. return scanStringLiteral();
  5187. }
  5188. // Dot (.) U+002E can also start a floating-point number, hence the need
  5189. // to check the next character.
  5190. if (cp === 0x2E) {
  5191. if (isDecimalDigit(source.charCodeAt(index + 1))) {
  5192. return scanNumericLiteral();
  5193. }
  5194. return scanPunctuator();
  5195. }
  5196. if (isDecimalDigit(cp)) {
  5197. return scanNumericLiteral();
  5198. }
  5199. // Slash (/) U+002F can also start a regex.
  5200. if (extra.tokenize && cp === 0x2F) {
  5201. return advanceSlash();
  5202. }
  5203. // Template literals start with ` (U+0060) for template head
  5204. // or } (U+007D) for template middle or template tail.
  5205. if (cp === 0x60 || (cp === 0x7D && state.curlyStack[state.curlyStack.length - 1] === '${')) {
  5206. return scanTemplate();
  5207. }
  5208. // Possible identifier start in a surrogate pair.
  5209. if (cp >= 0xD800 && cp < 0xDFFF) {
  5210. cp = codePointAt(index);
  5211. if (isIdentifierStart(cp)) {
  5212. return scanIdentifier();
  5213. }
  5214. }
  5215. return scanPunctuator();
  5216. }
  5217. function collectToken() {
  5218. var loc, token, value, entry;
  5219. loc = {
  5220. start: {
  5221. line: lineNumber,
  5222. column: index - lineStart
  5223. }
  5224. };
  5225. token = advance();
  5226. loc.end = {
  5227. line: lineNumber,
  5228. column: index - lineStart
  5229. };
  5230. if (token.type !== Token.EOF) {
  5231. value = source.slice(token.start, token.end);
  5232. entry = {
  5233. type: TokenName[token.type],
  5234. value: value,
  5235. range: [token.start, token.end],
  5236. loc: loc
  5237. };
  5238. if (token.regex) {
  5239. entry.regex = {
  5240. pattern: token.regex.pattern,
  5241. flags: token.regex.flags
  5242. };
  5243. }
  5244. if (extra.tokenValues) {
  5245. extra.tokenValues.push((entry.type === 'Punctuator' || entry.type === 'Keyword') ? entry.value : null);
  5246. }
  5247. if (extra.tokenize) {
  5248. if (!extra.range) {
  5249. delete entry.range;
  5250. }
  5251. if (!extra.loc) {
  5252. delete entry.loc;
  5253. }
  5254. if (extra.delegate) {
  5255. entry = extra.delegate(entry);
  5256. }
  5257. }
  5258. extra.tokens.push(entry);
  5259. }
  5260. return token;
  5261. }
  5262. function lex() {
  5263. var token;
  5264. scanning = true;
  5265. lastIndex = index;
  5266. lastLineNumber = lineNumber;
  5267. lastLineStart = lineStart;
  5268. skipComment();
  5269. token = lookahead;
  5270. startIndex = index;
  5271. startLineNumber = lineNumber;
  5272. startLineStart = lineStart;
  5273. lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
  5274. scanning = false;
  5275. return token;
  5276. }
  5277. function peek() {
  5278. scanning = true;
  5279. skipComment();
  5280. lastIndex = index;
  5281. lastLineNumber = lineNumber;
  5282. lastLineStart = lineStart;
  5283. startIndex = index;
  5284. startLineNumber = lineNumber;
  5285. startLineStart = lineStart;
  5286. lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
  5287. scanning = false;
  5288. }
  5289. function Position() {
  5290. this.line = startLineNumber;
  5291. this.column = startIndex - startLineStart;
  5292. }
  5293. function SourceLocation() {
  5294. this.start = new Position();
  5295. this.end = null;
  5296. }
  5297. function WrappingSourceLocation(startToken) {
  5298. this.start = {
  5299. line: startToken.lineNumber,
  5300. column: startToken.start - startToken.lineStart
  5301. };
  5302. this.end = null;
  5303. }
  5304. function Node() {
  5305. if (extra.range) {
  5306. this.range = [startIndex, 0];
  5307. }
  5308. if (extra.loc) {
  5309. this.loc = new SourceLocation();
  5310. }
  5311. }
  5312. function WrappingNode(startToken) {
  5313. if (extra.range) {
  5314. this.range = [startToken.start, 0];
  5315. }
  5316. if (extra.loc) {
  5317. this.loc = new WrappingSourceLocation(startToken);
  5318. }
  5319. }
  5320. WrappingNode.prototype = Node.prototype = {
  5321. processComment: function () {
  5322. var lastChild,
  5323. innerComments,
  5324. leadingComments,
  5325. trailingComments,
  5326. bottomRight = extra.bottomRightStack,
  5327. i,
  5328. comment,
  5329. last = bottomRight[bottomRight.length - 1];
  5330. if (this.type === Syntax.Program) {
  5331. if (this.body.length > 0) {
  5332. return;
  5333. }
  5334. }
  5335. /**
  5336. * patch innnerComments for properties empty block
  5337. * `function a() {/** comments **\/}`
  5338. */
  5339. if (this.type === Syntax.BlockStatement && this.body.length === 0) {
  5340. innerComments = [];
  5341. for (i = extra.leadingComments.length - 1; i >= 0; --i) {
  5342. comment = extra.leadingComments[i];
  5343. if (this.range[1] >= comment.range[1]) {
  5344. innerComments.unshift(comment);
  5345. extra.leadingComments.splice(i, 1);
  5346. extra.trailingComments.splice(i, 1);
  5347. }
  5348. }
  5349. if (innerComments.length) {
  5350. this.innerComments = innerComments;
  5351. //bottomRight.push(this);
  5352. return;
  5353. }
  5354. }
  5355. if (extra.trailingComments.length > 0) {
  5356. trailingComments = [];
  5357. for (i = extra.trailingComments.length - 1; i >= 0; --i) {
  5358. comment = extra.trailingComments[i];
  5359. if (comment.range[0] >= this.range[1]) {
  5360. trailingComments.unshift(comment);
  5361. extra.trailingComments.splice(i, 1);
  5362. }
  5363. }
  5364. extra.trailingComments = [];
  5365. } else {
  5366. if (last && last.trailingComments && last.trailingComments[0].range[0] >= this.range[1]) {
  5367. trailingComments = last.trailingComments;
  5368. delete last.trailingComments;
  5369. }
  5370. }
  5371. // Eating the stack.
  5372. while (last && last.range[0] >= this.range[0]) {
  5373. lastChild = bottomRight.pop();
  5374. last = bottomRight[bottomRight.length - 1];
  5375. }
  5376. if (lastChild) {
  5377. if (lastChild.leadingComments) {
  5378. leadingComments = [];
  5379. for (i = lastChild.leadingComments.length - 1; i >= 0; --i) {
  5380. comment = lastChild.leadingComments[i];
  5381. if (comment.range[1] <= this.range[0]) {
  5382. leadingComments.unshift(comment);
  5383. lastChild.leadingComments.splice(i, 1);
  5384. }
  5385. }
  5386. if (!lastChild.leadingComments.length) {
  5387. lastChild.leadingComments = undefined;
  5388. }
  5389. }
  5390. } else if (extra.leadingComments.length > 0) {
  5391. leadingComments = [];
  5392. for (i = extra.leadingComments.length - 1; i >= 0; --i) {
  5393. comment = extra.leadingComments[i];
  5394. if (comment.range[1] <= this.range[0]) {
  5395. leadingComments.unshift(comment);
  5396. extra.leadingComments.splice(i, 1);
  5397. }
  5398. }
  5399. }
  5400. if (leadingComments && leadingComments.length > 0) {
  5401. this.leadingComments = leadingComments;
  5402. }
  5403. if (trailingComments && trailingComments.length > 0) {
  5404. this.trailingComments = trailingComments;
  5405. }
  5406. bottomRight.push(this);
  5407. },
  5408. finish: function () {
  5409. if (extra.range) {
  5410. this.range[1] = lastIndex;
  5411. }
  5412. if (extra.loc) {
  5413. this.loc.end = {
  5414. line: lastLineNumber,
  5415. column: lastIndex - lastLineStart
  5416. };
  5417. if (extra.source) {
  5418. this.loc.source = extra.source;
  5419. }
  5420. }
  5421. if (extra.attachComment) {
  5422. this.processComment();
  5423. }
  5424. },
  5425. finishArrayExpression: function (elements) {
  5426. this.type = Syntax.ArrayExpression;
  5427. this.elements = elements;
  5428. this.finish();
  5429. return this;
  5430. },
  5431. finishArrayPattern: function (elements) {
  5432. this.type = Syntax.ArrayPattern;
  5433. this.elements = elements;
  5434. this.finish();
  5435. return this;
  5436. },
  5437. finishArrowFunctionExpression: function (params, defaults, body, expression) {
  5438. this.type = Syntax.ArrowFunctionExpression;
  5439. this.id = null;
  5440. this.params = params;
  5441. this.defaults = defaults;
  5442. this.body = body;
  5443. this.generator = false;
  5444. this.expression = expression;
  5445. this.finish();
  5446. return this;
  5447. },
  5448. finishAssignmentExpression: function (operator, left, right) {
  5449. this.type = Syntax.AssignmentExpression;
  5450. this.operator = operator;
  5451. this.left = left;
  5452. this.right = right;
  5453. this.finish();
  5454. return this;
  5455. },
  5456. finishAssignmentPattern: function (left, right) {
  5457. this.type = Syntax.AssignmentPattern;
  5458. this.left = left;
  5459. this.right = right;
  5460. this.finish();
  5461. return this;
  5462. },
  5463. finishBinaryExpression: function (operator, left, right) {
  5464. this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression;
  5465. this.operator = operator;
  5466. this.left = left;
  5467. this.right = right;
  5468. this.finish();
  5469. return this;
  5470. },
  5471. finishBlockStatement: function (body) {
  5472. this.type = Syntax.BlockStatement;
  5473. this.body = body;
  5474. this.finish();
  5475. return this;
  5476. },
  5477. finishBreakStatement: function (label) {
  5478. this.type = Syntax.BreakStatement;
  5479. this.label = label;
  5480. this.finish();
  5481. return this;
  5482. },
  5483. finishCallExpression: function (callee, args) {
  5484. this.type = Syntax.CallExpression;
  5485. this.callee = callee;
  5486. this.arguments = args;
  5487. this.finish();
  5488. return this;
  5489. },
  5490. finishCatchClause: function (param, body) {
  5491. this.type = Syntax.CatchClause;
  5492. this.param = param;
  5493. this.body = body;
  5494. this.finish();
  5495. return this;
  5496. },
  5497. finishClassBody: function (body) {
  5498. this.type = Syntax.ClassBody;
  5499. this.body = body;
  5500. this.finish();
  5501. return this;
  5502. },
  5503. finishClassDeclaration: function (id, superClass, body) {
  5504. this.type = Syntax.ClassDeclaration;
  5505. this.id = id;
  5506. this.superClass = superClass;
  5507. this.body = body;
  5508. this.finish();
  5509. return this;
  5510. },
  5511. finishClassExpression: function (id, superClass, body) {
  5512. this.type = Syntax.ClassExpression;
  5513. this.id = id;
  5514. this.superClass = superClass;
  5515. this.body = body;
  5516. this.finish();
  5517. return this;
  5518. },
  5519. finishConditionalExpression: function (test, consequent, alternate) {
  5520. this.type = Syntax.ConditionalExpression;
  5521. this.test = test;
  5522. this.consequent = consequent;
  5523. this.alternate = alternate;
  5524. this.finish();
  5525. return this;
  5526. },
  5527. finishContinueStatement: function (label) {
  5528. this.type = Syntax.ContinueStatement;
  5529. this.label = label;
  5530. this.finish();
  5531. return this;
  5532. },
  5533. finishDebuggerStatement: function () {
  5534. this.type = Syntax.DebuggerStatement;
  5535. this.finish();
  5536. return this;
  5537. },
  5538. finishDoWhileStatement: function (body, test) {
  5539. this.type = Syntax.DoWhileStatement;
  5540. this.body = body;
  5541. this.test = test;
  5542. this.finish();
  5543. return this;
  5544. },
  5545. finishEmptyStatement: function () {
  5546. this.type = Syntax.EmptyStatement;
  5547. this.finish();
  5548. return this;
  5549. },
  5550. finishExpressionStatement: function (expression) {
  5551. this.type = Syntax.ExpressionStatement;
  5552. this.expression = expression;
  5553. this.finish();
  5554. return this;
  5555. },
  5556. finishForStatement: function (init, test, update, body) {
  5557. this.type = Syntax.ForStatement;
  5558. this.init = init;
  5559. this.test = test;
  5560. this.update = update;
  5561. this.body = body;
  5562. this.finish();
  5563. return this;
  5564. },
  5565. finishForOfStatement: function (left, right, body) {
  5566. this.type = Syntax.ForOfStatement;
  5567. this.left = left;
  5568. this.right = right;
  5569. this.body = body;
  5570. this.finish();
  5571. return this;
  5572. },
  5573. finishForInStatement: function (left, right, body) {
  5574. this.type = Syntax.ForInStatement;
  5575. this.left = left;
  5576. this.right = right;
  5577. this.body = body;
  5578. this.each = false;
  5579. this.finish();
  5580. return this;
  5581. },
  5582. finishFunctionDeclaration: function (id, params, defaults, body, generator) {
  5583. this.type = Syntax.FunctionDeclaration;
  5584. this.id = id;
  5585. this.params = params;
  5586. this.defaults = defaults;
  5587. this.body = body;
  5588. this.generator = generator;
  5589. this.expression = false;
  5590. this.finish();
  5591. return this;
  5592. },
  5593. finishFunctionExpression: function (id, params, defaults, body, generator) {
  5594. this.type = Syntax.FunctionExpression;
  5595. this.id = id;
  5596. this.params = params;
  5597. this.defaults = defaults;
  5598. this.body = body;
  5599. this.generator = generator;
  5600. this.expression = false;
  5601. this.finish();
  5602. return this;
  5603. },
  5604. finishIdentifier: function (name) {
  5605. this.type = Syntax.Identifier;
  5606. this.name = name;
  5607. this.finish();
  5608. return this;
  5609. },
  5610. finishIfStatement: function (test, consequent, alternate) {
  5611. this.type = Syntax.IfStatement;
  5612. this.test = test;
  5613. this.consequent = consequent;
  5614. this.alternate = alternate;
  5615. this.finish();
  5616. return this;
  5617. },
  5618. finishLabeledStatement: function (label, body) {
  5619. this.type = Syntax.LabeledStatement;
  5620. this.label = label;
  5621. this.body = body;
  5622. this.finish();
  5623. return this;
  5624. },
  5625. finishLiteral: function (token) {
  5626. this.type = Syntax.Literal;
  5627. this.value = token.value;
  5628. this.raw = source.slice(token.start, token.end);
  5629. if (token.regex) {
  5630. this.regex = token.regex;
  5631. }
  5632. this.finish();
  5633. return this;
  5634. },
  5635. finishMemberExpression: function (accessor, object, property) {
  5636. this.type = Syntax.MemberExpression;
  5637. this.computed = accessor === '[';
  5638. this.object = object;
  5639. this.property = property;
  5640. this.finish();
  5641. return this;
  5642. },
  5643. finishMetaProperty: function (meta, property) {
  5644. this.type = Syntax.MetaProperty;
  5645. this.meta = meta;
  5646. this.property = property;
  5647. this.finish();
  5648. return this;
  5649. },
  5650. finishNewExpression: function (callee, args) {
  5651. this.type = Syntax.NewExpression;
  5652. this.callee = callee;
  5653. this.arguments = args;
  5654. this.finish();
  5655. return this;
  5656. },
  5657. finishObjectExpression: function (properties) {
  5658. this.type = Syntax.ObjectExpression;
  5659. this.properties = properties;
  5660. this.finish();
  5661. return this;
  5662. },
  5663. finishObjectPattern: function (properties) {
  5664. this.type = Syntax.ObjectPattern;
  5665. this.properties = properties;
  5666. this.finish();
  5667. return this;
  5668. },
  5669. finishPostfixExpression: function (operator, argument) {
  5670. this.type = Syntax.UpdateExpression;
  5671. this.operator = operator;
  5672. this.argument = argument;
  5673. this.prefix = false;
  5674. this.finish();
  5675. return this;
  5676. },
  5677. finishProgram: function (body, sourceType) {
  5678. this.type = Syntax.Program;
  5679. this.body = body;
  5680. this.sourceType = sourceType;
  5681. this.finish();
  5682. return this;
  5683. },
  5684. finishProperty: function (kind, key, computed, value, method, shorthand) {
  5685. this.type = Syntax.Property;
  5686. this.key = key;
  5687. this.computed = computed;
  5688. this.value = value;
  5689. this.kind = kind;
  5690. this.method = method;
  5691. this.shorthand = shorthand;
  5692. this.finish();
  5693. return this;
  5694. },
  5695. finishRestElement: function (argument) {
  5696. this.type = Syntax.RestElement;
  5697. this.argument = argument;
  5698. this.finish();
  5699. return this;
  5700. },
  5701. finishReturnStatement: function (argument) {
  5702. this.type = Syntax.ReturnStatement;
  5703. this.argument = argument;
  5704. this.finish();
  5705. return this;
  5706. },
  5707. finishSequenceExpression: function (expressions) {
  5708. this.type = Syntax.SequenceExpression;
  5709. this.expressions = expressions;
  5710. this.finish();
  5711. return this;
  5712. },
  5713. finishSpreadElement: function (argument) {
  5714. this.type = Syntax.SpreadElement;
  5715. this.argument = argument;
  5716. this.finish();
  5717. return this;
  5718. },
  5719. finishSwitchCase: function (test, consequent) {
  5720. this.type = Syntax.SwitchCase;
  5721. this.test = test;
  5722. this.consequent = consequent;
  5723. this.finish();
  5724. return this;
  5725. },
  5726. finishSuper: function () {
  5727. this.type = Syntax.Super;
  5728. this.finish();
  5729. return this;
  5730. },
  5731. finishSwitchStatement: function (discriminant, cases) {
  5732. this.type = Syntax.SwitchStatement;
  5733. this.discriminant = discriminant;
  5734. this.cases = cases;
  5735. this.finish();
  5736. return this;
  5737. },
  5738. finishTaggedTemplateExpression: function (tag, quasi) {
  5739. this.type = Syntax.TaggedTemplateExpression;
  5740. this.tag = tag;
  5741. this.quasi = quasi;
  5742. this.finish();
  5743. return this;
  5744. },
  5745. finishTemplateElement: function (value, tail) {
  5746. this.type = Syntax.TemplateElement;
  5747. this.value = value;
  5748. this.tail = tail;
  5749. this.finish();
  5750. return this;
  5751. },
  5752. finishTemplateLiteral: function (quasis, expressions) {
  5753. this.type = Syntax.TemplateLiteral;
  5754. this.quasis = quasis;
  5755. this.expressions = expressions;
  5756. this.finish();
  5757. return this;
  5758. },
  5759. finishThisExpression: function () {
  5760. this.type = Syntax.ThisExpression;
  5761. this.finish();
  5762. return this;
  5763. },
  5764. finishThrowStatement: function (argument) {
  5765. this.type = Syntax.ThrowStatement;
  5766. this.argument = argument;
  5767. this.finish();
  5768. return this;
  5769. },
  5770. finishTryStatement: function (block, handler, finalizer) {
  5771. this.type = Syntax.TryStatement;
  5772. this.block = block;
  5773. this.guardedHandlers = [];
  5774. this.handlers = handler ? [handler] : [];
  5775. this.handler = handler;
  5776. this.finalizer = finalizer;
  5777. this.finish();
  5778. return this;
  5779. },
  5780. finishUnaryExpression: function (operator, argument) {
  5781. this.type = (operator === '++' || operator === '--') ? Syntax.UpdateExpression : Syntax.UnaryExpression;
  5782. this.operator = operator;
  5783. this.argument = argument;
  5784. this.prefix = true;
  5785. this.finish();
  5786. return this;
  5787. },
  5788. finishVariableDeclaration: function (declarations) {
  5789. this.type = Syntax.VariableDeclaration;
  5790. this.declarations = declarations;
  5791. this.kind = 'var';
  5792. this.finish();
  5793. return this;
  5794. },
  5795. finishLexicalDeclaration: function (declarations, kind) {
  5796. this.type = Syntax.VariableDeclaration;
  5797. this.declarations = declarations;
  5798. this.kind = kind;
  5799. this.finish();
  5800. return this;
  5801. },
  5802. finishVariableDeclarator: function (id, init) {
  5803. this.type = Syntax.VariableDeclarator;
  5804. this.id = id;
  5805. this.init = init;
  5806. this.finish();
  5807. return this;
  5808. },
  5809. finishWhileStatement: function (test, body) {
  5810. this.type = Syntax.WhileStatement;
  5811. this.test = test;
  5812. this.body = body;
  5813. this.finish();
  5814. return this;
  5815. },
  5816. finishWithStatement: function (object, body) {
  5817. this.type = Syntax.WithStatement;
  5818. this.object = object;
  5819. this.body = body;
  5820. this.finish();
  5821. return this;
  5822. },
  5823. finishExportSpecifier: function (local, exported) {
  5824. this.type = Syntax.ExportSpecifier;
  5825. this.exported = exported || local;
  5826. this.local = local;
  5827. this.finish();
  5828. return this;
  5829. },
  5830. finishImportDefaultSpecifier: function (local) {
  5831. this.type = Syntax.ImportDefaultSpecifier;
  5832. this.local = local;
  5833. this.finish();
  5834. return this;
  5835. },
  5836. finishImportNamespaceSpecifier: function (local) {
  5837. this.type = Syntax.ImportNamespaceSpecifier;
  5838. this.local = local;
  5839. this.finish();
  5840. return this;
  5841. },
  5842. finishExportNamedDeclaration: function (declaration, specifiers, src) {
  5843. this.type = Syntax.ExportNamedDeclaration;
  5844. this.declaration = declaration;
  5845. this.specifiers = specifiers;
  5846. this.source = src;
  5847. this.finish();
  5848. return this;
  5849. },
  5850. finishExportDefaultDeclaration: function (declaration) {
  5851. this.type = Syntax.ExportDefaultDeclaration;
  5852. this.declaration = declaration;
  5853. this.finish();
  5854. return this;
  5855. },
  5856. finishExportAllDeclaration: function (src) {
  5857. this.type = Syntax.ExportAllDeclaration;
  5858. this.source = src;
  5859. this.finish();
  5860. return this;
  5861. },
  5862. finishImportSpecifier: function (local, imported) {
  5863. this.type = Syntax.ImportSpecifier;
  5864. this.local = local || imported;
  5865. this.imported = imported;
  5866. this.finish();
  5867. return this;
  5868. },
  5869. finishImportDeclaration: function (specifiers, src) {
  5870. this.type = Syntax.ImportDeclaration;
  5871. this.specifiers = specifiers;
  5872. this.source = src;
  5873. this.finish();
  5874. return this;
  5875. },
  5876. finishYieldExpression: function (argument, delegate) {
  5877. this.type = Syntax.YieldExpression;
  5878. this.argument = argument;
  5879. this.delegate = delegate;
  5880. this.finish();
  5881. return this;
  5882. }
  5883. };
  5884. function recordError(error) {
  5885. var e, existing;
  5886. for (e = 0; e < extra.errors.length; e++) {
  5887. existing = extra.errors[e];
  5888. // Prevent duplicated error.
  5889. /* istanbul ignore next */
  5890. if (existing.index === error.index && existing.message === error.message) {
  5891. return;
  5892. }
  5893. }
  5894. extra.errors.push(error);
  5895. }
  5896. function constructError(msg, column) {
  5897. var error = new Error(msg);
  5898. try {
  5899. throw error;
  5900. } catch (base) {
  5901. /* istanbul ignore else */
  5902. if (Object.create && Object.defineProperty) {
  5903. error = Object.create(base);
  5904. Object.defineProperty(error, 'column', { value: column });
  5905. }
  5906. } finally {
  5907. return error;
  5908. }
  5909. }
  5910. function createError(line, pos, description) {
  5911. var msg, column, error;
  5912. msg = 'Line ' + line + ': ' + description;
  5913. column = pos - (scanning ? lineStart : lastLineStart) + 1;
  5914. error = constructError(msg, column);
  5915. error.lineNumber = line;
  5916. error.description = description;
  5917. error.index = pos;
  5918. return error;
  5919. }
  5920. // Throw an exception
  5921. function throwError(messageFormat) {
  5922. var args, msg;
  5923. args = Array.prototype.slice.call(arguments, 1);
  5924. msg = messageFormat.replace(/%(\d)/g,
  5925. function (whole, idx) {
  5926. assert(idx < args.length, 'Message reference must be in range');
  5927. return args[idx];
  5928. }
  5929. );
  5930. throw createError(lastLineNumber, lastIndex, msg);
  5931. }
  5932. function tolerateError(messageFormat) {
  5933. var args, msg, error;
  5934. args = Array.prototype.slice.call(arguments, 1);
  5935. /* istanbul ignore next */
  5936. msg = messageFormat.replace(/%(\d)/g,
  5937. function (whole, idx) {
  5938. assert(idx < args.length, 'Message reference must be in range');
  5939. return args[idx];
  5940. }
  5941. );
  5942. error = createError(lineNumber, lastIndex, msg);
  5943. if (extra.errors) {
  5944. recordError(error);
  5945. } else {
  5946. throw error;
  5947. }
  5948. }
  5949. // Throw an exception because of the token.
  5950. function unexpectedTokenError(token, message) {
  5951. var value, msg = message || Messages.UnexpectedToken;
  5952. if (token) {
  5953. if (!message) {
  5954. msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
  5955. (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
  5956. (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
  5957. (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
  5958. (token.type === Token.Template) ? Messages.UnexpectedTemplate :
  5959. Messages.UnexpectedToken;
  5960. if (token.type === Token.Keyword) {
  5961. if (isFutureReservedWord(token.value)) {
  5962. msg = Messages.UnexpectedReserved;
  5963. } else if (strict && isStrictModeReservedWord(token.value)) {
  5964. msg = Messages.StrictReservedWord;
  5965. }
  5966. }
  5967. }
  5968. value = (token.type === Token.Template) ? token.value.raw : token.value;
  5969. } else {
  5970. value = 'ILLEGAL';
  5971. }
  5972. msg = msg.replace('%0', value);
  5973. return (token && typeof token.lineNumber === 'number') ?
  5974. createError(token.lineNumber, token.start, msg) :
  5975. createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
  5976. }
  5977. function throwUnexpectedToken(token, message) {
  5978. throw unexpectedTokenError(token, message);
  5979. }
  5980. function tolerateUnexpectedToken(token, message) {
  5981. var error = unexpectedTokenError(token, message);
  5982. if (extra.errors) {
  5983. recordError(error);
  5984. } else {
  5985. throw error;
  5986. }
  5987. }
  5988. // Expect the next token to match the specified punctuator.
  5989. // If not, an exception will be thrown.
  5990. function expect(value) {
  5991. var token = lex();
  5992. if (token.type !== Token.Punctuator || token.value !== value) {
  5993. throwUnexpectedToken(token);
  5994. }
  5995. }
  5996. /**
  5997. * @name expectCommaSeparator
  5998. * @description Quietly expect a comma when in tolerant mode, otherwise delegates
  5999. * to <code>expect(value)</code>
  6000. * @since 2.0
  6001. */
  6002. function expectCommaSeparator() {
  6003. var token;
  6004. if (extra.errors) {
  6005. token = lookahead;
  6006. if (token.type === Token.Punctuator && token.value === ',') {
  6007. lex();
  6008. } else if (token.type === Token.Punctuator && token.value === ';') {
  6009. lex();
  6010. tolerateUnexpectedToken(token);
  6011. } else {
  6012. tolerateUnexpectedToken(token, Messages.UnexpectedToken);
  6013. }
  6014. } else {
  6015. expect(',');
  6016. }
  6017. }
  6018. // Expect the next token to match the specified keyword.
  6019. // If not, an exception will be thrown.
  6020. function expectKeyword(keyword) {
  6021. var token = lex();
  6022. if (token.type !== Token.Keyword || token.value !== keyword) {
  6023. throwUnexpectedToken(token);
  6024. }
  6025. }
  6026. // Return true if the next token matches the specified punctuator.
  6027. function match(value) {
  6028. return lookahead.type === Token.Punctuator && lookahead.value === value;
  6029. }
  6030. // Return true if the next token matches the specified keyword
  6031. function matchKeyword(keyword) {
  6032. return lookahead.type === Token.Keyword && lookahead.value === keyword;
  6033. }
  6034. // Return true if the next token matches the specified contextual keyword
  6035. // (where an identifier is sometimes a keyword depending on the context)
  6036. function matchContextualKeyword(keyword) {
  6037. return lookahead.type === Token.Identifier && lookahead.value === keyword;
  6038. }
  6039. // Return true if the next token is an assignment operator
  6040. function matchAssign() {
  6041. var op;
  6042. if (lookahead.type !== Token.Punctuator) {
  6043. return false;
  6044. }
  6045. op = lookahead.value;
  6046. return op === '=' ||
  6047. op === '*=' ||
  6048. op === '/=' ||
  6049. op === '%=' ||
  6050. op === '+=' ||
  6051. op === '-=' ||
  6052. op === '<<=' ||
  6053. op === '>>=' ||
  6054. op === '>>>=' ||
  6055. op === '&=' ||
  6056. op === '^=' ||
  6057. op === '|=';
  6058. }
  6059. function consumeSemicolon() {
  6060. // Catch the very common case first: immediately a semicolon (U+003B).
  6061. if (source.charCodeAt(startIndex) === 0x3B || match(';')) {
  6062. lex();
  6063. return;
  6064. }
  6065. if (hasLineTerminator) {
  6066. return;
  6067. }
  6068. // FIXME(ikarienator): this is seemingly an issue in the previous location info convention.
  6069. lastIndex = startIndex;
  6070. lastLineNumber = startLineNumber;
  6071. lastLineStart = startLineStart;
  6072. if (lookahead.type !== Token.EOF && !match('}')) {
  6073. throwUnexpectedToken(lookahead);
  6074. }
  6075. }
  6076. // Cover grammar support.
  6077. //
  6078. // When an assignment expression position starts with an left parenthesis, the determination of the type
  6079. // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
  6080. // or the first comma. This situation also defers the determination of all the expressions nested in the pair.
  6081. //
  6082. // There are three productions that can be parsed in a parentheses pair that needs to be determined
  6083. // after the outermost pair is closed. They are:
  6084. //
  6085. // 1. AssignmentExpression
  6086. // 2. BindingElements
  6087. // 3. AssignmentTargets
  6088. //
  6089. // In order to avoid exponential backtracking, we use two flags to denote if the production can be
  6090. // binding element or assignment target.
  6091. //
  6092. // The three productions have the relationship:
  6093. //
  6094. // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
  6095. //
  6096. // with a single exception that CoverInitializedName when used directly in an Expression, generates
  6097. // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
  6098. // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
  6099. //
  6100. // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
  6101. // effect the current flags. This means the production the parser parses is only used as an expression. Therefore
  6102. // the CoverInitializedName check is conducted.
  6103. //
  6104. // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
  6105. // the flags outside of the parser. This means the production the parser parses is used as a part of a potential
  6106. // pattern. The CoverInitializedName check is deferred.
  6107. function isolateCoverGrammar(parser) {
  6108. var oldIsBindingElement = isBindingElement,
  6109. oldIsAssignmentTarget = isAssignmentTarget,
  6110. oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
  6111. result;
  6112. isBindingElement = true;
  6113. isAssignmentTarget = true;
  6114. firstCoverInitializedNameError = null;
  6115. result = parser();
  6116. if (firstCoverInitializedNameError !== null) {
  6117. throwUnexpectedToken(firstCoverInitializedNameError);
  6118. }
  6119. isBindingElement = oldIsBindingElement;
  6120. isAssignmentTarget = oldIsAssignmentTarget;
  6121. firstCoverInitializedNameError = oldFirstCoverInitializedNameError;
  6122. return result;
  6123. }
  6124. function inheritCoverGrammar(parser) {
  6125. var oldIsBindingElement = isBindingElement,
  6126. oldIsAssignmentTarget = isAssignmentTarget,
  6127. oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
  6128. result;
  6129. isBindingElement = true;
  6130. isAssignmentTarget = true;
  6131. firstCoverInitializedNameError = null;
  6132. result = parser();
  6133. isBindingElement = isBindingElement && oldIsBindingElement;
  6134. isAssignmentTarget = isAssignmentTarget && oldIsAssignmentTarget;
  6135. firstCoverInitializedNameError = oldFirstCoverInitializedNameError || firstCoverInitializedNameError;
  6136. return result;
  6137. }
  6138. // ECMA-262 13.3.3 Destructuring Binding Patterns
  6139. function parseArrayPattern(params, kind) {
  6140. var node = new Node(), elements = [], rest, restNode;
  6141. expect('[');
  6142. while (!match(']')) {
  6143. if (match(',')) {
  6144. lex();
  6145. elements.push(null);
  6146. } else {
  6147. if (match('...')) {
  6148. restNode = new Node();
  6149. lex();
  6150. params.push(lookahead);
  6151. rest = parseVariableIdentifier(kind);
  6152. elements.push(restNode.finishRestElement(rest));
  6153. break;
  6154. } else {
  6155. elements.push(parsePatternWithDefault(params, kind));
  6156. }
  6157. if (!match(']')) {
  6158. expect(',');
  6159. }
  6160. }
  6161. }
  6162. expect(']');
  6163. return node.finishArrayPattern(elements);
  6164. }
  6165. function parsePropertyPattern(params, kind) {
  6166. var node = new Node(), key, keyToken, computed = match('['), init;
  6167. if (lookahead.type === Token.Identifier) {
  6168. keyToken = lookahead;
  6169. key = parseVariableIdentifier();
  6170. if (match('=')) {
  6171. params.push(keyToken);
  6172. lex();
  6173. init = parseAssignmentExpression();
  6174. return node.finishProperty(
  6175. 'init', key, false,
  6176. new WrappingNode(keyToken).finishAssignmentPattern(key, init), false, true);
  6177. } else if (!match(':')) {
  6178. params.push(keyToken);
  6179. return node.finishProperty('init', key, false, key, false, true);
  6180. }
  6181. } else {
  6182. key = parseObjectPropertyKey();
  6183. }
  6184. expect(':');
  6185. init = parsePatternWithDefault(params, kind);
  6186. return node.finishProperty('init', key, computed, init, false, false);
  6187. }
  6188. function parseObjectPattern(params, kind) {
  6189. var node = new Node(), properties = [];
  6190. expect('{');
  6191. while (!match('}')) {
  6192. properties.push(parsePropertyPattern(params, kind));
  6193. if (!match('}')) {
  6194. expect(',');
  6195. }
  6196. }
  6197. lex();
  6198. return node.finishObjectPattern(properties);
  6199. }
  6200. function parsePattern(params, kind) {
  6201. if (match('[')) {
  6202. return parseArrayPattern(params, kind);
  6203. } else if (match('{')) {
  6204. return parseObjectPattern(params, kind);
  6205. } else if (matchKeyword('let')) {
  6206. if (kind === 'const' || kind === 'let') {
  6207. tolerateUnexpectedToken(lookahead, Messages.UnexpectedToken);
  6208. }
  6209. }
  6210. params.push(lookahead);
  6211. return parseVariableIdentifier(kind);
  6212. }
  6213. function parsePatternWithDefault(params, kind) {
  6214. var startToken = lookahead, pattern, previousAllowYield, right;
  6215. pattern = parsePattern(params, kind);
  6216. if (match('=')) {
  6217. lex();
  6218. previousAllowYield = state.allowYield;
  6219. state.allowYield = true;
  6220. right = isolateCoverGrammar(parseAssignmentExpression);
  6221. state.allowYield = previousAllowYield;
  6222. pattern = new WrappingNode(startToken).finishAssignmentPattern(pattern, right);
  6223. }
  6224. return pattern;
  6225. }
  6226. // ECMA-262 12.2.5 Array Initializer
  6227. function parseArrayInitializer() {
  6228. var elements = [], node = new Node(), restSpread;
  6229. expect('[');
  6230. while (!match(']')) {
  6231. if (match(',')) {
  6232. lex();
  6233. elements.push(null);
  6234. } else if (match('...')) {
  6235. restSpread = new Node();
  6236. lex();
  6237. restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));
  6238. if (!match(']')) {
  6239. isAssignmentTarget = isBindingElement = false;
  6240. expect(',');
  6241. }
  6242. elements.push(restSpread);
  6243. } else {
  6244. elements.push(inheritCoverGrammar(parseAssignmentExpression));
  6245. if (!match(']')) {
  6246. expect(',');
  6247. }
  6248. }
  6249. }
  6250. lex();
  6251. return node.finishArrayExpression(elements);
  6252. }
  6253. // ECMA-262 12.2.6 Object Initializer
  6254. function parsePropertyFunction(node, paramInfo, isGenerator) {
  6255. var previousStrict, body;
  6256. isAssignmentTarget = isBindingElement = false;
  6257. previousStrict = strict;
  6258. body = isolateCoverGrammar(parseFunctionSourceElements);
  6259. if (strict && paramInfo.firstRestricted) {
  6260. tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message);
  6261. }
  6262. if (strict && paramInfo.stricted) {
  6263. tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message);
  6264. }
  6265. strict = previousStrict;
  6266. return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body, isGenerator);
  6267. }
  6268. function parsePropertyMethodFunction() {
  6269. var params, method, node = new Node(),
  6270. previousAllowYield = state.allowYield;
  6271. state.allowYield = false;
  6272. params = parseParams();
  6273. state.allowYield = previousAllowYield;
  6274. state.allowYield = false;
  6275. method = parsePropertyFunction(node, params, false);
  6276. state.allowYield = previousAllowYield;
  6277. return method;
  6278. }
  6279. function parseObjectPropertyKey() {
  6280. var token, node = new Node(), expr;
  6281. token = lex();
  6282. // Note: This function is called only from parseObjectProperty(), where
  6283. // EOF and Punctuator tokens are already filtered out.
  6284. switch (token.type) {
  6285. case Token.StringLiteral:
  6286. case Token.NumericLiteral:
  6287. if (strict && token.octal) {
  6288. tolerateUnexpectedToken(token, Messages.StrictOctalLiteral);
  6289. }
  6290. return node.finishLiteral(token);
  6291. case Token.Identifier:
  6292. case Token.BooleanLiteral:
  6293. case Token.NullLiteral:
  6294. case Token.Keyword:
  6295. return node.finishIdentifier(token.value);
  6296. case Token.Punctuator:
  6297. if (token.value === '[') {
  6298. expr = isolateCoverGrammar(parseAssignmentExpression);
  6299. expect(']');
  6300. return expr;
  6301. }
  6302. break;
  6303. }
  6304. throwUnexpectedToken(token);
  6305. }
  6306. function lookaheadPropertyName() {
  6307. switch (lookahead.type) {
  6308. case Token.Identifier:
  6309. case Token.StringLiteral:
  6310. case Token.BooleanLiteral:
  6311. case Token.NullLiteral:
  6312. case Token.NumericLiteral:
  6313. case Token.Keyword:
  6314. return true;
  6315. case Token.Punctuator:
  6316. return lookahead.value === '[';
  6317. }
  6318. return false;
  6319. }
  6320. // This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals,
  6321. // it might be called at a position where there is in fact a short hand identifier pattern or a data property.
  6322. // This can only be determined after we consumed up to the left parentheses.
  6323. //
  6324. // In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller
  6325. // is responsible to visit other options.
  6326. function tryParseMethodDefinition(token, key, computed, node) {
  6327. var value, options, methodNode, params,
  6328. previousAllowYield = state.allowYield;
  6329. if (token.type === Token.Identifier) {
  6330. // check for `get` and `set`;
  6331. if (token.value === 'get' && lookaheadPropertyName()) {
  6332. computed = match('[');
  6333. key = parseObjectPropertyKey();
  6334. methodNode = new Node();
  6335. expect('(');
  6336. expect(')');
  6337. state.allowYield = false;
  6338. value = parsePropertyFunction(methodNode, {
  6339. params: [],
  6340. defaults: [],
  6341. stricted: null,
  6342. firstRestricted: null,
  6343. message: null
  6344. }, false);
  6345. state.allowYield = previousAllowYield;
  6346. return node.finishProperty('get', key, computed, value, false, false);
  6347. } else if (token.value === 'set' && lookaheadPropertyName()) {
  6348. computed = match('[');
  6349. key = parseObjectPropertyKey();
  6350. methodNode = new Node();
  6351. expect('(');
  6352. options = {
  6353. params: [],
  6354. defaultCount: 0,
  6355. defaults: [],
  6356. firstRestricted: null,
  6357. paramSet: {}
  6358. };
  6359. if (match(')')) {
  6360. tolerateUnexpectedToken(lookahead);
  6361. } else {
  6362. state.allowYield = false;
  6363. parseParam(options);
  6364. state.allowYield = previousAllowYield;
  6365. if (options.defaultCount === 0) {
  6366. options.defaults = [];
  6367. }
  6368. }
  6369. expect(')');
  6370. state.allowYield = false;
  6371. value = parsePropertyFunction(methodNode, options, false);
  6372. state.allowYield = previousAllowYield;
  6373. return node.finishProperty('set', key, computed, value, false, false);
  6374. }
  6375. } else if (token.type === Token.Punctuator && token.value === '*' && lookaheadPropertyName()) {
  6376. computed = match('[');
  6377. key = parseObjectPropertyKey();
  6378. methodNode = new Node();
  6379. state.allowYield = true;
  6380. params = parseParams();
  6381. state.allowYield = previousAllowYield;
  6382. state.allowYield = false;
  6383. value = parsePropertyFunction(methodNode, params, true);
  6384. state.allowYield = previousAllowYield;
  6385. return node.finishProperty('init', key, computed, value, true, false);
  6386. }
  6387. if (key && match('(')) {
  6388. value = parsePropertyMethodFunction();
  6389. return node.finishProperty('init', key, computed, value, true, false);
  6390. }
  6391. // Not a MethodDefinition.
  6392. return null;
  6393. }
  6394. function parseObjectProperty(hasProto) {
  6395. var token = lookahead, node = new Node(), computed, key, maybeMethod, proto, value;
  6396. computed = match('[');
  6397. if (match('*')) {
  6398. lex();
  6399. } else {
  6400. key = parseObjectPropertyKey();
  6401. }
  6402. maybeMethod = tryParseMethodDefinition(token, key, computed, node);
  6403. if (maybeMethod) {
  6404. return maybeMethod;
  6405. }
  6406. if (!key) {
  6407. throwUnexpectedToken(lookahead);
  6408. }
  6409. // Check for duplicated __proto__
  6410. if (!computed) {
  6411. proto = (key.type === Syntax.Identifier && key.name === '__proto__') ||
  6412. (key.type === Syntax.Literal && key.value === '__proto__');
  6413. if (hasProto.value && proto) {
  6414. tolerateError(Messages.DuplicateProtoProperty);
  6415. }
  6416. hasProto.value |= proto;
  6417. }
  6418. if (match(':')) {
  6419. lex();
  6420. value = inheritCoverGrammar(parseAssignmentExpression);
  6421. return node.finishProperty('init', key, computed, value, false, false);
  6422. }
  6423. if (token.type === Token.Identifier) {
  6424. if (match('=')) {
  6425. firstCoverInitializedNameError = lookahead;
  6426. lex();
  6427. value = isolateCoverGrammar(parseAssignmentExpression);
  6428. return node.finishProperty('init', key, computed,
  6429. new WrappingNode(token).finishAssignmentPattern(key, value), false, true);
  6430. }
  6431. return node.finishProperty('init', key, computed, key, false, true);
  6432. }
  6433. throwUnexpectedToken(lookahead);
  6434. }
  6435. function parseObjectInitializer() {
  6436. var properties = [], hasProto = {value: false}, node = new Node();
  6437. expect('{');
  6438. while (!match('}')) {
  6439. properties.push(parseObjectProperty(hasProto));
  6440. if (!match('}')) {
  6441. expectCommaSeparator();
  6442. }
  6443. }
  6444. expect('}');
  6445. return node.finishObjectExpression(properties);
  6446. }
  6447. function reinterpretExpressionAsPattern(expr) {
  6448. var i;
  6449. switch (expr.type) {
  6450. case Syntax.Identifier:
  6451. case Syntax.MemberExpression:
  6452. case Syntax.RestElement:
  6453. case Syntax.AssignmentPattern:
  6454. break;
  6455. case Syntax.SpreadElement:
  6456. expr.type = Syntax.RestElement;
  6457. reinterpretExpressionAsPattern(expr.argument);
  6458. break;
  6459. case Syntax.ArrayExpression:
  6460. expr.type = Syntax.ArrayPattern;
  6461. for (i = 0; i < expr.elements.length; i++) {
  6462. if (expr.elements[i] !== null) {
  6463. reinterpretExpressionAsPattern(expr.elements[i]);
  6464. }
  6465. }
  6466. break;
  6467. case Syntax.ObjectExpression:
  6468. expr.type = Syntax.ObjectPattern;
  6469. for (i = 0; i < expr.properties.length; i++) {
  6470. reinterpretExpressionAsPattern(expr.properties[i].value);
  6471. }
  6472. break;
  6473. case Syntax.AssignmentExpression:
  6474. expr.type = Syntax.AssignmentPattern;
  6475. reinterpretExpressionAsPattern(expr.left);
  6476. break;
  6477. default:
  6478. // Allow other node type for tolerant parsing.
  6479. break;
  6480. }
  6481. }
  6482. // ECMA-262 12.2.9 Template Literals
  6483. function parseTemplateElement(option) {
  6484. var node, token;
  6485. if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) {
  6486. throwUnexpectedToken();
  6487. }
  6488. node = new Node();
  6489. token = lex();
  6490. return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail);
  6491. }
  6492. function parseTemplateLiteral() {
  6493. var quasi, quasis, expressions, node = new Node();
  6494. quasi = parseTemplateElement({ head: true });
  6495. quasis = [quasi];
  6496. expressions = [];
  6497. while (!quasi.tail) {
  6498. expressions.push(parseExpression());
  6499. quasi = parseTemplateElement({ head: false });
  6500. quasis.push(quasi);
  6501. }
  6502. return node.finishTemplateLiteral(quasis, expressions);
  6503. }
  6504. // ECMA-262 12.2.10 The Grouping Operator
  6505. function parseGroupExpression() {
  6506. var expr, expressions, startToken, i, params = [];
  6507. expect('(');
  6508. if (match(')')) {
  6509. lex();
  6510. if (!match('=>')) {
  6511. expect('=>');
  6512. }
  6513. return {
  6514. type: PlaceHolders.ArrowParameterPlaceHolder,
  6515. params: [],
  6516. rawParams: []
  6517. };
  6518. }
  6519. startToken = lookahead;
  6520. if (match('...')) {
  6521. expr = parseRestElement(params);
  6522. expect(')');
  6523. if (!match('=>')) {
  6524. expect('=>');
  6525. }
  6526. return {
  6527. type: PlaceHolders.ArrowParameterPlaceHolder,
  6528. params: [expr]
  6529. };
  6530. }
  6531. isBindingElement = true;
  6532. expr = inheritCoverGrammar(parseAssignmentExpression);
  6533. if (match(',')) {
  6534. isAssignmentTarget = false;
  6535. expressions = [expr];
  6536. while (startIndex < length) {
  6537. if (!match(',')) {
  6538. break;
  6539. }
  6540. lex();
  6541. if (match('...')) {
  6542. if (!isBindingElement) {
  6543. throwUnexpectedToken(lookahead);
  6544. }
  6545. expressions.push(parseRestElement(params));
  6546. expect(')');
  6547. if (!match('=>')) {
  6548. expect('=>');
  6549. }
  6550. isBindingElement = false;
  6551. for (i = 0; i < expressions.length; i++) {
  6552. reinterpretExpressionAsPattern(expressions[i]);
  6553. }
  6554. return {
  6555. type: PlaceHolders.ArrowParameterPlaceHolder,
  6556. params: expressions
  6557. };
  6558. }
  6559. expressions.push(inheritCoverGrammar(parseAssignmentExpression));
  6560. }
  6561. expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
  6562. }
  6563. expect(')');
  6564. if (match('=>')) {
  6565. if (expr.type === Syntax.Identifier && expr.name === 'yield') {
  6566. return {
  6567. type: PlaceHolders.ArrowParameterPlaceHolder,
  6568. params: [expr]
  6569. };
  6570. }
  6571. if (!isBindingElement) {
  6572. throwUnexpectedToken(lookahead);
  6573. }
  6574. if (expr.type === Syntax.SequenceExpression) {
  6575. for (i = 0; i < expr.expressions.length; i++) {
  6576. reinterpretExpressionAsPattern(expr.expressions[i]);
  6577. }
  6578. } else {
  6579. reinterpretExpressionAsPattern(expr);
  6580. }
  6581. expr = {
  6582. type: PlaceHolders.ArrowParameterPlaceHolder,
  6583. params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr]
  6584. };
  6585. }
  6586. isBindingElement = false;
  6587. return expr;
  6588. }
  6589. // ECMA-262 12.2 Primary Expressions
  6590. function parsePrimaryExpression() {
  6591. var type, token, expr, node;
  6592. if (match('(')) {
  6593. isBindingElement = false;
  6594. return inheritCoverGrammar(parseGroupExpression);
  6595. }
  6596. if (match('[')) {
  6597. return inheritCoverGrammar(parseArrayInitializer);
  6598. }
  6599. if (match('{')) {
  6600. return inheritCoverGrammar(parseObjectInitializer);
  6601. }
  6602. type = lookahead.type;
  6603. node = new Node();
  6604. if (type === Token.Identifier) {
  6605. if (state.sourceType === 'module' && lookahead.value === 'await') {
  6606. tolerateUnexpectedToken(lookahead);
  6607. }
  6608. expr = node.finishIdentifier(lex().value);
  6609. } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
  6610. isAssignmentTarget = isBindingElement = false;
  6611. if (strict && lookahead.octal) {
  6612. tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral);
  6613. }
  6614. expr = node.finishLiteral(lex());
  6615. } else if (type === Token.Keyword) {
  6616. if (!strict && state.allowYield && matchKeyword('yield')) {
  6617. return parseNonComputedProperty();
  6618. }
  6619. if (!strict && matchKeyword('let')) {
  6620. return node.finishIdentifier(lex().value);
  6621. }
  6622. isAssignmentTarget = isBindingElement = false;
  6623. if (matchKeyword('function')) {
  6624. return parseFunctionExpression();
  6625. }
  6626. if (matchKeyword('this')) {
  6627. lex();
  6628. return node.finishThisExpression();
  6629. }
  6630. if (matchKeyword('class')) {
  6631. return parseClassExpression();
  6632. }
  6633. throwUnexpectedToken(lex());
  6634. } else if (type === Token.BooleanLiteral) {
  6635. isAssignmentTarget = isBindingElement = false;
  6636. token = lex();
  6637. token.value = (token.value === 'true');
  6638. expr = node.finishLiteral(token);
  6639. } else if (type === Token.NullLiteral) {
  6640. isAssignmentTarget = isBindingElement = false;
  6641. token = lex();
  6642. token.value = null;
  6643. expr = node.finishLiteral(token);
  6644. } else if (match('/') || match('/=')) {
  6645. isAssignmentTarget = isBindingElement = false;
  6646. index = startIndex;
  6647. if (typeof extra.tokens !== 'undefined') {
  6648. token = collectRegex();
  6649. } else {
  6650. token = scanRegExp();
  6651. }
  6652. lex();
  6653. expr = node.finishLiteral(token);
  6654. } else if (type === Token.Template) {
  6655. expr = parseTemplateLiteral();
  6656. } else {
  6657. throwUnexpectedToken(lex());
  6658. }
  6659. return expr;
  6660. }
  6661. // ECMA-262 12.3 Left-Hand-Side Expressions
  6662. function parseArguments() {
  6663. var args = [], expr;
  6664. expect('(');
  6665. if (!match(')')) {
  6666. while (startIndex < length) {
  6667. if (match('...')) {
  6668. expr = new Node();
  6669. lex();
  6670. expr.finishSpreadElement(isolateCoverGrammar(parseAssignmentExpression));
  6671. } else {
  6672. expr = isolateCoverGrammar(parseAssignmentExpression);
  6673. }
  6674. args.push(expr);
  6675. if (match(')')) {
  6676. break;
  6677. }
  6678. expectCommaSeparator();
  6679. }
  6680. }
  6681. expect(')');
  6682. return args;
  6683. }
  6684. function parseNonComputedProperty() {
  6685. var token, node = new Node();
  6686. token = lex();
  6687. if (!isIdentifierName(token)) {
  6688. throwUnexpectedToken(token);
  6689. }
  6690. return node.finishIdentifier(token.value);
  6691. }
  6692. function parseNonComputedMember() {
  6693. expect('.');
  6694. return parseNonComputedProperty();
  6695. }
  6696. function parseComputedMember() {
  6697. var expr;
  6698. expect('[');
  6699. expr = isolateCoverGrammar(parseExpression);
  6700. expect(']');
  6701. return expr;
  6702. }
  6703. // ECMA-262 12.3.3 The new Operator
  6704. function parseNewExpression() {
  6705. var callee, args, node = new Node();
  6706. expectKeyword('new');
  6707. if (match('.')) {
  6708. lex();
  6709. if (lookahead.type === Token.Identifier && lookahead.value === 'target') {
  6710. if (state.inFunctionBody) {
  6711. lex();
  6712. return node.finishMetaProperty('new', 'target');
  6713. }
  6714. }
  6715. throwUnexpectedToken(lookahead);
  6716. }
  6717. callee = isolateCoverGrammar(parseLeftHandSideExpression);
  6718. args = match('(') ? parseArguments() : [];
  6719. isAssignmentTarget = isBindingElement = false;
  6720. return node.finishNewExpression(callee, args);
  6721. }
  6722. // ECMA-262 12.3.4 Function Calls
  6723. function parseLeftHandSideExpressionAllowCall() {
  6724. var quasi, expr, args, property, startToken, previousAllowIn = state.allowIn;
  6725. startToken = lookahead;
  6726. state.allowIn = true;
  6727. if (matchKeyword('super') && state.inFunctionBody) {
  6728. expr = new Node();
  6729. lex();
  6730. expr = expr.finishSuper();
  6731. if (!match('(') && !match('.') && !match('[')) {
  6732. throwUnexpectedToken(lookahead);
  6733. }
  6734. } else {
  6735. expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
  6736. }
  6737. for (;;) {
  6738. if (match('.')) {
  6739. isBindingElement = false;
  6740. isAssignmentTarget = true;
  6741. property = parseNonComputedMember();
  6742. expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
  6743. } else if (match('(')) {
  6744. isBindingElement = false;
  6745. isAssignmentTarget = false;
  6746. args = parseArguments();
  6747. expr = new WrappingNode(startToken).finishCallExpression(expr, args);
  6748. } else if (match('[')) {
  6749. isBindingElement = false;
  6750. isAssignmentTarget = true;
  6751. property = parseComputedMember();
  6752. expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
  6753. } else if (lookahead.type === Token.Template && lookahead.head) {
  6754. quasi = parseTemplateLiteral();
  6755. expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
  6756. } else {
  6757. break;
  6758. }
  6759. }
  6760. state.allowIn = previousAllowIn;
  6761. return expr;
  6762. }
  6763. // ECMA-262 12.3 Left-Hand-Side Expressions
  6764. function parseLeftHandSideExpression() {
  6765. var quasi, expr, property, startToken;
  6766. assert(state.allowIn, 'callee of new expression always allow in keyword.');
  6767. startToken = lookahead;
  6768. if (matchKeyword('super') && state.inFunctionBody) {
  6769. expr = new Node();
  6770. lex();
  6771. expr = expr.finishSuper();
  6772. if (!match('[') && !match('.')) {
  6773. throwUnexpectedToken(lookahead);
  6774. }
  6775. } else {
  6776. expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
  6777. }
  6778. for (;;) {
  6779. if (match('[')) {
  6780. isBindingElement = false;
  6781. isAssignmentTarget = true;
  6782. property = parseComputedMember();
  6783. expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
  6784. } else if (match('.')) {
  6785. isBindingElement = false;
  6786. isAssignmentTarget = true;
  6787. property = parseNonComputedMember();
  6788. expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
  6789. } else if (lookahead.type === Token.Template && lookahead.head) {
  6790. quasi = parseTemplateLiteral();
  6791. expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
  6792. } else {
  6793. break;
  6794. }
  6795. }
  6796. return expr;
  6797. }
  6798. // ECMA-262 12.4 Postfix Expressions
  6799. function parsePostfixExpression() {
  6800. var expr, token, startToken = lookahead;
  6801. expr = inheritCoverGrammar(parseLeftHandSideExpressionAllowCall);
  6802. if (!hasLineTerminator && lookahead.type === Token.Punctuator) {
  6803. if (match('++') || match('--')) {
  6804. // ECMA-262 11.3.1, 11.3.2
  6805. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  6806. tolerateError(Messages.StrictLHSPostfix);
  6807. }
  6808. if (!isAssignmentTarget) {
  6809. tolerateError(Messages.InvalidLHSInAssignment);
  6810. }
  6811. isAssignmentTarget = isBindingElement = false;
  6812. token = lex();
  6813. expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr);
  6814. }
  6815. }
  6816. return expr;
  6817. }
  6818. // ECMA-262 12.5 Unary Operators
  6819. function parseUnaryExpression() {
  6820. var token, expr, startToken;
  6821. if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
  6822. expr = parsePostfixExpression();
  6823. } else if (match('++') || match('--')) {
  6824. startToken = lookahead;
  6825. token = lex();
  6826. expr = inheritCoverGrammar(parseUnaryExpression);
  6827. // ECMA-262 11.4.4, 11.4.5
  6828. if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
  6829. tolerateError(Messages.StrictLHSPrefix);
  6830. }
  6831. if (!isAssignmentTarget) {
  6832. tolerateError(Messages.InvalidLHSInAssignment);
  6833. }
  6834. expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
  6835. isAssignmentTarget = isBindingElement = false;
  6836. } else if (match('+') || match('-') || match('~') || match('!')) {
  6837. startToken = lookahead;
  6838. token = lex();
  6839. expr = inheritCoverGrammar(parseUnaryExpression);
  6840. expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
  6841. isAssignmentTarget = isBindingElement = false;
  6842. } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
  6843. startToken = lookahead;
  6844. token = lex();
  6845. expr = inheritCoverGrammar(parseUnaryExpression);
  6846. expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
  6847. if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
  6848. tolerateError(Messages.StrictDelete);
  6849. }
  6850. isAssignmentTarget = isBindingElement = false;
  6851. } else {
  6852. expr = parsePostfixExpression();
  6853. }
  6854. return expr;
  6855. }
  6856. function binaryPrecedence(token, allowIn) {
  6857. var prec = 0;
  6858. if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
  6859. return 0;
  6860. }
  6861. switch (token.value) {
  6862. case '||':
  6863. prec = 1;
  6864. break;
  6865. case '&&':
  6866. prec = 2;
  6867. break;
  6868. case '|':
  6869. prec = 3;
  6870. break;
  6871. case '^':
  6872. prec = 4;
  6873. break;
  6874. case '&':
  6875. prec = 5;
  6876. break;
  6877. case '==':
  6878. case '!=':
  6879. case '===':
  6880. case '!==':
  6881. prec = 6;
  6882. break;
  6883. case '<':
  6884. case '>':
  6885. case '<=':
  6886. case '>=':
  6887. case 'instanceof':
  6888. prec = 7;
  6889. break;
  6890. case 'in':
  6891. prec = allowIn ? 7 : 0;
  6892. break;
  6893. case '<<':
  6894. case '>>':
  6895. case '>>>':
  6896. prec = 8;
  6897. break;
  6898. case '+':
  6899. case '-':
  6900. prec = 9;
  6901. break;
  6902. case '*':
  6903. case '/':
  6904. case '%':
  6905. prec = 11;
  6906. break;
  6907. default:
  6908. break;
  6909. }
  6910. return prec;
  6911. }
  6912. // ECMA-262 12.6 Multiplicative Operators
  6913. // ECMA-262 12.7 Additive Operators
  6914. // ECMA-262 12.8 Bitwise Shift Operators
  6915. // ECMA-262 12.9 Relational Operators
  6916. // ECMA-262 12.10 Equality Operators
  6917. // ECMA-262 12.11 Binary Bitwise Operators
  6918. // ECMA-262 12.12 Binary Logical Operators
  6919. function parseBinaryExpression() {
  6920. var marker, markers, expr, token, prec, stack, right, operator, left, i;
  6921. marker = lookahead;
  6922. left = inheritCoverGrammar(parseUnaryExpression);
  6923. token = lookahead;
  6924. prec = binaryPrecedence(token, state.allowIn);
  6925. if (prec === 0) {
  6926. return left;
  6927. }
  6928. isAssignmentTarget = isBindingElement = false;
  6929. token.prec = prec;
  6930. lex();
  6931. markers = [marker, lookahead];
  6932. right = isolateCoverGrammar(parseUnaryExpression);
  6933. stack = [left, token, right];
  6934. while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {
  6935. // Reduce: make a binary expression from the three topmost entries.
  6936. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
  6937. right = stack.pop();
  6938. operator = stack.pop().value;
  6939. left = stack.pop();
  6940. markers.pop();
  6941. expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right);
  6942. stack.push(expr);
  6943. }
  6944. // Shift.
  6945. token = lex();
  6946. token.prec = prec;
  6947. stack.push(token);
  6948. markers.push(lookahead);
  6949. expr = isolateCoverGrammar(parseUnaryExpression);
  6950. stack.push(expr);
  6951. }
  6952. // Final reduce to clean-up the stack.
  6953. i = stack.length - 1;
  6954. expr = stack[i];
  6955. markers.pop();
  6956. while (i > 1) {
  6957. expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
  6958. i -= 2;
  6959. }
  6960. return expr;
  6961. }
  6962. // ECMA-262 12.13 Conditional Operator
  6963. function parseConditionalExpression() {
  6964. var expr, previousAllowIn, consequent, alternate, startToken;
  6965. startToken = lookahead;
  6966. expr = inheritCoverGrammar(parseBinaryExpression);
  6967. if (match('?')) {
  6968. lex();
  6969. previousAllowIn = state.allowIn;
  6970. state.allowIn = true;
  6971. consequent = isolateCoverGrammar(parseAssignmentExpression);
  6972. state.allowIn = previousAllowIn;
  6973. expect(':');
  6974. alternate = isolateCoverGrammar(parseAssignmentExpression);
  6975. expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate);
  6976. isAssignmentTarget = isBindingElement = false;
  6977. }
  6978. return expr;
  6979. }
  6980. // ECMA-262 14.2 Arrow Function Definitions
  6981. function parseConciseBody() {
  6982. if (match('{')) {
  6983. return parseFunctionSourceElements();
  6984. }
  6985. return isolateCoverGrammar(parseAssignmentExpression);
  6986. }
  6987. function checkPatternParam(options, param) {
  6988. var i;
  6989. switch (param.type) {
  6990. case Syntax.Identifier:
  6991. validateParam(options, param, param.name);
  6992. break;
  6993. case Syntax.RestElement:
  6994. checkPatternParam(options, param.argument);
  6995. break;
  6996. case Syntax.AssignmentPattern:
  6997. checkPatternParam(options, param.left);
  6998. break;
  6999. case Syntax.ArrayPattern:
  7000. for (i = 0; i < param.elements.length; i++) {
  7001. if (param.elements[i] !== null) {
  7002. checkPatternParam(options, param.elements[i]);
  7003. }
  7004. }
  7005. break;
  7006. case Syntax.YieldExpression:
  7007. break;
  7008. default:
  7009. assert(param.type === Syntax.ObjectPattern, 'Invalid type');
  7010. for (i = 0; i < param.properties.length; i++) {
  7011. checkPatternParam(options, param.properties[i].value);
  7012. }
  7013. break;
  7014. }
  7015. }
  7016. function reinterpretAsCoverFormalsList(expr) {
  7017. var i, len, param, params, defaults, defaultCount, options, token;
  7018. defaults = [];
  7019. defaultCount = 0;
  7020. params = [expr];
  7021. switch (expr.type) {
  7022. case Syntax.Identifier:
  7023. break;
  7024. case PlaceHolders.ArrowParameterPlaceHolder:
  7025. params = expr.params;
  7026. break;
  7027. default:
  7028. return null;
  7029. }
  7030. options = {
  7031. paramSet: {}
  7032. };
  7033. for (i = 0, len = params.length; i < len; i += 1) {
  7034. param = params[i];
  7035. switch (param.type) {
  7036. case Syntax.AssignmentPattern:
  7037. params[i] = param.left;
  7038. if (param.right.type === Syntax.YieldExpression) {
  7039. if (param.right.argument) {
  7040. throwUnexpectedToken(lookahead);
  7041. }
  7042. param.right.type = Syntax.Identifier;
  7043. param.right.name = 'yield';
  7044. delete param.right.argument;
  7045. delete param.right.delegate;
  7046. }
  7047. defaults.push(param.right);
  7048. ++defaultCount;
  7049. checkPatternParam(options, param.left);
  7050. break;
  7051. default:
  7052. checkPatternParam(options, param);
  7053. params[i] = param;
  7054. defaults.push(null);
  7055. break;
  7056. }
  7057. }
  7058. if (strict || !state.allowYield) {
  7059. for (i = 0, len = params.length; i < len; i += 1) {
  7060. param = params[i];
  7061. if (param.type === Syntax.YieldExpression) {
  7062. throwUnexpectedToken(lookahead);
  7063. }
  7064. }
  7065. }
  7066. if (options.message === Messages.StrictParamDupe) {
  7067. token = strict ? options.stricted : options.firstRestricted;
  7068. throwUnexpectedToken(token, options.message);
  7069. }
  7070. if (defaultCount === 0) {
  7071. defaults = [];
  7072. }
  7073. return {
  7074. params: params,
  7075. defaults: defaults,
  7076. stricted: options.stricted,
  7077. firstRestricted: options.firstRestricted,
  7078. message: options.message
  7079. };
  7080. }
  7081. function parseArrowFunctionExpression(options, node) {
  7082. var previousStrict, previousAllowYield, body;
  7083. if (hasLineTerminator) {
  7084. tolerateUnexpectedToken(lookahead);
  7085. }
  7086. expect('=>');
  7087. previousStrict = strict;
  7088. previousAllowYield = state.allowYield;
  7089. state.allowYield = true;
  7090. body = parseConciseBody();
  7091. if (strict && options.firstRestricted) {
  7092. throwUnexpectedToken(options.firstRestricted, options.message);
  7093. }
  7094. if (strict && options.stricted) {
  7095. tolerateUnexpectedToken(options.stricted, options.message);
  7096. }
  7097. strict = previousStrict;
  7098. state.allowYield = previousAllowYield;
  7099. return node.finishArrowFunctionExpression(options.params, options.defaults, body, body.type !== Syntax.BlockStatement);
  7100. }
  7101. // ECMA-262 14.4 Yield expression
  7102. function parseYieldExpression() {
  7103. var argument, expr, delegate, previousAllowYield;
  7104. argument = null;
  7105. expr = new Node();
  7106. delegate = false;
  7107. expectKeyword('yield');
  7108. if (!hasLineTerminator) {
  7109. previousAllowYield = state.allowYield;
  7110. state.allowYield = false;
  7111. delegate = match('*');
  7112. if (delegate) {
  7113. lex();
  7114. argument = parseAssignmentExpression();
  7115. } else {
  7116. if (!match(';') && !match('}') && !match(')') && lookahead.type !== Token.EOF) {
  7117. argument = parseAssignmentExpression();
  7118. }
  7119. }
  7120. state.allowYield = previousAllowYield;
  7121. }
  7122. return expr.finishYieldExpression(argument, delegate);
  7123. }
  7124. // ECMA-262 12.14 Assignment Operators
  7125. function parseAssignmentExpression() {
  7126. var token, expr, right, list, startToken;
  7127. startToken = lookahead;
  7128. token = lookahead;
  7129. if (!state.allowYield && matchKeyword('yield')) {
  7130. return parseYieldExpression();
  7131. }
  7132. expr = parseConditionalExpression();
  7133. if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) {
  7134. isAssignmentTarget = isBindingElement = false;
  7135. list = reinterpretAsCoverFormalsList(expr);
  7136. if (list) {
  7137. firstCoverInitializedNameError = null;
  7138. return parseArrowFunctionExpression(list, new WrappingNode(startToken));
  7139. }
  7140. return expr;
  7141. }
  7142. if (matchAssign()) {
  7143. if (!isAssignmentTarget) {
  7144. tolerateError(Messages.InvalidLHSInAssignment);
  7145. }
  7146. // ECMA-262 12.1.1
  7147. if (strict && expr.type === Syntax.Identifier) {
  7148. if (isRestrictedWord(expr.name)) {
  7149. tolerateUnexpectedToken(token, Messages.StrictLHSAssignment);
  7150. }
  7151. if (isStrictModeReservedWord(expr.name)) {
  7152. tolerateUnexpectedToken(token, Messages.StrictReservedWord);
  7153. }
  7154. }
  7155. if (!match('=')) {
  7156. isAssignmentTarget = isBindingElement = false;
  7157. } else {
  7158. reinterpretExpressionAsPattern(expr);
  7159. }
  7160. token = lex();
  7161. right = isolateCoverGrammar(parseAssignmentExpression);
  7162. expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right);
  7163. firstCoverInitializedNameError = null;
  7164. }
  7165. return expr;
  7166. }
  7167. // ECMA-262 12.15 Comma Operator
  7168. function parseExpression() {
  7169. var expr, startToken = lookahead, expressions;
  7170. expr = isolateCoverGrammar(parseAssignmentExpression);
  7171. if (match(',')) {
  7172. expressions = [expr];
  7173. while (startIndex < length) {
  7174. if (!match(',')) {
  7175. break;
  7176. }
  7177. lex();
  7178. expressions.push(isolateCoverGrammar(parseAssignmentExpression));
  7179. }
  7180. expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
  7181. }
  7182. return expr;
  7183. }
  7184. // ECMA-262 13.2 Block
  7185. function parseStatementListItem() {
  7186. if (lookahead.type === Token.Keyword) {
  7187. switch (lookahead.value) {
  7188. case 'export':
  7189. if (state.sourceType !== 'module') {
  7190. tolerateUnexpectedToken(lookahead, Messages.IllegalExportDeclaration);
  7191. }
  7192. return parseExportDeclaration();
  7193. case 'import':
  7194. if (state.sourceType !== 'module') {
  7195. tolerateUnexpectedToken(lookahead, Messages.IllegalImportDeclaration);
  7196. }
  7197. return parseImportDeclaration();
  7198. case 'const':
  7199. return parseLexicalDeclaration({inFor: false});
  7200. case 'function':
  7201. return parseFunctionDeclaration(new Node());
  7202. case 'class':
  7203. return parseClassDeclaration();
  7204. }
  7205. }
  7206. if (matchKeyword('let') && isLexicalDeclaration()) {
  7207. return parseLexicalDeclaration({inFor: false});
  7208. }
  7209. return parseStatement();
  7210. }
  7211. function parseStatementList() {
  7212. var list = [];
  7213. while (startIndex < length) {
  7214. if (match('}')) {
  7215. break;
  7216. }
  7217. list.push(parseStatementListItem());
  7218. }
  7219. return list;
  7220. }
  7221. function parseBlock() {
  7222. var block, node = new Node();
  7223. expect('{');
  7224. block = parseStatementList();
  7225. expect('}');
  7226. return node.finishBlockStatement(block);
  7227. }
  7228. // ECMA-262 13.3.2 Variable Statement
  7229. function parseVariableIdentifier(kind) {
  7230. var token, node = new Node();
  7231. token = lex();
  7232. if (token.type === Token.Keyword && token.value === 'yield') {
  7233. if (strict) {
  7234. tolerateUnexpectedToken(token, Messages.StrictReservedWord);
  7235. } if (!state.allowYield) {
  7236. throwUnexpectedToken(token);
  7237. }
  7238. } else if (token.type !== Token.Identifier) {
  7239. if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) {
  7240. tolerateUnexpectedToken(token, Messages.StrictReservedWord);
  7241. } else {
  7242. if (strict || token.value !== 'let' || kind !== 'var') {
  7243. throwUnexpectedToken(token);
  7244. }
  7245. }
  7246. } else if (state.sourceType === 'module' && token.type === Token.Identifier && token.value === 'await') {
  7247. tolerateUnexpectedToken(token);
  7248. }
  7249. return node.finishIdentifier(token.value);
  7250. }
  7251. function parseVariableDeclaration(options) {
  7252. var init = null, id, node = new Node(), params = [];
  7253. id = parsePattern(params, 'var');
  7254. // ECMA-262 12.2.1
  7255. if (strict && isRestrictedWord(id.name)) {
  7256. tolerateError(Messages.StrictVarName);
  7257. }
  7258. if (match('=')) {
  7259. lex();
  7260. init = isolateCoverGrammar(parseAssignmentExpression);
  7261. } else if (id.type !== Syntax.Identifier && !options.inFor) {
  7262. expect('=');
  7263. }
  7264. return node.finishVariableDeclarator(id, init);
  7265. }
  7266. function parseVariableDeclarationList(options) {
  7267. var opt, list;
  7268. opt = { inFor: options.inFor };
  7269. list = [parseVariableDeclaration(opt)];
  7270. while (match(',')) {
  7271. lex();
  7272. list.push(parseVariableDeclaration(opt));
  7273. }
  7274. return list;
  7275. }
  7276. function parseVariableStatement(node) {
  7277. var declarations;
  7278. expectKeyword('var');
  7279. declarations = parseVariableDeclarationList({ inFor: false });
  7280. consumeSemicolon();
  7281. return node.finishVariableDeclaration(declarations);
  7282. }
  7283. // ECMA-262 13.3.1 Let and Const Declarations
  7284. function parseLexicalBinding(kind, options) {
  7285. var init = null, id, node = new Node(), params = [];
  7286. id = parsePattern(params, kind);
  7287. // ECMA-262 12.2.1
  7288. if (strict && id.type === Syntax.Identifier && isRestrictedWord(id.name)) {
  7289. tolerateError(Messages.StrictVarName);
  7290. }
  7291. if (kind === 'const') {
  7292. if (!matchKeyword('in') && !matchContextualKeyword('of')) {
  7293. expect('=');
  7294. init = isolateCoverGrammar(parseAssignmentExpression);
  7295. }
  7296. } else if ((!options.inFor && id.type !== Syntax.Identifier) || match('=')) {
  7297. expect('=');
  7298. init = isolateCoverGrammar(parseAssignmentExpression);
  7299. }
  7300. return node.finishVariableDeclarator(id, init);
  7301. }
  7302. function parseBindingList(kind, options) {
  7303. var list = [parseLexicalBinding(kind, options)];
  7304. while (match(',')) {
  7305. lex();
  7306. list.push(parseLexicalBinding(kind, options));
  7307. }
  7308. return list;
  7309. }
  7310. function tokenizerState() {
  7311. return {
  7312. index: index,
  7313. lineNumber: lineNumber,
  7314. lineStart: lineStart,
  7315. hasLineTerminator: hasLineTerminator,
  7316. lastIndex: lastIndex,
  7317. lastLineNumber: lastLineNumber,
  7318. lastLineStart: lastLineStart,
  7319. startIndex: startIndex,
  7320. startLineNumber: startLineNumber,
  7321. startLineStart: startLineStart,
  7322. lookahead: lookahead,
  7323. tokenCount: extra.tokens ? extra.tokens.length : 0
  7324. };
  7325. }
  7326. function resetTokenizerState(ts) {
  7327. index = ts.index;
  7328. lineNumber = ts.lineNumber;
  7329. lineStart = ts.lineStart;
  7330. hasLineTerminator = ts.hasLineTerminator;
  7331. lastIndex = ts.lastIndex;
  7332. lastLineNumber = ts.lastLineNumber;
  7333. lastLineStart = ts.lastLineStart;
  7334. startIndex = ts.startIndex;
  7335. startLineNumber = ts.startLineNumber;
  7336. startLineStart = ts.startLineStart;
  7337. lookahead = ts.lookahead;
  7338. if (extra.tokens) {
  7339. extra.tokens.splice(ts.tokenCount, extra.tokens.length);
  7340. }
  7341. }
  7342. function isLexicalDeclaration() {
  7343. var lexical, ts;
  7344. ts = tokenizerState();
  7345. lex();
  7346. lexical = (lookahead.type === Token.Identifier) || match('[') || match('{') ||
  7347. matchKeyword('let') || matchKeyword('yield');
  7348. resetTokenizerState(ts);
  7349. return lexical;
  7350. }
  7351. function parseLexicalDeclaration(options) {
  7352. var kind, declarations, node = new Node();
  7353. kind = lex().value;
  7354. assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
  7355. declarations = parseBindingList(kind, options);
  7356. consumeSemicolon();
  7357. return node.finishLexicalDeclaration(declarations, kind);
  7358. }
  7359. function parseRestElement(params) {
  7360. var param, node = new Node();
  7361. lex();
  7362. if (match('{')) {
  7363. throwError(Messages.ObjectPatternAsRestParameter);
  7364. }
  7365. params.push(lookahead);
  7366. param = parseVariableIdentifier();
  7367. if (match('=')) {
  7368. throwError(Messages.DefaultRestParameter);
  7369. }
  7370. if (!match(')')) {
  7371. throwError(Messages.ParameterAfterRestParameter);
  7372. }
  7373. return node.finishRestElement(param);
  7374. }
  7375. // ECMA-262 13.4 Empty Statement
  7376. function parseEmptyStatement(node) {
  7377. expect(';');
  7378. return node.finishEmptyStatement();
  7379. }
  7380. // ECMA-262 12.4 Expression Statement
  7381. function parseExpressionStatement(node) {
  7382. var expr = parseExpression();
  7383. consumeSemicolon();
  7384. return node.finishExpressionStatement(expr);
  7385. }
  7386. // ECMA-262 13.6 If statement
  7387. function parseIfStatement(node) {
  7388. var test, consequent, alternate;
  7389. expectKeyword('if');
  7390. expect('(');
  7391. test = parseExpression();
  7392. expect(')');
  7393. consequent = parseStatement();
  7394. if (matchKeyword('else')) {
  7395. lex();
  7396. alternate = parseStatement();
  7397. } else {
  7398. alternate = null;
  7399. }
  7400. return node.finishIfStatement(test, consequent, alternate);
  7401. }
  7402. // ECMA-262 13.7 Iteration Statements
  7403. function parseDoWhileStatement(node) {
  7404. var body, test, oldInIteration;
  7405. expectKeyword('do');
  7406. oldInIteration = state.inIteration;
  7407. state.inIteration = true;
  7408. body = parseStatement();
  7409. state.inIteration = oldInIteration;
  7410. expectKeyword('while');
  7411. expect('(');
  7412. test = parseExpression();
  7413. expect(')');
  7414. if (match(';')) {
  7415. lex();
  7416. }
  7417. return node.finishDoWhileStatement(body, test);
  7418. }
  7419. function parseWhileStatement(node) {
  7420. var test, body, oldInIteration;
  7421. expectKeyword('while');
  7422. expect('(');
  7423. test = parseExpression();
  7424. expect(')');
  7425. oldInIteration = state.inIteration;
  7426. state.inIteration = true;
  7427. body = parseStatement();
  7428. state.inIteration = oldInIteration;
  7429. return node.finishWhileStatement(test, body);
  7430. }
  7431. function parseForStatement(node) {
  7432. var init, forIn, initSeq, initStartToken, test, update, left, right, kind, declarations,
  7433. body, oldInIteration, previousAllowIn = state.allowIn;
  7434. init = test = update = null;
  7435. forIn = true;
  7436. expectKeyword('for');
  7437. expect('(');
  7438. if (match(';')) {
  7439. lex();
  7440. } else {
  7441. if (matchKeyword('var')) {
  7442. init = new Node();
  7443. lex();
  7444. state.allowIn = false;
  7445. declarations = parseVariableDeclarationList({ inFor: true });
  7446. state.allowIn = previousAllowIn;
  7447. if (declarations.length === 1 && matchKeyword('in')) {
  7448. init = init.finishVariableDeclaration(declarations);
  7449. lex();
  7450. left = init;
  7451. right = parseExpression();
  7452. init = null;
  7453. } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
  7454. init = init.finishVariableDeclaration(declarations);
  7455. lex();
  7456. left = init;
  7457. right = parseAssignmentExpression();
  7458. init = null;
  7459. forIn = false;
  7460. } else {
  7461. init = init.finishVariableDeclaration(declarations);
  7462. expect(';');
  7463. }
  7464. } else if (matchKeyword('const') || matchKeyword('let')) {
  7465. init = new Node();
  7466. kind = lex().value;
  7467. if (!strict && lookahead.value === 'in') {
  7468. init = init.finishIdentifier(kind);
  7469. lex();
  7470. left = init;
  7471. right = parseExpression();
  7472. init = null;
  7473. } else {
  7474. state.allowIn = false;
  7475. declarations = parseBindingList(kind, {inFor: true});
  7476. state.allowIn = previousAllowIn;
  7477. if (declarations.length === 1 && declarations[0].init === null && matchKeyword('in')) {
  7478. init = init.finishLexicalDeclaration(declarations, kind);
  7479. lex();
  7480. left = init;
  7481. right = parseExpression();
  7482. init = null;
  7483. } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) {
  7484. init = init.finishLexicalDeclaration(declarations, kind);
  7485. lex();
  7486. left = init;
  7487. right = parseAssignmentExpression();
  7488. init = null;
  7489. forIn = false;
  7490. } else {
  7491. consumeSemicolon();
  7492. init = init.finishLexicalDeclaration(declarations, kind);
  7493. }
  7494. }
  7495. } else {
  7496. initStartToken = lookahead;
  7497. state.allowIn = false;
  7498. init = inheritCoverGrammar(parseAssignmentExpression);
  7499. state.allowIn = previousAllowIn;
  7500. if (matchKeyword('in')) {
  7501. if (!isAssignmentTarget) {
  7502. tolerateError(Messages.InvalidLHSInForIn);
  7503. }
  7504. lex();
  7505. reinterpretExpressionAsPattern(init);
  7506. left = init;
  7507. right = parseExpression();
  7508. init = null;
  7509. } else if (matchContextualKeyword('of')) {
  7510. if (!isAssignmentTarget) {
  7511. tolerateError(Messages.InvalidLHSInForLoop);
  7512. }
  7513. lex();
  7514. reinterpretExpressionAsPattern(init);
  7515. left = init;
  7516. right = parseAssignmentExpression();
  7517. init = null;
  7518. forIn = false;
  7519. } else {
  7520. if (match(',')) {
  7521. initSeq = [init];
  7522. while (match(',')) {
  7523. lex();
  7524. initSeq.push(isolateCoverGrammar(parseAssignmentExpression));
  7525. }
  7526. init = new WrappingNode(initStartToken).finishSequenceExpression(initSeq);
  7527. }
  7528. expect(';');
  7529. }
  7530. }
  7531. }
  7532. if (typeof left === 'undefined') {
  7533. if (!match(';')) {
  7534. test = parseExpression();
  7535. }
  7536. expect(';');
  7537. if (!match(')')) {
  7538. update = parseExpression();
  7539. }
  7540. }
  7541. expect(')');
  7542. oldInIteration = state.inIteration;
  7543. state.inIteration = true;
  7544. body = isolateCoverGrammar(parseStatement);
  7545. state.inIteration = oldInIteration;
  7546. return (typeof left === 'undefined') ?
  7547. node.finishForStatement(init, test, update, body) :
  7548. forIn ? node.finishForInStatement(left, right, body) :
  7549. node.finishForOfStatement(left, right, body);
  7550. }
  7551. // ECMA-262 13.8 The continue statement
  7552. function parseContinueStatement(node) {
  7553. var label = null, key;
  7554. expectKeyword('continue');
  7555. // Optimize the most common form: 'continue;'.
  7556. if (source.charCodeAt(startIndex) === 0x3B) {
  7557. lex();
  7558. if (!state.inIteration) {
  7559. throwError(Messages.IllegalContinue);
  7560. }
  7561. return node.finishContinueStatement(null);
  7562. }
  7563. if (hasLineTerminator) {
  7564. if (!state.inIteration) {
  7565. throwError(Messages.IllegalContinue);
  7566. }
  7567. return node.finishContinueStatement(null);
  7568. }
  7569. if (lookahead.type === Token.Identifier) {
  7570. label = parseVariableIdentifier();
  7571. key = '$' + label.name;
  7572. if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  7573. throwError(Messages.UnknownLabel, label.name);
  7574. }
  7575. }
  7576. consumeSemicolon();
  7577. if (label === null && !state.inIteration) {
  7578. throwError(Messages.IllegalContinue);
  7579. }
  7580. return node.finishContinueStatement(label);
  7581. }
  7582. // ECMA-262 13.9 The break statement
  7583. function parseBreakStatement(node) {
  7584. var label = null, key;
  7585. expectKeyword('break');
  7586. // Catch the very common case first: immediately a semicolon (U+003B).
  7587. if (source.charCodeAt(lastIndex) === 0x3B) {
  7588. lex();
  7589. if (!(state.inIteration || state.inSwitch)) {
  7590. throwError(Messages.IllegalBreak);
  7591. }
  7592. return node.finishBreakStatement(null);
  7593. }
  7594. if (hasLineTerminator) {
  7595. if (!(state.inIteration || state.inSwitch)) {
  7596. throwError(Messages.IllegalBreak);
  7597. }
  7598. } else if (lookahead.type === Token.Identifier) {
  7599. label = parseVariableIdentifier();
  7600. key = '$' + label.name;
  7601. if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  7602. throwError(Messages.UnknownLabel, label.name);
  7603. }
  7604. }
  7605. consumeSemicolon();
  7606. if (label === null && !(state.inIteration || state.inSwitch)) {
  7607. throwError(Messages.IllegalBreak);
  7608. }
  7609. return node.finishBreakStatement(label);
  7610. }
  7611. // ECMA-262 13.10 The return statement
  7612. function parseReturnStatement(node) {
  7613. var argument = null;
  7614. expectKeyword('return');
  7615. if (!state.inFunctionBody) {
  7616. tolerateError(Messages.IllegalReturn);
  7617. }
  7618. // 'return' followed by a space and an identifier is very common.
  7619. if (source.charCodeAt(lastIndex) === 0x20) {
  7620. if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) {
  7621. argument = parseExpression();
  7622. consumeSemicolon();
  7623. return node.finishReturnStatement(argument);
  7624. }
  7625. }
  7626. if (hasLineTerminator) {
  7627. // HACK
  7628. return node.finishReturnStatement(null);
  7629. }
  7630. if (!match(';')) {
  7631. if (!match('}') && lookahead.type !== Token.EOF) {
  7632. argument = parseExpression();
  7633. }
  7634. }
  7635. consumeSemicolon();
  7636. return node.finishReturnStatement(argument);
  7637. }
  7638. // ECMA-262 13.11 The with statement
  7639. function parseWithStatement(node) {
  7640. var object, body;
  7641. if (strict) {
  7642. tolerateError(Messages.StrictModeWith);
  7643. }
  7644. expectKeyword('with');
  7645. expect('(');
  7646. object = parseExpression();
  7647. expect(')');
  7648. body = parseStatement();
  7649. return node.finishWithStatement(object, body);
  7650. }
  7651. // ECMA-262 13.12 The switch statement
  7652. function parseSwitchCase() {
  7653. var test, consequent = [], statement, node = new Node();
  7654. if (matchKeyword('default')) {
  7655. lex();
  7656. test = null;
  7657. } else {
  7658. expectKeyword('case');
  7659. test = parseExpression();
  7660. }
  7661. expect(':');
  7662. while (startIndex < length) {
  7663. if (match('}') || matchKeyword('default') || matchKeyword('case')) {
  7664. break;
  7665. }
  7666. statement = parseStatementListItem();
  7667. consequent.push(statement);
  7668. }
  7669. return node.finishSwitchCase(test, consequent);
  7670. }
  7671. function parseSwitchStatement(node) {
  7672. var discriminant, cases, clause, oldInSwitch, defaultFound;
  7673. expectKeyword('switch');
  7674. expect('(');
  7675. discriminant = parseExpression();
  7676. expect(')');
  7677. expect('{');
  7678. cases = [];
  7679. if (match('}')) {
  7680. lex();
  7681. return node.finishSwitchStatement(discriminant, cases);
  7682. }
  7683. oldInSwitch = state.inSwitch;
  7684. state.inSwitch = true;
  7685. defaultFound = false;
  7686. while (startIndex < length) {
  7687. if (match('}')) {
  7688. break;
  7689. }
  7690. clause = parseSwitchCase();
  7691. if (clause.test === null) {
  7692. if (defaultFound) {
  7693. throwError(Messages.MultipleDefaultsInSwitch);
  7694. }
  7695. defaultFound = true;
  7696. }
  7697. cases.push(clause);
  7698. }
  7699. state.inSwitch = oldInSwitch;
  7700. expect('}');
  7701. return node.finishSwitchStatement(discriminant, cases);
  7702. }
  7703. // ECMA-262 13.14 The throw statement
  7704. function parseThrowStatement(node) {
  7705. var argument;
  7706. expectKeyword('throw');
  7707. if (hasLineTerminator) {
  7708. throwError(Messages.NewlineAfterThrow);
  7709. }
  7710. argument = parseExpression();
  7711. consumeSemicolon();
  7712. return node.finishThrowStatement(argument);
  7713. }
  7714. // ECMA-262 13.15 The try statement
  7715. function parseCatchClause() {
  7716. var param, params = [], paramMap = {}, key, i, body, node = new Node();
  7717. expectKeyword('catch');
  7718. expect('(');
  7719. if (match(')')) {
  7720. throwUnexpectedToken(lookahead);
  7721. }
  7722. param = parsePattern(params);
  7723. for (i = 0; i < params.length; i++) {
  7724. key = '$' + params[i].value;
  7725. if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
  7726. tolerateError(Messages.DuplicateBinding, params[i].value);
  7727. }
  7728. paramMap[key] = true;
  7729. }
  7730. // ECMA-262 12.14.1
  7731. if (strict && isRestrictedWord(param.name)) {
  7732. tolerateError(Messages.StrictCatchVariable);
  7733. }
  7734. expect(')');
  7735. body = parseBlock();
  7736. return node.finishCatchClause(param, body);
  7737. }
  7738. function parseTryStatement(node) {
  7739. var block, handler = null, finalizer = null;
  7740. expectKeyword('try');
  7741. block = parseBlock();
  7742. if (matchKeyword('catch')) {
  7743. handler = parseCatchClause();
  7744. }
  7745. if (matchKeyword('finally')) {
  7746. lex();
  7747. finalizer = parseBlock();
  7748. }
  7749. if (!handler && !finalizer) {
  7750. throwError(Messages.NoCatchOrFinally);
  7751. }
  7752. return node.finishTryStatement(block, handler, finalizer);
  7753. }
  7754. // ECMA-262 13.16 The debugger statement
  7755. function parseDebuggerStatement(node) {
  7756. expectKeyword('debugger');
  7757. consumeSemicolon();
  7758. return node.finishDebuggerStatement();
  7759. }
  7760. // 13 Statements
  7761. function parseStatement() {
  7762. var type = lookahead.type,
  7763. expr,
  7764. labeledBody,
  7765. key,
  7766. node;
  7767. if (type === Token.EOF) {
  7768. throwUnexpectedToken(lookahead);
  7769. }
  7770. if (type === Token.Punctuator && lookahead.value === '{') {
  7771. return parseBlock();
  7772. }
  7773. isAssignmentTarget = isBindingElement = true;
  7774. node = new Node();
  7775. if (type === Token.Punctuator) {
  7776. switch (lookahead.value) {
  7777. case ';':
  7778. return parseEmptyStatement(node);
  7779. case '(':
  7780. return parseExpressionStatement(node);
  7781. default:
  7782. break;
  7783. }
  7784. } else if (type === Token.Keyword) {
  7785. switch (lookahead.value) {
  7786. case 'break':
  7787. return parseBreakStatement(node);
  7788. case 'continue':
  7789. return parseContinueStatement(node);
  7790. case 'debugger':
  7791. return parseDebuggerStatement(node);
  7792. case 'do':
  7793. return parseDoWhileStatement(node);
  7794. case 'for':
  7795. return parseForStatement(node);
  7796. case 'function':
  7797. return parseFunctionDeclaration(node);
  7798. case 'if':
  7799. return parseIfStatement(node);
  7800. case 'return':
  7801. return parseReturnStatement(node);
  7802. case 'switch':
  7803. return parseSwitchStatement(node);
  7804. case 'throw':
  7805. return parseThrowStatement(node);
  7806. case 'try':
  7807. return parseTryStatement(node);
  7808. case 'var':
  7809. return parseVariableStatement(node);
  7810. case 'while':
  7811. return parseWhileStatement(node);
  7812. case 'with':
  7813. return parseWithStatement(node);
  7814. default:
  7815. break;
  7816. }
  7817. }
  7818. expr = parseExpression();
  7819. // ECMA-262 12.12 Labelled Statements
  7820. if ((expr.type === Syntax.Identifier) && match(':')) {
  7821. lex();
  7822. key = '$' + expr.name;
  7823. if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
  7824. throwError(Messages.Redeclaration, 'Label', expr.name);
  7825. }
  7826. state.labelSet[key] = true;
  7827. labeledBody = parseStatement();
  7828. delete state.labelSet[key];
  7829. return node.finishLabeledStatement(expr, labeledBody);
  7830. }
  7831. consumeSemicolon();
  7832. return node.finishExpressionStatement(expr);
  7833. }
  7834. // ECMA-262 14.1 Function Definition
  7835. function parseFunctionSourceElements() {
  7836. var statement, body = [], token, directive, firstRestricted,
  7837. oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody,
  7838. node = new Node();
  7839. expect('{');
  7840. while (startIndex < length) {
  7841. if (lookahead.type !== Token.StringLiteral) {
  7842. break;
  7843. }
  7844. token = lookahead;
  7845. statement = parseStatementListItem();
  7846. body.push(statement);
  7847. if (statement.expression.type !== Syntax.Literal) {
  7848. // this is not directive
  7849. break;
  7850. }
  7851. directive = source.slice(token.start + 1, token.end - 1);
  7852. if (directive === 'use strict') {
  7853. strict = true;
  7854. if (firstRestricted) {
  7855. tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
  7856. }
  7857. } else {
  7858. if (!firstRestricted && token.octal) {
  7859. firstRestricted = token;
  7860. }
  7861. }
  7862. }
  7863. oldLabelSet = state.labelSet;
  7864. oldInIteration = state.inIteration;
  7865. oldInSwitch = state.inSwitch;
  7866. oldInFunctionBody = state.inFunctionBody;
  7867. state.labelSet = {};
  7868. state.inIteration = false;
  7869. state.inSwitch = false;
  7870. state.inFunctionBody = true;
  7871. while (startIndex < length) {
  7872. if (match('}')) {
  7873. break;
  7874. }
  7875. body.push(parseStatementListItem());
  7876. }
  7877. expect('}');
  7878. state.labelSet = oldLabelSet;
  7879. state.inIteration = oldInIteration;
  7880. state.inSwitch = oldInSwitch;
  7881. state.inFunctionBody = oldInFunctionBody;
  7882. return node.finishBlockStatement(body);
  7883. }
  7884. function validateParam(options, param, name) {
  7885. var key = '$' + name;
  7886. if (strict) {
  7887. if (isRestrictedWord(name)) {
  7888. options.stricted = param;
  7889. options.message = Messages.StrictParamName;
  7890. }
  7891. if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
  7892. options.stricted = param;
  7893. options.message = Messages.StrictParamDupe;
  7894. }
  7895. } else if (!options.firstRestricted) {
  7896. if (isRestrictedWord(name)) {
  7897. options.firstRestricted = param;
  7898. options.message = Messages.StrictParamName;
  7899. } else if (isStrictModeReservedWord(name)) {
  7900. options.firstRestricted = param;
  7901. options.message = Messages.StrictReservedWord;
  7902. } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
  7903. options.stricted = param;
  7904. options.message = Messages.StrictParamDupe;
  7905. }
  7906. }
  7907. options.paramSet[key] = true;
  7908. }
  7909. function parseParam(options) {
  7910. var token, param, params = [], i, def;
  7911. token = lookahead;
  7912. if (token.value === '...') {
  7913. param = parseRestElement(params);
  7914. validateParam(options, param.argument, param.argument.name);
  7915. options.params.push(param);
  7916. options.defaults.push(null);
  7917. return false;
  7918. }
  7919. param = parsePatternWithDefault(params);
  7920. for (i = 0; i < params.length; i++) {
  7921. validateParam(options, params[i], params[i].value);
  7922. }
  7923. if (param.type === Syntax.AssignmentPattern) {
  7924. def = param.right;
  7925. param = param.left;
  7926. ++options.defaultCount;
  7927. }
  7928. options.params.push(param);
  7929. options.defaults.push(def);
  7930. return !match(')');
  7931. }
  7932. function parseParams(firstRestricted) {
  7933. var options;
  7934. options = {
  7935. params: [],
  7936. defaultCount: 0,
  7937. defaults: [],
  7938. firstRestricted: firstRestricted
  7939. };
  7940. expect('(');
  7941. if (!match(')')) {
  7942. options.paramSet = {};
  7943. while (startIndex < length) {
  7944. if (!parseParam(options)) {
  7945. break;
  7946. }
  7947. expect(',');
  7948. }
  7949. }
  7950. expect(')');
  7951. if (options.defaultCount === 0) {
  7952. options.defaults = [];
  7953. }
  7954. return {
  7955. params: options.params,
  7956. defaults: options.defaults,
  7957. stricted: options.stricted,
  7958. firstRestricted: options.firstRestricted,
  7959. message: options.message
  7960. };
  7961. }
  7962. function parseFunctionDeclaration(node, identifierIsOptional) {
  7963. var id = null, params = [], defaults = [], body, token, stricted, tmp, firstRestricted, message, previousStrict,
  7964. isGenerator, previousAllowYield;
  7965. previousAllowYield = state.allowYield;
  7966. expectKeyword('function');
  7967. isGenerator = match('*');
  7968. if (isGenerator) {
  7969. lex();
  7970. }
  7971. if (!identifierIsOptional || !match('(')) {
  7972. token = lookahead;
  7973. id = parseVariableIdentifier();
  7974. if (strict) {
  7975. if (isRestrictedWord(token.value)) {
  7976. tolerateUnexpectedToken(token, Messages.StrictFunctionName);
  7977. }
  7978. } else {
  7979. if (isRestrictedWord(token.value)) {
  7980. firstRestricted = token;
  7981. message = Messages.StrictFunctionName;
  7982. } else if (isStrictModeReservedWord(token.value)) {
  7983. firstRestricted = token;
  7984. message = Messages.StrictReservedWord;
  7985. }
  7986. }
  7987. }
  7988. state.allowYield = !isGenerator;
  7989. tmp = parseParams(firstRestricted);
  7990. params = tmp.params;
  7991. defaults = tmp.defaults;
  7992. stricted = tmp.stricted;
  7993. firstRestricted = tmp.firstRestricted;
  7994. if (tmp.message) {
  7995. message = tmp.message;
  7996. }
  7997. previousStrict = strict;
  7998. body = parseFunctionSourceElements();
  7999. if (strict && firstRestricted) {
  8000. throwUnexpectedToken(firstRestricted, message);
  8001. }
  8002. if (strict && stricted) {
  8003. tolerateUnexpectedToken(stricted, message);
  8004. }
  8005. strict = previousStrict;
  8006. state.allowYield = previousAllowYield;
  8007. return node.finishFunctionDeclaration(id, params, defaults, body, isGenerator);
  8008. }
  8009. function parseFunctionExpression() {
  8010. var token, id = null, stricted, firstRestricted, message, tmp,
  8011. params = [], defaults = [], body, previousStrict, node = new Node(),
  8012. isGenerator, previousAllowYield;
  8013. previousAllowYield = state.allowYield;
  8014. expectKeyword('function');
  8015. isGenerator = match('*');
  8016. if (isGenerator) {
  8017. lex();
  8018. }
  8019. state.allowYield = !isGenerator;
  8020. if (!match('(')) {
  8021. token = lookahead;
  8022. id = (!strict && !isGenerator && matchKeyword('yield')) ? parseNonComputedProperty() : parseVariableIdentifier();
  8023. if (strict) {
  8024. if (isRestrictedWord(token.value)) {
  8025. tolerateUnexpectedToken(token, Messages.StrictFunctionName);
  8026. }
  8027. } else {
  8028. if (isRestrictedWord(token.value)) {
  8029. firstRestricted = token;
  8030. message = Messages.StrictFunctionName;
  8031. } else if (isStrictModeReservedWord(token.value)) {
  8032. firstRestricted = token;
  8033. message = Messages.StrictReservedWord;
  8034. }
  8035. }
  8036. }
  8037. tmp = parseParams(firstRestricted);
  8038. params = tmp.params;
  8039. defaults = tmp.defaults;
  8040. stricted = tmp.stricted;
  8041. firstRestricted = tmp.firstRestricted;
  8042. if (tmp.message) {
  8043. message = tmp.message;
  8044. }
  8045. previousStrict = strict;
  8046. body = parseFunctionSourceElements();
  8047. if (strict && firstRestricted) {
  8048. throwUnexpectedToken(firstRestricted, message);
  8049. }
  8050. if (strict && stricted) {
  8051. tolerateUnexpectedToken(stricted, message);
  8052. }
  8053. strict = previousStrict;
  8054. state.allowYield = previousAllowYield;
  8055. return node.finishFunctionExpression(id, params, defaults, body, isGenerator);
  8056. }
  8057. // ECMA-262 14.5 Class Definitions
  8058. function parseClassBody() {
  8059. var classBody, token, isStatic, hasConstructor = false, body, method, computed, key;
  8060. classBody = new Node();
  8061. expect('{');
  8062. body = [];
  8063. while (!match('}')) {
  8064. if (match(';')) {
  8065. lex();
  8066. } else {
  8067. method = new Node();
  8068. token = lookahead;
  8069. isStatic = false;
  8070. computed = match('[');
  8071. if (match('*')) {
  8072. lex();
  8073. } else {
  8074. key = parseObjectPropertyKey();
  8075. if (key.name === 'static' && (lookaheadPropertyName() || match('*'))) {
  8076. token = lookahead;
  8077. isStatic = true;
  8078. computed = match('[');
  8079. if (match('*')) {
  8080. lex();
  8081. } else {
  8082. key = parseObjectPropertyKey();
  8083. }
  8084. }
  8085. }
  8086. method = tryParseMethodDefinition(token, key, computed, method);
  8087. if (method) {
  8088. method['static'] = isStatic; // jscs:ignore requireDotNotation
  8089. if (method.kind === 'init') {
  8090. method.kind = 'method';
  8091. }
  8092. if (!isStatic) {
  8093. if (!method.computed && (method.key.name || method.key.value.toString()) === 'constructor') {
  8094. if (method.kind !== 'method' || !method.method || method.value.generator) {
  8095. throwUnexpectedToken(token, Messages.ConstructorSpecialMethod);
  8096. }
  8097. if (hasConstructor) {
  8098. throwUnexpectedToken(token, Messages.DuplicateConstructor);
  8099. } else {
  8100. hasConstructor = true;
  8101. }
  8102. method.kind = 'constructor';
  8103. }
  8104. } else {
  8105. if (!method.computed && (method.key.name || method.key.value.toString()) === 'prototype') {
  8106. throwUnexpectedToken(token, Messages.StaticPrototype);
  8107. }
  8108. }
  8109. method.type = Syntax.MethodDefinition;
  8110. delete method.method;
  8111. delete method.shorthand;
  8112. body.push(method);
  8113. } else {
  8114. throwUnexpectedToken(lookahead);
  8115. }
  8116. }
  8117. }
  8118. lex();
  8119. return classBody.finishClassBody(body);
  8120. }
  8121. function parseClassDeclaration(identifierIsOptional) {
  8122. var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
  8123. strict = true;
  8124. expectKeyword('class');
  8125. if (!identifierIsOptional || lookahead.type === Token.Identifier) {
  8126. id = parseVariableIdentifier();
  8127. }
  8128. if (matchKeyword('extends')) {
  8129. lex();
  8130. superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
  8131. }
  8132. classBody = parseClassBody();
  8133. strict = previousStrict;
  8134. return classNode.finishClassDeclaration(id, superClass, classBody);
  8135. }
  8136. function parseClassExpression() {
  8137. var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
  8138. strict = true;
  8139. expectKeyword('class');
  8140. if (lookahead.type === Token.Identifier) {
  8141. id = parseVariableIdentifier();
  8142. }
  8143. if (matchKeyword('extends')) {
  8144. lex();
  8145. superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
  8146. }
  8147. classBody = parseClassBody();
  8148. strict = previousStrict;
  8149. return classNode.finishClassExpression(id, superClass, classBody);
  8150. }
  8151. // ECMA-262 15.2 Modules
  8152. function parseModuleSpecifier() {
  8153. var node = new Node();
  8154. if (lookahead.type !== Token.StringLiteral) {
  8155. throwError(Messages.InvalidModuleSpecifier);
  8156. }
  8157. return node.finishLiteral(lex());
  8158. }
  8159. // ECMA-262 15.2.3 Exports
  8160. function parseExportSpecifier() {
  8161. var exported, local, node = new Node(), def;
  8162. if (matchKeyword('default')) {
  8163. // export {default} from 'something';
  8164. def = new Node();
  8165. lex();
  8166. local = def.finishIdentifier('default');
  8167. } else {
  8168. local = parseVariableIdentifier();
  8169. }
  8170. if (matchContextualKeyword('as')) {
  8171. lex();
  8172. exported = parseNonComputedProperty();
  8173. }
  8174. return node.finishExportSpecifier(local, exported);
  8175. }
  8176. function parseExportNamedDeclaration(node) {
  8177. var declaration = null,
  8178. isExportFromIdentifier,
  8179. src = null, specifiers = [];
  8180. // non-default export
  8181. if (lookahead.type === Token.Keyword) {
  8182. // covers:
  8183. // export var f = 1;
  8184. switch (lookahead.value) {
  8185. case 'let':
  8186. case 'const':
  8187. declaration = parseLexicalDeclaration({inFor: false});
  8188. return node.finishExportNamedDeclaration(declaration, specifiers, null);
  8189. case 'var':
  8190. case 'class':
  8191. case 'function':
  8192. declaration = parseStatementListItem();
  8193. return node.finishExportNamedDeclaration(declaration, specifiers, null);
  8194. }
  8195. }
  8196. expect('{');
  8197. while (!match('}')) {
  8198. isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
  8199. specifiers.push(parseExportSpecifier());
  8200. if (!match('}')) {
  8201. expect(',');
  8202. if (match('}')) {
  8203. break;
  8204. }
  8205. }
  8206. }
  8207. expect('}');
  8208. if (matchContextualKeyword('from')) {
  8209. // covering:
  8210. // export {default} from 'foo';
  8211. // export {foo} from 'foo';
  8212. lex();
  8213. src = parseModuleSpecifier();
  8214. consumeSemicolon();
  8215. } else if (isExportFromIdentifier) {
  8216. // covering:
  8217. // export {default}; // missing fromClause
  8218. throwError(lookahead.value ?
  8219. Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
  8220. } else {
  8221. // cover
  8222. // export {foo};
  8223. consumeSemicolon();
  8224. }
  8225. return node.finishExportNamedDeclaration(declaration, specifiers, src);
  8226. }
  8227. function parseExportDefaultDeclaration(node) {
  8228. var declaration = null,
  8229. expression = null;
  8230. // covers:
  8231. // export default ...
  8232. expectKeyword('default');
  8233. if (matchKeyword('function')) {
  8234. // covers:
  8235. // export default function foo () {}
  8236. // export default function () {}
  8237. declaration = parseFunctionDeclaration(new Node(), true);
  8238. return node.finishExportDefaultDeclaration(declaration);
  8239. }
  8240. if (matchKeyword('class')) {
  8241. declaration = parseClassDeclaration(true);
  8242. return node.finishExportDefaultDeclaration(declaration);
  8243. }
  8244. if (matchContextualKeyword('from')) {
  8245. throwError(Messages.UnexpectedToken, lookahead.value);
  8246. }
  8247. // covers:
  8248. // export default {};
  8249. // export default [];
  8250. // export default (1 + 2);
  8251. if (match('{')) {
  8252. expression = parseObjectInitializer();
  8253. } else if (match('[')) {
  8254. expression = parseArrayInitializer();
  8255. } else {
  8256. expression = parseAssignmentExpression();
  8257. }
  8258. consumeSemicolon();
  8259. return node.finishExportDefaultDeclaration(expression);
  8260. }
  8261. function parseExportAllDeclaration(node) {
  8262. var src;
  8263. // covers:
  8264. // export * from 'foo';
  8265. expect('*');
  8266. if (!matchContextualKeyword('from')) {
  8267. throwError(lookahead.value ?
  8268. Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
  8269. }
  8270. lex();
  8271. src = parseModuleSpecifier();
  8272. consumeSemicolon();
  8273. return node.finishExportAllDeclaration(src);
  8274. }
  8275. function parseExportDeclaration() {
  8276. var node = new Node();
  8277. if (state.inFunctionBody) {
  8278. throwError(Messages.IllegalExportDeclaration);
  8279. }
  8280. expectKeyword('export');
  8281. if (matchKeyword('default')) {
  8282. return parseExportDefaultDeclaration(node);
  8283. }
  8284. if (match('*')) {
  8285. return parseExportAllDeclaration(node);
  8286. }
  8287. return parseExportNamedDeclaration(node);
  8288. }
  8289. // ECMA-262 15.2.2 Imports
  8290. function parseImportSpecifier() {
  8291. // import {<foo as bar>} ...;
  8292. var local, imported, node = new Node();
  8293. imported = parseNonComputedProperty();
  8294. if (matchContextualKeyword('as')) {
  8295. lex();
  8296. local = parseVariableIdentifier();
  8297. }
  8298. return node.finishImportSpecifier(local, imported);
  8299. }
  8300. function parseNamedImports() {
  8301. var specifiers = [];
  8302. // {foo, bar as bas}
  8303. expect('{');
  8304. while (!match('}')) {
  8305. specifiers.push(parseImportSpecifier());
  8306. if (!match('}')) {
  8307. expect(',');
  8308. if (match('}')) {
  8309. break;
  8310. }
  8311. }
  8312. }
  8313. expect('}');
  8314. return specifiers;
  8315. }
  8316. function parseImportDefaultSpecifier() {
  8317. // import <foo> ...;
  8318. var local, node = new Node();
  8319. local = parseNonComputedProperty();
  8320. return node.finishImportDefaultSpecifier(local);
  8321. }
  8322. function parseImportNamespaceSpecifier() {
  8323. // import <* as foo> ...;
  8324. var local, node = new Node();
  8325. expect('*');
  8326. if (!matchContextualKeyword('as')) {
  8327. throwError(Messages.NoAsAfterImportNamespace);
  8328. }
  8329. lex();
  8330. local = parseNonComputedProperty();
  8331. return node.finishImportNamespaceSpecifier(local);
  8332. }
  8333. function parseImportDeclaration() {
  8334. var specifiers = [], src, node = new Node();
  8335. if (state.inFunctionBody) {
  8336. throwError(Messages.IllegalImportDeclaration);
  8337. }
  8338. expectKeyword('import');
  8339. if (lookahead.type === Token.StringLiteral) {
  8340. // import 'foo';
  8341. src = parseModuleSpecifier();
  8342. } else {
  8343. if (match('{')) {
  8344. // import {bar}
  8345. specifiers = specifiers.concat(parseNamedImports());
  8346. } else if (match('*')) {
  8347. // import * as foo
  8348. specifiers.push(parseImportNamespaceSpecifier());
  8349. } else if (isIdentifierName(lookahead) && !matchKeyword('default')) {
  8350. // import foo
  8351. specifiers.push(parseImportDefaultSpecifier());
  8352. if (match(',')) {
  8353. lex();
  8354. if (match('*')) {
  8355. // import foo, * as foo
  8356. specifiers.push(parseImportNamespaceSpecifier());
  8357. } else if (match('{')) {
  8358. // import foo, {bar}
  8359. specifiers = specifiers.concat(parseNamedImports());
  8360. } else {
  8361. throwUnexpectedToken(lookahead);
  8362. }
  8363. }
  8364. } else {
  8365. throwUnexpectedToken(lex());
  8366. }
  8367. if (!matchContextualKeyword('from')) {
  8368. throwError(lookahead.value ?
  8369. Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
  8370. }
  8371. lex();
  8372. src = parseModuleSpecifier();
  8373. }
  8374. consumeSemicolon();
  8375. return node.finishImportDeclaration(specifiers, src);
  8376. }
  8377. // ECMA-262 15.1 Scripts
  8378. function parseScriptBody() {
  8379. var statement, body = [], token, directive, firstRestricted;
  8380. while (startIndex < length) {
  8381. token = lookahead;
  8382. if (token.type !== Token.StringLiteral) {
  8383. break;
  8384. }
  8385. statement = parseStatementListItem();
  8386. body.push(statement);
  8387. if (statement.expression.type !== Syntax.Literal) {
  8388. // this is not directive
  8389. break;
  8390. }
  8391. directive = source.slice(token.start + 1, token.end - 1);
  8392. if (directive === 'use strict') {
  8393. strict = true;
  8394. if (firstRestricted) {
  8395. tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
  8396. }
  8397. } else {
  8398. if (!firstRestricted && token.octal) {
  8399. firstRestricted = token;
  8400. }
  8401. }
  8402. }
  8403. while (startIndex < length) {
  8404. statement = parseStatementListItem();
  8405. /* istanbul ignore if */
  8406. if (typeof statement === 'undefined') {
  8407. break;
  8408. }
  8409. body.push(statement);
  8410. }
  8411. return body;
  8412. }
  8413. function parseProgram() {
  8414. var body, node;
  8415. peek();
  8416. node = new Node();
  8417. body = parseScriptBody();
  8418. return node.finishProgram(body, state.sourceType);
  8419. }
  8420. function filterTokenLocation() {
  8421. var i, entry, token, tokens = [];
  8422. for (i = 0; i < extra.tokens.length; ++i) {
  8423. entry = extra.tokens[i];
  8424. token = {
  8425. type: entry.type,
  8426. value: entry.value
  8427. };
  8428. if (entry.regex) {
  8429. token.regex = {
  8430. pattern: entry.regex.pattern,
  8431. flags: entry.regex.flags
  8432. };
  8433. }
  8434. if (extra.range) {
  8435. token.range = entry.range;
  8436. }
  8437. if (extra.loc) {
  8438. token.loc = entry.loc;
  8439. }
  8440. tokens.push(token);
  8441. }
  8442. extra.tokens = tokens;
  8443. }
  8444. function tokenize(code, options, delegate) {
  8445. var toString,
  8446. tokens;
  8447. toString = String;
  8448. if (typeof code !== 'string' && !(code instanceof String)) {
  8449. code = toString(code);
  8450. }
  8451. source = code;
  8452. index = 0;
  8453. lineNumber = (source.length > 0) ? 1 : 0;
  8454. lineStart = 0;
  8455. startIndex = index;
  8456. startLineNumber = lineNumber;
  8457. startLineStart = lineStart;
  8458. length = source.length;
  8459. lookahead = null;
  8460. state = {
  8461. allowIn: true,
  8462. allowYield: true,
  8463. labelSet: {},
  8464. inFunctionBody: false,
  8465. inIteration: false,
  8466. inSwitch: false,
  8467. lastCommentStart: -1,
  8468. curlyStack: []
  8469. };
  8470. extra = {};
  8471. // Options matching.
  8472. options = options || {};
  8473. // Of course we collect tokens here.
  8474. options.tokens = true;
  8475. extra.tokens = [];
  8476. extra.tokenValues = [];
  8477. extra.tokenize = true;
  8478. extra.delegate = delegate;
  8479. // The following two fields are necessary to compute the Regex tokens.
  8480. extra.openParenToken = -1;
  8481. extra.openCurlyToken = -1;
  8482. extra.range = (typeof options.range === 'boolean') && options.range;
  8483. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  8484. if (typeof options.comment === 'boolean' && options.comment) {
  8485. extra.comments = [];
  8486. }
  8487. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  8488. extra.errors = [];
  8489. }
  8490. try {
  8491. peek();
  8492. if (lookahead.type === Token.EOF) {
  8493. return extra.tokens;
  8494. }
  8495. lex();
  8496. while (lookahead.type !== Token.EOF) {
  8497. try {
  8498. lex();
  8499. } catch (lexError) {
  8500. if (extra.errors) {
  8501. recordError(lexError);
  8502. // We have to break on the first error
  8503. // to avoid infinite loops.
  8504. break;
  8505. } else {
  8506. throw lexError;
  8507. }
  8508. }
  8509. }
  8510. tokens = extra.tokens;
  8511. if (typeof extra.errors !== 'undefined') {
  8512. tokens.errors = extra.errors;
  8513. }
  8514. } catch (e) {
  8515. throw e;
  8516. } finally {
  8517. extra = {};
  8518. }
  8519. return tokens;
  8520. }
  8521. function parse(code, options) {
  8522. var program, toString;
  8523. toString = String;
  8524. if (typeof code !== 'string' && !(code instanceof String)) {
  8525. code = toString(code);
  8526. }
  8527. source = code;
  8528. index = 0;
  8529. lineNumber = (source.length > 0) ? 1 : 0;
  8530. lineStart = 0;
  8531. startIndex = index;
  8532. startLineNumber = lineNumber;
  8533. startLineStart = lineStart;
  8534. length = source.length;
  8535. lookahead = null;
  8536. state = {
  8537. allowIn: true,
  8538. allowYield: true,
  8539. labelSet: {},
  8540. inFunctionBody: false,
  8541. inIteration: false,
  8542. inSwitch: false,
  8543. lastCommentStart: -1,
  8544. curlyStack: [],
  8545. sourceType: 'script'
  8546. };
  8547. strict = false;
  8548. extra = {};
  8549. if (typeof options !== 'undefined') {
  8550. extra.range = (typeof options.range === 'boolean') && options.range;
  8551. extra.loc = (typeof options.loc === 'boolean') && options.loc;
  8552. extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
  8553. if (extra.loc && options.source !== null && options.source !== undefined) {
  8554. extra.source = toString(options.source);
  8555. }
  8556. if (typeof options.tokens === 'boolean' && options.tokens) {
  8557. extra.tokens = [];
  8558. }
  8559. if (typeof options.comment === 'boolean' && options.comment) {
  8560. extra.comments = [];
  8561. }
  8562. if (typeof options.tolerant === 'boolean' && options.tolerant) {
  8563. extra.errors = [];
  8564. }
  8565. if (extra.attachComment) {
  8566. extra.range = true;
  8567. extra.comments = [];
  8568. extra.bottomRightStack = [];
  8569. extra.trailingComments = [];
  8570. extra.leadingComments = [];
  8571. }
  8572. if (options.sourceType === 'module') {
  8573. // very restrictive condition for now
  8574. state.sourceType = options.sourceType;
  8575. strict = true;
  8576. }
  8577. }
  8578. try {
  8579. program = parseProgram();
  8580. if (typeof extra.comments !== 'undefined') {
  8581. program.comments = extra.comments;
  8582. }
  8583. if (typeof extra.tokens !== 'undefined') {
  8584. filterTokenLocation();
  8585. program.tokens = extra.tokens;
  8586. }
  8587. if (typeof extra.errors !== 'undefined') {
  8588. program.errors = extra.errors;
  8589. }
  8590. } catch (e) {
  8591. throw e;
  8592. } finally {
  8593. extra = {};
  8594. }
  8595. return program;
  8596. }
  8597. // Sync with *.json manifests.
  8598. exports.version = '2.7.3';
  8599. exports.tokenize = tokenize;
  8600. exports.parse = parse;
  8601. // Deep copy.
  8602. /* istanbul ignore next */
  8603. exports.Syntax = (function () {
  8604. var name, types = {};
  8605. if (typeof Object.create === 'function') {
  8606. types = Object.create(null);
  8607. }
  8608. for (name in Syntax) {
  8609. if (Syntax.hasOwnProperty(name)) {
  8610. types[name] = Syntax[name];
  8611. }
  8612. }
  8613. if (typeof Object.freeze === 'function') {
  8614. Object.freeze(types);
  8615. }
  8616. return types;
  8617. }());
  8618. }));
  8619. /* vim: set sw=4 ts=4 et tw=80 : */
  8620. /*global define, Reflect */
  8621. /*
  8622. * xpcshell has a smaller stack on linux and windows (1MB vs 9MB on mac),
  8623. * and the recursive nature of esprima can cause it to overflow pretty
  8624. * quickly. So favor it built in Reflect parser:
  8625. * https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  8626. */
  8627. define('esprimaAdapter', ['./esprima', 'env'], function (esprima, env) {
  8628. if (env.get() === 'xpconnect' && typeof Reflect !== 'undefined') {
  8629. return Reflect;
  8630. } else {
  8631. return esprima;
  8632. }
  8633. });
  8634. (function webpackUniversalModuleDefinition(root, factory) {
  8635. var exports, module;
  8636. if(typeof exports === 'object' && typeof module === 'object')
  8637. module.exports = factory();
  8638. else if(typeof define === 'function' && define.amd)
  8639. define('source-map', [], factory);
  8640. else if(typeof exports === 'object')
  8641. exports["sourceMap"] = factory();
  8642. else
  8643. root["sourceMap"] = factory();
  8644. })(this, function() {
  8645. return /******/ (function(modules) { // webpackBootstrap
  8646. /******/ // The module cache
  8647. /******/ var installedModules = {};
  8648. /******/ // The require function
  8649. /******/ function __webpack_require__(moduleId) {
  8650. /******/ // Check if module is in cache
  8651. /******/ if(installedModules[moduleId])
  8652. /******/ return installedModules[moduleId].exports;
  8653. /******/ // Create a new module (and put it into the cache)
  8654. /******/ var module = installedModules[moduleId] = {
  8655. /******/ exports: {},
  8656. /******/ id: moduleId,
  8657. /******/ loaded: false
  8658. /******/ };
  8659. /******/ // Execute the module function
  8660. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  8661. /******/ // Flag the module as loaded
  8662. /******/ module.loaded = true;
  8663. /******/ // Return the exports of the module
  8664. /******/ return module.exports;
  8665. /******/ }
  8666. /******/ // expose the modules object (__webpack_modules__)
  8667. /******/ __webpack_require__.m = modules;
  8668. /******/ // expose the module cache
  8669. /******/ __webpack_require__.c = installedModules;
  8670. /******/ // __webpack_public_path__
  8671. /******/ __webpack_require__.p = "";
  8672. /******/ // Load entry module and return exports
  8673. /******/ return __webpack_require__(0);
  8674. /******/ })
  8675. /************************************************************************/
  8676. /******/ ([
  8677. /* 0 */
  8678. /***/ function(module, exports, __webpack_require__) {
  8679. /*
  8680. * Copyright 2009-2011 Mozilla Foundation and contributors
  8681. * Licensed under the New BSD license. See LICENSE.txt or:
  8682. * http://opensource.org/licenses/BSD-3-Clause
  8683. */
  8684. exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;
  8685. exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer;
  8686. exports.SourceNode = __webpack_require__(10).SourceNode;
  8687. /***/ },
  8688. /* 1 */
  8689. /***/ function(module, exports, __webpack_require__) {
  8690. /* -*- Mode: js; js-indent-level: 2; -*- */
  8691. /*
  8692. * Copyright 2011 Mozilla Foundation and contributors
  8693. * Licensed under the New BSD license. See LICENSE or:
  8694. * http://opensource.org/licenses/BSD-3-Clause
  8695. */
  8696. var base64VLQ = __webpack_require__(2);
  8697. var util = __webpack_require__(4);
  8698. var ArraySet = __webpack_require__(5).ArraySet;
  8699. var MappingList = __webpack_require__(6).MappingList;
  8700. /**
  8701. * An instance of the SourceMapGenerator represents a source map which is
  8702. * being built incrementally. You may pass an object with the following
  8703. * properties:
  8704. *
  8705. * - file: The filename of the generated source.
  8706. * - sourceRoot: A root for all relative URLs in this source map.
  8707. */
  8708. function SourceMapGenerator(aArgs) {
  8709. if (!aArgs) {
  8710. aArgs = {};
  8711. }
  8712. this._file = util.getArg(aArgs, 'file', null);
  8713. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  8714. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  8715. this._sources = new ArraySet();
  8716. this._names = new ArraySet();
  8717. this._mappings = new MappingList();
  8718. this._sourcesContents = null;
  8719. }
  8720. SourceMapGenerator.prototype._version = 3;
  8721. /**
  8722. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8723. *
  8724. * @param aSourceMapConsumer The SourceMap.
  8725. */
  8726. SourceMapGenerator.fromSourceMap =
  8727. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8728. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8729. var generator = new SourceMapGenerator({
  8730. file: aSourceMapConsumer.file,
  8731. sourceRoot: sourceRoot
  8732. });
  8733. aSourceMapConsumer.eachMapping(function (mapping) {
  8734. var newMapping = {
  8735. generated: {
  8736. line: mapping.generatedLine,
  8737. column: mapping.generatedColumn
  8738. }
  8739. };
  8740. if (mapping.source != null) {
  8741. newMapping.source = mapping.source;
  8742. if (sourceRoot != null) {
  8743. newMapping.source = util.relative(sourceRoot, newMapping.source);
  8744. }
  8745. newMapping.original = {
  8746. line: mapping.originalLine,
  8747. column: mapping.originalColumn
  8748. };
  8749. if (mapping.name != null) {
  8750. newMapping.name = mapping.name;
  8751. }
  8752. }
  8753. generator.addMapping(newMapping);
  8754. });
  8755. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8756. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8757. if (content != null) {
  8758. generator.setSourceContent(sourceFile, content);
  8759. }
  8760. });
  8761. return generator;
  8762. };
  8763. /**
  8764. * Add a single mapping from original source line and column to the generated
  8765. * source's line and column for this source map being created. The mapping
  8766. * object should have the following properties:
  8767. *
  8768. * - generated: An object with the generated line and column positions.
  8769. * - original: An object with the original line and column positions.
  8770. * - source: The original source file (relative to the sourceRoot).
  8771. * - name: An optional original token name for this mapping.
  8772. */
  8773. SourceMapGenerator.prototype.addMapping =
  8774. function SourceMapGenerator_addMapping(aArgs) {
  8775. var generated = util.getArg(aArgs, 'generated');
  8776. var original = util.getArg(aArgs, 'original', null);
  8777. var source = util.getArg(aArgs, 'source', null);
  8778. var name = util.getArg(aArgs, 'name', null);
  8779. if (!this._skipValidation) {
  8780. this._validateMapping(generated, original, source, name);
  8781. }
  8782. if (source != null) {
  8783. source = String(source);
  8784. if (!this._sources.has(source)) {
  8785. this._sources.add(source);
  8786. }
  8787. }
  8788. if (name != null) {
  8789. name = String(name);
  8790. if (!this._names.has(name)) {
  8791. this._names.add(name);
  8792. }
  8793. }
  8794. this._mappings.add({
  8795. generatedLine: generated.line,
  8796. generatedColumn: generated.column,
  8797. originalLine: original != null && original.line,
  8798. originalColumn: original != null && original.column,
  8799. source: source,
  8800. name: name
  8801. });
  8802. };
  8803. /**
  8804. * Set the source content for a source file.
  8805. */
  8806. SourceMapGenerator.prototype.setSourceContent =
  8807. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8808. var source = aSourceFile;
  8809. if (this._sourceRoot != null) {
  8810. source = util.relative(this._sourceRoot, source);
  8811. }
  8812. if (aSourceContent != null) {
  8813. // Add the source content to the _sourcesContents map.
  8814. // Create a new _sourcesContents map if the property is null.
  8815. if (!this._sourcesContents) {
  8816. this._sourcesContents = Object.create(null);
  8817. }
  8818. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  8819. } else if (this._sourcesContents) {
  8820. // Remove the source file from the _sourcesContents map.
  8821. // If the _sourcesContents map is empty, set the property to null.
  8822. delete this._sourcesContents[util.toSetString(source)];
  8823. if (Object.keys(this._sourcesContents).length === 0) {
  8824. this._sourcesContents = null;
  8825. }
  8826. }
  8827. };
  8828. /**
  8829. * Applies the mappings of a sub-source-map for a specific source file to the
  8830. * source map being generated. Each mapping to the supplied source file is
  8831. * rewritten using the supplied source map. Note: The resolution for the
  8832. * resulting mappings is the minimium of this map and the supplied map.
  8833. *
  8834. * @param aSourceMapConsumer The source map to be applied.
  8835. * @param aSourceFile Optional. The filename of the source file.
  8836. * If omitted, SourceMapConsumer's file property will be used.
  8837. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8838. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8839. * This parameter is needed when the two source maps aren't in the same
  8840. * directory, and the source map to be applied contains relative source
  8841. * paths. If so, those relative source paths need to be rewritten
  8842. * relative to the SourceMapGenerator.
  8843. */
  8844. SourceMapGenerator.prototype.applySourceMap =
  8845. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8846. var sourceFile = aSourceFile;
  8847. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8848. if (aSourceFile == null) {
  8849. if (aSourceMapConsumer.file == null) {
  8850. throw new Error(
  8851. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8852. 'or the source map\'s "file" property. Both were omitted.'
  8853. );
  8854. }
  8855. sourceFile = aSourceMapConsumer.file;
  8856. }
  8857. var sourceRoot = this._sourceRoot;
  8858. // Make "sourceFile" relative if an absolute Url is passed.
  8859. if (sourceRoot != null) {
  8860. sourceFile = util.relative(sourceRoot, sourceFile);
  8861. }
  8862. // Applying the SourceMap can add and remove items from the sources and
  8863. // the names array.
  8864. var newSources = new ArraySet();
  8865. var newNames = new ArraySet();
  8866. // Find mappings for the "sourceFile"
  8867. this._mappings.unsortedForEach(function (mapping) {
  8868. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8869. // Check if it can be mapped by the source map, then update the mapping.
  8870. var original = aSourceMapConsumer.originalPositionFor({
  8871. line: mapping.originalLine,
  8872. column: mapping.originalColumn
  8873. });
  8874. if (original.source != null) {
  8875. // Copy mapping
  8876. mapping.source = original.source;
  8877. if (aSourceMapPath != null) {
  8878. mapping.source = util.join(aSourceMapPath, mapping.source)
  8879. }
  8880. if (sourceRoot != null) {
  8881. mapping.source = util.relative(sourceRoot, mapping.source);
  8882. }
  8883. mapping.originalLine = original.line;
  8884. mapping.originalColumn = original.column;
  8885. if (original.name != null) {
  8886. mapping.name = original.name;
  8887. }
  8888. }
  8889. }
  8890. var source = mapping.source;
  8891. if (source != null && !newSources.has(source)) {
  8892. newSources.add(source);
  8893. }
  8894. var name = mapping.name;
  8895. if (name != null && !newNames.has(name)) {
  8896. newNames.add(name);
  8897. }
  8898. }, this);
  8899. this._sources = newSources;
  8900. this._names = newNames;
  8901. // Copy sourcesContents of applied map.
  8902. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8903. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8904. if (content != null) {
  8905. if (aSourceMapPath != null) {
  8906. sourceFile = util.join(aSourceMapPath, sourceFile);
  8907. }
  8908. if (sourceRoot != null) {
  8909. sourceFile = util.relative(sourceRoot, sourceFile);
  8910. }
  8911. this.setSourceContent(sourceFile, content);
  8912. }
  8913. }, this);
  8914. };
  8915. /**
  8916. * A mapping can have one of the three levels of data:
  8917. *
  8918. * 1. Just the generated position.
  8919. * 2. The Generated position, original position, and original source.
  8920. * 3. Generated and original position, original source, as well as a name
  8921. * token.
  8922. *
  8923. * To maintain consistency, we validate that any new mapping being added falls
  8924. * in to one of these categories.
  8925. */
  8926. SourceMapGenerator.prototype._validateMapping =
  8927. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8928. aName) {
  8929. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8930. && aGenerated.line > 0 && aGenerated.column >= 0
  8931. && !aOriginal && !aSource && !aName) {
  8932. // Case 1.
  8933. return;
  8934. }
  8935. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8936. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8937. && aGenerated.line > 0 && aGenerated.column >= 0
  8938. && aOriginal.line > 0 && aOriginal.column >= 0
  8939. && aSource) {
  8940. // Cases 2 and 3.
  8941. return;
  8942. }
  8943. else {
  8944. throw new Error('Invalid mapping: ' + JSON.stringify({
  8945. generated: aGenerated,
  8946. source: aSource,
  8947. original: aOriginal,
  8948. name: aName
  8949. }));
  8950. }
  8951. };
  8952. /**
  8953. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8954. * specified by the source map format.
  8955. */
  8956. SourceMapGenerator.prototype._serializeMappings =
  8957. function SourceMapGenerator_serializeMappings() {
  8958. var previousGeneratedColumn = 0;
  8959. var previousGeneratedLine = 1;
  8960. var previousOriginalColumn = 0;
  8961. var previousOriginalLine = 0;
  8962. var previousName = 0;
  8963. var previousSource = 0;
  8964. var result = '';
  8965. var next;
  8966. var mapping;
  8967. var nameIdx;
  8968. var sourceIdx;
  8969. var mappings = this._mappings.toArray();
  8970. for (var i = 0, len = mappings.length; i < len; i++) {
  8971. mapping = mappings[i];
  8972. next = ''
  8973. if (mapping.generatedLine !== previousGeneratedLine) {
  8974. previousGeneratedColumn = 0;
  8975. while (mapping.generatedLine !== previousGeneratedLine) {
  8976. next += ';';
  8977. previousGeneratedLine++;
  8978. }
  8979. }
  8980. else {
  8981. if (i > 0) {
  8982. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8983. continue;
  8984. }
  8985. next += ',';
  8986. }
  8987. }
  8988. next += base64VLQ.encode(mapping.generatedColumn
  8989. - previousGeneratedColumn);
  8990. previousGeneratedColumn = mapping.generatedColumn;
  8991. if (mapping.source != null) {
  8992. sourceIdx = this._sources.indexOf(mapping.source);
  8993. next += base64VLQ.encode(sourceIdx - previousSource);
  8994. previousSource = sourceIdx;
  8995. // lines are stored 0-based in SourceMap spec version 3
  8996. next += base64VLQ.encode(mapping.originalLine - 1
  8997. - previousOriginalLine);
  8998. previousOriginalLine = mapping.originalLine - 1;
  8999. next += base64VLQ.encode(mapping.originalColumn
  9000. - previousOriginalColumn);
  9001. previousOriginalColumn = mapping.originalColumn;
  9002. if (mapping.name != null) {
  9003. nameIdx = this._names.indexOf(mapping.name);
  9004. next += base64VLQ.encode(nameIdx - previousName);
  9005. previousName = nameIdx;
  9006. }
  9007. }
  9008. result += next;
  9009. }
  9010. return result;
  9011. };
  9012. SourceMapGenerator.prototype._generateSourcesContent =
  9013. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  9014. return aSources.map(function (source) {
  9015. if (!this._sourcesContents) {
  9016. return null;
  9017. }
  9018. if (aSourceRoot != null) {
  9019. source = util.relative(aSourceRoot, source);
  9020. }
  9021. var key = util.toSetString(source);
  9022. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  9023. ? this._sourcesContents[key]
  9024. : null;
  9025. }, this);
  9026. };
  9027. /**
  9028. * Externalize the source map.
  9029. */
  9030. SourceMapGenerator.prototype.toJSON =
  9031. function SourceMapGenerator_toJSON() {
  9032. var map = {
  9033. version: this._version,
  9034. sources: this._sources.toArray(),
  9035. names: this._names.toArray(),
  9036. mappings: this._serializeMappings()
  9037. };
  9038. if (this._file != null) {
  9039. map.file = this._file;
  9040. }
  9041. if (this._sourceRoot != null) {
  9042. map.sourceRoot = this._sourceRoot;
  9043. }
  9044. if (this._sourcesContents) {
  9045. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  9046. }
  9047. return map;
  9048. };
  9049. /**
  9050. * Render the source map being generated to a string.
  9051. */
  9052. SourceMapGenerator.prototype.toString =
  9053. function SourceMapGenerator_toString() {
  9054. return JSON.stringify(this.toJSON());
  9055. };
  9056. exports.SourceMapGenerator = SourceMapGenerator;
  9057. /***/ },
  9058. /* 2 */
  9059. /***/ function(module, exports, __webpack_require__) {
  9060. /* -*- Mode: js; js-indent-level: 2; -*- */
  9061. /*
  9062. * Copyright 2011 Mozilla Foundation and contributors
  9063. * Licensed under the New BSD license. See LICENSE or:
  9064. * http://opensource.org/licenses/BSD-3-Clause
  9065. *
  9066. * Based on the Base 64 VLQ implementation in Closure Compiler:
  9067. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  9068. *
  9069. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  9070. * Redistribution and use in source and binary forms, with or without
  9071. * modification, are permitted provided that the following conditions are
  9072. * met:
  9073. *
  9074. * * Redistributions of source code must retain the above copyright
  9075. * notice, this list of conditions and the following disclaimer.
  9076. * * Redistributions in binary form must reproduce the above
  9077. * copyright notice, this list of conditions and the following
  9078. * disclaimer in the documentation and/or other materials provided
  9079. * with the distribution.
  9080. * * Neither the name of Google Inc. nor the names of its
  9081. * contributors may be used to endorse or promote products derived
  9082. * from this software without specific prior written permission.
  9083. *
  9084. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  9085. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  9086. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  9087. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9088. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  9089. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9090. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  9091. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  9092. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  9093. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  9094. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9095. */
  9096. var base64 = __webpack_require__(3);
  9097. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  9098. // length quantities we use in the source map spec, the first bit is the sign,
  9099. // the next four bits are the actual value, and the 6th bit is the
  9100. // continuation bit. The continuation bit tells us whether there are more
  9101. // digits in this value following this digit.
  9102. //
  9103. // Continuation
  9104. // | Sign
  9105. // | |
  9106. // V V
  9107. // 101011
  9108. var VLQ_BASE_SHIFT = 5;
  9109. // binary: 100000
  9110. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  9111. // binary: 011111
  9112. var VLQ_BASE_MASK = VLQ_BASE - 1;
  9113. // binary: 100000
  9114. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  9115. /**
  9116. * Converts from a two-complement value to a value where the sign bit is
  9117. * placed in the least significant bit. For example, as decimals:
  9118. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  9119. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  9120. */
  9121. function toVLQSigned(aValue) {
  9122. return aValue < 0
  9123. ? ((-aValue) << 1) + 1
  9124. : (aValue << 1) + 0;
  9125. }
  9126. /**
  9127. * Converts to a two-complement value from a value where the sign bit is
  9128. * placed in the least significant bit. For example, as decimals:
  9129. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  9130. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  9131. */
  9132. function fromVLQSigned(aValue) {
  9133. var isNegative = (aValue & 1) === 1;
  9134. var shifted = aValue >> 1;
  9135. return isNegative
  9136. ? -shifted
  9137. : shifted;
  9138. }
  9139. /**
  9140. * Returns the base 64 VLQ encoded value.
  9141. */
  9142. exports.encode = function base64VLQ_encode(aValue) {
  9143. var encoded = "";
  9144. var digit;
  9145. var vlq = toVLQSigned(aValue);
  9146. do {
  9147. digit = vlq & VLQ_BASE_MASK;
  9148. vlq >>>= VLQ_BASE_SHIFT;
  9149. if (vlq > 0) {
  9150. // There are still more digits in this value, so we must make sure the
  9151. // continuation bit is marked.
  9152. digit |= VLQ_CONTINUATION_BIT;
  9153. }
  9154. encoded += base64.encode(digit);
  9155. } while (vlq > 0);
  9156. return encoded;
  9157. };
  9158. /**
  9159. * Decodes the next base 64 VLQ value from the given string and returns the
  9160. * value and the rest of the string via the out parameter.
  9161. */
  9162. exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  9163. var strLen = aStr.length;
  9164. var result = 0;
  9165. var shift = 0;
  9166. var continuation, digit;
  9167. do {
  9168. if (aIndex >= strLen) {
  9169. throw new Error("Expected more digits in base 64 VLQ value.");
  9170. }
  9171. digit = base64.decode(aStr.charCodeAt(aIndex++));
  9172. if (digit === -1) {
  9173. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  9174. }
  9175. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  9176. digit &= VLQ_BASE_MASK;
  9177. result = result + (digit << shift);
  9178. shift += VLQ_BASE_SHIFT;
  9179. } while (continuation);
  9180. aOutParam.value = fromVLQSigned(result);
  9181. aOutParam.rest = aIndex;
  9182. };
  9183. /***/ },
  9184. /* 3 */
  9185. /***/ function(module, exports) {
  9186. /* -*- Mode: js; js-indent-level: 2; -*- */
  9187. /*
  9188. * Copyright 2011 Mozilla Foundation and contributors
  9189. * Licensed under the New BSD license. See LICENSE or:
  9190. * http://opensource.org/licenses/BSD-3-Clause
  9191. */
  9192. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  9193. /**
  9194. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  9195. */
  9196. exports.encode = function (number) {
  9197. if (0 <= number && number < intToCharMap.length) {
  9198. return intToCharMap[number];
  9199. }
  9200. throw new TypeError("Must be between 0 and 63: " + number);
  9201. };
  9202. /**
  9203. * Decode a single base 64 character code digit to an integer. Returns -1 on
  9204. * failure.
  9205. */
  9206. exports.decode = function (charCode) {
  9207. var bigA = 65; // 'A'
  9208. var bigZ = 90; // 'Z'
  9209. var littleA = 97; // 'a'
  9210. var littleZ = 122; // 'z'
  9211. var zero = 48; // '0'
  9212. var nine = 57; // '9'
  9213. var plus = 43; // '+'
  9214. var slash = 47; // '/'
  9215. var littleOffset = 26;
  9216. var numberOffset = 52;
  9217. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  9218. if (bigA <= charCode && charCode <= bigZ) {
  9219. return (charCode - bigA);
  9220. }
  9221. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  9222. if (littleA <= charCode && charCode <= littleZ) {
  9223. return (charCode - littleA + littleOffset);
  9224. }
  9225. // 52 - 61: 0123456789
  9226. if (zero <= charCode && charCode <= nine) {
  9227. return (charCode - zero + numberOffset);
  9228. }
  9229. // 62: +
  9230. if (charCode == plus) {
  9231. return 62;
  9232. }
  9233. // 63: /
  9234. if (charCode == slash) {
  9235. return 63;
  9236. }
  9237. // Invalid base64 digit.
  9238. return -1;
  9239. };
  9240. /***/ },
  9241. /* 4 */
  9242. /***/ function(module, exports) {
  9243. /* -*- Mode: js; js-indent-level: 2; -*- */
  9244. /*
  9245. * Copyright 2011 Mozilla Foundation and contributors
  9246. * Licensed under the New BSD license. See LICENSE or:
  9247. * http://opensource.org/licenses/BSD-3-Clause
  9248. */
  9249. /**
  9250. * This is a helper function for getting values from parameter/options
  9251. * objects.
  9252. *
  9253. * @param args The object we are extracting values from
  9254. * @param name The name of the property we are getting.
  9255. * @param defaultValue An optional value to return if the property is missing
  9256. * from the object. If this is not specified and the property is missing, an
  9257. * error will be thrown.
  9258. */
  9259. function getArg(aArgs, aName, aDefaultValue) {
  9260. if (aName in aArgs) {
  9261. return aArgs[aName];
  9262. } else if (arguments.length === 3) {
  9263. return aDefaultValue;
  9264. } else {
  9265. throw new Error('"' + aName + '" is a required argument.');
  9266. }
  9267. }
  9268. exports.getArg = getArg;
  9269. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
  9270. var dataUrlRegexp = /^data:.+\,.+$/;
  9271. function urlParse(aUrl) {
  9272. var match = aUrl.match(urlRegexp);
  9273. if (!match) {
  9274. return null;
  9275. }
  9276. return {
  9277. scheme: match[1],
  9278. auth: match[2],
  9279. host: match[3],
  9280. port: match[4],
  9281. path: match[5]
  9282. };
  9283. }
  9284. exports.urlParse = urlParse;
  9285. function urlGenerate(aParsedUrl) {
  9286. var url = '';
  9287. if (aParsedUrl.scheme) {
  9288. url += aParsedUrl.scheme + ':';
  9289. }
  9290. url += '//';
  9291. if (aParsedUrl.auth) {
  9292. url += aParsedUrl.auth + '@';
  9293. }
  9294. if (aParsedUrl.host) {
  9295. url += aParsedUrl.host;
  9296. }
  9297. if (aParsedUrl.port) {
  9298. url += ":" + aParsedUrl.port
  9299. }
  9300. if (aParsedUrl.path) {
  9301. url += aParsedUrl.path;
  9302. }
  9303. return url;
  9304. }
  9305. exports.urlGenerate = urlGenerate;
  9306. /**
  9307. * Normalizes a path, or the path portion of a URL:
  9308. *
  9309. * - Replaces consequtive slashes with one slash.
  9310. * - Removes unnecessary '.' parts.
  9311. * - Removes unnecessary '<dir>/..' parts.
  9312. *
  9313. * Based on code in the Node.js 'path' core module.
  9314. *
  9315. * @param aPath The path or url to normalize.
  9316. */
  9317. function normalize(aPath) {
  9318. var path = aPath;
  9319. var url = urlParse(aPath);
  9320. if (url) {
  9321. if (!url.path) {
  9322. return aPath;
  9323. }
  9324. path = url.path;
  9325. }
  9326. var isAbsolute = exports.isAbsolute(path);
  9327. var parts = path.split(/\/+/);
  9328. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  9329. part = parts[i];
  9330. if (part === '.') {
  9331. parts.splice(i, 1);
  9332. } else if (part === '..') {
  9333. up++;
  9334. } else if (up > 0) {
  9335. if (part === '') {
  9336. // The first part is blank if the path is absolute. Trying to go
  9337. // above the root is a no-op. Therefore we can remove all '..' parts
  9338. // directly after the root.
  9339. parts.splice(i + 1, up);
  9340. up = 0;
  9341. } else {
  9342. parts.splice(i, 2);
  9343. up--;
  9344. }
  9345. }
  9346. }
  9347. path = parts.join('/');
  9348. if (path === '') {
  9349. path = isAbsolute ? '/' : '.';
  9350. }
  9351. if (url) {
  9352. url.path = path;
  9353. return urlGenerate(url);
  9354. }
  9355. return path;
  9356. }
  9357. exports.normalize = normalize;
  9358. /**
  9359. * Joins two paths/URLs.
  9360. *
  9361. * @param aRoot The root path or URL.
  9362. * @param aPath The path or URL to be joined with the root.
  9363. *
  9364. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  9365. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  9366. * first.
  9367. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  9368. * is updated with the result and aRoot is returned. Otherwise the result
  9369. * is returned.
  9370. * - If aPath is absolute, the result is aPath.
  9371. * - Otherwise the two paths are joined with a slash.
  9372. * - Joining for example 'http://' and 'www.example.com' is also supported.
  9373. */
  9374. function join(aRoot, aPath) {
  9375. if (aRoot === "") {
  9376. aRoot = ".";
  9377. }
  9378. if (aPath === "") {
  9379. aPath = ".";
  9380. }
  9381. var aPathUrl = urlParse(aPath);
  9382. var aRootUrl = urlParse(aRoot);
  9383. if (aRootUrl) {
  9384. aRoot = aRootUrl.path || '/';
  9385. }
  9386. // `join(foo, '//www.example.org')`
  9387. if (aPathUrl && !aPathUrl.scheme) {
  9388. if (aRootUrl) {
  9389. aPathUrl.scheme = aRootUrl.scheme;
  9390. }
  9391. return urlGenerate(aPathUrl);
  9392. }
  9393. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  9394. return aPath;
  9395. }
  9396. // `join('http://', 'www.example.com')`
  9397. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  9398. aRootUrl.host = aPath;
  9399. return urlGenerate(aRootUrl);
  9400. }
  9401. var joined = aPath.charAt(0) === '/'
  9402. ? aPath
  9403. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  9404. if (aRootUrl) {
  9405. aRootUrl.path = joined;
  9406. return urlGenerate(aRootUrl);
  9407. }
  9408. return joined;
  9409. }
  9410. exports.join = join;
  9411. exports.isAbsolute = function (aPath) {
  9412. return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
  9413. };
  9414. /**
  9415. * Make a path relative to a URL or another path.
  9416. *
  9417. * @param aRoot The root path or URL.
  9418. * @param aPath The path or URL to be made relative to aRoot.
  9419. */
  9420. function relative(aRoot, aPath) {
  9421. if (aRoot === "") {
  9422. aRoot = ".";
  9423. }
  9424. aRoot = aRoot.replace(/\/$/, '');
  9425. // It is possible for the path to be above the root. In this case, simply
  9426. // checking whether the root is a prefix of the path won't work. Instead, we
  9427. // need to remove components from the root one by one, until either we find
  9428. // a prefix that fits, or we run out of components to remove.
  9429. var level = 0;
  9430. while (aPath.indexOf(aRoot + '/') !== 0) {
  9431. var index = aRoot.lastIndexOf("/");
  9432. if (index < 0) {
  9433. return aPath;
  9434. }
  9435. // If the only part of the root that is left is the scheme (i.e. http://,
  9436. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  9437. // have exhausted all components, so the path is not relative to the root.
  9438. aRoot = aRoot.slice(0, index);
  9439. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  9440. return aPath;
  9441. }
  9442. ++level;
  9443. }
  9444. // Make sure we add a "../" for each component we removed from the root.
  9445. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  9446. }
  9447. exports.relative = relative;
  9448. var supportsNullProto = (function () {
  9449. var obj = Object.create(null);
  9450. return !('__proto__' in obj);
  9451. }());
  9452. function identity (s) {
  9453. return s;
  9454. }
  9455. /**
  9456. * Because behavior goes wacky when you set `__proto__` on objects, we
  9457. * have to prefix all the strings in our set with an arbitrary character.
  9458. *
  9459. * See https://github.com/mozilla/source-map/pull/31 and
  9460. * https://github.com/mozilla/source-map/issues/30
  9461. *
  9462. * @param String aStr
  9463. */
  9464. function toSetString(aStr) {
  9465. if (isProtoString(aStr)) {
  9466. return '$' + aStr;
  9467. }
  9468. return aStr;
  9469. }
  9470. exports.toSetString = supportsNullProto ? identity : toSetString;
  9471. function fromSetString(aStr) {
  9472. if (isProtoString(aStr)) {
  9473. return aStr.slice(1);
  9474. }
  9475. return aStr;
  9476. }
  9477. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  9478. function isProtoString(s) {
  9479. if (!s) {
  9480. return false;
  9481. }
  9482. var length = s.length;
  9483. if (length < 9 /* "__proto__".length */) {
  9484. return false;
  9485. }
  9486. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  9487. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  9488. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  9489. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  9490. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  9491. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  9492. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  9493. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  9494. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  9495. return false;
  9496. }
  9497. for (var i = length - 10; i >= 0; i--) {
  9498. if (s.charCodeAt(i) !== 36 /* '$' */) {
  9499. return false;
  9500. }
  9501. }
  9502. return true;
  9503. }
  9504. /**
  9505. * Comparator between two mappings where the original positions are compared.
  9506. *
  9507. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  9508. * mappings with the same original source/line/column, but different generated
  9509. * line and column the same. Useful when searching for a mapping with a
  9510. * stubbed out mapping.
  9511. */
  9512. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  9513. var cmp = mappingA.source - mappingB.source;
  9514. if (cmp !== 0) {
  9515. return cmp;
  9516. }
  9517. cmp = mappingA.originalLine - mappingB.originalLine;
  9518. if (cmp !== 0) {
  9519. return cmp;
  9520. }
  9521. cmp = mappingA.originalColumn - mappingB.originalColumn;
  9522. if (cmp !== 0 || onlyCompareOriginal) {
  9523. return cmp;
  9524. }
  9525. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  9526. if (cmp !== 0) {
  9527. return cmp;
  9528. }
  9529. cmp = mappingA.generatedLine - mappingB.generatedLine;
  9530. if (cmp !== 0) {
  9531. return cmp;
  9532. }
  9533. return mappingA.name - mappingB.name;
  9534. }
  9535. exports.compareByOriginalPositions = compareByOriginalPositions;
  9536. /**
  9537. * Comparator between two mappings with deflated source and name indices where
  9538. * the generated positions are compared.
  9539. *
  9540. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  9541. * mappings with the same generated line and column, but different
  9542. * source/name/original line and column the same. Useful when searching for a
  9543. * mapping with a stubbed out mapping.
  9544. */
  9545. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  9546. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  9547. if (cmp !== 0) {
  9548. return cmp;
  9549. }
  9550. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  9551. if (cmp !== 0 || onlyCompareGenerated) {
  9552. return cmp;
  9553. }
  9554. cmp = mappingA.source - mappingB.source;
  9555. if (cmp !== 0) {
  9556. return cmp;
  9557. }
  9558. cmp = mappingA.originalLine - mappingB.originalLine;
  9559. if (cmp !== 0) {
  9560. return cmp;
  9561. }
  9562. cmp = mappingA.originalColumn - mappingB.originalColumn;
  9563. if (cmp !== 0) {
  9564. return cmp;
  9565. }
  9566. return mappingA.name - mappingB.name;
  9567. }
  9568. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  9569. function strcmp(aStr1, aStr2) {
  9570. if (aStr1 === aStr2) {
  9571. return 0;
  9572. }
  9573. if (aStr1 > aStr2) {
  9574. return 1;
  9575. }
  9576. return -1;
  9577. }
  9578. /**
  9579. * Comparator between two mappings with inflated source and name strings where
  9580. * the generated positions are compared.
  9581. */
  9582. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  9583. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  9584. if (cmp !== 0) {
  9585. return cmp;
  9586. }
  9587. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  9588. if (cmp !== 0) {
  9589. return cmp;
  9590. }
  9591. cmp = strcmp(mappingA.source, mappingB.source);
  9592. if (cmp !== 0) {
  9593. return cmp;
  9594. }
  9595. cmp = mappingA.originalLine - mappingB.originalLine;
  9596. if (cmp !== 0) {
  9597. return cmp;
  9598. }
  9599. cmp = mappingA.originalColumn - mappingB.originalColumn;
  9600. if (cmp !== 0) {
  9601. return cmp;
  9602. }
  9603. return strcmp(mappingA.name, mappingB.name);
  9604. }
  9605. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  9606. /***/ },
  9607. /* 5 */
  9608. /***/ function(module, exports, __webpack_require__) {
  9609. /* -*- Mode: js; js-indent-level: 2; -*- */
  9610. /*
  9611. * Copyright 2011 Mozilla Foundation and contributors
  9612. * Licensed under the New BSD license. See LICENSE or:
  9613. * http://opensource.org/licenses/BSD-3-Clause
  9614. */
  9615. var util = __webpack_require__(4);
  9616. var has = Object.prototype.hasOwnProperty;
  9617. /**
  9618. * A data structure which is a combination of an array and a set. Adding a new
  9619. * member is O(1), testing for membership is O(1), and finding the index of an
  9620. * element is O(1). Removing elements from the set is not supported. Only
  9621. * strings are supported for membership.
  9622. */
  9623. function ArraySet() {
  9624. this._array = [];
  9625. this._set = Object.create(null);
  9626. }
  9627. /**
  9628. * Static method for creating ArraySet instances from an existing array.
  9629. */
  9630. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  9631. var set = new ArraySet();
  9632. for (var i = 0, len = aArray.length; i < len; i++) {
  9633. set.add(aArray[i], aAllowDuplicates);
  9634. }
  9635. return set;
  9636. };
  9637. /**
  9638. * Return how many unique items are in this ArraySet. If duplicates have been
  9639. * added, than those do not count towards the size.
  9640. *
  9641. * @returns Number
  9642. */
  9643. ArraySet.prototype.size = function ArraySet_size() {
  9644. return Object.getOwnPropertyNames(this._set).length;
  9645. };
  9646. /**
  9647. * Add the given string to this set.
  9648. *
  9649. * @param String aStr
  9650. */
  9651. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  9652. var sStr = util.toSetString(aStr);
  9653. var isDuplicate = has.call(this._set, sStr);
  9654. var idx = this._array.length;
  9655. if (!isDuplicate || aAllowDuplicates) {
  9656. this._array.push(aStr);
  9657. }
  9658. if (!isDuplicate) {
  9659. this._set[sStr] = idx;
  9660. }
  9661. };
  9662. /**
  9663. * Is the given string a member of this set?
  9664. *
  9665. * @param String aStr
  9666. */
  9667. ArraySet.prototype.has = function ArraySet_has(aStr) {
  9668. var sStr = util.toSetString(aStr);
  9669. return has.call(this._set, sStr);
  9670. };
  9671. /**
  9672. * What is the index of the given string in the array?
  9673. *
  9674. * @param String aStr
  9675. */
  9676. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  9677. var sStr = util.toSetString(aStr);
  9678. if (has.call(this._set, sStr)) {
  9679. return this._set[sStr];
  9680. }
  9681. throw new Error('"' + aStr + '" is not in the set.');
  9682. };
  9683. /**
  9684. * What is the element at the given index?
  9685. *
  9686. * @param Number aIdx
  9687. */
  9688. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  9689. if (aIdx >= 0 && aIdx < this._array.length) {
  9690. return this._array[aIdx];
  9691. }
  9692. throw new Error('No element indexed by ' + aIdx);
  9693. };
  9694. /**
  9695. * Returns the array representation of this set (which has the proper indices
  9696. * indicated by indexOf). Note that this is a copy of the internal array used
  9697. * for storing the members so that no one can mess with internal state.
  9698. */
  9699. ArraySet.prototype.toArray = function ArraySet_toArray() {
  9700. return this._array.slice();
  9701. };
  9702. exports.ArraySet = ArraySet;
  9703. /***/ },
  9704. /* 6 */
  9705. /***/ function(module, exports, __webpack_require__) {
  9706. /* -*- Mode: js; js-indent-level: 2; -*- */
  9707. /*
  9708. * Copyright 2014 Mozilla Foundation and contributors
  9709. * Licensed under the New BSD license. See LICENSE or:
  9710. * http://opensource.org/licenses/BSD-3-Clause
  9711. */
  9712. var util = __webpack_require__(4);
  9713. /**
  9714. * Determine whether mappingB is after mappingA with respect to generated
  9715. * position.
  9716. */
  9717. function generatedPositionAfter(mappingA, mappingB) {
  9718. // Optimized for most common case
  9719. var lineA = mappingA.generatedLine;
  9720. var lineB = mappingB.generatedLine;
  9721. var columnA = mappingA.generatedColumn;
  9722. var columnB = mappingB.generatedColumn;
  9723. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  9724. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  9725. }
  9726. /**
  9727. * A data structure to provide a sorted view of accumulated mappings in a
  9728. * performance conscious manner. It trades a neglibable overhead in general
  9729. * case for a large speedup in case of mappings being added in order.
  9730. */
  9731. function MappingList() {
  9732. this._array = [];
  9733. this._sorted = true;
  9734. // Serves as infimum
  9735. this._last = {generatedLine: -1, generatedColumn: 0};
  9736. }
  9737. /**
  9738. * Iterate through internal items. This method takes the same arguments that
  9739. * `Array.prototype.forEach` takes.
  9740. *
  9741. * NOTE: The order of the mappings is NOT guaranteed.
  9742. */
  9743. MappingList.prototype.unsortedForEach =
  9744. function MappingList_forEach(aCallback, aThisArg) {
  9745. this._array.forEach(aCallback, aThisArg);
  9746. };
  9747. /**
  9748. * Add the given source mapping.
  9749. *
  9750. * @param Object aMapping
  9751. */
  9752. MappingList.prototype.add = function MappingList_add(aMapping) {
  9753. if (generatedPositionAfter(this._last, aMapping)) {
  9754. this._last = aMapping;
  9755. this._array.push(aMapping);
  9756. } else {
  9757. this._sorted = false;
  9758. this._array.push(aMapping);
  9759. }
  9760. };
  9761. /**
  9762. * Returns the flat, sorted array of mappings. The mappings are sorted by
  9763. * generated position.
  9764. *
  9765. * WARNING: This method returns internal data without copying, for
  9766. * performance. The return value must NOT be mutated, and should be treated as
  9767. * an immutable borrow. If you want to take ownership, you must make your own
  9768. * copy.
  9769. */
  9770. MappingList.prototype.toArray = function MappingList_toArray() {
  9771. if (!this._sorted) {
  9772. this._array.sort(util.compareByGeneratedPositionsInflated);
  9773. this._sorted = true;
  9774. }
  9775. return this._array;
  9776. };
  9777. exports.MappingList = MappingList;
  9778. /***/ },
  9779. /* 7 */
  9780. /***/ function(module, exports, __webpack_require__) {
  9781. /* -*- Mode: js; js-indent-level: 2; -*- */
  9782. /*
  9783. * Copyright 2011 Mozilla Foundation and contributors
  9784. * Licensed under the New BSD license. See LICENSE or:
  9785. * http://opensource.org/licenses/BSD-3-Clause
  9786. */
  9787. var util = __webpack_require__(4);
  9788. var binarySearch = __webpack_require__(8);
  9789. var ArraySet = __webpack_require__(5).ArraySet;
  9790. var base64VLQ = __webpack_require__(2);
  9791. var quickSort = __webpack_require__(9).quickSort;
  9792. function SourceMapConsumer(aSourceMap) {
  9793. var sourceMap = aSourceMap;
  9794. if (typeof aSourceMap === 'string') {
  9795. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  9796. }
  9797. return sourceMap.sections != null
  9798. ? new IndexedSourceMapConsumer(sourceMap)
  9799. : new BasicSourceMapConsumer(sourceMap);
  9800. }
  9801. SourceMapConsumer.fromSourceMap = function(aSourceMap) {
  9802. return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
  9803. }
  9804. /**
  9805. * The version of the source mapping spec that we are consuming.
  9806. */
  9807. SourceMapConsumer.prototype._version = 3;
  9808. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9809. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9810. // are lazily instantiated, accessed via the `_generatedMappings` and
  9811. // `_originalMappings` getters respectively, and we only parse the mappings
  9812. // and create these arrays once queried for a source location. We jump through
  9813. // these hoops because there can be many thousands of mappings, and parsing
  9814. // them is expensive, so we only want to do it if we must.
  9815. //
  9816. // Each object in the arrays is of the form:
  9817. //
  9818. // {
  9819. // generatedLine: The line number in the generated code,
  9820. // generatedColumn: The column number in the generated code,
  9821. // source: The path to the original source file that generated this
  9822. // chunk of code,
  9823. // originalLine: The line number in the original source that
  9824. // corresponds to this chunk of generated code,
  9825. // originalColumn: The column number in the original source that
  9826. // corresponds to this chunk of generated code,
  9827. // name: The name of the original symbol which generated this chunk of
  9828. // code.
  9829. // }
  9830. //
  9831. // All properties except for `generatedLine` and `generatedColumn` can be
  9832. // `null`.
  9833. //
  9834. // `_generatedMappings` is ordered by the generated positions.
  9835. //
  9836. // `_originalMappings` is ordered by the original positions.
  9837. SourceMapConsumer.prototype.__generatedMappings = null;
  9838. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9839. get: function () {
  9840. if (!this.__generatedMappings) {
  9841. this._parseMappings(this._mappings, this.sourceRoot);
  9842. }
  9843. return this.__generatedMappings;
  9844. }
  9845. });
  9846. SourceMapConsumer.prototype.__originalMappings = null;
  9847. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9848. get: function () {
  9849. if (!this.__originalMappings) {
  9850. this._parseMappings(this._mappings, this.sourceRoot);
  9851. }
  9852. return this.__originalMappings;
  9853. }
  9854. });
  9855. SourceMapConsumer.prototype._charIsMappingSeparator =
  9856. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9857. var c = aStr.charAt(index);
  9858. return c === ";" || c === ",";
  9859. };
  9860. /**
  9861. * Parse the mappings in a string in to a data structure which we can easily
  9862. * query (the ordered arrays in the `this.__generatedMappings` and
  9863. * `this.__originalMappings` properties).
  9864. */
  9865. SourceMapConsumer.prototype._parseMappings =
  9866. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9867. throw new Error("Subclasses must implement _parseMappings");
  9868. };
  9869. SourceMapConsumer.GENERATED_ORDER = 1;
  9870. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9871. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9872. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9873. /**
  9874. * Iterate over each mapping between an original source/line/column and a
  9875. * generated line/column in this source map.
  9876. *
  9877. * @param Function aCallback
  9878. * The function that is called with each mapping.
  9879. * @param Object aContext
  9880. * Optional. If specified, this object will be the value of `this` every
  9881. * time that `aCallback` is called.
  9882. * @param aOrder
  9883. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9884. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9885. * iterate over the mappings sorted by the generated file's line/column
  9886. * order or the original's source/line/column order, respectively. Defaults to
  9887. * `SourceMapConsumer.GENERATED_ORDER`.
  9888. */
  9889. SourceMapConsumer.prototype.eachMapping =
  9890. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9891. var context = aContext || null;
  9892. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9893. var mappings;
  9894. switch (order) {
  9895. case SourceMapConsumer.GENERATED_ORDER:
  9896. mappings = this._generatedMappings;
  9897. break;
  9898. case SourceMapConsumer.ORIGINAL_ORDER:
  9899. mappings = this._originalMappings;
  9900. break;
  9901. default:
  9902. throw new Error("Unknown order of iteration.");
  9903. }
  9904. var sourceRoot = this.sourceRoot;
  9905. mappings.map(function (mapping) {
  9906. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9907. if (source != null && sourceRoot != null) {
  9908. source = util.join(sourceRoot, source);
  9909. }
  9910. return {
  9911. source: source,
  9912. generatedLine: mapping.generatedLine,
  9913. generatedColumn: mapping.generatedColumn,
  9914. originalLine: mapping.originalLine,
  9915. originalColumn: mapping.originalColumn,
  9916. name: mapping.name === null ? null : this._names.at(mapping.name)
  9917. };
  9918. }, this).forEach(aCallback, context);
  9919. };
  9920. /**
  9921. * Returns all generated line and column information for the original source,
  9922. * line, and column provided. If no column is provided, returns all mappings
  9923. * corresponding to a either the line we are searching for or the next
  9924. * closest line that has any mappings. Otherwise, returns all mappings
  9925. * corresponding to the given line and either the column we are searching for
  9926. * or the next closest column that has any offsets.
  9927. *
  9928. * The only argument is an object with the following properties:
  9929. *
  9930. * - source: The filename of the original source.
  9931. * - line: The line number in the original source.
  9932. * - column: Optional. the column number in the original source.
  9933. *
  9934. * and an array of objects is returned, each with the following properties:
  9935. *
  9936. * - line: The line number in the generated source, or null.
  9937. * - column: The column number in the generated source, or null.
  9938. */
  9939. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  9940. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9941. var line = util.getArg(aArgs, 'line');
  9942. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9943. // returns the index of the closest mapping less than the needle. By
  9944. // setting needle.originalColumn to 0, we thus find the last mapping for
  9945. // the given line, provided such a mapping exists.
  9946. var needle = {
  9947. source: util.getArg(aArgs, 'source'),
  9948. originalLine: line,
  9949. originalColumn: util.getArg(aArgs, 'column', 0)
  9950. };
  9951. if (this.sourceRoot != null) {
  9952. needle.source = util.relative(this.sourceRoot, needle.source);
  9953. }
  9954. if (!this._sources.has(needle.source)) {
  9955. return [];
  9956. }
  9957. needle.source = this._sources.indexOf(needle.source);
  9958. var mappings = [];
  9959. var index = this._findMapping(needle,
  9960. this._originalMappings,
  9961. "originalLine",
  9962. "originalColumn",
  9963. util.compareByOriginalPositions,
  9964. binarySearch.LEAST_UPPER_BOUND);
  9965. if (index >= 0) {
  9966. var mapping = this._originalMappings[index];
  9967. if (aArgs.column === undefined) {
  9968. var originalLine = mapping.originalLine;
  9969. // Iterate until either we run out of mappings, or we run into
  9970. // a mapping for a different line than the one we found. Since
  9971. // mappings are sorted, this is guaranteed to find all mappings for
  9972. // the line we found.
  9973. while (mapping && mapping.originalLine === originalLine) {
  9974. mappings.push({
  9975. line: util.getArg(mapping, 'generatedLine', null),
  9976. column: util.getArg(mapping, 'generatedColumn', null),
  9977. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9978. });
  9979. mapping = this._originalMappings[++index];
  9980. }
  9981. } else {
  9982. var originalColumn = mapping.originalColumn;
  9983. // Iterate until either we run out of mappings, or we run into
  9984. // a mapping for a different line than the one we were searching for.
  9985. // Since mappings are sorted, this is guaranteed to find all mappings for
  9986. // the line we are searching for.
  9987. while (mapping &&
  9988. mapping.originalLine === line &&
  9989. mapping.originalColumn == originalColumn) {
  9990. mappings.push({
  9991. line: util.getArg(mapping, 'generatedLine', null),
  9992. column: util.getArg(mapping, 'generatedColumn', null),
  9993. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9994. });
  9995. mapping = this._originalMappings[++index];
  9996. }
  9997. }
  9998. }
  9999. return mappings;
  10000. };
  10001. exports.SourceMapConsumer = SourceMapConsumer;
  10002. /**
  10003. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  10004. * query for information about the original file positions by giving it a file
  10005. * position in the generated source.
  10006. *
  10007. * The only parameter is the raw source map (either as a JSON string, or
  10008. * already parsed to an object). According to the spec, source maps have the
  10009. * following attributes:
  10010. *
  10011. * - version: Which version of the source map spec this map is following.
  10012. * - sources: An array of URLs to the original source files.
  10013. * - names: An array of identifiers which can be referrenced by individual mappings.
  10014. * - sourceRoot: Optional. The URL root from which all sources are relative.
  10015. * - sourcesContent: Optional. An array of contents of the original source files.
  10016. * - mappings: A string of base64 VLQs which contain the actual mappings.
  10017. * - file: Optional. The generated file this source map is associated with.
  10018. *
  10019. * Here is an example source map, taken from the source map spec[0]:
  10020. *
  10021. * {
  10022. * version : 3,
  10023. * file: "out.js",
  10024. * sourceRoot : "",
  10025. * sources: ["foo.js", "bar.js"],
  10026. * names: ["src", "maps", "are", "fun"],
  10027. * mappings: "AA,AB;;ABCDE;"
  10028. * }
  10029. *
  10030. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  10031. */
  10032. function BasicSourceMapConsumer(aSourceMap) {
  10033. var sourceMap = aSourceMap;
  10034. if (typeof aSourceMap === 'string') {
  10035. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  10036. }
  10037. var version = util.getArg(sourceMap, 'version');
  10038. var sources = util.getArg(sourceMap, 'sources');
  10039. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  10040. // requires the array) to play nice here.
  10041. var names = util.getArg(sourceMap, 'names', []);
  10042. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  10043. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  10044. var mappings = util.getArg(sourceMap, 'mappings');
  10045. var file = util.getArg(sourceMap, 'file', null);
  10046. // Once again, Sass deviates from the spec and supplies the version as a
  10047. // string rather than a number, so we use loose equality checking here.
  10048. if (version != this._version) {
  10049. throw new Error('Unsupported version: ' + version);
  10050. }
  10051. sources = sources
  10052. .map(String)
  10053. // Some source maps produce relative source paths like "./foo.js" instead of
  10054. // "foo.js". Normalize these first so that future comparisons will succeed.
  10055. // See bugzil.la/1090768.
  10056. .map(util.normalize)
  10057. // Always ensure that absolute sources are internally stored relative to
  10058. // the source root, if the source root is absolute. Not doing this would
  10059. // be particularly problematic when the source root is a prefix of the
  10060. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  10061. .map(function (source) {
  10062. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  10063. ? util.relative(sourceRoot, source)
  10064. : source;
  10065. });
  10066. // Pass `true` below to allow duplicate names and sources. While source maps
  10067. // are intended to be compressed and deduplicated, the TypeScript compiler
  10068. // sometimes generates source maps with duplicates in them. See Github issue
  10069. // #72 and bugzil.la/889492.
  10070. this._names = ArraySet.fromArray(names.map(String), true);
  10071. this._sources = ArraySet.fromArray(sources, true);
  10072. this.sourceRoot = sourceRoot;
  10073. this.sourcesContent = sourcesContent;
  10074. this._mappings = mappings;
  10075. this.file = file;
  10076. }
  10077. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  10078. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  10079. /**
  10080. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  10081. *
  10082. * @param SourceMapGenerator aSourceMap
  10083. * The source map that will be consumed.
  10084. * @returns BasicSourceMapConsumer
  10085. */
  10086. BasicSourceMapConsumer.fromSourceMap =
  10087. function SourceMapConsumer_fromSourceMap(aSourceMap) {
  10088. var smc = Object.create(BasicSourceMapConsumer.prototype);
  10089. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  10090. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  10091. smc.sourceRoot = aSourceMap._sourceRoot;
  10092. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  10093. smc.sourceRoot);
  10094. smc.file = aSourceMap._file;
  10095. // Because we are modifying the entries (by converting string sources and
  10096. // names to indices into the sources and names ArraySets), we have to make
  10097. // a copy of the entry or else bad things happen. Shared mutable state
  10098. // strikes again! See github issue #191.
  10099. var generatedMappings = aSourceMap._mappings.toArray().slice();
  10100. var destGeneratedMappings = smc.__generatedMappings = [];
  10101. var destOriginalMappings = smc.__originalMappings = [];
  10102. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  10103. var srcMapping = generatedMappings[i];
  10104. var destMapping = new Mapping;
  10105. destMapping.generatedLine = srcMapping.generatedLine;
  10106. destMapping.generatedColumn = srcMapping.generatedColumn;
  10107. if (srcMapping.source) {
  10108. destMapping.source = sources.indexOf(srcMapping.source);
  10109. destMapping.originalLine = srcMapping.originalLine;
  10110. destMapping.originalColumn = srcMapping.originalColumn;
  10111. if (srcMapping.name) {
  10112. destMapping.name = names.indexOf(srcMapping.name);
  10113. }
  10114. destOriginalMappings.push(destMapping);
  10115. }
  10116. destGeneratedMappings.push(destMapping);
  10117. }
  10118. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  10119. return smc;
  10120. };
  10121. /**
  10122. * The version of the source mapping spec that we are consuming.
  10123. */
  10124. BasicSourceMapConsumer.prototype._version = 3;
  10125. /**
  10126. * The list of original sources.
  10127. */
  10128. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  10129. get: function () {
  10130. return this._sources.toArray().map(function (s) {
  10131. return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
  10132. }, this);
  10133. }
  10134. });
  10135. /**
  10136. * Provide the JIT with a nice shape / hidden class.
  10137. */
  10138. function Mapping() {
  10139. this.generatedLine = 0;
  10140. this.generatedColumn = 0;
  10141. this.source = null;
  10142. this.originalLine = null;
  10143. this.originalColumn = null;
  10144. this.name = null;
  10145. }
  10146. /**
  10147. * Parse the mappings in a string in to a data structure which we can easily
  10148. * query (the ordered arrays in the `this.__generatedMappings` and
  10149. * `this.__originalMappings` properties).
  10150. */
  10151. BasicSourceMapConsumer.prototype._parseMappings =
  10152. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10153. var generatedLine = 1;
  10154. var previousGeneratedColumn = 0;
  10155. var previousOriginalLine = 0;
  10156. var previousOriginalColumn = 0;
  10157. var previousSource = 0;
  10158. var previousName = 0;
  10159. var length = aStr.length;
  10160. var index = 0;
  10161. var cachedSegments = {};
  10162. var temp = {};
  10163. var originalMappings = [];
  10164. var generatedMappings = [];
  10165. var mapping, str, segment, end, value;
  10166. while (index < length) {
  10167. if (aStr.charAt(index) === ';') {
  10168. generatedLine++;
  10169. index++;
  10170. previousGeneratedColumn = 0;
  10171. }
  10172. else if (aStr.charAt(index) === ',') {
  10173. index++;
  10174. }
  10175. else {
  10176. mapping = new Mapping();
  10177. mapping.generatedLine = generatedLine;
  10178. // Because each offset is encoded relative to the previous one,
  10179. // many segments often have the same encoding. We can exploit this
  10180. // fact by caching the parsed variable length fields of each segment,
  10181. // allowing us to avoid a second parse if we encounter the same
  10182. // segment again.
  10183. for (end = index; end < length; end++) {
  10184. if (this._charIsMappingSeparator(aStr, end)) {
  10185. break;
  10186. }
  10187. }
  10188. str = aStr.slice(index, end);
  10189. segment = cachedSegments[str];
  10190. if (segment) {
  10191. index += str.length;
  10192. } else {
  10193. segment = [];
  10194. while (index < end) {
  10195. base64VLQ.decode(aStr, index, temp);
  10196. value = temp.value;
  10197. index = temp.rest;
  10198. segment.push(value);
  10199. }
  10200. if (segment.length === 2) {
  10201. throw new Error('Found a source, but no line and column');
  10202. }
  10203. if (segment.length === 3) {
  10204. throw new Error('Found a source and line, but no column');
  10205. }
  10206. cachedSegments[str] = segment;
  10207. }
  10208. // Generated column.
  10209. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  10210. previousGeneratedColumn = mapping.generatedColumn;
  10211. if (segment.length > 1) {
  10212. // Original source.
  10213. mapping.source = previousSource + segment[1];
  10214. previousSource += segment[1];
  10215. // Original line.
  10216. mapping.originalLine = previousOriginalLine + segment[2];
  10217. previousOriginalLine = mapping.originalLine;
  10218. // Lines are stored 0-based
  10219. mapping.originalLine += 1;
  10220. // Original column.
  10221. mapping.originalColumn = previousOriginalColumn + segment[3];
  10222. previousOriginalColumn = mapping.originalColumn;
  10223. if (segment.length > 4) {
  10224. // Original name.
  10225. mapping.name = previousName + segment[4];
  10226. previousName += segment[4];
  10227. }
  10228. }
  10229. generatedMappings.push(mapping);
  10230. if (typeof mapping.originalLine === 'number') {
  10231. originalMappings.push(mapping);
  10232. }
  10233. }
  10234. }
  10235. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  10236. this.__generatedMappings = generatedMappings;
  10237. quickSort(originalMappings, util.compareByOriginalPositions);
  10238. this.__originalMappings = originalMappings;
  10239. };
  10240. /**
  10241. * Find the mapping that best matches the hypothetical "needle" mapping that
  10242. * we are searching for in the given "haystack" of mappings.
  10243. */
  10244. BasicSourceMapConsumer.prototype._findMapping =
  10245. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  10246. aColumnName, aComparator, aBias) {
  10247. // To return the position we are searching for, we must first find the
  10248. // mapping for the given position and then return the opposite position it
  10249. // points to. Because the mappings are sorted, we can use binary search to
  10250. // find the best mapping.
  10251. if (aNeedle[aLineName] <= 0) {
  10252. throw new TypeError('Line must be greater than or equal to 1, got '
  10253. + aNeedle[aLineName]);
  10254. }
  10255. if (aNeedle[aColumnName] < 0) {
  10256. throw new TypeError('Column must be greater than or equal to 0, got '
  10257. + aNeedle[aColumnName]);
  10258. }
  10259. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  10260. };
  10261. /**
  10262. * Compute the last column for each generated mapping. The last column is
  10263. * inclusive.
  10264. */
  10265. BasicSourceMapConsumer.prototype.computeColumnSpans =
  10266. function SourceMapConsumer_computeColumnSpans() {
  10267. for (var index = 0; index < this._generatedMappings.length; ++index) {
  10268. var mapping = this._generatedMappings[index];
  10269. // Mappings do not contain a field for the last generated columnt. We
  10270. // can come up with an optimistic estimate, however, by assuming that
  10271. // mappings are contiguous (i.e. given two consecutive mappings, the
  10272. // first mapping ends where the second one starts).
  10273. if (index + 1 < this._generatedMappings.length) {
  10274. var nextMapping = this._generatedMappings[index + 1];
  10275. if (mapping.generatedLine === nextMapping.generatedLine) {
  10276. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  10277. continue;
  10278. }
  10279. }
  10280. // The last mapping for each line spans the entire line.
  10281. mapping.lastGeneratedColumn = Infinity;
  10282. }
  10283. };
  10284. /**
  10285. * Returns the original source, line, and column information for the generated
  10286. * source's line and column positions provided. The only argument is an object
  10287. * with the following properties:
  10288. *
  10289. * - line: The line number in the generated source.
  10290. * - column: The column number in the generated source.
  10291. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  10292. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  10293. * closest element that is smaller than or greater than the one we are
  10294. * searching for, respectively, if the exact element cannot be found.
  10295. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  10296. *
  10297. * and an object is returned with the following properties:
  10298. *
  10299. * - source: The original source file, or null.
  10300. * - line: The line number in the original source, or null.
  10301. * - column: The column number in the original source, or null.
  10302. * - name: The original identifier, or null.
  10303. */
  10304. BasicSourceMapConsumer.prototype.originalPositionFor =
  10305. function SourceMapConsumer_originalPositionFor(aArgs) {
  10306. var needle = {
  10307. generatedLine: util.getArg(aArgs, 'line'),
  10308. generatedColumn: util.getArg(aArgs, 'column')
  10309. };
  10310. var index = this._findMapping(
  10311. needle,
  10312. this._generatedMappings,
  10313. "generatedLine",
  10314. "generatedColumn",
  10315. util.compareByGeneratedPositionsDeflated,
  10316. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  10317. );
  10318. if (index >= 0) {
  10319. var mapping = this._generatedMappings[index];
  10320. if (mapping.generatedLine === needle.generatedLine) {
  10321. var source = util.getArg(mapping, 'source', null);
  10322. if (source !== null) {
  10323. source = this._sources.at(source);
  10324. if (this.sourceRoot != null) {
  10325. source = util.join(this.sourceRoot, source);
  10326. }
  10327. }
  10328. var name = util.getArg(mapping, 'name', null);
  10329. if (name !== null) {
  10330. name = this._names.at(name);
  10331. }
  10332. return {
  10333. source: source,
  10334. line: util.getArg(mapping, 'originalLine', null),
  10335. column: util.getArg(mapping, 'originalColumn', null),
  10336. name: name
  10337. };
  10338. }
  10339. }
  10340. return {
  10341. source: null,
  10342. line: null,
  10343. column: null,
  10344. name: null
  10345. };
  10346. };
  10347. /**
  10348. * Return true if we have the source content for every source in the source
  10349. * map, false otherwise.
  10350. */
  10351. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  10352. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  10353. if (!this.sourcesContent) {
  10354. return false;
  10355. }
  10356. return this.sourcesContent.length >= this._sources.size() &&
  10357. !this.sourcesContent.some(function (sc) { return sc == null; });
  10358. };
  10359. /**
  10360. * Returns the original source content. The only argument is the url of the
  10361. * original source file. Returns null if no original source content is
  10362. * available.
  10363. */
  10364. BasicSourceMapConsumer.prototype.sourceContentFor =
  10365. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10366. if (!this.sourcesContent) {
  10367. return null;
  10368. }
  10369. if (this.sourceRoot != null) {
  10370. aSource = util.relative(this.sourceRoot, aSource);
  10371. }
  10372. if (this._sources.has(aSource)) {
  10373. return this.sourcesContent[this._sources.indexOf(aSource)];
  10374. }
  10375. var url;
  10376. if (this.sourceRoot != null
  10377. && (url = util.urlParse(this.sourceRoot))) {
  10378. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  10379. // many users. We can help them out when they expect file:// URIs to
  10380. // behave like it would if they were running a local HTTP server. See
  10381. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  10382. var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
  10383. if (url.scheme == "file"
  10384. && this._sources.has(fileUriAbsPath)) {
  10385. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  10386. }
  10387. if ((!url.path || url.path == "/")
  10388. && this._sources.has("/" + aSource)) {
  10389. return this.sourcesContent[this._sources.indexOf("/" + aSource)];
  10390. }
  10391. }
  10392. // This function is used recursively from
  10393. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  10394. // don't want to throw if we can't find the source - we just want to
  10395. // return null, so we provide a flag to exit gracefully.
  10396. if (nullOnMissing) {
  10397. return null;
  10398. }
  10399. else {
  10400. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10401. }
  10402. };
  10403. /**
  10404. * Returns the generated line and column information for the original source,
  10405. * line, and column positions provided. The only argument is an object with
  10406. * the following properties:
  10407. *
  10408. * - source: The filename of the original source.
  10409. * - line: The line number in the original source.
  10410. * - column: The column number in the original source.
  10411. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  10412. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  10413. * closest element that is smaller than or greater than the one we are
  10414. * searching for, respectively, if the exact element cannot be found.
  10415. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  10416. *
  10417. * and an object is returned with the following properties:
  10418. *
  10419. * - line: The line number in the generated source, or null.
  10420. * - column: The column number in the generated source, or null.
  10421. */
  10422. BasicSourceMapConsumer.prototype.generatedPositionFor =
  10423. function SourceMapConsumer_generatedPositionFor(aArgs) {
  10424. var source = util.getArg(aArgs, 'source');
  10425. if (this.sourceRoot != null) {
  10426. source = util.relative(this.sourceRoot, source);
  10427. }
  10428. if (!this._sources.has(source)) {
  10429. return {
  10430. line: null,
  10431. column: null,
  10432. lastColumn: null
  10433. };
  10434. }
  10435. source = this._sources.indexOf(source);
  10436. var needle = {
  10437. source: source,
  10438. originalLine: util.getArg(aArgs, 'line'),
  10439. originalColumn: util.getArg(aArgs, 'column')
  10440. };
  10441. var index = this._findMapping(
  10442. needle,
  10443. this._originalMappings,
  10444. "originalLine",
  10445. "originalColumn",
  10446. util.compareByOriginalPositions,
  10447. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  10448. );
  10449. if (index >= 0) {
  10450. var mapping = this._originalMappings[index];
  10451. if (mapping.source === needle.source) {
  10452. return {
  10453. line: util.getArg(mapping, 'generatedLine', null),
  10454. column: util.getArg(mapping, 'generatedColumn', null),
  10455. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  10456. };
  10457. }
  10458. }
  10459. return {
  10460. line: null,
  10461. column: null,
  10462. lastColumn: null
  10463. };
  10464. };
  10465. exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
  10466. /**
  10467. * An IndexedSourceMapConsumer instance represents a parsed source map which
  10468. * we can query for information. It differs from BasicSourceMapConsumer in
  10469. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  10470. * input.
  10471. *
  10472. * The only parameter is a raw source map (either as a JSON string, or already
  10473. * parsed to an object). According to the spec for indexed source maps, they
  10474. * have the following attributes:
  10475. *
  10476. * - version: Which version of the source map spec this map is following.
  10477. * - file: Optional. The generated file this source map is associated with.
  10478. * - sections: A list of section definitions.
  10479. *
  10480. * Each value under the "sections" field has two fields:
  10481. * - offset: The offset into the original specified at which this section
  10482. * begins to apply, defined as an object with a "line" and "column"
  10483. * field.
  10484. * - map: A source map definition. This source map could also be indexed,
  10485. * but doesn't have to be.
  10486. *
  10487. * Instead of the "map" field, it's also possible to have a "url" field
  10488. * specifying a URL to retrieve a source map from, but that's currently
  10489. * unsupported.
  10490. *
  10491. * Here's an example source map, taken from the source map spec[0], but
  10492. * modified to omit a section which uses the "url" field.
  10493. *
  10494. * {
  10495. * version : 3,
  10496. * file: "app.js",
  10497. * sections: [{
  10498. * offset: {line:100, column:10},
  10499. * map: {
  10500. * version : 3,
  10501. * file: "section.js",
  10502. * sources: ["foo.js", "bar.js"],
  10503. * names: ["src", "maps", "are", "fun"],
  10504. * mappings: "AAAA,E;;ABCDE;"
  10505. * }
  10506. * }],
  10507. * }
  10508. *
  10509. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  10510. */
  10511. function IndexedSourceMapConsumer(aSourceMap) {
  10512. var sourceMap = aSourceMap;
  10513. if (typeof aSourceMap === 'string') {
  10514. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  10515. }
  10516. var version = util.getArg(sourceMap, 'version');
  10517. var sections = util.getArg(sourceMap, 'sections');
  10518. if (version != this._version) {
  10519. throw new Error('Unsupported version: ' + version);
  10520. }
  10521. this._sources = new ArraySet();
  10522. this._names = new ArraySet();
  10523. var lastOffset = {
  10524. line: -1,
  10525. column: 0
  10526. };
  10527. this._sections = sections.map(function (s) {
  10528. if (s.url) {
  10529. // The url field will require support for asynchronicity.
  10530. // See https://github.com/mozilla/source-map/issues/16
  10531. throw new Error('Support for url field in sections not implemented.');
  10532. }
  10533. var offset = util.getArg(s, 'offset');
  10534. var offsetLine = util.getArg(offset, 'line');
  10535. var offsetColumn = util.getArg(offset, 'column');
  10536. if (offsetLine < lastOffset.line ||
  10537. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  10538. throw new Error('Section offsets must be ordered and non-overlapping.');
  10539. }
  10540. lastOffset = offset;
  10541. return {
  10542. generatedOffset: {
  10543. // The offset fields are 0-based, but we use 1-based indices when
  10544. // encoding/decoding from VLQ.
  10545. generatedLine: offsetLine + 1,
  10546. generatedColumn: offsetColumn + 1
  10547. },
  10548. consumer: new SourceMapConsumer(util.getArg(s, 'map'))
  10549. }
  10550. });
  10551. }
  10552. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  10553. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  10554. /**
  10555. * The version of the source mapping spec that we are consuming.
  10556. */
  10557. IndexedSourceMapConsumer.prototype._version = 3;
  10558. /**
  10559. * The list of original sources.
  10560. */
  10561. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  10562. get: function () {
  10563. var sources = [];
  10564. for (var i = 0; i < this._sections.length; i++) {
  10565. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  10566. sources.push(this._sections[i].consumer.sources[j]);
  10567. }
  10568. }
  10569. return sources;
  10570. }
  10571. });
  10572. /**
  10573. * Returns the original source, line, and column information for the generated
  10574. * source's line and column positions provided. The only argument is an object
  10575. * with the following properties:
  10576. *
  10577. * - line: The line number in the generated source.
  10578. * - column: The column number in the generated source.
  10579. *
  10580. * and an object is returned with the following properties:
  10581. *
  10582. * - source: The original source file, or null.
  10583. * - line: The line number in the original source, or null.
  10584. * - column: The column number in the original source, or null.
  10585. * - name: The original identifier, or null.
  10586. */
  10587. IndexedSourceMapConsumer.prototype.originalPositionFor =
  10588. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  10589. var needle = {
  10590. generatedLine: util.getArg(aArgs, 'line'),
  10591. generatedColumn: util.getArg(aArgs, 'column')
  10592. };
  10593. // Find the section containing the generated position we're trying to map
  10594. // to an original position.
  10595. var sectionIndex = binarySearch.search(needle, this._sections,
  10596. function(needle, section) {
  10597. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  10598. if (cmp) {
  10599. return cmp;
  10600. }
  10601. return (needle.generatedColumn -
  10602. section.generatedOffset.generatedColumn);
  10603. });
  10604. var section = this._sections[sectionIndex];
  10605. if (!section) {
  10606. return {
  10607. source: null,
  10608. line: null,
  10609. column: null,
  10610. name: null
  10611. };
  10612. }
  10613. return section.consumer.originalPositionFor({
  10614. line: needle.generatedLine -
  10615. (section.generatedOffset.generatedLine - 1),
  10616. column: needle.generatedColumn -
  10617. (section.generatedOffset.generatedLine === needle.generatedLine
  10618. ? section.generatedOffset.generatedColumn - 1
  10619. : 0),
  10620. bias: aArgs.bias
  10621. });
  10622. };
  10623. /**
  10624. * Return true if we have the source content for every source in the source
  10625. * map, false otherwise.
  10626. */
  10627. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10628. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10629. return this._sections.every(function (s) {
  10630. return s.consumer.hasContentsOfAllSources();
  10631. });
  10632. };
  10633. /**
  10634. * Returns the original source content. The only argument is the url of the
  10635. * original source file. Returns null if no original source content is
  10636. * available.
  10637. */
  10638. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10639. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10640. for (var i = 0; i < this._sections.length; i++) {
  10641. var section = this._sections[i];
  10642. var content = section.consumer.sourceContentFor(aSource, true);
  10643. if (content) {
  10644. return content;
  10645. }
  10646. }
  10647. if (nullOnMissing) {
  10648. return null;
  10649. }
  10650. else {
  10651. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10652. }
  10653. };
  10654. /**
  10655. * Returns the generated line and column information for the original source,
  10656. * line, and column positions provided. The only argument is an object with
  10657. * the following properties:
  10658. *
  10659. * - source: The filename of the original source.
  10660. * - line: The line number in the original source.
  10661. * - column: The column number in the original source.
  10662. *
  10663. * and an object is returned with the following properties:
  10664. *
  10665. * - line: The line number in the generated source, or null.
  10666. * - column: The column number in the generated source, or null.
  10667. */
  10668. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10669. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10670. for (var i = 0; i < this._sections.length; i++) {
  10671. var section = this._sections[i];
  10672. // Only consider this section if the requested source is in the list of
  10673. // sources of the consumer.
  10674. if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {
  10675. continue;
  10676. }
  10677. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10678. if (generatedPosition) {
  10679. var ret = {
  10680. line: generatedPosition.line +
  10681. (section.generatedOffset.generatedLine - 1),
  10682. column: generatedPosition.column +
  10683. (section.generatedOffset.generatedLine === generatedPosition.line
  10684. ? section.generatedOffset.generatedColumn - 1
  10685. : 0)
  10686. };
  10687. return ret;
  10688. }
  10689. }
  10690. return {
  10691. line: null,
  10692. column: null
  10693. };
  10694. };
  10695. /**
  10696. * Parse the mappings in a string in to a data structure which we can easily
  10697. * query (the ordered arrays in the `this.__generatedMappings` and
  10698. * `this.__originalMappings` properties).
  10699. */
  10700. IndexedSourceMapConsumer.prototype._parseMappings =
  10701. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10702. this.__generatedMappings = [];
  10703. this.__originalMappings = [];
  10704. for (var i = 0; i < this._sections.length; i++) {
  10705. var section = this._sections[i];
  10706. var sectionMappings = section.consumer._generatedMappings;
  10707. for (var j = 0; j < sectionMappings.length; j++) {
  10708. var mapping = sectionMappings[j];
  10709. var source = section.consumer._sources.at(mapping.source);
  10710. if (section.consumer.sourceRoot !== null) {
  10711. source = util.join(section.consumer.sourceRoot, source);
  10712. }
  10713. this._sources.add(source);
  10714. source = this._sources.indexOf(source);
  10715. var name = section.consumer._names.at(mapping.name);
  10716. this._names.add(name);
  10717. name = this._names.indexOf(name);
  10718. // The mappings coming from the consumer for the section have
  10719. // generated positions relative to the start of the section, so we
  10720. // need to offset them to be relative to the start of the concatenated
  10721. // generated file.
  10722. var adjustedMapping = {
  10723. source: source,
  10724. generatedLine: mapping.generatedLine +
  10725. (section.generatedOffset.generatedLine - 1),
  10726. generatedColumn: mapping.generatedColumn +
  10727. (section.generatedOffset.generatedLine === mapping.generatedLine
  10728. ? section.generatedOffset.generatedColumn - 1
  10729. : 0),
  10730. originalLine: mapping.originalLine,
  10731. originalColumn: mapping.originalColumn,
  10732. name: name
  10733. };
  10734. this.__generatedMappings.push(adjustedMapping);
  10735. if (typeof adjustedMapping.originalLine === 'number') {
  10736. this.__originalMappings.push(adjustedMapping);
  10737. }
  10738. }
  10739. }
  10740. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10741. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10742. };
  10743. exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10744. /***/ },
  10745. /* 8 */
  10746. /***/ function(module, exports) {
  10747. /* -*- Mode: js; js-indent-level: 2; -*- */
  10748. /*
  10749. * Copyright 2011 Mozilla Foundation and contributors
  10750. * Licensed under the New BSD license. See LICENSE or:
  10751. * http://opensource.org/licenses/BSD-3-Clause
  10752. */
  10753. exports.GREATEST_LOWER_BOUND = 1;
  10754. exports.LEAST_UPPER_BOUND = 2;
  10755. /**
  10756. * Recursive implementation of binary search.
  10757. *
  10758. * @param aLow Indices here and lower do not contain the needle.
  10759. * @param aHigh Indices here and higher do not contain the needle.
  10760. * @param aNeedle The element being searched for.
  10761. * @param aHaystack The non-empty array being searched.
  10762. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  10763. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  10764. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  10765. * closest element that is smaller than or greater than the one we are
  10766. * searching for, respectively, if the exact element cannot be found.
  10767. */
  10768. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  10769. // This function terminates when one of the following is true:
  10770. //
  10771. // 1. We find the exact element we are looking for.
  10772. //
  10773. // 2. We did not find the exact element, but we can return the index of
  10774. // the next-closest element.
  10775. //
  10776. // 3. We did not find the exact element, and there is no next-closest
  10777. // element than the one we are searching for, so we return -1.
  10778. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  10779. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  10780. if (cmp === 0) {
  10781. // Found the element we are looking for.
  10782. return mid;
  10783. }
  10784. else if (cmp > 0) {
  10785. // Our needle is greater than aHaystack[mid].
  10786. if (aHigh - mid > 1) {
  10787. // The element is in the upper half.
  10788. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  10789. }
  10790. // The exact needle element was not found in this haystack. Determine if
  10791. // we are in termination case (3) or (2) and return the appropriate thing.
  10792. if (aBias == exports.LEAST_UPPER_BOUND) {
  10793. return aHigh < aHaystack.length ? aHigh : -1;
  10794. } else {
  10795. return mid;
  10796. }
  10797. }
  10798. else {
  10799. // Our needle is less than aHaystack[mid].
  10800. if (mid - aLow > 1) {
  10801. // The element is in the lower half.
  10802. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  10803. }
  10804. // we are in termination case (3) or (2) and return the appropriate thing.
  10805. if (aBias == exports.LEAST_UPPER_BOUND) {
  10806. return mid;
  10807. } else {
  10808. return aLow < 0 ? -1 : aLow;
  10809. }
  10810. }
  10811. }
  10812. /**
  10813. * This is an implementation of binary search which will always try and return
  10814. * the index of the closest element if there is no exact hit. This is because
  10815. * mappings between original and generated line/col pairs are single points,
  10816. * and there is an implicit region between each of them, so a miss just means
  10817. * that you aren't on the very start of a region.
  10818. *
  10819. * @param aNeedle The element you are looking for.
  10820. * @param aHaystack The array that is being searched.
  10821. * @param aCompare A function which takes the needle and an element in the
  10822. * array and returns -1, 0, or 1 depending on whether the needle is less
  10823. * than, equal to, or greater than the element, respectively.
  10824. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  10825. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  10826. * closest element that is smaller than or greater than the one we are
  10827. * searching for, respectively, if the exact element cannot be found.
  10828. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  10829. */
  10830. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  10831. if (aHaystack.length === 0) {
  10832. return -1;
  10833. }
  10834. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  10835. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  10836. if (index < 0) {
  10837. return -1;
  10838. }
  10839. // We have found either the exact element, or the next-closest element than
  10840. // the one we are searching for. However, there may be more than one such
  10841. // element. Make sure we always return the smallest of these.
  10842. while (index - 1 >= 0) {
  10843. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  10844. break;
  10845. }
  10846. --index;
  10847. }
  10848. return index;
  10849. };
  10850. /***/ },
  10851. /* 9 */
  10852. /***/ function(module, exports) {
  10853. /* -*- Mode: js; js-indent-level: 2; -*- */
  10854. /*
  10855. * Copyright 2011 Mozilla Foundation and contributors
  10856. * Licensed under the New BSD license. See LICENSE or:
  10857. * http://opensource.org/licenses/BSD-3-Clause
  10858. */
  10859. // It turns out that some (most?) JavaScript engines don't self-host
  10860. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  10861. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  10862. // custom comparator function, calling back and forth between the VM's C++ and
  10863. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  10864. // worse generated code for the comparator function than would be optimal. In
  10865. // fact, when sorting with a comparator, these costs outweigh the benefits of
  10866. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  10867. // a ~3500ms mean speed-up in `bench/bench.html`.
  10868. /**
  10869. * Swap the elements indexed by `x` and `y` in the array `ary`.
  10870. *
  10871. * @param {Array} ary
  10872. * The array.
  10873. * @param {Number} x
  10874. * The index of the first item.
  10875. * @param {Number} y
  10876. * The index of the second item.
  10877. */
  10878. function swap(ary, x, y) {
  10879. var temp = ary[x];
  10880. ary[x] = ary[y];
  10881. ary[y] = temp;
  10882. }
  10883. /**
  10884. * Returns a random integer within the range `low .. high` inclusive.
  10885. *
  10886. * @param {Number} low
  10887. * The lower bound on the range.
  10888. * @param {Number} high
  10889. * The upper bound on the range.
  10890. */
  10891. function randomIntInRange(low, high) {
  10892. return Math.round(low + (Math.random() * (high - low)));
  10893. }
  10894. /**
  10895. * The Quick Sort algorithm.
  10896. *
  10897. * @param {Array} ary
  10898. * An array to sort.
  10899. * @param {function} comparator
  10900. * Function to use to compare two items.
  10901. * @param {Number} p
  10902. * Start index of the array
  10903. * @param {Number} r
  10904. * End index of the array
  10905. */
  10906. function doQuickSort(ary, comparator, p, r) {
  10907. // If our lower bound is less than our upper bound, we (1) partition the
  10908. // array into two pieces and (2) recurse on each half. If it is not, this is
  10909. // the empty array and our base case.
  10910. if (p < r) {
  10911. // (1) Partitioning.
  10912. //
  10913. // The partitioning chooses a pivot between `p` and `r` and moves all
  10914. // elements that are less than or equal to the pivot to the before it, and
  10915. // all the elements that are greater than it after it. The effect is that
  10916. // once partition is done, the pivot is in the exact place it will be when
  10917. // the array is put in sorted order, and it will not need to be moved
  10918. // again. This runs in O(n) time.
  10919. // Always choose a random pivot so that an input array which is reverse
  10920. // sorted does not cause O(n^2) running time.
  10921. var pivotIndex = randomIntInRange(p, r);
  10922. var i = p - 1;
  10923. swap(ary, pivotIndex, r);
  10924. var pivot = ary[r];
  10925. // Immediately after `j` is incremented in this loop, the following hold
  10926. // true:
  10927. //
  10928. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  10929. //
  10930. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  10931. for (var j = p; j < r; j++) {
  10932. if (comparator(ary[j], pivot) <= 0) {
  10933. i += 1;
  10934. swap(ary, i, j);
  10935. }
  10936. }
  10937. swap(ary, i + 1, j);
  10938. var q = i + 1;
  10939. // (2) Recurse on each half.
  10940. doQuickSort(ary, comparator, p, q - 1);
  10941. doQuickSort(ary, comparator, q + 1, r);
  10942. }
  10943. }
  10944. /**
  10945. * Sort the given array in-place with the given comparator function.
  10946. *
  10947. * @param {Array} ary
  10948. * An array to sort.
  10949. * @param {function} comparator
  10950. * Function to use to compare two items.
  10951. */
  10952. exports.quickSort = function (ary, comparator) {
  10953. doQuickSort(ary, comparator, 0, ary.length - 1);
  10954. };
  10955. /***/ },
  10956. /* 10 */
  10957. /***/ function(module, exports, __webpack_require__) {
  10958. /* -*- Mode: js; js-indent-level: 2; -*- */
  10959. /*
  10960. * Copyright 2011 Mozilla Foundation and contributors
  10961. * Licensed under the New BSD license. See LICENSE or:
  10962. * http://opensource.org/licenses/BSD-3-Clause
  10963. */
  10964. var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;
  10965. var util = __webpack_require__(4);
  10966. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  10967. // operating systems these days (capturing the result).
  10968. var REGEX_NEWLINE = /(\r?\n)/;
  10969. // Newline character code for charCodeAt() comparisons
  10970. var NEWLINE_CODE = 10;
  10971. // Private symbol for identifying `SourceNode`s when multiple versions of
  10972. // the source-map library are loaded. This MUST NOT CHANGE across
  10973. // versions!
  10974. var isSourceNode = "$$$isSourceNode$$$";
  10975. /**
  10976. * SourceNodes provide a way to abstract over interpolating/concatenating
  10977. * snippets of generated JavaScript source code while maintaining the line and
  10978. * column information associated with the original source code.
  10979. *
  10980. * @param aLine The original line number.
  10981. * @param aColumn The original column number.
  10982. * @param aSource The original source's filename.
  10983. * @param aChunks Optional. An array of strings which are snippets of
  10984. * generated JS, or other SourceNodes.
  10985. * @param aName The original identifier.
  10986. */
  10987. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  10988. this.children = [];
  10989. this.sourceContents = {};
  10990. this.line = aLine == null ? null : aLine;
  10991. this.column = aColumn == null ? null : aColumn;
  10992. this.source = aSource == null ? null : aSource;
  10993. this.name = aName == null ? null : aName;
  10994. this[isSourceNode] = true;
  10995. if (aChunks != null) this.add(aChunks);
  10996. }
  10997. /**
  10998. * Creates a SourceNode from generated code and a SourceMapConsumer.
  10999. *
  11000. * @param aGeneratedCode The generated code
  11001. * @param aSourceMapConsumer The SourceMap for the generated code
  11002. * @param aRelativePath Optional. The path that relative sources in the
  11003. * SourceMapConsumer should be relative to.
  11004. */
  11005. SourceNode.fromStringWithSourceMap =
  11006. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  11007. // The SourceNode we want to fill with the generated code
  11008. // and the SourceMap
  11009. var node = new SourceNode();
  11010. // All even indices of this array are one line of the generated code,
  11011. // while all odd indices are the newlines between two adjacent lines
  11012. // (since `REGEX_NEWLINE` captures its match).
  11013. // Processed fragments are removed from this array, by calling `shiftNextLine`.
  11014. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  11015. var shiftNextLine = function() {
  11016. var lineContents = remainingLines.shift();
  11017. // The last line of a file might not have a newline.
  11018. var newLine = remainingLines.shift() || "";
  11019. return lineContents + newLine;
  11020. };
  11021. // We need to remember the position of "remainingLines"
  11022. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  11023. // The generate SourceNodes we need a code range.
  11024. // To extract it current and last mapping is used.
  11025. // Here we store the last mapping.
  11026. var lastMapping = null;
  11027. aSourceMapConsumer.eachMapping(function (mapping) {
  11028. if (lastMapping !== null) {
  11029. // We add the code from "lastMapping" to "mapping":
  11030. // First check if there is a new line in between.
  11031. if (lastGeneratedLine < mapping.generatedLine) {
  11032. // Associate first line with "lastMapping"
  11033. addMappingWithCode(lastMapping, shiftNextLine());
  11034. lastGeneratedLine++;
  11035. lastGeneratedColumn = 0;
  11036. // The remaining code is added without mapping
  11037. } else {
  11038. // There is no new line in between.
  11039. // Associate the code between "lastGeneratedColumn" and
  11040. // "mapping.generatedColumn" with "lastMapping"
  11041. var nextLine = remainingLines[0];
  11042. var code = nextLine.substr(0, mapping.generatedColumn -
  11043. lastGeneratedColumn);
  11044. remainingLines[0] = nextLine.substr(mapping.generatedColumn -
  11045. lastGeneratedColumn);
  11046. lastGeneratedColumn = mapping.generatedColumn;
  11047. addMappingWithCode(lastMapping, code);
  11048. // No more remaining code, continue
  11049. lastMapping = mapping;
  11050. return;
  11051. }
  11052. }
  11053. // We add the generated code until the first mapping
  11054. // to the SourceNode without any mapping.
  11055. // Each line is added as separate string.
  11056. while (lastGeneratedLine < mapping.generatedLine) {
  11057. node.add(shiftNextLine());
  11058. lastGeneratedLine++;
  11059. }
  11060. if (lastGeneratedColumn < mapping.generatedColumn) {
  11061. var nextLine = remainingLines[0];
  11062. node.add(nextLine.substr(0, mapping.generatedColumn));
  11063. remainingLines[0] = nextLine.substr(mapping.generatedColumn);
  11064. lastGeneratedColumn = mapping.generatedColumn;
  11065. }
  11066. lastMapping = mapping;
  11067. }, this);
  11068. // We have processed all mappings.
  11069. if (remainingLines.length > 0) {
  11070. if (lastMapping) {
  11071. // Associate the remaining code in the current line with "lastMapping"
  11072. addMappingWithCode(lastMapping, shiftNextLine());
  11073. }
  11074. // and add the remaining lines without any mapping
  11075. node.add(remainingLines.join(""));
  11076. }
  11077. // Copy sourcesContent into SourceNode
  11078. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  11079. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  11080. if (content != null) {
  11081. if (aRelativePath != null) {
  11082. sourceFile = util.join(aRelativePath, sourceFile);
  11083. }
  11084. node.setSourceContent(sourceFile, content);
  11085. }
  11086. });
  11087. return node;
  11088. function addMappingWithCode(mapping, code) {
  11089. if (mapping === null || mapping.source === undefined) {
  11090. node.add(code);
  11091. } else {
  11092. var source = aRelativePath
  11093. ? util.join(aRelativePath, mapping.source)
  11094. : mapping.source;
  11095. node.add(new SourceNode(mapping.originalLine,
  11096. mapping.originalColumn,
  11097. source,
  11098. code,
  11099. mapping.name));
  11100. }
  11101. }
  11102. };
  11103. /**
  11104. * Add a chunk of generated JS to this source node.
  11105. *
  11106. * @param aChunk A string snippet of generated JS code, another instance of
  11107. * SourceNode, or an array where each member is one of those things.
  11108. */
  11109. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  11110. if (Array.isArray(aChunk)) {
  11111. aChunk.forEach(function (chunk) {
  11112. this.add(chunk);
  11113. }, this);
  11114. }
  11115. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  11116. if (aChunk) {
  11117. this.children.push(aChunk);
  11118. }
  11119. }
  11120. else {
  11121. throw new TypeError(
  11122. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  11123. );
  11124. }
  11125. return this;
  11126. };
  11127. /**
  11128. * Add a chunk of generated JS to the beginning of this source node.
  11129. *
  11130. * @param aChunk A string snippet of generated JS code, another instance of
  11131. * SourceNode, or an array where each member is one of those things.
  11132. */
  11133. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  11134. if (Array.isArray(aChunk)) {
  11135. for (var i = aChunk.length-1; i >= 0; i--) {
  11136. this.prepend(aChunk[i]);
  11137. }
  11138. }
  11139. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  11140. this.children.unshift(aChunk);
  11141. }
  11142. else {
  11143. throw new TypeError(
  11144. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  11145. );
  11146. }
  11147. return this;
  11148. };
  11149. /**
  11150. * Walk over the tree of JS snippets in this node and its children. The
  11151. * walking function is called once for each snippet of JS and is passed that
  11152. * snippet and the its original associated source's line/column location.
  11153. *
  11154. * @param aFn The traversal function.
  11155. */
  11156. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  11157. var chunk;
  11158. for (var i = 0, len = this.children.length; i < len; i++) {
  11159. chunk = this.children[i];
  11160. if (chunk[isSourceNode]) {
  11161. chunk.walk(aFn);
  11162. }
  11163. else {
  11164. if (chunk !== '') {
  11165. aFn(chunk, { source: this.source,
  11166. line: this.line,
  11167. column: this.column,
  11168. name: this.name });
  11169. }
  11170. }
  11171. }
  11172. };
  11173. /**
  11174. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  11175. * each of `this.children`.
  11176. *
  11177. * @param aSep The separator.
  11178. */
  11179. SourceNode.prototype.join = function SourceNode_join(aSep) {
  11180. var newChildren;
  11181. var i;
  11182. var len = this.children.length;
  11183. if (len > 0) {
  11184. newChildren = [];
  11185. for (i = 0; i < len-1; i++) {
  11186. newChildren.push(this.children[i]);
  11187. newChildren.push(aSep);
  11188. }
  11189. newChildren.push(this.children[i]);
  11190. this.children = newChildren;
  11191. }
  11192. return this;
  11193. };
  11194. /**
  11195. * Call String.prototype.replace on the very right-most source snippet. Useful
  11196. * for trimming whitespace from the end of a source node, etc.
  11197. *
  11198. * @param aPattern The pattern to replace.
  11199. * @param aReplacement The thing to replace the pattern with.
  11200. */
  11201. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  11202. var lastChild = this.children[this.children.length - 1];
  11203. if (lastChild[isSourceNode]) {
  11204. lastChild.replaceRight(aPattern, aReplacement);
  11205. }
  11206. else if (typeof lastChild === 'string') {
  11207. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  11208. }
  11209. else {
  11210. this.children.push(''.replace(aPattern, aReplacement));
  11211. }
  11212. return this;
  11213. };
  11214. /**
  11215. * Set the source content for a source file. This will be added to the SourceMapGenerator
  11216. * in the sourcesContent field.
  11217. *
  11218. * @param aSourceFile The filename of the source file
  11219. * @param aSourceContent The content of the source file
  11220. */
  11221. SourceNode.prototype.setSourceContent =
  11222. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  11223. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  11224. };
  11225. /**
  11226. * Walk over the tree of SourceNodes. The walking function is called for each
  11227. * source file content and is passed the filename and source content.
  11228. *
  11229. * @param aFn The traversal function.
  11230. */
  11231. SourceNode.prototype.walkSourceContents =
  11232. function SourceNode_walkSourceContents(aFn) {
  11233. for (var i = 0, len = this.children.length; i < len; i++) {
  11234. if (this.children[i][isSourceNode]) {
  11235. this.children[i].walkSourceContents(aFn);
  11236. }
  11237. }
  11238. var sources = Object.keys(this.sourceContents);
  11239. for (var i = 0, len = sources.length; i < len; i++) {
  11240. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  11241. }
  11242. };
  11243. /**
  11244. * Return the string representation of this source node. Walks over the tree
  11245. * and concatenates all the various snippets together to one string.
  11246. */
  11247. SourceNode.prototype.toString = function SourceNode_toString() {
  11248. var str = "";
  11249. this.walk(function (chunk) {
  11250. str += chunk;
  11251. });
  11252. return str;
  11253. };
  11254. /**
  11255. * Returns the string representation of this source node along with a source
  11256. * map.
  11257. */
  11258. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  11259. var generated = {
  11260. code: "",
  11261. line: 1,
  11262. column: 0
  11263. };
  11264. var map = new SourceMapGenerator(aArgs);
  11265. var sourceMappingActive = false;
  11266. var lastOriginalSource = null;
  11267. var lastOriginalLine = null;
  11268. var lastOriginalColumn = null;
  11269. var lastOriginalName = null;
  11270. this.walk(function (chunk, original) {
  11271. generated.code += chunk;
  11272. if (original.source !== null
  11273. && original.line !== null
  11274. && original.column !== null) {
  11275. if(lastOriginalSource !== original.source
  11276. || lastOriginalLine !== original.line
  11277. || lastOriginalColumn !== original.column
  11278. || lastOriginalName !== original.name) {
  11279. map.addMapping({
  11280. source: original.source,
  11281. original: {
  11282. line: original.line,
  11283. column: original.column
  11284. },
  11285. generated: {
  11286. line: generated.line,
  11287. column: generated.column
  11288. },
  11289. name: original.name
  11290. });
  11291. }
  11292. lastOriginalSource = original.source;
  11293. lastOriginalLine = original.line;
  11294. lastOriginalColumn = original.column;
  11295. lastOriginalName = original.name;
  11296. sourceMappingActive = true;
  11297. } else if (sourceMappingActive) {
  11298. map.addMapping({
  11299. generated: {
  11300. line: generated.line,
  11301. column: generated.column
  11302. }
  11303. });
  11304. lastOriginalSource = null;
  11305. sourceMappingActive = false;
  11306. }
  11307. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  11308. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  11309. generated.line++;
  11310. generated.column = 0;
  11311. // Mappings end at eol
  11312. if (idx + 1 === length) {
  11313. lastOriginalSource = null;
  11314. sourceMappingActive = false;
  11315. } else if (sourceMappingActive) {
  11316. map.addMapping({
  11317. source: original.source,
  11318. original: {
  11319. line: original.line,
  11320. column: original.column
  11321. },
  11322. generated: {
  11323. line: generated.line,
  11324. column: generated.column
  11325. },
  11326. name: original.name
  11327. });
  11328. }
  11329. } else {
  11330. generated.column++;
  11331. }
  11332. }
  11333. });
  11334. this.walkSourceContents(function (sourceFile, sourceContent) {
  11335. map.setSourceContent(sourceFile, sourceContent);
  11336. });
  11337. return { code: generated.code, map: map };
  11338. };
  11339. exports.SourceNode = SourceNode;
  11340. /***/ }
  11341. /******/ ])
  11342. });
  11343. ;//Distributed under the BSD license:
  11344. //Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  11345. define('uglifyjs', ['exports', 'source-map', 'logger', 'env!env/file'], function (exports, MOZ_SourceMap, logger, rjsFile) {
  11346. /***********************************************************************
  11347. A JavaScript tokenizer / parser / beautifier / compressor.
  11348. https://github.com/mishoo/UglifyJS2
  11349. -------------------------------- (C) ---------------------------------
  11350. Author: Mihai Bazon
  11351. <mihai.bazon@gmail.com>
  11352. http://mihai.bazon.net/blog
  11353. Distributed under the BSD license:
  11354. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  11355. Redistribution and use in source and binary forms, with or without
  11356. modification, are permitted provided that the following conditions
  11357. are met:
  11358. * Redistributions of source code must retain the above
  11359. copyright notice, this list of conditions and the following
  11360. disclaimer.
  11361. * Redistributions in binary form must reproduce the above
  11362. copyright notice, this list of conditions and the following
  11363. disclaimer in the documentation and/or other materials
  11364. provided with the distribution.
  11365. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  11366. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  11367. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  11368. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  11369. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  11370. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  11371. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  11372. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11373. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  11374. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  11375. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  11376. SUCH DAMAGE.
  11377. ***********************************************************************/
  11378. "use strict";
  11379. function array_to_hash(a) {
  11380. var ret = Object.create(null);
  11381. for (var i = 0; i < a.length; ++i)
  11382. ret[a[i]] = true;
  11383. return ret;
  11384. };
  11385. function slice(a, start) {
  11386. return Array.prototype.slice.call(a, start || 0);
  11387. };
  11388. function characters(str) {
  11389. return str.split("");
  11390. };
  11391. function member(name, array) {
  11392. return array.indexOf(name) >= 0;
  11393. };
  11394. function find_if(func, array) {
  11395. for (var i = 0, n = array.length; i < n; ++i) {
  11396. if (func(array[i]))
  11397. return array[i];
  11398. }
  11399. };
  11400. function repeat_string(str, i) {
  11401. if (i <= 0) return "";
  11402. if (i == 1) return str;
  11403. var d = repeat_string(str, i >> 1);
  11404. d += d;
  11405. if (i & 1) d += str;
  11406. return d;
  11407. };
  11408. function DefaultsError(msg, defs) {
  11409. Error.call(this, msg);
  11410. this.msg = msg;
  11411. this.defs = defs;
  11412. };
  11413. DefaultsError.prototype = Object.create(Error.prototype);
  11414. DefaultsError.prototype.constructor = DefaultsError;
  11415. DefaultsError.croak = function(msg, defs) {
  11416. throw new DefaultsError(msg, defs);
  11417. };
  11418. function defaults(args, defs, croak) {
  11419. if (args === true)
  11420. args = {};
  11421. var ret = args || {};
  11422. if (croak) for (var i in ret) if (HOP(ret, i) && !HOP(defs, i))
  11423. DefaultsError.croak("`" + i + "` is not a supported option", defs);
  11424. for (var i in defs) if (HOP(defs, i)) {
  11425. ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
  11426. }
  11427. return ret;
  11428. };
  11429. function merge(obj, ext) {
  11430. var count = 0;
  11431. for (var i in ext) if (HOP(ext, i)) {
  11432. obj[i] = ext[i];
  11433. count++;
  11434. }
  11435. return count;
  11436. };
  11437. function noop() {};
  11438. var MAP = (function(){
  11439. function MAP(a, f, backwards) {
  11440. var ret = [], top = [], i;
  11441. function doit() {
  11442. var val = f(a[i], i);
  11443. var is_last = val instanceof Last;
  11444. if (is_last) val = val.v;
  11445. if (val instanceof AtTop) {
  11446. val = val.v;
  11447. if (val instanceof Splice) {
  11448. top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
  11449. } else {
  11450. top.push(val);
  11451. }
  11452. }
  11453. else if (val !== skip) {
  11454. if (val instanceof Splice) {
  11455. ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
  11456. } else {
  11457. ret.push(val);
  11458. }
  11459. }
  11460. return is_last;
  11461. };
  11462. if (a instanceof Array) {
  11463. if (backwards) {
  11464. for (i = a.length; --i >= 0;) if (doit()) break;
  11465. ret.reverse();
  11466. top.reverse();
  11467. } else {
  11468. for (i = 0; i < a.length; ++i) if (doit()) break;
  11469. }
  11470. }
  11471. else {
  11472. for (i in a) if (HOP(a, i)) if (doit()) break;
  11473. }
  11474. return top.concat(ret);
  11475. };
  11476. MAP.at_top = function(val) { return new AtTop(val) };
  11477. MAP.splice = function(val) { return new Splice(val) };
  11478. MAP.last = function(val) { return new Last(val) };
  11479. var skip = MAP.skip = {};
  11480. function AtTop(val) { this.v = val };
  11481. function Splice(val) { this.v = val };
  11482. function Last(val) { this.v = val };
  11483. return MAP;
  11484. })();
  11485. function push_uniq(array, el) {
  11486. if (array.indexOf(el) < 0)
  11487. array.push(el);
  11488. };
  11489. function string_template(text, props) {
  11490. return text.replace(/\{(.+?)\}/g, function(str, p){
  11491. return props[p];
  11492. });
  11493. };
  11494. function remove(array, el) {
  11495. for (var i = array.length; --i >= 0;) {
  11496. if (array[i] === el) array.splice(i, 1);
  11497. }
  11498. };
  11499. function mergeSort(array, cmp) {
  11500. if (array.length < 2) return array.slice();
  11501. function merge(a, b) {
  11502. var r = [], ai = 0, bi = 0, i = 0;
  11503. while (ai < a.length && bi < b.length) {
  11504. cmp(a[ai], b[bi]) <= 0
  11505. ? r[i++] = a[ai++]
  11506. : r[i++] = b[bi++];
  11507. }
  11508. if (ai < a.length) r.push.apply(r, a.slice(ai));
  11509. if (bi < b.length) r.push.apply(r, b.slice(bi));
  11510. return r;
  11511. };
  11512. function _ms(a) {
  11513. if (a.length <= 1)
  11514. return a;
  11515. var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
  11516. left = _ms(left);
  11517. right = _ms(right);
  11518. return merge(left, right);
  11519. };
  11520. return _ms(array);
  11521. };
  11522. function set_difference(a, b) {
  11523. return a.filter(function(el){
  11524. return b.indexOf(el) < 0;
  11525. });
  11526. };
  11527. function set_intersection(a, b) {
  11528. return a.filter(function(el){
  11529. return b.indexOf(el) >= 0;
  11530. });
  11531. };
  11532. // this function is taken from Acorn [1], written by Marijn Haverbeke
  11533. // [1] https://github.com/marijnh/acorn
  11534. function makePredicate(words) {
  11535. if (!(words instanceof Array)) words = words.split(" ");
  11536. var f = "", cats = [];
  11537. out: for (var i = 0; i < words.length; ++i) {
  11538. for (var j = 0; j < cats.length; ++j)
  11539. if (cats[j][0].length == words[i].length) {
  11540. cats[j].push(words[i]);
  11541. continue out;
  11542. }
  11543. cats.push([words[i]]);
  11544. }
  11545. function quote(word) {
  11546. return JSON.stringify(word).replace(/[\u2028\u2029]/g, function(s) {
  11547. switch (s) {
  11548. case "\u2028": return "\\u2028";
  11549. case "\u2029": return "\\u2029";
  11550. }
  11551. return s;
  11552. });
  11553. }
  11554. function compareTo(arr) {
  11555. if (arr.length == 1) return f += "return str === " + quote(arr[0]) + ";";
  11556. f += "switch(str){";
  11557. for (var i = 0; i < arr.length; ++i) f += "case " + quote(arr[i]) + ":";
  11558. f += "return true}return false;";
  11559. }
  11560. // When there are more than three length categories, an outer
  11561. // switch first dispatches on the lengths, to save on comparisons.
  11562. if (cats.length > 3) {
  11563. cats.sort(function(a, b) {return b.length - a.length;});
  11564. f += "switch(str.length){";
  11565. for (var i = 0; i < cats.length; ++i) {
  11566. var cat = cats[i];
  11567. f += "case " + cat[0].length + ":";
  11568. compareTo(cat);
  11569. }
  11570. f += "}";
  11571. // Otherwise, simply generate a flat `switch` statement.
  11572. } else {
  11573. compareTo(words);
  11574. }
  11575. return new Function("str", f);
  11576. };
  11577. function all(array, predicate) {
  11578. for (var i = array.length; --i >= 0;)
  11579. if (!predicate(array[i]))
  11580. return false;
  11581. return true;
  11582. };
  11583. function Dictionary() {
  11584. this._values = Object.create(null);
  11585. this._size = 0;
  11586. };
  11587. Dictionary.prototype = {
  11588. set: function(key, val) {
  11589. if (!this.has(key)) ++this._size;
  11590. this._values["$" + key] = val;
  11591. return this;
  11592. },
  11593. add: function(key, val) {
  11594. if (this.has(key)) {
  11595. this.get(key).push(val);
  11596. } else {
  11597. this.set(key, [ val ]);
  11598. }
  11599. return this;
  11600. },
  11601. get: function(key) { return this._values["$" + key] },
  11602. del: function(key) {
  11603. if (this.has(key)) {
  11604. --this._size;
  11605. delete this._values["$" + key];
  11606. }
  11607. return this;
  11608. },
  11609. has: function(key) { return ("$" + key) in this._values },
  11610. each: function(f) {
  11611. for (var i in this._values)
  11612. f(this._values[i], i.substr(1));
  11613. },
  11614. size: function() {
  11615. return this._size;
  11616. },
  11617. map: function(f) {
  11618. var ret = [];
  11619. for (var i in this._values)
  11620. ret.push(f(this._values[i], i.substr(1)));
  11621. return ret;
  11622. },
  11623. toObject: function() { return this._values }
  11624. };
  11625. Dictionary.fromObject = function(obj) {
  11626. var dict = new Dictionary();
  11627. dict._size = merge(dict._values, obj);
  11628. return dict;
  11629. };
  11630. function HOP(obj, prop) {
  11631. return Object.prototype.hasOwnProperty.call(obj, prop);
  11632. }
  11633. /***********************************************************************
  11634. A JavaScript tokenizer / parser / beautifier / compressor.
  11635. https://github.com/mishoo/UglifyJS2
  11636. -------------------------------- (C) ---------------------------------
  11637. Author: Mihai Bazon
  11638. <mihai.bazon@gmail.com>
  11639. http://mihai.bazon.net/blog
  11640. Distributed under the BSD license:
  11641. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  11642. Redistribution and use in source and binary forms, with or without
  11643. modification, are permitted provided that the following conditions
  11644. are met:
  11645. * Redistributions of source code must retain the above
  11646. copyright notice, this list of conditions and the following
  11647. disclaimer.
  11648. * Redistributions in binary form must reproduce the above
  11649. copyright notice, this list of conditions and the following
  11650. disclaimer in the documentation and/or other materials
  11651. provided with the distribution.
  11652. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  11653. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  11654. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  11655. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  11656. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  11657. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  11658. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  11659. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11660. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  11661. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  11662. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  11663. SUCH DAMAGE.
  11664. ***********************************************************************/
  11665. "use strict";
  11666. function DEFNODE(type, props, methods, base) {
  11667. if (arguments.length < 4) base = AST_Node;
  11668. if (!props) props = [];
  11669. else props = props.split(/\s+/);
  11670. var self_props = props;
  11671. if (base && base.PROPS)
  11672. props = props.concat(base.PROPS);
  11673. var code = "return function AST_" + type + "(props){ if (props) { ";
  11674. for (var i = props.length; --i >= 0;) {
  11675. code += "this." + props[i] + " = props." + props[i] + ";";
  11676. }
  11677. var proto = base && new base;
  11678. if (proto && proto.initialize || (methods && methods.initialize))
  11679. code += "this.initialize();";
  11680. code += "}}";
  11681. var ctor = new Function(code)();
  11682. if (proto) {
  11683. ctor.prototype = proto;
  11684. ctor.BASE = base;
  11685. }
  11686. if (base) base.SUBCLASSES.push(ctor);
  11687. ctor.prototype.CTOR = ctor;
  11688. ctor.PROPS = props || null;
  11689. ctor.SELF_PROPS = self_props;
  11690. ctor.SUBCLASSES = [];
  11691. if (type) {
  11692. ctor.prototype.TYPE = ctor.TYPE = type;
  11693. }
  11694. if (methods) for (i in methods) if (HOP(methods, i)) {
  11695. if (/^\$/.test(i)) {
  11696. ctor[i.substr(1)] = methods[i];
  11697. } else {
  11698. ctor.prototype[i] = methods[i];
  11699. }
  11700. }
  11701. ctor.DEFMETHOD = function(name, method) {
  11702. this.prototype[name] = method;
  11703. };
  11704. exports["AST_" + type] = ctor;
  11705. return ctor;
  11706. };
  11707. var AST_Token = DEFNODE("Token", "type value line col pos endline endcol endpos nlb comments_before file raw", {
  11708. }, null);
  11709. var AST_Node = DEFNODE("Node", "start end", {
  11710. clone: function() {
  11711. return new this.CTOR(this);
  11712. },
  11713. $documentation: "Base class of all AST nodes",
  11714. $propdoc: {
  11715. start: "[AST_Token] The first token of this node",
  11716. end: "[AST_Token] The last token of this node"
  11717. },
  11718. _walk: function(visitor) {
  11719. return visitor._visit(this);
  11720. },
  11721. walk: function(visitor) {
  11722. return this._walk(visitor); // not sure the indirection will be any help
  11723. }
  11724. }, null);
  11725. AST_Node.warn_function = null;
  11726. AST_Node.warn = function(txt, props) {
  11727. if (AST_Node.warn_function)
  11728. AST_Node.warn_function(string_template(txt, props));
  11729. };
  11730. /* -----[ statements ]----- */
  11731. var AST_Statement = DEFNODE("Statement", null, {
  11732. $documentation: "Base class of all statements",
  11733. });
  11734. var AST_Debugger = DEFNODE("Debugger", null, {
  11735. $documentation: "Represents a debugger statement",
  11736. }, AST_Statement);
  11737. var AST_Directive = DEFNODE("Directive", "value scope quote", {
  11738. $documentation: "Represents a directive, like \"use strict\";",
  11739. $propdoc: {
  11740. value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
  11741. scope: "[AST_Scope/S] The scope that this directive affects",
  11742. quote: "[string] the original quote character"
  11743. },
  11744. }, AST_Statement);
  11745. var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
  11746. $documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
  11747. $propdoc: {
  11748. body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
  11749. },
  11750. _walk: function(visitor) {
  11751. return visitor._visit(this, function(){
  11752. this.body._walk(visitor);
  11753. });
  11754. }
  11755. }, AST_Statement);
  11756. function walk_body(node, visitor) {
  11757. if (node.body instanceof AST_Statement) {
  11758. node.body._walk(visitor);
  11759. }
  11760. else node.body.forEach(function(stat){
  11761. stat._walk(visitor);
  11762. });
  11763. };
  11764. var AST_Block = DEFNODE("Block", "body", {
  11765. $documentation: "A body of statements (usually bracketed)",
  11766. $propdoc: {
  11767. body: "[AST_Statement*] an array of statements"
  11768. },
  11769. _walk: function(visitor) {
  11770. return visitor._visit(this, function(){
  11771. walk_body(this, visitor);
  11772. });
  11773. }
  11774. }, AST_Statement);
  11775. var AST_BlockStatement = DEFNODE("BlockStatement", null, {
  11776. $documentation: "A block statement",
  11777. }, AST_Block);
  11778. var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
  11779. $documentation: "The empty statement (empty block or simply a semicolon)",
  11780. _walk: function(visitor) {
  11781. return visitor._visit(this);
  11782. }
  11783. }, AST_Statement);
  11784. var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
  11785. $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
  11786. $propdoc: {
  11787. body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
  11788. },
  11789. _walk: function(visitor) {
  11790. return visitor._visit(this, function(){
  11791. this.body._walk(visitor);
  11792. });
  11793. }
  11794. }, AST_Statement);
  11795. var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
  11796. $documentation: "Statement with a label",
  11797. $propdoc: {
  11798. label: "[AST_Label] a label definition"
  11799. },
  11800. _walk: function(visitor) {
  11801. return visitor._visit(this, function(){
  11802. this.label._walk(visitor);
  11803. this.body._walk(visitor);
  11804. });
  11805. }
  11806. }, AST_StatementWithBody);
  11807. var AST_IterationStatement = DEFNODE("IterationStatement", null, {
  11808. $documentation: "Internal class. All loops inherit from it."
  11809. }, AST_StatementWithBody);
  11810. var AST_DWLoop = DEFNODE("DWLoop", "condition", {
  11811. $documentation: "Base class for do/while statements",
  11812. $propdoc: {
  11813. condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
  11814. }
  11815. }, AST_IterationStatement);
  11816. var AST_Do = DEFNODE("Do", null, {
  11817. $documentation: "A `do` statement",
  11818. _walk: function(visitor) {
  11819. return visitor._visit(this, function(){
  11820. this.body._walk(visitor);
  11821. this.condition._walk(visitor);
  11822. });
  11823. }
  11824. }, AST_DWLoop);
  11825. var AST_While = DEFNODE("While", null, {
  11826. $documentation: "A `while` statement",
  11827. _walk: function(visitor) {
  11828. return visitor._visit(this, function(){
  11829. this.condition._walk(visitor);
  11830. this.body._walk(visitor);
  11831. });
  11832. }
  11833. }, AST_DWLoop);
  11834. var AST_For = DEFNODE("For", "init condition step", {
  11835. $documentation: "A `for` statement",
  11836. $propdoc: {
  11837. init: "[AST_Node?] the `for` initialization code, or null if empty",
  11838. condition: "[AST_Node?] the `for` termination clause, or null if empty",
  11839. step: "[AST_Node?] the `for` update clause, or null if empty"
  11840. },
  11841. _walk: function(visitor) {
  11842. return visitor._visit(this, function(){
  11843. if (this.init) this.init._walk(visitor);
  11844. if (this.condition) this.condition._walk(visitor);
  11845. if (this.step) this.step._walk(visitor);
  11846. this.body._walk(visitor);
  11847. });
  11848. }
  11849. }, AST_IterationStatement);
  11850. var AST_ForIn = DEFNODE("ForIn", "init name object", {
  11851. $documentation: "A `for ... in` statement",
  11852. $propdoc: {
  11853. init: "[AST_Node] the `for/in` initialization code",
  11854. name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var",
  11855. object: "[AST_Node] the object that we're looping through"
  11856. },
  11857. _walk: function(visitor) {
  11858. return visitor._visit(this, function(){
  11859. this.init._walk(visitor);
  11860. this.object._walk(visitor);
  11861. this.body._walk(visitor);
  11862. });
  11863. }
  11864. }, AST_IterationStatement);
  11865. var AST_With = DEFNODE("With", "expression", {
  11866. $documentation: "A `with` statement",
  11867. $propdoc: {
  11868. expression: "[AST_Node] the `with` expression"
  11869. },
  11870. _walk: function(visitor) {
  11871. return visitor._visit(this, function(){
  11872. this.expression._walk(visitor);
  11873. this.body._walk(visitor);
  11874. });
  11875. }
  11876. }, AST_StatementWithBody);
  11877. /* -----[ scope and functions ]----- */
  11878. var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", {
  11879. $documentation: "Base class for all statements introducing a lexical scope",
  11880. $propdoc: {
  11881. directives: "[string*/S] an array of directives declared in this scope",
  11882. variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
  11883. functions: "[Object/S] like `variables`, but only lists function declarations",
  11884. uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
  11885. uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
  11886. parent_scope: "[AST_Scope?/S] link to the parent scope",
  11887. enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
  11888. cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
  11889. },
  11890. }, AST_Block);
  11891. var AST_Toplevel = DEFNODE("Toplevel", "globals", {
  11892. $documentation: "The toplevel scope",
  11893. $propdoc: {
  11894. globals: "[Object/S] a map of name -> SymbolDef for all undeclared names",
  11895. },
  11896. wrap_enclose: function(arg_parameter_pairs) {
  11897. var self = this;
  11898. var args = [];
  11899. var parameters = [];
  11900. arg_parameter_pairs.forEach(function(pair) {
  11901. var splitAt = pair.lastIndexOf(":");
  11902. args.push(pair.substr(0, splitAt));
  11903. parameters.push(pair.substr(splitAt + 1));
  11904. });
  11905. var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")";
  11906. wrapped_tl = parse(wrapped_tl);
  11907. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  11908. if (node instanceof AST_Directive && node.value == "$ORIG") {
  11909. return MAP.splice(self.body);
  11910. }
  11911. }));
  11912. return wrapped_tl;
  11913. },
  11914. wrap_commonjs: function(name, export_all) {
  11915. var self = this;
  11916. var to_export = [];
  11917. if (export_all) {
  11918. self.figure_out_scope();
  11919. self.walk(new TreeWalker(function(node){
  11920. if (node instanceof AST_SymbolDeclaration && node.definition().global) {
  11921. if (!find_if(function(n){ return n.name == node.name }, to_export))
  11922. to_export.push(node);
  11923. }
  11924. }));
  11925. }
  11926. var wrapped_tl = "(function(exports, global){ '$ORIG'; '$EXPORTS'; global['" + name + "'] = exports; }({}, (function(){return this}())))";
  11927. wrapped_tl = parse(wrapped_tl);
  11928. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  11929. if (node instanceof AST_Directive) {
  11930. switch (node.value) {
  11931. case "$ORIG":
  11932. return MAP.splice(self.body);
  11933. case "$EXPORTS":
  11934. var body = [];
  11935. to_export.forEach(function(sym){
  11936. body.push(new AST_SimpleStatement({
  11937. body: new AST_Assign({
  11938. left: new AST_Sub({
  11939. expression: new AST_SymbolRef({ name: "exports" }),
  11940. property: new AST_String({ value: sym.name }),
  11941. }),
  11942. operator: "=",
  11943. right: new AST_SymbolRef(sym),
  11944. }),
  11945. }));
  11946. });
  11947. return MAP.splice(body);
  11948. }
  11949. }
  11950. }));
  11951. return wrapped_tl;
  11952. }
  11953. }, AST_Scope);
  11954. var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", {
  11955. $documentation: "Base class for functions",
  11956. $propdoc: {
  11957. name: "[AST_SymbolDeclaration?] the name of this function",
  11958. argnames: "[AST_SymbolFunarg*] array of function arguments",
  11959. uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
  11960. },
  11961. _walk: function(visitor) {
  11962. return visitor._visit(this, function(){
  11963. if (this.name) this.name._walk(visitor);
  11964. this.argnames.forEach(function(arg){
  11965. arg._walk(visitor);
  11966. });
  11967. walk_body(this, visitor);
  11968. });
  11969. }
  11970. }, AST_Scope);
  11971. var AST_Accessor = DEFNODE("Accessor", null, {
  11972. $documentation: "A setter/getter function. The `name` property is always null."
  11973. }, AST_Lambda);
  11974. var AST_Function = DEFNODE("Function", null, {
  11975. $documentation: "A function expression"
  11976. }, AST_Lambda);
  11977. var AST_Defun = DEFNODE("Defun", null, {
  11978. $documentation: "A function definition"
  11979. }, AST_Lambda);
  11980. /* -----[ JUMPS ]----- */
  11981. var AST_Jump = DEFNODE("Jump", null, {
  11982. $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
  11983. }, AST_Statement);
  11984. var AST_Exit = DEFNODE("Exit", "value", {
  11985. $documentation: "Base class for “exits” (`return` and `throw`)",
  11986. $propdoc: {
  11987. value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
  11988. },
  11989. _walk: function(visitor) {
  11990. return visitor._visit(this, this.value && function(){
  11991. this.value._walk(visitor);
  11992. });
  11993. }
  11994. }, AST_Jump);
  11995. var AST_Return = DEFNODE("Return", null, {
  11996. $documentation: "A `return` statement"
  11997. }, AST_Exit);
  11998. var AST_Throw = DEFNODE("Throw", null, {
  11999. $documentation: "A `throw` statement"
  12000. }, AST_Exit);
  12001. var AST_LoopControl = DEFNODE("LoopControl", "label", {
  12002. $documentation: "Base class for loop control statements (`break` and `continue`)",
  12003. $propdoc: {
  12004. label: "[AST_LabelRef?] the label, or null if none",
  12005. },
  12006. _walk: function(visitor) {
  12007. return visitor._visit(this, this.label && function(){
  12008. this.label._walk(visitor);
  12009. });
  12010. }
  12011. }, AST_Jump);
  12012. var AST_Break = DEFNODE("Break", null, {
  12013. $documentation: "A `break` statement"
  12014. }, AST_LoopControl);
  12015. var AST_Continue = DEFNODE("Continue", null, {
  12016. $documentation: "A `continue` statement"
  12017. }, AST_LoopControl);
  12018. /* -----[ IF ]----- */
  12019. var AST_If = DEFNODE("If", "condition alternative", {
  12020. $documentation: "A `if` statement",
  12021. $propdoc: {
  12022. condition: "[AST_Node] the `if` condition",
  12023. alternative: "[AST_Statement?] the `else` part, or null if not present"
  12024. },
  12025. _walk: function(visitor) {
  12026. return visitor._visit(this, function(){
  12027. this.condition._walk(visitor);
  12028. this.body._walk(visitor);
  12029. if (this.alternative) this.alternative._walk(visitor);
  12030. });
  12031. }
  12032. }, AST_StatementWithBody);
  12033. /* -----[ SWITCH ]----- */
  12034. var AST_Switch = DEFNODE("Switch", "expression", {
  12035. $documentation: "A `switch` statement",
  12036. $propdoc: {
  12037. expression: "[AST_Node] the `switch` “discriminant”"
  12038. },
  12039. _walk: function(visitor) {
  12040. return visitor._visit(this, function(){
  12041. this.expression._walk(visitor);
  12042. walk_body(this, visitor);
  12043. });
  12044. }
  12045. }, AST_Block);
  12046. var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
  12047. $documentation: "Base class for `switch` branches",
  12048. }, AST_Block);
  12049. var AST_Default = DEFNODE("Default", null, {
  12050. $documentation: "A `default` switch branch",
  12051. }, AST_SwitchBranch);
  12052. var AST_Case = DEFNODE("Case", "expression", {
  12053. $documentation: "A `case` switch branch",
  12054. $propdoc: {
  12055. expression: "[AST_Node] the `case` expression"
  12056. },
  12057. _walk: function(visitor) {
  12058. return visitor._visit(this, function(){
  12059. this.expression._walk(visitor);
  12060. walk_body(this, visitor);
  12061. });
  12062. }
  12063. }, AST_SwitchBranch);
  12064. /* -----[ EXCEPTIONS ]----- */
  12065. var AST_Try = DEFNODE("Try", "bcatch bfinally", {
  12066. $documentation: "A `try` statement",
  12067. $propdoc: {
  12068. bcatch: "[AST_Catch?] the catch block, or null if not present",
  12069. bfinally: "[AST_Finally?] the finally block, or null if not present"
  12070. },
  12071. _walk: function(visitor) {
  12072. return visitor._visit(this, function(){
  12073. walk_body(this, visitor);
  12074. if (this.bcatch) this.bcatch._walk(visitor);
  12075. if (this.bfinally) this.bfinally._walk(visitor);
  12076. });
  12077. }
  12078. }, AST_Block);
  12079. var AST_Catch = DEFNODE("Catch", "argname", {
  12080. $documentation: "A `catch` node; only makes sense as part of a `try` statement",
  12081. $propdoc: {
  12082. argname: "[AST_SymbolCatch] symbol for the exception"
  12083. },
  12084. _walk: function(visitor) {
  12085. return visitor._visit(this, function(){
  12086. this.argname._walk(visitor);
  12087. walk_body(this, visitor);
  12088. });
  12089. }
  12090. }, AST_Block);
  12091. var AST_Finally = DEFNODE("Finally", null, {
  12092. $documentation: "A `finally` node; only makes sense as part of a `try` statement"
  12093. }, AST_Block);
  12094. /* -----[ VAR/CONST ]----- */
  12095. var AST_Definitions = DEFNODE("Definitions", "definitions", {
  12096. $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)",
  12097. $propdoc: {
  12098. definitions: "[AST_VarDef*] array of variable definitions"
  12099. },
  12100. _walk: function(visitor) {
  12101. return visitor._visit(this, function(){
  12102. this.definitions.forEach(function(def){
  12103. def._walk(visitor);
  12104. });
  12105. });
  12106. }
  12107. }, AST_Statement);
  12108. var AST_Var = DEFNODE("Var", null, {
  12109. $documentation: "A `var` statement"
  12110. }, AST_Definitions);
  12111. var AST_Const = DEFNODE("Const", null, {
  12112. $documentation: "A `const` statement"
  12113. }, AST_Definitions);
  12114. var AST_VarDef = DEFNODE("VarDef", "name value", {
  12115. $documentation: "A variable declaration; only appears in a AST_Definitions node",
  12116. $propdoc: {
  12117. name: "[AST_SymbolVar|AST_SymbolConst] name of the variable",
  12118. value: "[AST_Node?] initializer, or null of there's no initializer"
  12119. },
  12120. _walk: function(visitor) {
  12121. return visitor._visit(this, function(){
  12122. this.name._walk(visitor);
  12123. if (this.value) this.value._walk(visitor);
  12124. });
  12125. }
  12126. });
  12127. /* -----[ OTHER ]----- */
  12128. var AST_Call = DEFNODE("Call", "expression args", {
  12129. $documentation: "A function call expression",
  12130. $propdoc: {
  12131. expression: "[AST_Node] expression to invoke as function",
  12132. args: "[AST_Node*] array of arguments"
  12133. },
  12134. _walk: function(visitor) {
  12135. return visitor._visit(this, function(){
  12136. this.expression._walk(visitor);
  12137. this.args.forEach(function(arg){
  12138. arg._walk(visitor);
  12139. });
  12140. });
  12141. }
  12142. });
  12143. var AST_New = DEFNODE("New", null, {
  12144. $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
  12145. }, AST_Call);
  12146. var AST_Seq = DEFNODE("Seq", "car cdr", {
  12147. $documentation: "A sequence expression (two comma-separated expressions)",
  12148. $propdoc: {
  12149. car: "[AST_Node] first element in sequence",
  12150. cdr: "[AST_Node] second element in sequence"
  12151. },
  12152. $cons: function(x, y) {
  12153. var seq = new AST_Seq(x);
  12154. seq.car = x;
  12155. seq.cdr = y;
  12156. return seq;
  12157. },
  12158. $from_array: function(array) {
  12159. if (array.length == 0) return null;
  12160. if (array.length == 1) return array[0].clone();
  12161. var list = null;
  12162. for (var i = array.length; --i >= 0;) {
  12163. list = AST_Seq.cons(array[i], list);
  12164. }
  12165. var p = list;
  12166. while (p) {
  12167. if (p.cdr && !p.cdr.cdr) {
  12168. p.cdr = p.cdr.car;
  12169. break;
  12170. }
  12171. p = p.cdr;
  12172. }
  12173. return list;
  12174. },
  12175. to_array: function() {
  12176. var p = this, a = [];
  12177. while (p) {
  12178. a.push(p.car);
  12179. if (p.cdr && !(p.cdr instanceof AST_Seq)) {
  12180. a.push(p.cdr);
  12181. break;
  12182. }
  12183. p = p.cdr;
  12184. }
  12185. return a;
  12186. },
  12187. add: function(node) {
  12188. var p = this;
  12189. while (p) {
  12190. if (!(p.cdr instanceof AST_Seq)) {
  12191. var cell = AST_Seq.cons(p.cdr, node);
  12192. return p.cdr = cell;
  12193. }
  12194. p = p.cdr;
  12195. }
  12196. },
  12197. len: function() {
  12198. if (this.cdr instanceof AST_Seq) {
  12199. return this.cdr.len() + 1;
  12200. } else {
  12201. return 2;
  12202. }
  12203. },
  12204. _walk: function(visitor) {
  12205. return visitor._visit(this, function(){
  12206. this.car._walk(visitor);
  12207. if (this.cdr) this.cdr._walk(visitor);
  12208. });
  12209. }
  12210. });
  12211. var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
  12212. $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
  12213. $propdoc: {
  12214. expression: "[AST_Node] the “container” expression",
  12215. property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node"
  12216. }
  12217. });
  12218. var AST_Dot = DEFNODE("Dot", null, {
  12219. $documentation: "A dotted property access expression",
  12220. _walk: function(visitor) {
  12221. return visitor._visit(this, function(){
  12222. this.expression._walk(visitor);
  12223. });
  12224. }
  12225. }, AST_PropAccess);
  12226. var AST_Sub = DEFNODE("Sub", null, {
  12227. $documentation: "Index-style property access, i.e. `a[\"foo\"]`",
  12228. _walk: function(visitor) {
  12229. return visitor._visit(this, function(){
  12230. this.expression._walk(visitor);
  12231. this.property._walk(visitor);
  12232. });
  12233. }
  12234. }, AST_PropAccess);
  12235. var AST_Unary = DEFNODE("Unary", "operator expression", {
  12236. $documentation: "Base class for unary expressions",
  12237. $propdoc: {
  12238. operator: "[string] the operator",
  12239. expression: "[AST_Node] expression that this unary operator applies to"
  12240. },
  12241. _walk: function(visitor) {
  12242. return visitor._visit(this, function(){
  12243. this.expression._walk(visitor);
  12244. });
  12245. }
  12246. });
  12247. var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
  12248. $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
  12249. }, AST_Unary);
  12250. var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
  12251. $documentation: "Unary postfix expression, i.e. `i++`"
  12252. }, AST_Unary);
  12253. var AST_Binary = DEFNODE("Binary", "left operator right", {
  12254. $documentation: "Binary expression, i.e. `a + b`",
  12255. $propdoc: {
  12256. left: "[AST_Node] left-hand side expression",
  12257. operator: "[string] the operator",
  12258. right: "[AST_Node] right-hand side expression"
  12259. },
  12260. _walk: function(visitor) {
  12261. return visitor._visit(this, function(){
  12262. this.left._walk(visitor);
  12263. this.right._walk(visitor);
  12264. });
  12265. }
  12266. });
  12267. var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
  12268. $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
  12269. $propdoc: {
  12270. condition: "[AST_Node]",
  12271. consequent: "[AST_Node]",
  12272. alternative: "[AST_Node]"
  12273. },
  12274. _walk: function(visitor) {
  12275. return visitor._visit(this, function(){
  12276. this.condition._walk(visitor);
  12277. this.consequent._walk(visitor);
  12278. this.alternative._walk(visitor);
  12279. });
  12280. }
  12281. });
  12282. var AST_Assign = DEFNODE("Assign", null, {
  12283. $documentation: "An assignment expression — `a = b + 5`",
  12284. }, AST_Binary);
  12285. /* -----[ LITERALS ]----- */
  12286. var AST_Array = DEFNODE("Array", "elements", {
  12287. $documentation: "An array literal",
  12288. $propdoc: {
  12289. elements: "[AST_Node*] array of elements"
  12290. },
  12291. _walk: function(visitor) {
  12292. return visitor._visit(this, function(){
  12293. this.elements.forEach(function(el){
  12294. el._walk(visitor);
  12295. });
  12296. });
  12297. }
  12298. });
  12299. var AST_Object = DEFNODE("Object", "properties", {
  12300. $documentation: "An object literal",
  12301. $propdoc: {
  12302. properties: "[AST_ObjectProperty*] array of properties"
  12303. },
  12304. _walk: function(visitor) {
  12305. return visitor._visit(this, function(){
  12306. this.properties.forEach(function(prop){
  12307. prop._walk(visitor);
  12308. });
  12309. });
  12310. }
  12311. });
  12312. var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
  12313. $documentation: "Base class for literal object properties",
  12314. $propdoc: {
  12315. key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.",
  12316. value: "[AST_Node] property value. For setters and getters this is an AST_Function."
  12317. },
  12318. _walk: function(visitor) {
  12319. return visitor._visit(this, function(){
  12320. this.value._walk(visitor);
  12321. });
  12322. }
  12323. });
  12324. var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", {
  12325. $documentation: "A key: value object property",
  12326. $propdoc: {
  12327. quote: "[string] the original quote character"
  12328. }
  12329. }, AST_ObjectProperty);
  12330. var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
  12331. $documentation: "An object setter property",
  12332. }, AST_ObjectProperty);
  12333. var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
  12334. $documentation: "An object getter property",
  12335. }, AST_ObjectProperty);
  12336. var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
  12337. $propdoc: {
  12338. name: "[string] name of this symbol",
  12339. scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
  12340. thedef: "[SymbolDef/S] the definition of this symbol"
  12341. },
  12342. $documentation: "Base class for all symbols",
  12343. });
  12344. var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
  12345. $documentation: "The name of a property accessor (setter/getter function)"
  12346. }, AST_Symbol);
  12347. var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
  12348. $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",
  12349. $propdoc: {
  12350. init: "[AST_Node*/S] array of initializers for this declaration."
  12351. }
  12352. }, AST_Symbol);
  12353. var AST_SymbolVar = DEFNODE("SymbolVar", null, {
  12354. $documentation: "Symbol defining a variable",
  12355. }, AST_SymbolDeclaration);
  12356. var AST_SymbolConst = DEFNODE("SymbolConst", null, {
  12357. $documentation: "A constant declaration"
  12358. }, AST_SymbolDeclaration);
  12359. var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
  12360. $documentation: "Symbol naming a function argument",
  12361. }, AST_SymbolVar);
  12362. var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
  12363. $documentation: "Symbol defining a function",
  12364. }, AST_SymbolDeclaration);
  12365. var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
  12366. $documentation: "Symbol naming a function expression",
  12367. }, AST_SymbolDeclaration);
  12368. var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
  12369. $documentation: "Symbol naming the exception in catch",
  12370. }, AST_SymbolDeclaration);
  12371. var AST_Label = DEFNODE("Label", "references", {
  12372. $documentation: "Symbol naming a label (declaration)",
  12373. $propdoc: {
  12374. references: "[AST_LoopControl*] a list of nodes referring to this label"
  12375. },
  12376. initialize: function() {
  12377. this.references = [];
  12378. this.thedef = this;
  12379. }
  12380. }, AST_Symbol);
  12381. var AST_SymbolRef = DEFNODE("SymbolRef", null, {
  12382. $documentation: "Reference to some symbol (not definition/declaration)",
  12383. }, AST_Symbol);
  12384. var AST_LabelRef = DEFNODE("LabelRef", null, {
  12385. $documentation: "Reference to a label symbol",
  12386. }, AST_Symbol);
  12387. var AST_This = DEFNODE("This", null, {
  12388. $documentation: "The `this` symbol",
  12389. }, AST_Symbol);
  12390. var AST_Constant = DEFNODE("Constant", null, {
  12391. $documentation: "Base class for all constants",
  12392. getValue: function() {
  12393. return this.value;
  12394. }
  12395. });
  12396. var AST_String = DEFNODE("String", "value quote", {
  12397. $documentation: "A string literal",
  12398. $propdoc: {
  12399. value: "[string] the contents of this string",
  12400. quote: "[string] the original quote character"
  12401. }
  12402. }, AST_Constant);
  12403. var AST_Number = DEFNODE("Number", "value literal", {
  12404. $documentation: "A number literal",
  12405. $propdoc: {
  12406. value: "[number] the numeric value",
  12407. literal: "[string] numeric value as string (optional)"
  12408. }
  12409. }, AST_Constant);
  12410. var AST_RegExp = DEFNODE("RegExp", "value", {
  12411. $documentation: "A regexp literal",
  12412. $propdoc: {
  12413. value: "[RegExp] the actual regexp"
  12414. }
  12415. }, AST_Constant);
  12416. var AST_Atom = DEFNODE("Atom", null, {
  12417. $documentation: "Base class for atoms",
  12418. }, AST_Constant);
  12419. var AST_Null = DEFNODE("Null", null, {
  12420. $documentation: "The `null` atom",
  12421. value: null
  12422. }, AST_Atom);
  12423. var AST_NaN = DEFNODE("NaN", null, {
  12424. $documentation: "The impossible value",
  12425. value: 0/0
  12426. }, AST_Atom);
  12427. var AST_Undefined = DEFNODE("Undefined", null, {
  12428. $documentation: "The `undefined` value",
  12429. value: (function(){}())
  12430. }, AST_Atom);
  12431. var AST_Hole = DEFNODE("Hole", null, {
  12432. $documentation: "A hole in an array",
  12433. value: (function(){}())
  12434. }, AST_Atom);
  12435. var AST_Infinity = DEFNODE("Infinity", null, {
  12436. $documentation: "The `Infinity` value",
  12437. value: 1/0
  12438. }, AST_Atom);
  12439. var AST_Boolean = DEFNODE("Boolean", null, {
  12440. $documentation: "Base class for booleans",
  12441. }, AST_Atom);
  12442. var AST_False = DEFNODE("False", null, {
  12443. $documentation: "The `false` atom",
  12444. value: false
  12445. }, AST_Boolean);
  12446. var AST_True = DEFNODE("True", null, {
  12447. $documentation: "The `true` atom",
  12448. value: true
  12449. }, AST_Boolean);
  12450. /* -----[ TreeWalker ]----- */
  12451. function TreeWalker(callback) {
  12452. this.visit = callback;
  12453. this.stack = [];
  12454. this.directives = Object.create(null);
  12455. };
  12456. TreeWalker.prototype = {
  12457. _visit: function(node, descend) {
  12458. this.push(node);
  12459. var ret = this.visit(node, descend ? function(){
  12460. descend.call(node);
  12461. } : noop);
  12462. if (!ret && descend) {
  12463. descend.call(node);
  12464. }
  12465. this.pop(node);
  12466. return ret;
  12467. },
  12468. parent: function(n) {
  12469. return this.stack[this.stack.length - 2 - (n || 0)];
  12470. },
  12471. push: function (node) {
  12472. if (node instanceof AST_Lambda) {
  12473. this.directives = Object.create(this.directives);
  12474. } else if (node instanceof AST_Directive) {
  12475. this.directives[node.value] = this.directives[node.value] ? "up" : true;
  12476. }
  12477. this.stack.push(node);
  12478. },
  12479. pop: function(node) {
  12480. this.stack.pop();
  12481. if (node instanceof AST_Lambda) {
  12482. this.directives = Object.getPrototypeOf(this.directives);
  12483. }
  12484. },
  12485. self: function() {
  12486. return this.stack[this.stack.length - 1];
  12487. },
  12488. find_parent: function(type) {
  12489. var stack = this.stack;
  12490. for (var i = stack.length; --i >= 0;) {
  12491. var x = stack[i];
  12492. if (x instanceof type) return x;
  12493. }
  12494. },
  12495. has_directive: function(type) {
  12496. var dir = this.directives[type];
  12497. if (dir) return dir;
  12498. var node = this.stack[this.stack.length - 1];
  12499. if (node instanceof AST_Scope) {
  12500. for (var i = 0; i < node.body.length; ++i) {
  12501. var st = node.body[i];
  12502. if (!(st instanceof AST_Directive)) break;
  12503. if (st.value == type) return true;
  12504. }
  12505. }
  12506. },
  12507. in_boolean_context: function() {
  12508. var stack = this.stack;
  12509. var i = stack.length, self = stack[--i];
  12510. while (i > 0) {
  12511. var p = stack[--i];
  12512. if ((p instanceof AST_If && p.condition === self) ||
  12513. (p instanceof AST_Conditional && p.condition === self) ||
  12514. (p instanceof AST_DWLoop && p.condition === self) ||
  12515. (p instanceof AST_For && p.condition === self) ||
  12516. (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self))
  12517. {
  12518. return true;
  12519. }
  12520. if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")))
  12521. return false;
  12522. self = p;
  12523. }
  12524. },
  12525. loopcontrol_target: function(label) {
  12526. var stack = this.stack;
  12527. if (label) for (var i = stack.length; --i >= 0;) {
  12528. var x = stack[i];
  12529. if (x instanceof AST_LabeledStatement && x.label.name == label.name) {
  12530. return x.body;
  12531. }
  12532. } else for (var i = stack.length; --i >= 0;) {
  12533. var x = stack[i];
  12534. if (x instanceof AST_Switch || x instanceof AST_IterationStatement)
  12535. return x;
  12536. }
  12537. }
  12538. };
  12539. /***********************************************************************
  12540. A JavaScript tokenizer / parser / beautifier / compressor.
  12541. https://github.com/mishoo/UglifyJS2
  12542. -------------------------------- (C) ---------------------------------
  12543. Author: Mihai Bazon
  12544. <mihai.bazon@gmail.com>
  12545. http://mihai.bazon.net/blog
  12546. Distributed under the BSD license:
  12547. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  12548. Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  12549. Redistribution and use in source and binary forms, with or without
  12550. modification, are permitted provided that the following conditions
  12551. are met:
  12552. * Redistributions of source code must retain the above
  12553. copyright notice, this list of conditions and the following
  12554. disclaimer.
  12555. * Redistributions in binary form must reproduce the above
  12556. copyright notice, this list of conditions and the following
  12557. disclaimer in the documentation and/or other materials
  12558. provided with the distribution.
  12559. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  12560. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12561. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  12562. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  12563. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  12564. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  12565. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  12566. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  12567. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  12568. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  12569. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12570. SUCH DAMAGE.
  12571. ***********************************************************************/
  12572. "use strict";
  12573. var KEYWORDS = 'break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with';
  12574. var KEYWORDS_ATOM = 'false null true';
  12575. var RESERVED_WORDS = 'abstract boolean byte char class double enum export extends final float goto implements import int interface let long native package private protected public short static super synchronized this throws transient volatile yield'
  12576. + " " + KEYWORDS_ATOM + " " + KEYWORDS;
  12577. var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case';
  12578. KEYWORDS = makePredicate(KEYWORDS);
  12579. RESERVED_WORDS = makePredicate(RESERVED_WORDS);
  12580. KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION);
  12581. KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM);
  12582. var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^"));
  12583. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  12584. var RE_OCT_NUMBER = /^0[0-7]+$/;
  12585. var OPERATORS = makePredicate([
  12586. "in",
  12587. "instanceof",
  12588. "typeof",
  12589. "new",
  12590. "void",
  12591. "delete",
  12592. "++",
  12593. "--",
  12594. "+",
  12595. "-",
  12596. "!",
  12597. "~",
  12598. "&",
  12599. "|",
  12600. "^",
  12601. "*",
  12602. "/",
  12603. "%",
  12604. ">>",
  12605. "<<",
  12606. ">>>",
  12607. "<",
  12608. ">",
  12609. "<=",
  12610. ">=",
  12611. "==",
  12612. "===",
  12613. "!=",
  12614. "!==",
  12615. "?",
  12616. "=",
  12617. "+=",
  12618. "-=",
  12619. "/=",
  12620. "*=",
  12621. "%=",
  12622. ">>=",
  12623. "<<=",
  12624. ">>>=",
  12625. "|=",
  12626. "^=",
  12627. "&=",
  12628. "&&",
  12629. "||"
  12630. ]);
  12631. var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\uFEFF"));
  12632. var NEWLINE_CHARS = makePredicate(characters("\n\r\u2028\u2029"));
  12633. var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:"));
  12634. var PUNC_CHARS = makePredicate(characters("[]{}(),;:"));
  12635. var REGEXP_MODIFIERS = makePredicate(characters("gmsiy"));
  12636. /* -----[ Tokenizer ]----- */
  12637. // regexps adapted from http://xregexp.com/plugins/#unicode
  12638. var UNICODE = {
  12639. letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\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]"),
  12640. digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0DE6-\\u0DEF\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uA9F0-\\uA9F9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]"),
  12641. non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
  12642. space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"),
  12643. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
  12644. };
  12645. function is_letter(code) {
  12646. return (code >= 97 && code <= 122)
  12647. || (code >= 65 && code <= 90)
  12648. || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code)));
  12649. };
  12650. function is_digit(code) {
  12651. return code >= 48 && code <= 57;
  12652. };
  12653. function is_alphanumeric_char(code) {
  12654. return is_digit(code) || is_letter(code);
  12655. };
  12656. function is_unicode_digit(code) {
  12657. return UNICODE.digit.test(String.fromCharCode(code));
  12658. }
  12659. function is_unicode_combining_mark(ch) {
  12660. return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
  12661. };
  12662. function is_unicode_connector_punctuation(ch) {
  12663. return UNICODE.connector_punctuation.test(ch);
  12664. };
  12665. function is_identifier(name) {
  12666. return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name);
  12667. };
  12668. function is_identifier_start(code) {
  12669. return code == 36 || code == 95 || is_letter(code);
  12670. };
  12671. function is_identifier_char(ch) {
  12672. var code = ch.charCodeAt(0);
  12673. return is_identifier_start(code)
  12674. || is_digit(code)
  12675. || code == 8204 // \u200c: zero-width non-joiner <ZWNJ>
  12676. || code == 8205 // \u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
  12677. || is_unicode_combining_mark(ch)
  12678. || is_unicode_connector_punctuation(ch)
  12679. || is_unicode_digit(code)
  12680. ;
  12681. };
  12682. function is_identifier_string(str){
  12683. return /^[a-z_$][a-z0-9_$]*$/i.test(str);
  12684. };
  12685. function parse_js_number(num) {
  12686. if (RE_HEX_NUMBER.test(num)) {
  12687. return parseInt(num.substr(2), 16);
  12688. } else if (RE_OCT_NUMBER.test(num)) {
  12689. return parseInt(num.substr(1), 8);
  12690. } else {
  12691. var val = parseFloat(num);
  12692. if (val == num) return val;
  12693. }
  12694. };
  12695. function JS_Parse_Error(message, filename, line, col, pos) {
  12696. this.message = message;
  12697. this.filename = filename;
  12698. this.line = line;
  12699. this.col = col;
  12700. this.pos = pos;
  12701. this.stack = new Error().stack;
  12702. };
  12703. JS_Parse_Error.prototype.toString = function() {
  12704. return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
  12705. };
  12706. function js_error(message, filename, line, col, pos) {
  12707. throw new JS_Parse_Error(message, filename, line, col, pos);
  12708. };
  12709. function is_token(token, type, val) {
  12710. return token.type == type && (val == null || token.value == val);
  12711. };
  12712. var EX_EOF = {};
  12713. function tokenizer($TEXT, filename, html5_comments, shebang) {
  12714. var S = {
  12715. text : $TEXT,
  12716. filename : filename,
  12717. pos : 0,
  12718. tokpos : 0,
  12719. line : 1,
  12720. tokline : 0,
  12721. col : 0,
  12722. tokcol : 0,
  12723. newline_before : false,
  12724. regex_allowed : false,
  12725. comments_before : [],
  12726. directives : {},
  12727. directive_stack : []
  12728. };
  12729. function peek() { return S.text.charAt(S.pos); };
  12730. function next(signal_eof, in_string) {
  12731. var ch = S.text.charAt(S.pos++);
  12732. if (signal_eof && !ch)
  12733. throw EX_EOF;
  12734. if (NEWLINE_CHARS(ch)) {
  12735. S.newline_before = S.newline_before || !in_string;
  12736. ++S.line;
  12737. S.col = 0;
  12738. if (!in_string && ch == "\r" && peek() == "\n") {
  12739. // treat a \r\n sequence as a single \n
  12740. ++S.pos;
  12741. ch = "\n";
  12742. }
  12743. } else {
  12744. ++S.col;
  12745. }
  12746. return ch;
  12747. };
  12748. function forward(i) {
  12749. while (i-- > 0) next();
  12750. };
  12751. function looking_at(str) {
  12752. return S.text.substr(S.pos, str.length) == str;
  12753. };
  12754. function find_eol() {
  12755. var text = S.text;
  12756. for (var i = S.pos, n = S.text.length; i < n; ++i) {
  12757. var ch = text[i];
  12758. if (NEWLINE_CHARS(ch))
  12759. return i;
  12760. }
  12761. return -1;
  12762. };
  12763. function find(what, signal_eof) {
  12764. var pos = S.text.indexOf(what, S.pos);
  12765. if (signal_eof && pos == -1) throw EX_EOF;
  12766. return pos;
  12767. };
  12768. function start_token() {
  12769. S.tokline = S.line;
  12770. S.tokcol = S.col;
  12771. S.tokpos = S.pos;
  12772. };
  12773. var prev_was_dot = false;
  12774. function token(type, value, is_comment) {
  12775. S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX(value)) ||
  12776. (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) ||
  12777. (type == "punc" && PUNC_BEFORE_EXPRESSION(value)));
  12778. prev_was_dot = (type == "punc" && value == ".");
  12779. var ret = {
  12780. type : type,
  12781. value : value,
  12782. line : S.tokline,
  12783. col : S.tokcol,
  12784. pos : S.tokpos,
  12785. endline : S.line,
  12786. endcol : S.col,
  12787. endpos : S.pos,
  12788. nlb : S.newline_before,
  12789. file : filename
  12790. };
  12791. if (/^(?:num|string|regexp)$/i.test(type)) {
  12792. ret.raw = $TEXT.substring(ret.pos, ret.endpos);
  12793. }
  12794. if (!is_comment) {
  12795. ret.comments_before = S.comments_before;
  12796. S.comments_before = [];
  12797. // make note of any newlines in the comments that came before
  12798. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  12799. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  12800. }
  12801. }
  12802. S.newline_before = false;
  12803. return new AST_Token(ret);
  12804. };
  12805. function skip_whitespace() {
  12806. while (WHITESPACE_CHARS(peek()))
  12807. next();
  12808. };
  12809. function read_while(pred) {
  12810. var ret = "", ch, i = 0;
  12811. while ((ch = peek()) && pred(ch, i++))
  12812. ret += next();
  12813. return ret;
  12814. };
  12815. function parse_error(err) {
  12816. js_error(err, filename, S.tokline, S.tokcol, S.tokpos);
  12817. };
  12818. function read_num(prefix) {
  12819. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  12820. var num = read_while(function(ch, i){
  12821. var code = ch.charCodeAt(0);
  12822. switch (code) {
  12823. case 120: case 88: // xX
  12824. return has_x ? false : (has_x = true);
  12825. case 101: case 69: // eE
  12826. return has_x ? true : has_e ? false : (has_e = after_e = true);
  12827. case 45: // -
  12828. return after_e || (i == 0 && !prefix);
  12829. case 43: // +
  12830. return after_e;
  12831. case (after_e = false, 46): // .
  12832. return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false;
  12833. }
  12834. return is_alphanumeric_char(code);
  12835. });
  12836. if (prefix) num = prefix + num;
  12837. if (RE_OCT_NUMBER.test(num) && next_token.has_directive("use strict")) {
  12838. parse_error("SyntaxError: Legacy octal literals are not allowed in strict mode");
  12839. }
  12840. var valid = parse_js_number(num);
  12841. if (!isNaN(valid)) {
  12842. return token("num", valid);
  12843. } else {
  12844. parse_error("SyntaxError: Invalid syntax: " + num);
  12845. }
  12846. };
  12847. function read_escaped_char(in_string) {
  12848. var ch = next(true, in_string);
  12849. switch (ch.charCodeAt(0)) {
  12850. case 110 : return "\n";
  12851. case 114 : return "\r";
  12852. case 116 : return "\t";
  12853. case 98 : return "\b";
  12854. case 118 : return "\u000b"; // \v
  12855. case 102 : return "\f";
  12856. case 120 : return String.fromCharCode(hex_bytes(2)); // \x
  12857. case 117 : return String.fromCharCode(hex_bytes(4)); // \u
  12858. case 10 : return ""; // newline
  12859. case 13 : // \r
  12860. if (peek() == "\n") { // DOS newline
  12861. next(true, in_string);
  12862. return "";
  12863. }
  12864. }
  12865. if (ch >= "0" && ch <= "7")
  12866. return read_octal_escape_sequence(ch);
  12867. return ch;
  12868. };
  12869. function read_octal_escape_sequence(ch) {
  12870. // Read
  12871. var p = peek();
  12872. if (p >= "0" && p <= "7") {
  12873. ch += next(true);
  12874. if (ch[0] <= "3" && (p = peek()) >= "0" && p <= "7")
  12875. ch += next(true);
  12876. }
  12877. // Parse
  12878. if (ch === "0") return "\0";
  12879. if (ch.length > 0 && next_token.has_directive("use strict"))
  12880. parse_error("SyntaxError: Legacy octal escape sequences are not allowed in strict mode");
  12881. return String.fromCharCode(parseInt(ch, 8));
  12882. }
  12883. function hex_bytes(n) {
  12884. var num = 0;
  12885. for (; n > 0; --n) {
  12886. var digit = parseInt(next(true), 16);
  12887. if (isNaN(digit))
  12888. parse_error("SyntaxError: Invalid hex-character pattern in string");
  12889. num = (num << 4) | digit;
  12890. }
  12891. return num;
  12892. };
  12893. var read_string = with_eof_error("SyntaxError: Unterminated string constant", function(quote_char){
  12894. var quote = next(), ret = "";
  12895. for (;;) {
  12896. var ch = next(true, true);
  12897. if (ch == "\\") ch = read_escaped_char(true);
  12898. else if (NEWLINE_CHARS(ch)) parse_error("SyntaxError: Unterminated string constant");
  12899. else if (ch == quote) break;
  12900. ret += ch;
  12901. }
  12902. var tok = token("string", ret);
  12903. tok.quote = quote_char;
  12904. return tok;
  12905. });
  12906. function skip_line_comment(type) {
  12907. var regex_allowed = S.regex_allowed;
  12908. var i = find_eol(), ret;
  12909. if (i == -1) {
  12910. ret = S.text.substr(S.pos);
  12911. S.pos = S.text.length;
  12912. } else {
  12913. ret = S.text.substring(S.pos, i);
  12914. S.pos = i;
  12915. }
  12916. S.col = S.tokcol + (S.pos - S.tokpos);
  12917. S.comments_before.push(token(type, ret, true));
  12918. S.regex_allowed = regex_allowed;
  12919. return next_token;
  12920. };
  12921. var skip_multiline_comment = with_eof_error("SyntaxError: Unterminated multiline comment", function(){
  12922. var regex_allowed = S.regex_allowed;
  12923. var i = find("*/", true);
  12924. var text = S.text.substring(S.pos, i).replace(/\r\n|\r|\u2028|\u2029/g, '\n');
  12925. // update stream position
  12926. forward(text.length /* doesn't count \r\n as 2 char while S.pos - i does */ + 2);
  12927. S.comments_before.push(token("comment2", text, true));
  12928. S.regex_allowed = regex_allowed;
  12929. return next_token;
  12930. });
  12931. function read_name() {
  12932. var backslash = false, name = "", ch, escaped = false, hex;
  12933. while ((ch = peek()) != null) {
  12934. if (!backslash) {
  12935. if (ch == "\\") escaped = backslash = true, next();
  12936. else if (is_identifier_char(ch)) name += next();
  12937. else break;
  12938. }
  12939. else {
  12940. if (ch != "u") parse_error("SyntaxError: Expecting UnicodeEscapeSequence -- uXXXX");
  12941. ch = read_escaped_char();
  12942. if (!is_identifier_char(ch)) parse_error("SyntaxError: Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  12943. name += ch;
  12944. backslash = false;
  12945. }
  12946. }
  12947. if (KEYWORDS(name) && escaped) {
  12948. hex = name.charCodeAt(0).toString(16).toUpperCase();
  12949. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  12950. }
  12951. return name;
  12952. };
  12953. var read_regexp = with_eof_error("SyntaxError: Unterminated regular expression", function(regexp){
  12954. var prev_backslash = false, ch, in_class = false;
  12955. while ((ch = next(true))) if (NEWLINE_CHARS(ch)) {
  12956. parse_error("SyntaxError: Unexpected line terminator");
  12957. } else if (prev_backslash) {
  12958. regexp += "\\" + ch;
  12959. prev_backslash = false;
  12960. } else if (ch == "[") {
  12961. in_class = true;
  12962. regexp += ch;
  12963. } else if (ch == "]" && in_class) {
  12964. in_class = false;
  12965. regexp += ch;
  12966. } else if (ch == "/" && !in_class) {
  12967. break;
  12968. } else if (ch == "\\") {
  12969. prev_backslash = true;
  12970. } else {
  12971. regexp += ch;
  12972. }
  12973. var mods = read_name();
  12974. try {
  12975. return token("regexp", new RegExp(regexp, mods));
  12976. } catch(e) {
  12977. parse_error("SyntaxError: " + e.message);
  12978. }
  12979. });
  12980. function read_operator(prefix) {
  12981. function grow(op) {
  12982. if (!peek()) return op;
  12983. var bigger = op + peek();
  12984. if (OPERATORS(bigger)) {
  12985. next();
  12986. return grow(bigger);
  12987. } else {
  12988. return op;
  12989. }
  12990. };
  12991. return token("operator", grow(prefix || next()));
  12992. };
  12993. function handle_slash() {
  12994. next();
  12995. switch (peek()) {
  12996. case "/":
  12997. next();
  12998. return skip_line_comment("comment1");
  12999. case "*":
  13000. next();
  13001. return skip_multiline_comment();
  13002. }
  13003. return S.regex_allowed ? read_regexp("") : read_operator("/");
  13004. };
  13005. function handle_dot() {
  13006. next();
  13007. return is_digit(peek().charCodeAt(0))
  13008. ? read_num(".")
  13009. : token("punc", ".");
  13010. };
  13011. function read_word() {
  13012. var word = read_name();
  13013. if (prev_was_dot) return token("name", word);
  13014. return KEYWORDS_ATOM(word) ? token("atom", word)
  13015. : !KEYWORDS(word) ? token("name", word)
  13016. : OPERATORS(word) ? token("operator", word)
  13017. : token("keyword", word);
  13018. };
  13019. function with_eof_error(eof_error, cont) {
  13020. return function(x) {
  13021. try {
  13022. return cont(x);
  13023. } catch(ex) {
  13024. if (ex === EX_EOF) parse_error(eof_error);
  13025. else throw ex;
  13026. }
  13027. };
  13028. };
  13029. function next_token(force_regexp) {
  13030. if (force_regexp != null)
  13031. return read_regexp(force_regexp);
  13032. for (;;) {
  13033. skip_whitespace();
  13034. start_token();
  13035. if (html5_comments) {
  13036. if (looking_at("<!--")) {
  13037. forward(4);
  13038. skip_line_comment("comment3");
  13039. continue;
  13040. }
  13041. if (looking_at("-->") && S.newline_before) {
  13042. forward(3);
  13043. skip_line_comment("comment4");
  13044. continue;
  13045. }
  13046. }
  13047. var ch = peek();
  13048. if (!ch) return token("eof");
  13049. var code = ch.charCodeAt(0);
  13050. switch (code) {
  13051. case 34: case 39: return read_string(ch);
  13052. case 46: return handle_dot();
  13053. case 47: {
  13054. var tok = handle_slash();
  13055. if (tok === next_token) continue;
  13056. return tok;
  13057. }
  13058. }
  13059. if (is_digit(code)) return read_num();
  13060. if (PUNC_CHARS(ch)) return token("punc", next());
  13061. if (OPERATOR_CHARS(ch)) return read_operator();
  13062. if (code == 92 || is_identifier_start(code)) return read_word();
  13063. if (shebang) {
  13064. if (S.pos == 0 && looking_at("#!")) {
  13065. forward(2);
  13066. skip_line_comment("comment5");
  13067. continue;
  13068. }
  13069. }
  13070. break;
  13071. }
  13072. parse_error("SyntaxError: Unexpected character '" + ch + "'");
  13073. };
  13074. next_token.context = function(nc) {
  13075. if (nc) S = nc;
  13076. return S;
  13077. };
  13078. next_token.add_directive = function(directive) {
  13079. S.directive_stack[S.directive_stack.length - 1].push(directive);
  13080. if (S.directives[directive] === undefined) {
  13081. S.directives[directive] = 1;
  13082. } else {
  13083. S.directives[directive]++;
  13084. }
  13085. }
  13086. next_token.push_directives_stack = function() {
  13087. S.directive_stack.push([]);
  13088. }
  13089. next_token.pop_directives_stack = function() {
  13090. var directives = S.directive_stack[S.directive_stack.length - 1];
  13091. for (var i = 0; i < directives.length; i++) {
  13092. S.directives[directives[i]]--;
  13093. }
  13094. S.directive_stack.pop();
  13095. }
  13096. next_token.has_directive = function(directive) {
  13097. return S.directives[directive] !== undefined &&
  13098. S.directives[directive] > 0;
  13099. }
  13100. return next_token;
  13101. };
  13102. /* -----[ Parser (constants) ]----- */
  13103. var UNARY_PREFIX = makePredicate([
  13104. "typeof",
  13105. "void",
  13106. "delete",
  13107. "--",
  13108. "++",
  13109. "!",
  13110. "~",
  13111. "-",
  13112. "+"
  13113. ]);
  13114. var UNARY_POSTFIX = makePredicate([ "--", "++" ]);
  13115. var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]);
  13116. var PRECEDENCE = (function(a, ret){
  13117. for (var i = 0; i < a.length; ++i) {
  13118. var b = a[i];
  13119. for (var j = 0; j < b.length; ++j) {
  13120. ret[b[j]] = i + 1;
  13121. }
  13122. }
  13123. return ret;
  13124. })(
  13125. [
  13126. ["||"],
  13127. ["&&"],
  13128. ["|"],
  13129. ["^"],
  13130. ["&"],
  13131. ["==", "===", "!=", "!=="],
  13132. ["<", ">", "<=", ">=", "in", "instanceof"],
  13133. [">>", "<<", ">>>"],
  13134. ["+", "-"],
  13135. ["*", "/", "%"]
  13136. ],
  13137. {}
  13138. );
  13139. var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
  13140. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  13141. /* -----[ Parser ]----- */
  13142. function parse($TEXT, options) {
  13143. options = defaults(options, {
  13144. strict : false,
  13145. filename : null,
  13146. toplevel : null,
  13147. expression : false,
  13148. html5_comments : true,
  13149. bare_returns : false,
  13150. shebang : true,
  13151. });
  13152. var S = {
  13153. input : (typeof $TEXT == "string"
  13154. ? tokenizer($TEXT, options.filename,
  13155. options.html5_comments, options.shebang)
  13156. : $TEXT),
  13157. token : null,
  13158. prev : null,
  13159. peeked : null,
  13160. in_function : 0,
  13161. in_directives : true,
  13162. in_loop : 0,
  13163. labels : []
  13164. };
  13165. S.token = next();
  13166. function is(type, value) {
  13167. return is_token(S.token, type, value);
  13168. };
  13169. function peek() { return S.peeked || (S.peeked = S.input()); };
  13170. function next() {
  13171. S.prev = S.token;
  13172. if (S.peeked) {
  13173. S.token = S.peeked;
  13174. S.peeked = null;
  13175. } else {
  13176. S.token = S.input();
  13177. }
  13178. S.in_directives = S.in_directives && (
  13179. S.token.type == "string" || is("punc", ";")
  13180. );
  13181. return S.token;
  13182. };
  13183. function prev() {
  13184. return S.prev;
  13185. };
  13186. function croak(msg, line, col, pos) {
  13187. var ctx = S.input.context();
  13188. js_error(msg,
  13189. ctx.filename,
  13190. line != null ? line : ctx.tokline,
  13191. col != null ? col : ctx.tokcol,
  13192. pos != null ? pos : ctx.tokpos);
  13193. };
  13194. function token_error(token, msg) {
  13195. croak(msg, token.line, token.col);
  13196. };
  13197. function unexpected(token) {
  13198. if (token == null)
  13199. token = S.token;
  13200. token_error(token, "SyntaxError: Unexpected token: " + token.type + " (" + token.value + ")");
  13201. };
  13202. function expect_token(type, val) {
  13203. if (is(type, val)) {
  13204. return next();
  13205. }
  13206. token_error(S.token, "SyntaxError: Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»");
  13207. };
  13208. function expect(punc) { return expect_token("punc", punc); };
  13209. function can_insert_semicolon() {
  13210. return !options.strict && (
  13211. S.token.nlb || is("eof") || is("punc", "}")
  13212. );
  13213. };
  13214. function semicolon(optional) {
  13215. if (is("punc", ";")) next();
  13216. else if (!optional && !can_insert_semicolon()) unexpected();
  13217. };
  13218. function parenthesised() {
  13219. expect("(");
  13220. var exp = expression(true);
  13221. expect(")");
  13222. return exp;
  13223. };
  13224. function embed_tokens(parser) {
  13225. return function() {
  13226. var start = S.token;
  13227. var expr = parser();
  13228. var end = prev();
  13229. expr.start = start;
  13230. expr.end = end;
  13231. return expr;
  13232. };
  13233. };
  13234. function handle_regexp() {
  13235. if (is("operator", "/") || is("operator", "/=")) {
  13236. S.peeked = null;
  13237. S.token = S.input(S.token.value.substr(1)); // force regexp
  13238. }
  13239. };
  13240. var statement = embed_tokens(function() {
  13241. var tmp;
  13242. handle_regexp();
  13243. switch (S.token.type) {
  13244. case "string":
  13245. var dir = false;
  13246. if (S.in_directives === true) {
  13247. if ((is_token(peek(), "punc", ";") || peek().nlb) && S.token.raw.indexOf("\\") === -1) {
  13248. S.input.add_directive(S.token.value);
  13249. } else {
  13250. S.in_directives = false;
  13251. }
  13252. }
  13253. var dir = S.in_directives, stat = simple_statement();
  13254. if (dir) {
  13255. return new AST_Directive({
  13256. start : stat.body.start,
  13257. end : stat.body.end,
  13258. quote : stat.body.quote,
  13259. value : stat.body.value,
  13260. });
  13261. }
  13262. return stat;
  13263. case "num":
  13264. case "regexp":
  13265. case "operator":
  13266. case "atom":
  13267. return simple_statement();
  13268. case "name":
  13269. return is_token(peek(), "punc", ":")
  13270. ? labeled_statement()
  13271. : simple_statement();
  13272. case "punc":
  13273. switch (S.token.value) {
  13274. case "{":
  13275. return new AST_BlockStatement({
  13276. start : S.token,
  13277. body : block_(),
  13278. end : prev()
  13279. });
  13280. case "[":
  13281. case "(":
  13282. return simple_statement();
  13283. case ";":
  13284. S.in_directives = false;
  13285. next();
  13286. return new AST_EmptyStatement();
  13287. default:
  13288. unexpected();
  13289. }
  13290. case "keyword":
  13291. switch (tmp = S.token.value, next(), tmp) {
  13292. case "break":
  13293. return break_cont(AST_Break);
  13294. case "continue":
  13295. return break_cont(AST_Continue);
  13296. case "debugger":
  13297. semicolon();
  13298. return new AST_Debugger();
  13299. case "do":
  13300. return new AST_Do({
  13301. body : in_loop(statement),
  13302. condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(true), tmp)
  13303. });
  13304. case "while":
  13305. return new AST_While({
  13306. condition : parenthesised(),
  13307. body : in_loop(statement)
  13308. });
  13309. case "for":
  13310. return for_();
  13311. case "function":
  13312. return function_(AST_Defun);
  13313. case "if":
  13314. return if_();
  13315. case "return":
  13316. if (S.in_function == 0 && !options.bare_returns)
  13317. croak("SyntaxError: 'return' outside of function");
  13318. return new AST_Return({
  13319. value: ( is("punc", ";")
  13320. ? (next(), null)
  13321. : can_insert_semicolon()
  13322. ? null
  13323. : (tmp = expression(true), semicolon(), tmp) )
  13324. });
  13325. case "switch":
  13326. return new AST_Switch({
  13327. expression : parenthesised(),
  13328. body : in_loop(switch_body_)
  13329. });
  13330. case "throw":
  13331. if (S.token.nlb)
  13332. croak("SyntaxError: Illegal newline after 'throw'");
  13333. return new AST_Throw({
  13334. value: (tmp = expression(true), semicolon(), tmp)
  13335. });
  13336. case "try":
  13337. return try_();
  13338. case "var":
  13339. return tmp = var_(), semicolon(), tmp;
  13340. case "const":
  13341. return tmp = const_(), semicolon(), tmp;
  13342. case "with":
  13343. if (S.input.has_directive("use strict")) {
  13344. croak("SyntaxError: Strict mode may not include a with statement");
  13345. }
  13346. return new AST_With({
  13347. expression : parenthesised(),
  13348. body : statement()
  13349. });
  13350. default:
  13351. unexpected();
  13352. }
  13353. }
  13354. });
  13355. function labeled_statement() {
  13356. var label = as_symbol(AST_Label);
  13357. if (find_if(function(l){ return l.name == label.name }, S.labels)) {
  13358. // ECMA-262, 12.12: An ECMAScript program is considered
  13359. // syntactically incorrect if it contains a
  13360. // LabelledStatement that is enclosed by a
  13361. // LabelledStatement with the same Identifier as label.
  13362. croak("SyntaxError: Label " + label.name + " defined twice");
  13363. }
  13364. expect(":");
  13365. S.labels.push(label);
  13366. var stat = statement();
  13367. S.labels.pop();
  13368. if (!(stat instanceof AST_IterationStatement)) {
  13369. // check for `continue` that refers to this label.
  13370. // those should be reported as syntax errors.
  13371. // https://github.com/mishoo/UglifyJS2/issues/287
  13372. label.references.forEach(function(ref){
  13373. if (ref instanceof AST_Continue) {
  13374. ref = ref.label.start;
  13375. croak("SyntaxError: Continue label `" + label.name + "` refers to non-IterationStatement.",
  13376. ref.line, ref.col, ref.pos);
  13377. }
  13378. });
  13379. }
  13380. return new AST_LabeledStatement({ body: stat, label: label });
  13381. };
  13382. function simple_statement(tmp) {
  13383. return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) });
  13384. };
  13385. function break_cont(type) {
  13386. var label = null, ldef;
  13387. if (!can_insert_semicolon()) {
  13388. label = as_symbol(AST_LabelRef, true);
  13389. }
  13390. if (label != null) {
  13391. ldef = find_if(function(l){ return l.name == label.name }, S.labels);
  13392. if (!ldef)
  13393. croak("SyntaxError: Undefined label " + label.name);
  13394. label.thedef = ldef;
  13395. }
  13396. else if (S.in_loop == 0)
  13397. croak("SyntaxError: " + type.TYPE + " not inside a loop or switch");
  13398. semicolon();
  13399. var stat = new type({ label: label });
  13400. if (ldef) ldef.references.push(stat);
  13401. return stat;
  13402. };
  13403. function for_() {
  13404. expect("(");
  13405. var init = null;
  13406. if (!is("punc", ";")) {
  13407. init = is("keyword", "var")
  13408. ? (next(), var_(true))
  13409. : expression(true, true);
  13410. if (is("operator", "in")) {
  13411. if (init instanceof AST_Var && init.definitions.length > 1)
  13412. croak("SyntaxError: Only one variable declaration allowed in for..in loop");
  13413. next();
  13414. return for_in(init);
  13415. }
  13416. }
  13417. return regular_for(init);
  13418. };
  13419. function regular_for(init) {
  13420. expect(";");
  13421. var test = is("punc", ";") ? null : expression(true);
  13422. expect(";");
  13423. var step = is("punc", ")") ? null : expression(true);
  13424. expect(")");
  13425. return new AST_For({
  13426. init : init,
  13427. condition : test,
  13428. step : step,
  13429. body : in_loop(statement)
  13430. });
  13431. };
  13432. function for_in(init) {
  13433. var lhs = init instanceof AST_Var ? init.definitions[0].name : null;
  13434. var obj = expression(true);
  13435. expect(")");
  13436. return new AST_ForIn({
  13437. init : init,
  13438. name : lhs,
  13439. object : obj,
  13440. body : in_loop(statement)
  13441. });
  13442. };
  13443. var function_ = function(ctor) {
  13444. var in_statement = ctor === AST_Defun;
  13445. var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null;
  13446. if (in_statement && !name)
  13447. unexpected();
  13448. expect("(");
  13449. return new ctor({
  13450. name: name,
  13451. argnames: (function(first, a){
  13452. while (!is("punc", ")")) {
  13453. if (first) first = false; else expect(",");
  13454. a.push(as_symbol(AST_SymbolFunarg));
  13455. }
  13456. next();
  13457. return a;
  13458. })(true, []),
  13459. body: (function(loop, labels){
  13460. ++S.in_function;
  13461. S.in_directives = true;
  13462. S.input.push_directives_stack();
  13463. S.in_loop = 0;
  13464. S.labels = [];
  13465. var a = block_();
  13466. S.input.pop_directives_stack();
  13467. --S.in_function;
  13468. S.in_loop = loop;
  13469. S.labels = labels;
  13470. return a;
  13471. })(S.in_loop, S.labels)
  13472. });
  13473. };
  13474. function if_() {
  13475. var cond = parenthesised(), body = statement(), belse = null;
  13476. if (is("keyword", "else")) {
  13477. next();
  13478. belse = statement();
  13479. }
  13480. return new AST_If({
  13481. condition : cond,
  13482. body : body,
  13483. alternative : belse
  13484. });
  13485. };
  13486. function block_() {
  13487. expect("{");
  13488. var a = [];
  13489. while (!is("punc", "}")) {
  13490. if (is("eof")) unexpected();
  13491. a.push(statement());
  13492. }
  13493. next();
  13494. return a;
  13495. };
  13496. function switch_body_() {
  13497. expect("{");
  13498. var a = [], cur = null, branch = null, tmp;
  13499. while (!is("punc", "}")) {
  13500. if (is("eof")) unexpected();
  13501. if (is("keyword", "case")) {
  13502. if (branch) branch.end = prev();
  13503. cur = [];
  13504. branch = new AST_Case({
  13505. start : (tmp = S.token, next(), tmp),
  13506. expression : expression(true),
  13507. body : cur
  13508. });
  13509. a.push(branch);
  13510. expect(":");
  13511. }
  13512. else if (is("keyword", "default")) {
  13513. if (branch) branch.end = prev();
  13514. cur = [];
  13515. branch = new AST_Default({
  13516. start : (tmp = S.token, next(), expect(":"), tmp),
  13517. body : cur
  13518. });
  13519. a.push(branch);
  13520. }
  13521. else {
  13522. if (!cur) unexpected();
  13523. cur.push(statement());
  13524. }
  13525. }
  13526. if (branch) branch.end = prev();
  13527. next();
  13528. return a;
  13529. };
  13530. function try_() {
  13531. var body = block_(), bcatch = null, bfinally = null;
  13532. if (is("keyword", "catch")) {
  13533. var start = S.token;
  13534. next();
  13535. expect("(");
  13536. var name = as_symbol(AST_SymbolCatch);
  13537. expect(")");
  13538. bcatch = new AST_Catch({
  13539. start : start,
  13540. argname : name,
  13541. body : block_(),
  13542. end : prev()
  13543. });
  13544. }
  13545. if (is("keyword", "finally")) {
  13546. var start = S.token;
  13547. next();
  13548. bfinally = new AST_Finally({
  13549. start : start,
  13550. body : block_(),
  13551. end : prev()
  13552. });
  13553. }
  13554. if (!bcatch && !bfinally)
  13555. croak("SyntaxError: Missing catch/finally blocks");
  13556. return new AST_Try({
  13557. body : body,
  13558. bcatch : bcatch,
  13559. bfinally : bfinally
  13560. });
  13561. };
  13562. function vardefs(no_in, in_const) {
  13563. var a = [];
  13564. for (;;) {
  13565. a.push(new AST_VarDef({
  13566. start : S.token,
  13567. name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar),
  13568. value : is("operator", "=") ? (next(), expression(false, no_in)) : null,
  13569. end : prev()
  13570. }));
  13571. if (!is("punc", ","))
  13572. break;
  13573. next();
  13574. }
  13575. return a;
  13576. };
  13577. var var_ = function(no_in) {
  13578. return new AST_Var({
  13579. start : prev(),
  13580. definitions : vardefs(no_in, false),
  13581. end : prev()
  13582. });
  13583. };
  13584. var const_ = function() {
  13585. return new AST_Const({
  13586. start : prev(),
  13587. definitions : vardefs(false, true),
  13588. end : prev()
  13589. });
  13590. };
  13591. var new_ = function(allow_calls) {
  13592. var start = S.token;
  13593. expect_token("operator", "new");
  13594. var newexp = expr_atom(false), args;
  13595. if (is("punc", "(")) {
  13596. next();
  13597. args = expr_list(")");
  13598. } else {
  13599. args = [];
  13600. }
  13601. return subscripts(new AST_New({
  13602. start : start,
  13603. expression : newexp,
  13604. args : args,
  13605. end : prev()
  13606. }), allow_calls);
  13607. };
  13608. function as_atom_node() {
  13609. var tok = S.token, ret;
  13610. switch (tok.type) {
  13611. case "name":
  13612. case "keyword":
  13613. ret = _make_symbol(AST_SymbolRef);
  13614. break;
  13615. case "num":
  13616. ret = new AST_Number({ start: tok, end: tok, value: tok.value });
  13617. break;
  13618. case "string":
  13619. ret = new AST_String({
  13620. start : tok,
  13621. end : tok,
  13622. value : tok.value,
  13623. quote : tok.quote
  13624. });
  13625. break;
  13626. case "regexp":
  13627. ret = new AST_RegExp({ start: tok, end: tok, value: tok.value });
  13628. break;
  13629. case "atom":
  13630. switch (tok.value) {
  13631. case "false":
  13632. ret = new AST_False({ start: tok, end: tok });
  13633. break;
  13634. case "true":
  13635. ret = new AST_True({ start: tok, end: tok });
  13636. break;
  13637. case "null":
  13638. ret = new AST_Null({ start: tok, end: tok });
  13639. break;
  13640. }
  13641. break;
  13642. case "operator":
  13643. if (!is_identifier_string(tok.value)) {
  13644. croak("SyntaxError: Invalid getter/setter name: " + tok.value,
  13645. tok.line, tok.col, tok.pos);
  13646. }
  13647. ret = _make_symbol(AST_SymbolRef);
  13648. break;
  13649. }
  13650. next();
  13651. return ret;
  13652. };
  13653. var expr_atom = function(allow_calls) {
  13654. if (is("operator", "new")) {
  13655. return new_(allow_calls);
  13656. }
  13657. var start = S.token;
  13658. if (is("punc")) {
  13659. switch (start.value) {
  13660. case "(":
  13661. next();
  13662. var ex = expression(true);
  13663. ex.start = start;
  13664. ex.end = S.token;
  13665. expect(")");
  13666. return subscripts(ex, allow_calls);
  13667. case "[":
  13668. return subscripts(array_(), allow_calls);
  13669. case "{":
  13670. return subscripts(object_(), allow_calls);
  13671. }
  13672. unexpected();
  13673. }
  13674. if (is("keyword", "function")) {
  13675. next();
  13676. var func = function_(AST_Function);
  13677. func.start = start;
  13678. func.end = prev();
  13679. return subscripts(func, allow_calls);
  13680. }
  13681. if (ATOMIC_START_TOKEN[S.token.type]) {
  13682. return subscripts(as_atom_node(), allow_calls);
  13683. }
  13684. unexpected();
  13685. };
  13686. function expr_list(closing, allow_trailing_comma, allow_empty) {
  13687. var first = true, a = [];
  13688. while (!is("punc", closing)) {
  13689. if (first) first = false; else expect(",");
  13690. if (allow_trailing_comma && is("punc", closing)) break;
  13691. if (is("punc", ",") && allow_empty) {
  13692. a.push(new AST_Hole({ start: S.token, end: S.token }));
  13693. } else {
  13694. a.push(expression(false));
  13695. }
  13696. }
  13697. next();
  13698. return a;
  13699. };
  13700. var array_ = embed_tokens(function() {
  13701. expect("[");
  13702. return new AST_Array({
  13703. elements: expr_list("]", !options.strict, true)
  13704. });
  13705. });
  13706. var object_ = embed_tokens(function() {
  13707. expect("{");
  13708. var first = true, a = [];
  13709. while (!is("punc", "}")) {
  13710. if (first) first = false; else expect(",");
  13711. if (!options.strict && is("punc", "}"))
  13712. // allow trailing comma
  13713. break;
  13714. var start = S.token;
  13715. var type = start.type;
  13716. var name = as_property_name();
  13717. if (type == "name" && !is("punc", ":")) {
  13718. if (name == "get") {
  13719. a.push(new AST_ObjectGetter({
  13720. start : start,
  13721. key : as_atom_node(),
  13722. value : function_(AST_Accessor),
  13723. end : prev()
  13724. }));
  13725. continue;
  13726. }
  13727. if (name == "set") {
  13728. a.push(new AST_ObjectSetter({
  13729. start : start,
  13730. key : as_atom_node(),
  13731. value : function_(AST_Accessor),
  13732. end : prev()
  13733. }));
  13734. continue;
  13735. }
  13736. }
  13737. expect(":");
  13738. a.push(new AST_ObjectKeyVal({
  13739. start : start,
  13740. quote : start.quote,
  13741. key : name,
  13742. value : expression(false),
  13743. end : prev()
  13744. }));
  13745. }
  13746. next();
  13747. return new AST_Object({ properties: a });
  13748. });
  13749. function as_property_name() {
  13750. var tmp = S.token;
  13751. next();
  13752. switch (tmp.type) {
  13753. case "num":
  13754. case "string":
  13755. case "name":
  13756. case "operator":
  13757. case "keyword":
  13758. case "atom":
  13759. return tmp.value;
  13760. default:
  13761. unexpected();
  13762. }
  13763. };
  13764. function as_name() {
  13765. var tmp = S.token;
  13766. next();
  13767. switch (tmp.type) {
  13768. case "name":
  13769. case "operator":
  13770. case "keyword":
  13771. case "atom":
  13772. return tmp.value;
  13773. default:
  13774. unexpected();
  13775. }
  13776. };
  13777. function _make_symbol(type) {
  13778. var name = S.token.value;
  13779. return new (name == "this" ? AST_This : type)({
  13780. name : String(name),
  13781. start : S.token,
  13782. end : S.token
  13783. });
  13784. };
  13785. function as_symbol(type, noerror) {
  13786. if (!is("name")) {
  13787. if (!noerror) croak("SyntaxError: Name expected");
  13788. return null;
  13789. }
  13790. var sym = _make_symbol(type);
  13791. next();
  13792. return sym;
  13793. };
  13794. var subscripts = function(expr, allow_calls) {
  13795. var start = expr.start;
  13796. if (is("punc", ".")) {
  13797. next();
  13798. return subscripts(new AST_Dot({
  13799. start : start,
  13800. expression : expr,
  13801. property : as_name(),
  13802. end : prev()
  13803. }), allow_calls);
  13804. }
  13805. if (is("punc", "[")) {
  13806. next();
  13807. var prop = expression(true);
  13808. expect("]");
  13809. return subscripts(new AST_Sub({
  13810. start : start,
  13811. expression : expr,
  13812. property : prop,
  13813. end : prev()
  13814. }), allow_calls);
  13815. }
  13816. if (allow_calls && is("punc", "(")) {
  13817. next();
  13818. return subscripts(new AST_Call({
  13819. start : start,
  13820. expression : expr,
  13821. args : expr_list(")"),
  13822. end : prev()
  13823. }), true);
  13824. }
  13825. return expr;
  13826. };
  13827. var maybe_unary = function(allow_calls) {
  13828. var start = S.token;
  13829. if (is("operator") && UNARY_PREFIX(start.value)) {
  13830. next();
  13831. handle_regexp();
  13832. var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls));
  13833. ex.start = start;
  13834. ex.end = prev();
  13835. return ex;
  13836. }
  13837. var val = expr_atom(allow_calls);
  13838. while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) {
  13839. val = make_unary(AST_UnaryPostfix, S.token.value, val);
  13840. val.start = start;
  13841. val.end = S.token;
  13842. next();
  13843. }
  13844. return val;
  13845. };
  13846. function make_unary(ctor, op, expr) {
  13847. if ((op == "++" || op == "--") && !is_assignable(expr))
  13848. croak("SyntaxError: Invalid use of " + op + " operator");
  13849. return new ctor({ operator: op, expression: expr });
  13850. };
  13851. var expr_op = function(left, min_prec, no_in) {
  13852. var op = is("operator") ? S.token.value : null;
  13853. if (op == "in" && no_in) op = null;
  13854. var prec = op != null ? PRECEDENCE[op] : null;
  13855. if (prec != null && prec > min_prec) {
  13856. next();
  13857. var right = expr_op(maybe_unary(true), prec, no_in);
  13858. return expr_op(new AST_Binary({
  13859. start : left.start,
  13860. left : left,
  13861. operator : op,
  13862. right : right,
  13863. end : right.end
  13864. }), min_prec, no_in);
  13865. }
  13866. return left;
  13867. };
  13868. function expr_ops(no_in) {
  13869. return expr_op(maybe_unary(true), 0, no_in);
  13870. };
  13871. var maybe_conditional = function(no_in) {
  13872. var start = S.token;
  13873. var expr = expr_ops(no_in);
  13874. if (is("operator", "?")) {
  13875. next();
  13876. var yes = expression(false);
  13877. expect(":");
  13878. return new AST_Conditional({
  13879. start : start,
  13880. condition : expr,
  13881. consequent : yes,
  13882. alternative : expression(false, no_in),
  13883. end : prev()
  13884. });
  13885. }
  13886. return expr;
  13887. };
  13888. function is_assignable(expr) {
  13889. if (!options.strict) return true;
  13890. if (expr instanceof AST_This) return false;
  13891. return (expr instanceof AST_PropAccess || expr instanceof AST_Symbol);
  13892. };
  13893. var maybe_assign = function(no_in) {
  13894. var start = S.token;
  13895. var left = maybe_conditional(no_in), val = S.token.value;
  13896. if (is("operator") && ASSIGNMENT(val)) {
  13897. if (is_assignable(left)) {
  13898. next();
  13899. return new AST_Assign({
  13900. start : start,
  13901. left : left,
  13902. operator : val,
  13903. right : maybe_assign(no_in),
  13904. end : prev()
  13905. });
  13906. }
  13907. croak("SyntaxError: Invalid assignment");
  13908. }
  13909. return left;
  13910. };
  13911. var expression = function(commas, no_in) {
  13912. var start = S.token;
  13913. var expr = maybe_assign(no_in);
  13914. if (commas && is("punc", ",")) {
  13915. next();
  13916. return new AST_Seq({
  13917. start : start,
  13918. car : expr,
  13919. cdr : expression(true, no_in),
  13920. end : peek()
  13921. });
  13922. }
  13923. return expr;
  13924. };
  13925. function in_loop(cont) {
  13926. ++S.in_loop;
  13927. var ret = cont();
  13928. --S.in_loop;
  13929. return ret;
  13930. };
  13931. if (options.expression) {
  13932. return expression(true);
  13933. }
  13934. return (function(){
  13935. var start = S.token;
  13936. var body = [];
  13937. S.input.push_directives_stack();
  13938. while (!is("eof"))
  13939. body.push(statement());
  13940. S.input.pop_directives_stack();
  13941. var end = prev();
  13942. var toplevel = options.toplevel;
  13943. if (toplevel) {
  13944. toplevel.body = toplevel.body.concat(body);
  13945. toplevel.end = end;
  13946. } else {
  13947. toplevel = new AST_Toplevel({ start: start, body: body, end: end });
  13948. }
  13949. return toplevel;
  13950. })();
  13951. };
  13952. /***********************************************************************
  13953. A JavaScript tokenizer / parser / beautifier / compressor.
  13954. https://github.com/mishoo/UglifyJS2
  13955. -------------------------------- (C) ---------------------------------
  13956. Author: Mihai Bazon
  13957. <mihai.bazon@gmail.com>
  13958. http://mihai.bazon.net/blog
  13959. Distributed under the BSD license:
  13960. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  13961. Redistribution and use in source and binary forms, with or without
  13962. modification, are permitted provided that the following conditions
  13963. are met:
  13964. * Redistributions of source code must retain the above
  13965. copyright notice, this list of conditions and the following
  13966. disclaimer.
  13967. * Redistributions in binary form must reproduce the above
  13968. copyright notice, this list of conditions and the following
  13969. disclaimer in the documentation and/or other materials
  13970. provided with the distribution.
  13971. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  13972. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13973. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  13974. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  13975. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  13976. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  13977. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  13978. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  13979. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  13980. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  13981. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13982. SUCH DAMAGE.
  13983. ***********************************************************************/
  13984. "use strict";
  13985. // Tree transformer helpers.
  13986. function TreeTransformer(before, after) {
  13987. TreeWalker.call(this);
  13988. this.before = before;
  13989. this.after = after;
  13990. }
  13991. TreeTransformer.prototype = new TreeWalker;
  13992. (function(undefined){
  13993. function _(node, descend) {
  13994. node.DEFMETHOD("transform", function(tw, in_list){
  13995. var x, y;
  13996. tw.push(this);
  13997. if (tw.before) x = tw.before(this, descend, in_list);
  13998. if (x === undefined) {
  13999. if (!tw.after) {
  14000. x = this;
  14001. descend(x, tw);
  14002. } else {
  14003. tw.stack[tw.stack.length - 1] = x = this;
  14004. descend(x, tw);
  14005. y = tw.after(x, in_list);
  14006. if (y !== undefined) x = y;
  14007. }
  14008. }
  14009. tw.pop(this);
  14010. return x;
  14011. });
  14012. };
  14013. function do_list(list, tw) {
  14014. return MAP(list, function(node){
  14015. return node.transform(tw, true);
  14016. });
  14017. };
  14018. _(AST_Node, noop);
  14019. _(AST_LabeledStatement, function(self, tw){
  14020. self.label = self.label.transform(tw);
  14021. self.body = self.body.transform(tw);
  14022. });
  14023. _(AST_SimpleStatement, function(self, tw){
  14024. self.body = self.body.transform(tw);
  14025. });
  14026. _(AST_Block, function(self, tw){
  14027. self.body = do_list(self.body, tw);
  14028. });
  14029. _(AST_DWLoop, function(self, tw){
  14030. self.condition = self.condition.transform(tw);
  14031. self.body = self.body.transform(tw);
  14032. });
  14033. _(AST_For, function(self, tw){
  14034. if (self.init) self.init = self.init.transform(tw);
  14035. if (self.condition) self.condition = self.condition.transform(tw);
  14036. if (self.step) self.step = self.step.transform(tw);
  14037. self.body = self.body.transform(tw);
  14038. });
  14039. _(AST_ForIn, function(self, tw){
  14040. self.init = self.init.transform(tw);
  14041. self.object = self.object.transform(tw);
  14042. self.body = self.body.transform(tw);
  14043. });
  14044. _(AST_With, function(self, tw){
  14045. self.expression = self.expression.transform(tw);
  14046. self.body = self.body.transform(tw);
  14047. });
  14048. _(AST_Exit, function(self, tw){
  14049. if (self.value) self.value = self.value.transform(tw);
  14050. });
  14051. _(AST_LoopControl, function(self, tw){
  14052. if (self.label) self.label = self.label.transform(tw);
  14053. });
  14054. _(AST_If, function(self, tw){
  14055. self.condition = self.condition.transform(tw);
  14056. self.body = self.body.transform(tw);
  14057. if (self.alternative) self.alternative = self.alternative.transform(tw);
  14058. });
  14059. _(AST_Switch, function(self, tw){
  14060. self.expression = self.expression.transform(tw);
  14061. self.body = do_list(self.body, tw);
  14062. });
  14063. _(AST_Case, function(self, tw){
  14064. self.expression = self.expression.transform(tw);
  14065. self.body = do_list(self.body, tw);
  14066. });
  14067. _(AST_Try, function(self, tw){
  14068. self.body = do_list(self.body, tw);
  14069. if (self.bcatch) self.bcatch = self.bcatch.transform(tw);
  14070. if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
  14071. });
  14072. _(AST_Catch, function(self, tw){
  14073. self.argname = self.argname.transform(tw);
  14074. self.body = do_list(self.body, tw);
  14075. });
  14076. _(AST_Definitions, function(self, tw){
  14077. self.definitions = do_list(self.definitions, tw);
  14078. });
  14079. _(AST_VarDef, function(self, tw){
  14080. self.name = self.name.transform(tw);
  14081. if (self.value) self.value = self.value.transform(tw);
  14082. });
  14083. _(AST_Lambda, function(self, tw){
  14084. if (self.name) self.name = self.name.transform(tw);
  14085. self.argnames = do_list(self.argnames, tw);
  14086. self.body = do_list(self.body, tw);
  14087. });
  14088. _(AST_Call, function(self, tw){
  14089. self.expression = self.expression.transform(tw);
  14090. self.args = do_list(self.args, tw);
  14091. });
  14092. _(AST_Seq, function(self, tw){
  14093. self.car = self.car.transform(tw);
  14094. self.cdr = self.cdr.transform(tw);
  14095. });
  14096. _(AST_Dot, function(self, tw){
  14097. self.expression = self.expression.transform(tw);
  14098. });
  14099. _(AST_Sub, function(self, tw){
  14100. self.expression = self.expression.transform(tw);
  14101. self.property = self.property.transform(tw);
  14102. });
  14103. _(AST_Unary, function(self, tw){
  14104. self.expression = self.expression.transform(tw);
  14105. });
  14106. _(AST_Binary, function(self, tw){
  14107. self.left = self.left.transform(tw);
  14108. self.right = self.right.transform(tw);
  14109. });
  14110. _(AST_Conditional, function(self, tw){
  14111. self.condition = self.condition.transform(tw);
  14112. self.consequent = self.consequent.transform(tw);
  14113. self.alternative = self.alternative.transform(tw);
  14114. });
  14115. _(AST_Array, function(self, tw){
  14116. self.elements = do_list(self.elements, tw);
  14117. });
  14118. _(AST_Object, function(self, tw){
  14119. self.properties = do_list(self.properties, tw);
  14120. });
  14121. _(AST_ObjectProperty, function(self, tw){
  14122. self.value = self.value.transform(tw);
  14123. });
  14124. })();
  14125. /***********************************************************************
  14126. A JavaScript tokenizer / parser / beautifier / compressor.
  14127. https://github.com/mishoo/UglifyJS2
  14128. -------------------------------- (C) ---------------------------------
  14129. Author: Mihai Bazon
  14130. <mihai.bazon@gmail.com>
  14131. http://mihai.bazon.net/blog
  14132. Distributed under the BSD license:
  14133. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  14134. Redistribution and use in source and binary forms, with or without
  14135. modification, are permitted provided that the following conditions
  14136. are met:
  14137. * Redistributions of source code must retain the above
  14138. copyright notice, this list of conditions and the following
  14139. disclaimer.
  14140. * Redistributions in binary form must reproduce the above
  14141. copyright notice, this list of conditions and the following
  14142. disclaimer in the documentation and/or other materials
  14143. provided with the distribution.
  14144. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  14145. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  14146. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  14147. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  14148. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  14149. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  14150. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  14151. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  14152. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  14153. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  14154. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  14155. SUCH DAMAGE.
  14156. ***********************************************************************/
  14157. "use strict";
  14158. function SymbolDef(scope, index, orig) {
  14159. this.name = orig.name;
  14160. this.orig = [ orig ];
  14161. this.scope = scope;
  14162. this.references = [];
  14163. this.global = false;
  14164. this.mangled_name = null;
  14165. this.undeclared = false;
  14166. this.constant = false;
  14167. this.index = index;
  14168. this.id = SymbolDef.next_id++;
  14169. };
  14170. SymbolDef.next_id = 1;
  14171. SymbolDef.prototype = {
  14172. unmangleable: function(options) {
  14173. if (!options) options = {};
  14174. return (this.global && !options.toplevel)
  14175. || this.undeclared
  14176. || (!options.eval && (this.scope.uses_eval || this.scope.uses_with))
  14177. || (options.keep_fnames
  14178. && (this.orig[0] instanceof AST_SymbolLambda
  14179. || this.orig[0] instanceof AST_SymbolDefun));
  14180. },
  14181. mangle: function(options) {
  14182. var cache = options.cache && options.cache.props;
  14183. if (this.global && cache && cache.has(this.name)) {
  14184. this.mangled_name = cache.get(this.name);
  14185. }
  14186. else if (!this.mangled_name && !this.unmangleable(options)) {
  14187. var s = this.scope;
  14188. if (!options.screw_ie8 && this.orig[0] instanceof AST_SymbolLambda)
  14189. s = s.parent_scope;
  14190. this.mangled_name = s.next_mangled(options, this);
  14191. if (this.global && cache) {
  14192. cache.set(this.name, this.mangled_name);
  14193. }
  14194. }
  14195. }
  14196. };
  14197. AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
  14198. options = defaults(options, {
  14199. screw_ie8: true,
  14200. cache: null
  14201. });
  14202. // pass 1: setup scope chaining and handle definitions
  14203. var self = this;
  14204. var scope = self.parent_scope = null;
  14205. var labels = new Dictionary();
  14206. var defun = null;
  14207. var last_var_had_const_pragma = false;
  14208. var nesting = 0;
  14209. var tw = new TreeWalker(function(node, descend){
  14210. if (options.screw_ie8 && node instanceof AST_Catch) {
  14211. var save_scope = scope;
  14212. scope = new AST_Scope(node);
  14213. scope.init_scope_vars(nesting);
  14214. scope.parent_scope = save_scope;
  14215. descend();
  14216. scope = save_scope;
  14217. return true;
  14218. }
  14219. if (node instanceof AST_Scope) {
  14220. node.init_scope_vars(nesting);
  14221. var save_scope = node.parent_scope = scope;
  14222. var save_defun = defun;
  14223. var save_labels = labels;
  14224. defun = scope = node;
  14225. labels = new Dictionary();
  14226. ++nesting; descend(); --nesting;
  14227. scope = save_scope;
  14228. defun = save_defun;
  14229. labels = save_labels;
  14230. return true; // don't descend again in TreeWalker
  14231. }
  14232. if (node instanceof AST_LabeledStatement) {
  14233. var l = node.label;
  14234. if (labels.has(l.name)) {
  14235. throw new Error(string_template("Label {name} defined twice", l));
  14236. }
  14237. labels.set(l.name, l);
  14238. descend();
  14239. labels.del(l.name);
  14240. return true; // no descend again
  14241. }
  14242. if (node instanceof AST_With) {
  14243. for (var s = scope; s; s = s.parent_scope)
  14244. s.uses_with = true;
  14245. return;
  14246. }
  14247. if (node instanceof AST_Symbol) {
  14248. node.scope = scope;
  14249. }
  14250. if (node instanceof AST_Label) {
  14251. node.thedef = node;
  14252. node.references = [];
  14253. }
  14254. if (node instanceof AST_SymbolLambda) {
  14255. defun.def_function(node);
  14256. }
  14257. else if (node instanceof AST_SymbolDefun) {
  14258. // Careful here, the scope where this should be defined is
  14259. // the parent scope. The reason is that we enter a new
  14260. // scope when we encounter the AST_Defun node (which is
  14261. // instanceof AST_Scope) but we get to the symbol a bit
  14262. // later.
  14263. (node.scope = defun.parent_scope).def_function(node);
  14264. }
  14265. else if (node instanceof AST_Var) {
  14266. last_var_had_const_pragma = node.has_const_pragma();
  14267. }
  14268. else if (node instanceof AST_SymbolVar
  14269. || node instanceof AST_SymbolConst) {
  14270. var def = defun.def_variable(node);
  14271. def.constant = node instanceof AST_SymbolConst || last_var_had_const_pragma;
  14272. def.init = tw.parent().value;
  14273. }
  14274. else if (node instanceof AST_SymbolCatch) {
  14275. (options.screw_ie8 ? scope : defun)
  14276. .def_variable(node);
  14277. }
  14278. else if (node instanceof AST_LabelRef) {
  14279. var sym = labels.get(node.name);
  14280. if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {
  14281. name: node.name,
  14282. line: node.start.line,
  14283. col: node.start.col
  14284. }));
  14285. node.thedef = sym;
  14286. }
  14287. });
  14288. self.walk(tw);
  14289. // pass 2: find back references and eval
  14290. var func = null;
  14291. var globals = self.globals = new Dictionary();
  14292. var tw = new TreeWalker(function(node, descend){
  14293. if (node instanceof AST_Lambda) {
  14294. var prev_func = func;
  14295. func = node;
  14296. descend();
  14297. func = prev_func;
  14298. return true;
  14299. }
  14300. if (node instanceof AST_LoopControl && node.label) {
  14301. node.label.thedef.references.push(node);
  14302. return true;
  14303. }
  14304. if (node instanceof AST_SymbolRef) {
  14305. var name = node.name;
  14306. if (name == "eval" && tw.parent() instanceof AST_Call) {
  14307. for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) {
  14308. s.uses_eval = true;
  14309. }
  14310. }
  14311. var sym = node.scope.find_variable(name);
  14312. if (!sym) {
  14313. var g;
  14314. if (globals.has(name)) {
  14315. g = globals.get(name);
  14316. } else {
  14317. g = new SymbolDef(self, globals.size(), node);
  14318. g.undeclared = true;
  14319. g.global = true;
  14320. globals.set(name, g);
  14321. }
  14322. node.thedef = g;
  14323. if (func && name == "arguments") {
  14324. func.uses_arguments = true;
  14325. }
  14326. } else {
  14327. node.thedef = sym;
  14328. }
  14329. node.reference();
  14330. return true;
  14331. }
  14332. });
  14333. self.walk(tw);
  14334. if (options.cache) {
  14335. this.cname = options.cache.cname;
  14336. }
  14337. });
  14338. AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){
  14339. this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
  14340. this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
  14341. this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
  14342. this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
  14343. this.parent_scope = null; // the parent scope
  14344. this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
  14345. this.cname = -1; // the current index for mangling functions/variables
  14346. this.nesting = nesting; // the nesting level of this scope (0 means toplevel)
  14347. });
  14348. AST_Lambda.DEFMETHOD("init_scope_vars", function(){
  14349. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  14350. this.uses_arguments = false;
  14351. var symbol = new AST_VarDef({ name: "arguments", start: this.start, end: this.end });
  14352. var def = new SymbolDef(this, this.variables.size(), symbol);
  14353. this.variables.set(symbol.name, def);
  14354. });
  14355. AST_SymbolRef.DEFMETHOD("reference", function() {
  14356. var def = this.definition();
  14357. def.references.push(this);
  14358. var s = this.scope;
  14359. while (s) {
  14360. push_uniq(s.enclosed, def);
  14361. if (s === def.scope) break;
  14362. s = s.parent_scope;
  14363. }
  14364. this.frame = this.scope.nesting - def.scope.nesting;
  14365. });
  14366. AST_Scope.DEFMETHOD("find_variable", function(name){
  14367. if (name instanceof AST_Symbol) name = name.name;
  14368. return this.variables.get(name)
  14369. || (this.parent_scope && this.parent_scope.find_variable(name));
  14370. });
  14371. AST_Scope.DEFMETHOD("def_function", function(symbol){
  14372. this.functions.set(symbol.name, this.def_variable(symbol));
  14373. });
  14374. AST_Scope.DEFMETHOD("def_variable", function(symbol){
  14375. var def;
  14376. if (!this.variables.has(symbol.name)) {
  14377. def = new SymbolDef(this, this.variables.size(), symbol);
  14378. this.variables.set(symbol.name, def);
  14379. def.global = !this.parent_scope;
  14380. } else {
  14381. def = this.variables.get(symbol.name);
  14382. def.orig.push(symbol);
  14383. }
  14384. return symbol.thedef = def;
  14385. });
  14386. AST_Scope.DEFMETHOD("next_mangled", function(options){
  14387. var ext = this.enclosed;
  14388. out: while (true) {
  14389. var m = base54(++this.cname);
  14390. if (!is_identifier(m)) continue; // skip over "do"
  14391. // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
  14392. // shadow a name excepted from mangling.
  14393. if (options.except.indexOf(m) >= 0) continue;
  14394. // we must ensure that the mangled name does not shadow a name
  14395. // from some parent scope that is referenced in this or in
  14396. // inner scopes.
  14397. for (var i = ext.length; --i >= 0;) {
  14398. var sym = ext[i];
  14399. var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);
  14400. if (m == name) continue out;
  14401. }
  14402. return m;
  14403. }
  14404. });
  14405. AST_Function.DEFMETHOD("next_mangled", function(options, def){
  14406. // #179, #326
  14407. // in Safari strict mode, something like (function x(x){...}) is a syntax error;
  14408. // a function expression's argument cannot shadow the function expression's name
  14409. var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
  14410. // the function's mangled_name is null when keep_fnames is true
  14411. var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null;
  14412. while (true) {
  14413. var name = AST_Lambda.prototype.next_mangled.call(this, options, def);
  14414. if (!tricky_name || tricky_name != name)
  14415. return name;
  14416. }
  14417. });
  14418. AST_Scope.DEFMETHOD("references", function(sym){
  14419. if (sym instanceof AST_Symbol) sym = sym.definition();
  14420. return this.enclosed.indexOf(sym) < 0 ? null : sym;
  14421. });
  14422. AST_Symbol.DEFMETHOD("unmangleable", function(options){
  14423. return this.definition().unmangleable(options);
  14424. });
  14425. // property accessors are not mangleable
  14426. AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){
  14427. return true;
  14428. });
  14429. // labels are always mangleable
  14430. AST_Label.DEFMETHOD("unmangleable", function(){
  14431. return false;
  14432. });
  14433. AST_Symbol.DEFMETHOD("unreferenced", function(){
  14434. return this.definition().references.length == 0
  14435. && !(this.scope.uses_eval || this.scope.uses_with);
  14436. });
  14437. AST_Symbol.DEFMETHOD("undeclared", function(){
  14438. return this.definition().undeclared;
  14439. });
  14440. AST_LabelRef.DEFMETHOD("undeclared", function(){
  14441. return false;
  14442. });
  14443. AST_Label.DEFMETHOD("undeclared", function(){
  14444. return false;
  14445. });
  14446. AST_Symbol.DEFMETHOD("definition", function(){
  14447. return this.thedef;
  14448. });
  14449. AST_Symbol.DEFMETHOD("global", function(){
  14450. return this.definition().global;
  14451. });
  14452. AST_Var.DEFMETHOD("has_const_pragma", function() {
  14453. var comments_before = this.start && this.start.comments_before;
  14454. var lastComment = comments_before && comments_before[comments_before.length - 1];
  14455. return lastComment && /@const\b/.test(lastComment.value);
  14456. });
  14457. AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){
  14458. return defaults(options, {
  14459. except : [],
  14460. eval : false,
  14461. sort : false, // Ignored. Flag retained for backwards compatibility.
  14462. toplevel : false,
  14463. screw_ie8 : true,
  14464. keep_fnames : false
  14465. });
  14466. });
  14467. AST_Toplevel.DEFMETHOD("mangle_names", function(options){
  14468. options = this._default_mangler_options(options);
  14469. // Never mangle arguments
  14470. options.except.push('arguments');
  14471. // We only need to mangle declaration nodes. Special logic wired
  14472. // into the code generator will display the mangled name if it's
  14473. // present (and for AST_SymbolRef-s it'll use the mangled name of
  14474. // the AST_SymbolDeclaration that it points to).
  14475. var lname = -1;
  14476. var to_mangle = [];
  14477. if (options.cache) {
  14478. this.globals.each(function(symbol){
  14479. if (options.except.indexOf(symbol.name) < 0) {
  14480. to_mangle.push(symbol);
  14481. }
  14482. });
  14483. }
  14484. var tw = new TreeWalker(function(node, descend){
  14485. if (node instanceof AST_LabeledStatement) {
  14486. // lname is incremented when we get to the AST_Label
  14487. var save_nesting = lname;
  14488. descend();
  14489. lname = save_nesting;
  14490. return true; // don't descend again in TreeWalker
  14491. }
  14492. if (node instanceof AST_Scope) {
  14493. var p = tw.parent(), a = [];
  14494. node.variables.each(function(symbol){
  14495. if (options.except.indexOf(symbol.name) < 0) {
  14496. a.push(symbol);
  14497. }
  14498. });
  14499. to_mangle.push.apply(to_mangle, a);
  14500. return;
  14501. }
  14502. if (node instanceof AST_Label) {
  14503. var name;
  14504. do name = base54(++lname); while (!is_identifier(name));
  14505. node.mangled_name = name;
  14506. return true;
  14507. }
  14508. if (options.screw_ie8 && node instanceof AST_SymbolCatch) {
  14509. to_mangle.push(node.definition());
  14510. return;
  14511. }
  14512. });
  14513. this.walk(tw);
  14514. to_mangle.forEach(function(def){ def.mangle(options) });
  14515. if (options.cache) {
  14516. options.cache.cname = this.cname;
  14517. }
  14518. });
  14519. AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){
  14520. options = this._default_mangler_options(options);
  14521. var tw = new TreeWalker(function(node){
  14522. if (node instanceof AST_Constant)
  14523. base54.consider(node.print_to_string());
  14524. else if (node instanceof AST_Return)
  14525. base54.consider("return");
  14526. else if (node instanceof AST_Throw)
  14527. base54.consider("throw");
  14528. else if (node instanceof AST_Continue)
  14529. base54.consider("continue");
  14530. else if (node instanceof AST_Break)
  14531. base54.consider("break");
  14532. else if (node instanceof AST_Debugger)
  14533. base54.consider("debugger");
  14534. else if (node instanceof AST_Directive)
  14535. base54.consider(node.value);
  14536. else if (node instanceof AST_While)
  14537. base54.consider("while");
  14538. else if (node instanceof AST_Do)
  14539. base54.consider("do while");
  14540. else if (node instanceof AST_If) {
  14541. base54.consider("if");
  14542. if (node.alternative) base54.consider("else");
  14543. }
  14544. else if (node instanceof AST_Var)
  14545. base54.consider("var");
  14546. else if (node instanceof AST_Const)
  14547. base54.consider("const");
  14548. else if (node instanceof AST_Lambda)
  14549. base54.consider("function");
  14550. else if (node instanceof AST_For)
  14551. base54.consider("for");
  14552. else if (node instanceof AST_ForIn)
  14553. base54.consider("for in");
  14554. else if (node instanceof AST_Switch)
  14555. base54.consider("switch");
  14556. else if (node instanceof AST_Case)
  14557. base54.consider("case");
  14558. else if (node instanceof AST_Default)
  14559. base54.consider("default");
  14560. else if (node instanceof AST_With)
  14561. base54.consider("with");
  14562. else if (node instanceof AST_ObjectSetter)
  14563. base54.consider("set" + node.key);
  14564. else if (node instanceof AST_ObjectGetter)
  14565. base54.consider("get" + node.key);
  14566. else if (node instanceof AST_ObjectKeyVal)
  14567. base54.consider(node.key);
  14568. else if (node instanceof AST_New)
  14569. base54.consider("new");
  14570. else if (node instanceof AST_This)
  14571. base54.consider("this");
  14572. else if (node instanceof AST_Try)
  14573. base54.consider("try");
  14574. else if (node instanceof AST_Catch)
  14575. base54.consider("catch");
  14576. else if (node instanceof AST_Finally)
  14577. base54.consider("finally");
  14578. else if (node instanceof AST_Symbol && node.unmangleable(options))
  14579. base54.consider(node.name);
  14580. else if (node instanceof AST_Unary || node instanceof AST_Binary)
  14581. base54.consider(node.operator);
  14582. else if (node instanceof AST_Dot)
  14583. base54.consider(node.property);
  14584. });
  14585. this.walk(tw);
  14586. base54.sort();
  14587. });
  14588. var base54 = (function() {
  14589. var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
  14590. var chars, frequency;
  14591. function reset() {
  14592. frequency = Object.create(null);
  14593. chars = string.split("").map(function(ch){ return ch.charCodeAt(0) });
  14594. chars.forEach(function(ch){ frequency[ch] = 0 });
  14595. }
  14596. base54.consider = function(str){
  14597. for (var i = str.length; --i >= 0;) {
  14598. var code = str.charCodeAt(i);
  14599. if (code in frequency) ++frequency[code];
  14600. }
  14601. };
  14602. base54.sort = function() {
  14603. chars = mergeSort(chars, function(a, b){
  14604. if (is_digit(a) && !is_digit(b)) return 1;
  14605. if (is_digit(b) && !is_digit(a)) return -1;
  14606. return frequency[b] - frequency[a];
  14607. });
  14608. };
  14609. base54.reset = reset;
  14610. reset();
  14611. base54.get = function(){ return chars };
  14612. base54.freq = function(){ return frequency };
  14613. function base54(num) {
  14614. var ret = "", base = 54;
  14615. num++;
  14616. do {
  14617. num--;
  14618. ret += String.fromCharCode(chars[num % base]);
  14619. num = Math.floor(num / base);
  14620. base = 64;
  14621. } while (num > 0);
  14622. return ret;
  14623. };
  14624. return base54;
  14625. })();
  14626. AST_Toplevel.DEFMETHOD("scope_warnings", function(options){
  14627. options = defaults(options, {
  14628. undeclared : false, // this makes a lot of noise
  14629. unreferenced : true,
  14630. assign_to_global : true,
  14631. func_arguments : true,
  14632. nested_defuns : true,
  14633. eval : true
  14634. });
  14635. var tw = new TreeWalker(function(node){
  14636. if (options.undeclared
  14637. && node instanceof AST_SymbolRef
  14638. && node.undeclared())
  14639. {
  14640. // XXX: this also warns about JS standard names,
  14641. // i.e. Object, Array, parseInt etc. Should add a list of
  14642. // exceptions.
  14643. AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", {
  14644. name: node.name,
  14645. file: node.start.file,
  14646. line: node.start.line,
  14647. col: node.start.col
  14648. });
  14649. }
  14650. if (options.assign_to_global)
  14651. {
  14652. var sym = null;
  14653. if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef)
  14654. sym = node.left;
  14655. else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef)
  14656. sym = node.init;
  14657. if (sym
  14658. && (sym.undeclared()
  14659. || (sym.global() && sym.scope !== sym.definition().scope))) {
  14660. AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", {
  14661. msg: sym.undeclared() ? "Accidental global?" : "Assignment to global",
  14662. name: sym.name,
  14663. file: sym.start.file,
  14664. line: sym.start.line,
  14665. col: sym.start.col
  14666. });
  14667. }
  14668. }
  14669. if (options.eval
  14670. && node instanceof AST_SymbolRef
  14671. && node.undeclared()
  14672. && node.name == "eval") {
  14673. AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start);
  14674. }
  14675. if (options.unreferenced
  14676. && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label)
  14677. && !(node instanceof AST_SymbolCatch)
  14678. && node.unreferenced()) {
  14679. AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", {
  14680. type: node instanceof AST_Label ? "Label" : "Symbol",
  14681. name: node.name,
  14682. file: node.start.file,
  14683. line: node.start.line,
  14684. col: node.start.col
  14685. });
  14686. }
  14687. if (options.func_arguments
  14688. && node instanceof AST_Lambda
  14689. && node.uses_arguments) {
  14690. AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", {
  14691. name: node.name ? node.name.name : "anonymous",
  14692. file: node.start.file,
  14693. line: node.start.line,
  14694. col: node.start.col
  14695. });
  14696. }
  14697. if (options.nested_defuns
  14698. && node instanceof AST_Defun
  14699. && !(tw.parent() instanceof AST_Scope)) {
  14700. AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", {
  14701. name: node.name.name,
  14702. type: tw.parent().TYPE,
  14703. file: node.start.file,
  14704. line: node.start.line,
  14705. col: node.start.col
  14706. });
  14707. }
  14708. });
  14709. this.walk(tw);
  14710. });
  14711. /***********************************************************************
  14712. A JavaScript tokenizer / parser / beautifier / compressor.
  14713. https://github.com/mishoo/UglifyJS2
  14714. -------------------------------- (C) ---------------------------------
  14715. Author: Mihai Bazon
  14716. <mihai.bazon@gmail.com>
  14717. http://mihai.bazon.net/blog
  14718. Distributed under the BSD license:
  14719. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  14720. Redistribution and use in source and binary forms, with or without
  14721. modification, are permitted provided that the following conditions
  14722. are met:
  14723. * Redistributions of source code must retain the above
  14724. copyright notice, this list of conditions and the following
  14725. disclaimer.
  14726. * Redistributions in binary form must reproduce the above
  14727. copyright notice, this list of conditions and the following
  14728. disclaimer in the documentation and/or other materials
  14729. provided with the distribution.
  14730. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  14731. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  14732. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  14733. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  14734. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  14735. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  14736. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  14737. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  14738. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  14739. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  14740. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  14741. SUCH DAMAGE.
  14742. ***********************************************************************/
  14743. "use strict";
  14744. var EXPECT_DIRECTIVE = /^$|[;{][\s\n]*$/;
  14745. function OutputStream(options) {
  14746. options = defaults(options, {
  14747. indent_start : 0,
  14748. indent_level : 4,
  14749. quote_keys : false,
  14750. space_colon : true,
  14751. ascii_only : false,
  14752. unescape_regexps : false,
  14753. inline_script : false,
  14754. width : 80,
  14755. max_line_len : 32000,
  14756. beautify : false,
  14757. source_map : null,
  14758. bracketize : false,
  14759. semicolons : true,
  14760. comments : false,
  14761. shebang : true,
  14762. preserve_line : false,
  14763. screw_ie8 : true,
  14764. preamble : null,
  14765. quote_style : 0,
  14766. keep_quoted_props: false
  14767. }, true);
  14768. var indentation = 0;
  14769. var current_col = 0;
  14770. var current_line = 1;
  14771. var current_pos = 0;
  14772. var OUTPUT = "";
  14773. function to_ascii(str, identifier) {
  14774. return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) {
  14775. var code = ch.charCodeAt(0).toString(16);
  14776. if (code.length <= 2 && !identifier) {
  14777. while (code.length < 2) code = "0" + code;
  14778. return "\\x" + code;
  14779. } else {
  14780. while (code.length < 4) code = "0" + code;
  14781. return "\\u" + code;
  14782. }
  14783. });
  14784. };
  14785. function make_string(str, quote) {
  14786. var dq = 0, sq = 0;
  14787. str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,
  14788. function(s, i){
  14789. switch (s) {
  14790. case '"': ++dq; return '"';
  14791. case "'": ++sq; return "'";
  14792. case "\\": return "\\\\";
  14793. case "\n": return "\\n";
  14794. case "\r": return "\\r";
  14795. case "\t": return "\\t";
  14796. case "\b": return "\\b";
  14797. case "\f": return "\\f";
  14798. case "\x0B": return options.screw_ie8 ? "\\v" : "\\x0B";
  14799. case "\u2028": return "\\u2028";
  14800. case "\u2029": return "\\u2029";
  14801. case "\ufeff": return "\\ufeff";
  14802. case "\0":
  14803. return /[0-7]/.test(str.charAt(i+1)) ? "\\x00" : "\\0";
  14804. }
  14805. return s;
  14806. });
  14807. function quote_single() {
  14808. return "'" + str.replace(/\x27/g, "\\'") + "'";
  14809. }
  14810. function quote_double() {
  14811. return '"' + str.replace(/\x22/g, '\\"') + '"';
  14812. }
  14813. if (options.ascii_only) str = to_ascii(str);
  14814. switch (options.quote_style) {
  14815. case 1:
  14816. return quote_single();
  14817. case 2:
  14818. return quote_double();
  14819. case 3:
  14820. return quote == "'" ? quote_single() : quote_double();
  14821. default:
  14822. return dq > sq ? quote_single() : quote_double();
  14823. }
  14824. };
  14825. function encode_string(str, quote) {
  14826. var ret = make_string(str, quote);
  14827. if (options.inline_script) {
  14828. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  14829. ret = ret.replace(/\x3c!--/g, "\\x3c!--");
  14830. ret = ret.replace(/--\x3e/g, "--\\x3e");
  14831. }
  14832. return ret;
  14833. };
  14834. function make_name(name) {
  14835. name = name.toString();
  14836. if (options.ascii_only)
  14837. name = to_ascii(name, true);
  14838. return name;
  14839. };
  14840. function make_indent(back) {
  14841. return repeat_string(" ", options.indent_start + indentation - back * options.indent_level);
  14842. };
  14843. /* -----[ beautification/minification ]----- */
  14844. var might_need_space = false;
  14845. var might_need_semicolon = false;
  14846. var last = null;
  14847. function last_char() {
  14848. return last.charAt(last.length - 1);
  14849. };
  14850. function maybe_newline() {
  14851. if (options.max_line_len && current_col > options.max_line_len)
  14852. print("\n");
  14853. };
  14854. var requireSemicolonChars = makePredicate("( [ + * / - , .");
  14855. function print(str) {
  14856. str = String(str);
  14857. var ch = str.charAt(0);
  14858. if (might_need_semicolon) {
  14859. might_need_semicolon = false;
  14860. if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) {
  14861. if (options.semicolons || requireSemicolonChars(ch)) {
  14862. OUTPUT += ";";
  14863. current_col++;
  14864. current_pos++;
  14865. } else {
  14866. OUTPUT += "\n";
  14867. current_pos++;
  14868. current_line++;
  14869. current_col = 0;
  14870. if (/^\s+$/.test(str)) {
  14871. // reset the semicolon flag, since we didn't print one
  14872. // now and might still have to later
  14873. might_need_semicolon = true;
  14874. }
  14875. }
  14876. if (!options.beautify)
  14877. might_need_space = false;
  14878. }
  14879. }
  14880. if (!options.beautify && options.preserve_line && stack[stack.length - 1]) {
  14881. var target_line = stack[stack.length - 1].start.line;
  14882. while (current_line < target_line) {
  14883. OUTPUT += "\n";
  14884. current_pos++;
  14885. current_line++;
  14886. current_col = 0;
  14887. might_need_space = false;
  14888. }
  14889. }
  14890. if (might_need_space) {
  14891. var prev = last_char();
  14892. if ((is_identifier_char(prev)
  14893. && (is_identifier_char(ch) || ch == "\\"))
  14894. || (/^[\+\-\/]$/.test(ch) && ch == prev))
  14895. {
  14896. OUTPUT += " ";
  14897. current_col++;
  14898. current_pos++;
  14899. }
  14900. might_need_space = false;
  14901. }
  14902. var a = str.split(/\r?\n/), n = a.length - 1;
  14903. current_line += n;
  14904. if (n == 0) {
  14905. current_col += a[n].length;
  14906. } else {
  14907. current_col = a[n].length;
  14908. }
  14909. current_pos += str.length;
  14910. last = str;
  14911. OUTPUT += str;
  14912. };
  14913. var space = options.beautify ? function() {
  14914. print(" ");
  14915. } : function() {
  14916. might_need_space = true;
  14917. };
  14918. var indent = options.beautify ? function(half) {
  14919. if (options.beautify) {
  14920. print(make_indent(half ? 0.5 : 0));
  14921. }
  14922. } : noop;
  14923. var with_indent = options.beautify ? function(col, cont) {
  14924. if (col === true) col = next_indent();
  14925. var save_indentation = indentation;
  14926. indentation = col;
  14927. var ret = cont();
  14928. indentation = save_indentation;
  14929. return ret;
  14930. } : function(col, cont) { return cont() };
  14931. var newline = options.beautify ? function() {
  14932. print("\n");
  14933. } : maybe_newline;
  14934. var semicolon = options.beautify ? function() {
  14935. print(";");
  14936. } : function() {
  14937. might_need_semicolon = true;
  14938. };
  14939. function force_semicolon() {
  14940. might_need_semicolon = false;
  14941. print(";");
  14942. };
  14943. function next_indent() {
  14944. return indentation + options.indent_level;
  14945. };
  14946. function with_block(cont) {
  14947. var ret;
  14948. print("{");
  14949. newline();
  14950. with_indent(next_indent(), function(){
  14951. ret = cont();
  14952. });
  14953. indent();
  14954. print("}");
  14955. return ret;
  14956. };
  14957. function with_parens(cont) {
  14958. print("(");
  14959. //XXX: still nice to have that for argument lists
  14960. //var ret = with_indent(current_col, cont);
  14961. var ret = cont();
  14962. print(")");
  14963. return ret;
  14964. };
  14965. function with_square(cont) {
  14966. print("[");
  14967. //var ret = with_indent(current_col, cont);
  14968. var ret = cont();
  14969. print("]");
  14970. return ret;
  14971. };
  14972. function comma() {
  14973. print(",");
  14974. space();
  14975. };
  14976. function colon() {
  14977. print(":");
  14978. if (options.space_colon) space();
  14979. };
  14980. var add_mapping = options.source_map ? function(token, name) {
  14981. try {
  14982. if (token) options.source_map.add(
  14983. token.file || "?",
  14984. current_line, current_col,
  14985. token.line, token.col,
  14986. (!name && token.type == "name") ? token.value : name
  14987. );
  14988. } catch(ex) {
  14989. AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
  14990. file: token.file,
  14991. line: token.line,
  14992. col: token.col,
  14993. cline: current_line,
  14994. ccol: current_col,
  14995. name: name || ""
  14996. })
  14997. }
  14998. } : noop;
  14999. function get() {
  15000. return OUTPUT;
  15001. };
  15002. if (options.preamble) {
  15003. print(options.preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n"));
  15004. }
  15005. var stack = [];
  15006. return {
  15007. get : get,
  15008. toString : get,
  15009. indent : indent,
  15010. indentation : function() { return indentation },
  15011. current_width : function() { return current_col - indentation },
  15012. should_break : function() { return options.width && this.current_width() >= options.width },
  15013. newline : newline,
  15014. print : print,
  15015. space : space,
  15016. comma : comma,
  15017. colon : colon,
  15018. last : function() { return last },
  15019. semicolon : semicolon,
  15020. force_semicolon : force_semicolon,
  15021. to_ascii : to_ascii,
  15022. print_name : function(name) { print(make_name(name)) },
  15023. print_string : function(str, quote, escape_directive) {
  15024. var encoded = encode_string(str, quote);
  15025. if (escape_directive === true && encoded.indexOf("\\") === -1) {
  15026. // Insert semicolons to break directive prologue
  15027. if (!EXPECT_DIRECTIVE.test(OUTPUT)) {
  15028. force_semicolon();
  15029. }
  15030. force_semicolon();
  15031. }
  15032. print(encoded);
  15033. },
  15034. encode_string : encode_string,
  15035. next_indent : next_indent,
  15036. with_indent : with_indent,
  15037. with_block : with_block,
  15038. with_parens : with_parens,
  15039. with_square : with_square,
  15040. add_mapping : add_mapping,
  15041. option : function(opt) { return options[opt] },
  15042. line : function() { return current_line },
  15043. col : function() { return current_col },
  15044. pos : function() { return current_pos },
  15045. push_node : function(node) { stack.push(node) },
  15046. pop_node : function() { return stack.pop() },
  15047. stack : function() { return stack },
  15048. parent : function(n) {
  15049. return stack[stack.length - 2 - (n || 0)];
  15050. }
  15051. };
  15052. };
  15053. /* -----[ code generators ]----- */
  15054. (function(){
  15055. /* -----[ utils ]----- */
  15056. function DEFPRINT(nodetype, generator) {
  15057. nodetype.DEFMETHOD("_codegen", generator);
  15058. };
  15059. var use_asm = false;
  15060. var in_directive = false;
  15061. AST_Node.DEFMETHOD("print", function(stream, force_parens){
  15062. var self = this, generator = self._codegen, prev_use_asm = use_asm;
  15063. if (self instanceof AST_Directive && self.value == "use asm" && stream.parent() instanceof AST_Scope) {
  15064. use_asm = true;
  15065. }
  15066. function doit() {
  15067. self.add_comments(stream);
  15068. self.add_source_map(stream);
  15069. generator(self, stream);
  15070. }
  15071. stream.push_node(self);
  15072. if (force_parens || self.needs_parens(stream)) {
  15073. stream.with_parens(doit);
  15074. } else {
  15075. doit();
  15076. }
  15077. stream.pop_node();
  15078. if (self instanceof AST_Scope) {
  15079. use_asm = prev_use_asm;
  15080. }
  15081. });
  15082. AST_Node.DEFMETHOD("print_to_string", function(options){
  15083. var s = OutputStream(options);
  15084. if (!options) s._readonly = true;
  15085. this.print(s);
  15086. return s.get();
  15087. });
  15088. /* -----[ comments ]----- */
  15089. AST_Node.DEFMETHOD("add_comments", function(output){
  15090. if (output._readonly) return;
  15091. var c = output.option("comments"), self = this;
  15092. var start = self.start;
  15093. if (start && !start._comments_dumped) {
  15094. start._comments_dumped = true;
  15095. var comments = start.comments_before || [];
  15096. // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112
  15097. // and https://github.com/mishoo/UglifyJS2/issues/372
  15098. if (self instanceof AST_Exit && self.value) {
  15099. self.value.walk(new TreeWalker(function(node){
  15100. if (node.start && node.start.comments_before) {
  15101. comments = comments.concat(node.start.comments_before);
  15102. node.start.comments_before = [];
  15103. }
  15104. if (node instanceof AST_Function ||
  15105. node instanceof AST_Array ||
  15106. node instanceof AST_Object)
  15107. {
  15108. return true; // don't go inside.
  15109. }
  15110. }));
  15111. }
  15112. if (!c) {
  15113. comments = comments.filter(function(comment) {
  15114. return comment.type == "comment5";
  15115. });
  15116. } else if (c.test) {
  15117. comments = comments.filter(function(comment){
  15118. return comment.type == "comment5" || c.test(comment.value);
  15119. });
  15120. } else if (typeof c == "function") {
  15121. comments = comments.filter(function(comment){
  15122. return comment.type == "comment5" || c(self, comment);
  15123. });
  15124. }
  15125. // Keep single line comments after nlb, after nlb
  15126. if (!output.option("beautify") && comments.length > 0 &&
  15127. /comment[134]/.test(comments[0].type) &&
  15128. output.col() !== 0 && comments[0].nlb)
  15129. {
  15130. output.print("\n");
  15131. }
  15132. comments.forEach(function(c){
  15133. if (/comment[134]/.test(c.type)) {
  15134. output.print("//" + c.value + "\n");
  15135. output.indent();
  15136. }
  15137. else if (c.type == "comment2") {
  15138. output.print("/*" + c.value + "*/");
  15139. if (start.nlb) {
  15140. output.print("\n");
  15141. output.indent();
  15142. } else {
  15143. output.space();
  15144. }
  15145. }
  15146. else if (output.pos() === 0 && c.type == "comment5" && output.option("shebang")) {
  15147. output.print("#!" + c.value + "\n");
  15148. output.indent();
  15149. }
  15150. });
  15151. }
  15152. });
  15153. /* -----[ PARENTHESES ]----- */
  15154. function PARENS(nodetype, func) {
  15155. if (Array.isArray(nodetype)) {
  15156. nodetype.forEach(function(nodetype){
  15157. PARENS(nodetype, func);
  15158. });
  15159. } else {
  15160. nodetype.DEFMETHOD("needs_parens", func);
  15161. }
  15162. };
  15163. PARENS(AST_Node, function(){
  15164. return false;
  15165. });
  15166. // a function expression needs parens around it when it's provably
  15167. // the first token to appear in a statement.
  15168. PARENS(AST_Function, function(output){
  15169. return first_in_statement(output);
  15170. });
  15171. // same goes for an object literal, because otherwise it would be
  15172. // interpreted as a block of code.
  15173. PARENS(AST_Object, function(output){
  15174. return first_in_statement(output);
  15175. });
  15176. PARENS([ AST_Unary, AST_Undefined ], function(output){
  15177. var p = output.parent();
  15178. return p instanceof AST_PropAccess && p.expression === this
  15179. || p instanceof AST_Call && p.expression === this;
  15180. });
  15181. PARENS(AST_Seq, function(output){
  15182. var p = output.parent();
  15183. return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)
  15184. || p instanceof AST_Unary // !(foo, bar, baz)
  15185. || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8
  15186. || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4
  15187. || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2
  15188. || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
  15189. || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2
  15190. || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)
  15191. * ==> 20 (side effect, set a := 10 and b := 20) */
  15192. ;
  15193. });
  15194. PARENS(AST_Binary, function(output){
  15195. var p = output.parent();
  15196. // (foo && bar)()
  15197. if (p instanceof AST_Call && p.expression === this)
  15198. return true;
  15199. // typeof (foo && bar)
  15200. if (p instanceof AST_Unary)
  15201. return true;
  15202. // (foo && bar)["prop"], (foo && bar).prop
  15203. if (p instanceof AST_PropAccess && p.expression === this)
  15204. return true;
  15205. // this deals with precedence: 3 * (2 + 1)
  15206. if (p instanceof AST_Binary) {
  15207. var po = p.operator, pp = PRECEDENCE[po];
  15208. var so = this.operator, sp = PRECEDENCE[so];
  15209. if (pp > sp
  15210. || (pp == sp
  15211. && this === p.right)) {
  15212. return true;
  15213. }
  15214. }
  15215. });
  15216. PARENS(AST_PropAccess, function(output){
  15217. var p = output.parent();
  15218. if (p instanceof AST_New && p.expression === this) {
  15219. // i.e. new (foo.bar().baz)
  15220. //
  15221. // if there's one call into this subtree, then we need
  15222. // parens around it too, otherwise the call will be
  15223. // interpreted as passing the arguments to the upper New
  15224. // expression.
  15225. try {
  15226. this.walk(new TreeWalker(function(node){
  15227. if (node instanceof AST_Call) throw p;
  15228. }));
  15229. } catch(ex) {
  15230. if (ex !== p) throw ex;
  15231. return true;
  15232. }
  15233. }
  15234. });
  15235. PARENS(AST_Call, function(output){
  15236. var p = output.parent(), p1;
  15237. if (p instanceof AST_New && p.expression === this)
  15238. return true;
  15239. // workaround for Safari bug.
  15240. // https://bugs.webkit.org/show_bug.cgi?id=123506
  15241. return this.expression instanceof AST_Function
  15242. && p instanceof AST_PropAccess
  15243. && p.expression === this
  15244. && (p1 = output.parent(1)) instanceof AST_Assign
  15245. && p1.left === p;
  15246. });
  15247. PARENS(AST_New, function(output){
  15248. var p = output.parent();
  15249. if (!need_constructor_parens(this, output)
  15250. && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]()
  15251. || p instanceof AST_Call && p.expression === this)) // (new foo)(bar)
  15252. return true;
  15253. });
  15254. PARENS(AST_Number, function(output){
  15255. var p = output.parent();
  15256. if (p instanceof AST_PropAccess && p.expression === this) {
  15257. var value = this.getValue();
  15258. if (value < 0 || /^0/.test(make_num(value))) {
  15259. return true;
  15260. }
  15261. }
  15262. });
  15263. PARENS([ AST_Assign, AST_Conditional ], function (output){
  15264. var p = output.parent();
  15265. // !(a = false) → true
  15266. if (p instanceof AST_Unary)
  15267. return true;
  15268. // 1 + (a = 2) + 3 → 6, side effect setting a = 2
  15269. if (p instanceof AST_Binary && !(p instanceof AST_Assign))
  15270. return true;
  15271. // (a = func)() —or— new (a = Object)()
  15272. if (p instanceof AST_Call && p.expression === this)
  15273. return true;
  15274. // (a = foo) ? bar : baz
  15275. if (p instanceof AST_Conditional && p.condition === this)
  15276. return true;
  15277. // (a = foo)["prop"] —or— (a = foo).prop
  15278. if (p instanceof AST_PropAccess && p.expression === this)
  15279. return true;
  15280. });
  15281. /* -----[ PRINTERS ]----- */
  15282. DEFPRINT(AST_Directive, function(self, output){
  15283. output.print_string(self.value, self.quote);
  15284. output.semicolon();
  15285. });
  15286. DEFPRINT(AST_Debugger, function(self, output){
  15287. output.print("debugger");
  15288. output.semicolon();
  15289. });
  15290. /* -----[ statements ]----- */
  15291. function display_body(body, is_toplevel, output, allow_directives) {
  15292. var last = body.length - 1;
  15293. in_directive = allow_directives;
  15294. body.forEach(function(stmt, i){
  15295. if (in_directive === true && !(stmt instanceof AST_Directive ||
  15296. stmt instanceof AST_EmptyStatement ||
  15297. (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String)
  15298. )) {
  15299. in_directive = false;
  15300. }
  15301. if (!(stmt instanceof AST_EmptyStatement)) {
  15302. output.indent();
  15303. stmt.print(output);
  15304. if (!(i == last && is_toplevel)) {
  15305. output.newline();
  15306. if (is_toplevel) output.newline();
  15307. }
  15308. }
  15309. if (in_directive === true &&
  15310. stmt instanceof AST_SimpleStatement &&
  15311. stmt.body instanceof AST_String
  15312. ) {
  15313. in_directive = false;
  15314. }
  15315. });
  15316. in_directive = false;
  15317. };
  15318. AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){
  15319. force_statement(this.body, output);
  15320. });
  15321. DEFPRINT(AST_Statement, function(self, output){
  15322. self.body.print(output);
  15323. output.semicolon();
  15324. });
  15325. DEFPRINT(AST_Toplevel, function(self, output){
  15326. display_body(self.body, true, output, true);
  15327. output.print("");
  15328. });
  15329. DEFPRINT(AST_LabeledStatement, function(self, output){
  15330. self.label.print(output);
  15331. output.colon();
  15332. self.body.print(output);
  15333. });
  15334. DEFPRINT(AST_SimpleStatement, function(self, output){
  15335. self.body.print(output);
  15336. output.semicolon();
  15337. });
  15338. function print_bracketed(body, output, allow_directives) {
  15339. if (body.length > 0) output.with_block(function(){
  15340. display_body(body, false, output, allow_directives);
  15341. });
  15342. else output.print("{}");
  15343. };
  15344. DEFPRINT(AST_BlockStatement, function(self, output){
  15345. print_bracketed(self.body, output);
  15346. });
  15347. DEFPRINT(AST_EmptyStatement, function(self, output){
  15348. output.semicolon();
  15349. });
  15350. DEFPRINT(AST_Do, function(self, output){
  15351. output.print("do");
  15352. output.space();
  15353. self._do_print_body(output);
  15354. output.space();
  15355. output.print("while");
  15356. output.space();
  15357. output.with_parens(function(){
  15358. self.condition.print(output);
  15359. });
  15360. output.semicolon();
  15361. });
  15362. DEFPRINT(AST_While, function(self, output){
  15363. output.print("while");
  15364. output.space();
  15365. output.with_parens(function(){
  15366. self.condition.print(output);
  15367. });
  15368. output.space();
  15369. self._do_print_body(output);
  15370. });
  15371. DEFPRINT(AST_For, function(self, output){
  15372. output.print("for");
  15373. output.space();
  15374. output.with_parens(function(){
  15375. if (self.init && !(self.init instanceof AST_EmptyStatement)) {
  15376. if (self.init instanceof AST_Definitions) {
  15377. self.init.print(output);
  15378. } else {
  15379. parenthesize_for_noin(self.init, output, true);
  15380. }
  15381. output.print(";");
  15382. output.space();
  15383. } else {
  15384. output.print(";");
  15385. }
  15386. if (self.condition) {
  15387. self.condition.print(output);
  15388. output.print(";");
  15389. output.space();
  15390. } else {
  15391. output.print(";");
  15392. }
  15393. if (self.step) {
  15394. self.step.print(output);
  15395. }
  15396. });
  15397. output.space();
  15398. self._do_print_body(output);
  15399. });
  15400. DEFPRINT(AST_ForIn, function(self, output){
  15401. output.print("for");
  15402. output.space();
  15403. output.with_parens(function(){
  15404. self.init.print(output);
  15405. output.space();
  15406. output.print("in");
  15407. output.space();
  15408. self.object.print(output);
  15409. });
  15410. output.space();
  15411. self._do_print_body(output);
  15412. });
  15413. DEFPRINT(AST_With, function(self, output){
  15414. output.print("with");
  15415. output.space();
  15416. output.with_parens(function(){
  15417. self.expression.print(output);
  15418. });
  15419. output.space();
  15420. self._do_print_body(output);
  15421. });
  15422. /* -----[ functions ]----- */
  15423. AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){
  15424. var self = this;
  15425. if (!nokeyword) {
  15426. output.print("function");
  15427. }
  15428. if (self.name) {
  15429. output.space();
  15430. self.name.print(output);
  15431. }
  15432. output.with_parens(function(){
  15433. self.argnames.forEach(function(arg, i){
  15434. if (i) output.comma();
  15435. arg.print(output);
  15436. });
  15437. });
  15438. output.space();
  15439. print_bracketed(self.body, output, true);
  15440. });
  15441. DEFPRINT(AST_Lambda, function(self, output){
  15442. self._do_print(output);
  15443. });
  15444. /* -----[ exits ]----- */
  15445. AST_Exit.DEFMETHOD("_do_print", function(output, kind){
  15446. output.print(kind);
  15447. if (this.value) {
  15448. output.space();
  15449. this.value.print(output);
  15450. }
  15451. output.semicolon();
  15452. });
  15453. DEFPRINT(AST_Return, function(self, output){
  15454. self._do_print(output, "return");
  15455. });
  15456. DEFPRINT(AST_Throw, function(self, output){
  15457. self._do_print(output, "throw");
  15458. });
  15459. /* -----[ loop control ]----- */
  15460. AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){
  15461. output.print(kind);
  15462. if (this.label) {
  15463. output.space();
  15464. this.label.print(output);
  15465. }
  15466. output.semicolon();
  15467. });
  15468. DEFPRINT(AST_Break, function(self, output){
  15469. self._do_print(output, "break");
  15470. });
  15471. DEFPRINT(AST_Continue, function(self, output){
  15472. self._do_print(output, "continue");
  15473. });
  15474. /* -----[ if ]----- */
  15475. function make_then(self, output) {
  15476. if (output.option("bracketize")) {
  15477. make_block(self.body, output);
  15478. return;
  15479. }
  15480. // The squeezer replaces "block"-s that contain only a single
  15481. // statement with the statement itself; technically, the AST
  15482. // is correct, but this can create problems when we output an
  15483. // IF having an ELSE clause where the THEN clause ends in an
  15484. // IF *without* an ELSE block (then the outer ELSE would refer
  15485. // to the inner IF). This function checks for this case and
  15486. // adds the block brackets if needed.
  15487. if (!self.body)
  15488. return output.force_semicolon();
  15489. if (self.body instanceof AST_Do) {
  15490. // Unconditionally use the if/do-while workaround for all browsers.
  15491. // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE
  15492. // croaks with "syntax error" on code like this: if (foo)
  15493. // do ... while(cond); else ... we need block brackets
  15494. // around do/while
  15495. make_block(self.body, output);
  15496. return;
  15497. }
  15498. var b = self.body;
  15499. while (true) {
  15500. if (b instanceof AST_If) {
  15501. if (!b.alternative) {
  15502. make_block(self.body, output);
  15503. return;
  15504. }
  15505. b = b.alternative;
  15506. }
  15507. else if (b instanceof AST_StatementWithBody) {
  15508. b = b.body;
  15509. }
  15510. else break;
  15511. }
  15512. force_statement(self.body, output);
  15513. };
  15514. DEFPRINT(AST_If, function(self, output){
  15515. output.print("if");
  15516. output.space();
  15517. output.with_parens(function(){
  15518. self.condition.print(output);
  15519. });
  15520. output.space();
  15521. if (self.alternative) {
  15522. make_then(self, output);
  15523. output.space();
  15524. output.print("else");
  15525. output.space();
  15526. force_statement(self.alternative, output);
  15527. } else {
  15528. self._do_print_body(output);
  15529. }
  15530. });
  15531. /* -----[ switch ]----- */
  15532. DEFPRINT(AST_Switch, function(self, output){
  15533. output.print("switch");
  15534. output.space();
  15535. output.with_parens(function(){
  15536. self.expression.print(output);
  15537. });
  15538. output.space();
  15539. if (self.body.length > 0) output.with_block(function(){
  15540. self.body.forEach(function(stmt, i){
  15541. if (i) output.newline();
  15542. output.indent(true);
  15543. stmt.print(output);
  15544. });
  15545. });
  15546. else output.print("{}");
  15547. });
  15548. AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){
  15549. if (this.body.length > 0) {
  15550. output.newline();
  15551. this.body.forEach(function(stmt){
  15552. output.indent();
  15553. stmt.print(output);
  15554. output.newline();
  15555. });
  15556. }
  15557. });
  15558. DEFPRINT(AST_Default, function(self, output){
  15559. output.print("default:");
  15560. self._do_print_body(output);
  15561. });
  15562. DEFPRINT(AST_Case, function(self, output){
  15563. output.print("case");
  15564. output.space();
  15565. self.expression.print(output);
  15566. output.print(":");
  15567. self._do_print_body(output);
  15568. });
  15569. /* -----[ exceptions ]----- */
  15570. DEFPRINT(AST_Try, function(self, output){
  15571. output.print("try");
  15572. output.space();
  15573. print_bracketed(self.body, output);
  15574. if (self.bcatch) {
  15575. output.space();
  15576. self.bcatch.print(output);
  15577. }
  15578. if (self.bfinally) {
  15579. output.space();
  15580. self.bfinally.print(output);
  15581. }
  15582. });
  15583. DEFPRINT(AST_Catch, function(self, output){
  15584. output.print("catch");
  15585. output.space();
  15586. output.with_parens(function(){
  15587. self.argname.print(output);
  15588. });
  15589. output.space();
  15590. print_bracketed(self.body, output);
  15591. });
  15592. DEFPRINT(AST_Finally, function(self, output){
  15593. output.print("finally");
  15594. output.space();
  15595. print_bracketed(self.body, output);
  15596. });
  15597. /* -----[ var/const ]----- */
  15598. AST_Definitions.DEFMETHOD("_do_print", function(output, kind){
  15599. output.print(kind);
  15600. output.space();
  15601. this.definitions.forEach(function(def, i){
  15602. if (i) output.comma();
  15603. def.print(output);
  15604. });
  15605. var p = output.parent();
  15606. var in_for = p instanceof AST_For || p instanceof AST_ForIn;
  15607. var avoid_semicolon = in_for && p.init === this;
  15608. if (!avoid_semicolon)
  15609. output.semicolon();
  15610. });
  15611. DEFPRINT(AST_Var, function(self, output){
  15612. self._do_print(output, "var");
  15613. });
  15614. DEFPRINT(AST_Const, function(self, output){
  15615. self._do_print(output, "const");
  15616. });
  15617. function parenthesize_for_noin(node, output, noin) {
  15618. if (!noin) node.print(output);
  15619. else try {
  15620. // need to take some precautions here:
  15621. // https://github.com/mishoo/UglifyJS2/issues/60
  15622. node.walk(new TreeWalker(function(node){
  15623. if (node instanceof AST_Binary && node.operator == "in")
  15624. throw output;
  15625. }));
  15626. node.print(output);
  15627. } catch(ex) {
  15628. if (ex !== output) throw ex;
  15629. node.print(output, true);
  15630. }
  15631. };
  15632. DEFPRINT(AST_VarDef, function(self, output){
  15633. self.name.print(output);
  15634. if (self.value) {
  15635. output.space();
  15636. output.print("=");
  15637. output.space();
  15638. var p = output.parent(1);
  15639. var noin = p instanceof AST_For || p instanceof AST_ForIn;
  15640. parenthesize_for_noin(self.value, output, noin);
  15641. }
  15642. });
  15643. /* -----[ other expressions ]----- */
  15644. DEFPRINT(AST_Call, function(self, output){
  15645. self.expression.print(output);
  15646. if (self instanceof AST_New && !need_constructor_parens(self, output))
  15647. return;
  15648. output.with_parens(function(){
  15649. self.args.forEach(function(expr, i){
  15650. if (i) output.comma();
  15651. expr.print(output);
  15652. });
  15653. });
  15654. });
  15655. DEFPRINT(AST_New, function(self, output){
  15656. output.print("new");
  15657. output.space();
  15658. AST_Call.prototype._codegen(self, output);
  15659. });
  15660. AST_Seq.DEFMETHOD("_do_print", function(output){
  15661. this.car.print(output);
  15662. if (this.cdr) {
  15663. output.comma();
  15664. if (output.should_break()) {
  15665. output.newline();
  15666. output.indent();
  15667. }
  15668. this.cdr.print(output);
  15669. }
  15670. });
  15671. DEFPRINT(AST_Seq, function(self, output){
  15672. self._do_print(output);
  15673. // var p = output.parent();
  15674. // if (p instanceof AST_Statement) {
  15675. // output.with_indent(output.next_indent(), function(){
  15676. // self._do_print(output);
  15677. // });
  15678. // } else {
  15679. // self._do_print(output);
  15680. // }
  15681. });
  15682. DEFPRINT(AST_Dot, function(self, output){
  15683. var expr = self.expression;
  15684. expr.print(output);
  15685. if (expr instanceof AST_Number && expr.getValue() >= 0) {
  15686. if (!/[xa-f.)]/i.test(output.last())) {
  15687. output.print(".");
  15688. }
  15689. }
  15690. output.print(".");
  15691. // the name after dot would be mapped about here.
  15692. output.add_mapping(self.end);
  15693. output.print_name(self.property);
  15694. });
  15695. DEFPRINT(AST_Sub, function(self, output){
  15696. self.expression.print(output);
  15697. output.print("[");
  15698. self.property.print(output);
  15699. output.print("]");
  15700. });
  15701. DEFPRINT(AST_UnaryPrefix, function(self, output){
  15702. var op = self.operator;
  15703. output.print(op);
  15704. if (/^[a-z]/i.test(op)
  15705. || (/[+-]$/.test(op)
  15706. && self.expression instanceof AST_UnaryPrefix
  15707. && /^[+-]/.test(self.expression.operator))) {
  15708. output.space();
  15709. }
  15710. self.expression.print(output);
  15711. });
  15712. DEFPRINT(AST_UnaryPostfix, function(self, output){
  15713. self.expression.print(output);
  15714. output.print(self.operator);
  15715. });
  15716. DEFPRINT(AST_Binary, function(self, output){
  15717. var op = self.operator;
  15718. self.left.print(output);
  15719. if (op[0] == ">" /* ">>" ">>>" ">" ">=" */
  15720. && self.left instanceof AST_UnaryPostfix
  15721. && self.left.operator == "--") {
  15722. // space is mandatory to avoid outputting -->
  15723. output.print(" ");
  15724. } else {
  15725. // the space is optional depending on "beautify"
  15726. output.space();
  15727. }
  15728. output.print(op);
  15729. if ((op == "<" || op == "<<")
  15730. && self.right instanceof AST_UnaryPrefix
  15731. && self.right.operator == "!"
  15732. && self.right.expression instanceof AST_UnaryPrefix
  15733. && self.right.expression.operator == "--") {
  15734. // space is mandatory to avoid outputting <!--
  15735. output.print(" ");
  15736. } else {
  15737. // the space is optional depending on "beautify"
  15738. output.space();
  15739. }
  15740. self.right.print(output);
  15741. });
  15742. DEFPRINT(AST_Conditional, function(self, output){
  15743. self.condition.print(output);
  15744. output.space();
  15745. output.print("?");
  15746. output.space();
  15747. self.consequent.print(output);
  15748. output.space();
  15749. output.colon();
  15750. self.alternative.print(output);
  15751. });
  15752. /* -----[ literals ]----- */
  15753. DEFPRINT(AST_Array, function(self, output){
  15754. output.with_square(function(){
  15755. var a = self.elements, len = a.length;
  15756. if (len > 0) output.space();
  15757. a.forEach(function(exp, i){
  15758. if (i) output.comma();
  15759. exp.print(output);
  15760. // If the final element is a hole, we need to make sure it
  15761. // doesn't look like a trailing comma, by inserting an actual
  15762. // trailing comma.
  15763. if (i === len - 1 && exp instanceof AST_Hole)
  15764. output.comma();
  15765. });
  15766. if (len > 0) output.space();
  15767. });
  15768. });
  15769. DEFPRINT(AST_Object, function(self, output){
  15770. if (self.properties.length > 0) output.with_block(function(){
  15771. self.properties.forEach(function(prop, i){
  15772. if (i) {
  15773. output.print(",");
  15774. output.newline();
  15775. }
  15776. output.indent();
  15777. prop.print(output);
  15778. });
  15779. output.newline();
  15780. });
  15781. else output.print("{}");
  15782. });
  15783. DEFPRINT(AST_ObjectKeyVal, function(self, output){
  15784. var key = self.key;
  15785. var quote = self.quote;
  15786. if (output.option("quote_keys")) {
  15787. output.print_string(key + "");
  15788. } else if ((typeof key == "number"
  15789. || !output.option("beautify")
  15790. && +key + "" == key)
  15791. && parseFloat(key) >= 0) {
  15792. output.print(make_num(key));
  15793. } else if (RESERVED_WORDS(key) ? output.option("screw_ie8") : is_identifier_string(key)) {
  15794. if (quote && output.option("keep_quoted_props")) {
  15795. output.print_string(key, quote);
  15796. } else {
  15797. output.print_name(key);
  15798. }
  15799. } else {
  15800. output.print_string(key, quote);
  15801. }
  15802. output.colon();
  15803. self.value.print(output);
  15804. });
  15805. DEFPRINT(AST_ObjectSetter, function(self, output){
  15806. output.print("set");
  15807. output.space();
  15808. self.key.print(output);
  15809. self.value._do_print(output, true);
  15810. });
  15811. DEFPRINT(AST_ObjectGetter, function(self, output){
  15812. output.print("get");
  15813. output.space();
  15814. self.key.print(output);
  15815. self.value._do_print(output, true);
  15816. });
  15817. DEFPRINT(AST_Symbol, function(self, output){
  15818. var def = self.definition();
  15819. output.print_name(def ? def.mangled_name || def.name : self.name);
  15820. });
  15821. DEFPRINT(AST_Undefined, function(self, output){
  15822. output.print("void 0");
  15823. });
  15824. DEFPRINT(AST_Hole, noop);
  15825. DEFPRINT(AST_Infinity, function(self, output){
  15826. output.print("Infinity");
  15827. });
  15828. DEFPRINT(AST_NaN, function(self, output){
  15829. output.print("NaN");
  15830. });
  15831. DEFPRINT(AST_This, function(self, output){
  15832. output.print("this");
  15833. });
  15834. DEFPRINT(AST_Constant, function(self, output){
  15835. output.print(self.getValue());
  15836. });
  15837. DEFPRINT(AST_String, function(self, output){
  15838. output.print_string(self.getValue(), self.quote, in_directive);
  15839. });
  15840. DEFPRINT(AST_Number, function(self, output){
  15841. if (use_asm && self.start && self.start.raw != null) {
  15842. output.print(self.start.raw);
  15843. } else {
  15844. output.print(make_num(self.getValue()));
  15845. }
  15846. });
  15847. function regexp_safe_literal(code) {
  15848. return [
  15849. 0x5c , // \
  15850. 0x2f , // /
  15851. 0x2e , // .
  15852. 0x2b , // +
  15853. 0x2a , // *
  15854. 0x3f , // ?
  15855. 0x28 , // (
  15856. 0x29 , // )
  15857. 0x5b , // [
  15858. 0x5d , // ]
  15859. 0x7b , // {
  15860. 0x7d , // }
  15861. 0x24 , // $
  15862. 0x5e , // ^
  15863. 0x3a , // :
  15864. 0x7c , // |
  15865. 0x21 , // !
  15866. 0x0a , // \n
  15867. 0x0d , // \r
  15868. 0x00 , // \0
  15869. 0xfeff , // Unicode BOM
  15870. 0x2028 , // unicode "line separator"
  15871. 0x2029 , // unicode "paragraph separator"
  15872. ].indexOf(code) < 0;
  15873. };
  15874. DEFPRINT(AST_RegExp, function(self, output){
  15875. var str = self.getValue().toString();
  15876. if (output.option("ascii_only")) {
  15877. str = output.to_ascii(str);
  15878. } else if (output.option("unescape_regexps")) {
  15879. str = str.split("\\\\").map(function(str){
  15880. return str.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g, function(s){
  15881. var code = parseInt(s.substr(2), 16);
  15882. return regexp_safe_literal(code) ? String.fromCharCode(code) : s;
  15883. });
  15884. }).join("\\\\");
  15885. }
  15886. output.print(str);
  15887. var p = output.parent();
  15888. if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self)
  15889. output.print(" ");
  15890. });
  15891. function force_statement(stat, output) {
  15892. if (output.option("bracketize")) {
  15893. if (!stat || stat instanceof AST_EmptyStatement)
  15894. output.print("{}");
  15895. else if (stat instanceof AST_BlockStatement)
  15896. stat.print(output);
  15897. else output.with_block(function(){
  15898. output.indent();
  15899. stat.print(output);
  15900. output.newline();
  15901. });
  15902. } else {
  15903. if (!stat || stat instanceof AST_EmptyStatement)
  15904. output.force_semicolon();
  15905. else
  15906. stat.print(output);
  15907. }
  15908. };
  15909. // return true if the node at the top of the stack (that means the
  15910. // innermost node in the current output) is lexically the first in
  15911. // a statement.
  15912. function first_in_statement(output) {
  15913. var a = output.stack(), i = a.length, node = a[--i], p = a[--i];
  15914. while (i > 0) {
  15915. if (p instanceof AST_Statement && p.body === node)
  15916. return true;
  15917. if ((p instanceof AST_Seq && p.car === node ) ||
  15918. (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) ||
  15919. (p instanceof AST_Dot && p.expression === node ) ||
  15920. (p instanceof AST_Sub && p.expression === node ) ||
  15921. (p instanceof AST_Conditional && p.condition === node ) ||
  15922. (p instanceof AST_Binary && p.left === node ) ||
  15923. (p instanceof AST_UnaryPostfix && p.expression === node ))
  15924. {
  15925. node = p;
  15926. p = a[--i];
  15927. } else {
  15928. return false;
  15929. }
  15930. }
  15931. };
  15932. // self should be AST_New. decide if we want to show parens or not.
  15933. function need_constructor_parens(self, output) {
  15934. // Always print parentheses with arguments
  15935. if (self.args.length > 0) return true;
  15936. return output.option("beautify");
  15937. };
  15938. function best_of(a) {
  15939. var best = a[0], len = best.length;
  15940. for (var i = 1; i < a.length; ++i) {
  15941. if (a[i].length < len) {
  15942. best = a[i];
  15943. len = best.length;
  15944. }
  15945. }
  15946. return best;
  15947. };
  15948. function make_num(num) {
  15949. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  15950. if (Math.floor(num) === num) {
  15951. if (num >= 0) {
  15952. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  15953. "0" + num.toString(8)); // same.
  15954. } else {
  15955. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  15956. "-0" + (-num).toString(8)); // same.
  15957. }
  15958. if ((m = /^(.*?)(0+)$/.exec(num))) {
  15959. a.push(m[1] + "e" + m[2].length);
  15960. }
  15961. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  15962. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  15963. str.substr(str.indexOf(".")));
  15964. }
  15965. return best_of(a);
  15966. };
  15967. function make_block(stmt, output) {
  15968. if (stmt instanceof AST_BlockStatement) {
  15969. stmt.print(output);
  15970. return;
  15971. }
  15972. output.with_block(function(){
  15973. output.indent();
  15974. stmt.print(output);
  15975. output.newline();
  15976. });
  15977. };
  15978. /* -----[ source map generators ]----- */
  15979. function DEFMAP(nodetype, generator) {
  15980. nodetype.DEFMETHOD("add_source_map", function(stream){
  15981. generator(this, stream);
  15982. });
  15983. };
  15984. // We could easily add info for ALL nodes, but it seems to me that
  15985. // would be quite wasteful, hence this noop in the base class.
  15986. DEFMAP(AST_Node, noop);
  15987. function basic_sourcemap_gen(self, output) {
  15988. output.add_mapping(self.start);
  15989. };
  15990. // XXX: I'm not exactly sure if we need it for all of these nodes,
  15991. // or if we should add even more.
  15992. DEFMAP(AST_Directive, basic_sourcemap_gen);
  15993. DEFMAP(AST_Debugger, basic_sourcemap_gen);
  15994. DEFMAP(AST_Symbol, basic_sourcemap_gen);
  15995. DEFMAP(AST_Jump, basic_sourcemap_gen);
  15996. DEFMAP(AST_StatementWithBody, basic_sourcemap_gen);
  15997. DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it
  15998. DEFMAP(AST_Lambda, basic_sourcemap_gen);
  15999. DEFMAP(AST_Switch, basic_sourcemap_gen);
  16000. DEFMAP(AST_SwitchBranch, basic_sourcemap_gen);
  16001. DEFMAP(AST_BlockStatement, basic_sourcemap_gen);
  16002. DEFMAP(AST_Toplevel, noop);
  16003. DEFMAP(AST_New, basic_sourcemap_gen);
  16004. DEFMAP(AST_Try, basic_sourcemap_gen);
  16005. DEFMAP(AST_Catch, basic_sourcemap_gen);
  16006. DEFMAP(AST_Finally, basic_sourcemap_gen);
  16007. DEFMAP(AST_Definitions, basic_sourcemap_gen);
  16008. DEFMAP(AST_Constant, basic_sourcemap_gen);
  16009. DEFMAP(AST_ObjectSetter, function(self, output){
  16010. output.add_mapping(self.start, self.key.name);
  16011. });
  16012. DEFMAP(AST_ObjectGetter, function(self, output){
  16013. output.add_mapping(self.start, self.key.name);
  16014. });
  16015. DEFMAP(AST_ObjectProperty, function(self, output){
  16016. output.add_mapping(self.start, self.key);
  16017. });
  16018. })();
  16019. /***********************************************************************
  16020. A JavaScript tokenizer / parser / beautifier / compressor.
  16021. https://github.com/mishoo/UglifyJS2
  16022. -------------------------------- (C) ---------------------------------
  16023. Author: Mihai Bazon
  16024. <mihai.bazon@gmail.com>
  16025. http://mihai.bazon.net/blog
  16026. Distributed under the BSD license:
  16027. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  16028. Redistribution and use in source and binary forms, with or without
  16029. modification, are permitted provided that the following conditions
  16030. are met:
  16031. * Redistributions of source code must retain the above
  16032. copyright notice, this list of conditions and the following
  16033. disclaimer.
  16034. * Redistributions in binary form must reproduce the above
  16035. copyright notice, this list of conditions and the following
  16036. disclaimer in the documentation and/or other materials
  16037. provided with the distribution.
  16038. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  16039. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16040. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  16041. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  16042. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  16043. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  16044. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  16045. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  16046. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  16047. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  16048. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  16049. SUCH DAMAGE.
  16050. ***********************************************************************/
  16051. "use strict";
  16052. function Compressor(options, false_by_default) {
  16053. if (!(this instanceof Compressor))
  16054. return new Compressor(options, false_by_default);
  16055. TreeTransformer.call(this, this.before, this.after);
  16056. this.options = defaults(options, {
  16057. sequences : !false_by_default,
  16058. properties : !false_by_default,
  16059. dead_code : !false_by_default,
  16060. drop_debugger : !false_by_default,
  16061. unsafe : false,
  16062. unsafe_comps : false,
  16063. conditionals : !false_by_default,
  16064. comparisons : !false_by_default,
  16065. evaluate : !false_by_default,
  16066. booleans : !false_by_default,
  16067. loops : !false_by_default,
  16068. unused : !false_by_default,
  16069. hoist_funs : !false_by_default,
  16070. keep_fargs : true,
  16071. keep_fnames : false,
  16072. hoist_vars : false,
  16073. if_return : !false_by_default,
  16074. join_vars : !false_by_default,
  16075. collapse_vars : false,
  16076. cascade : !false_by_default,
  16077. side_effects : !false_by_default,
  16078. pure_getters : false,
  16079. pure_funcs : null,
  16080. negate_iife : !false_by_default,
  16081. screw_ie8 : true,
  16082. drop_console : false,
  16083. angular : false,
  16084. warnings : true,
  16085. global_defs : {},
  16086. passes : 1,
  16087. }, true);
  16088. var sequences = this.options["sequences"];
  16089. this.sequences_limit = sequences == 1 ? 200 : sequences | 0;
  16090. this.warnings_produced = {};
  16091. };
  16092. Compressor.prototype = new TreeTransformer;
  16093. merge(Compressor.prototype, {
  16094. option: function(key) { return this.options[key] },
  16095. compress: function(node) {
  16096. var passes = +this.options.passes || 1;
  16097. for (var pass = 0; pass < passes && pass < 3; ++pass) {
  16098. if (pass > 0) node.clear_opt_flags();
  16099. node = node.transform(this);
  16100. }
  16101. return node;
  16102. },
  16103. warn: function(text, props) {
  16104. if (this.options.warnings) {
  16105. // only emit unique warnings
  16106. var message = string_template(text, props);
  16107. if (!(message in this.warnings_produced)) {
  16108. this.warnings_produced[message] = true;
  16109. AST_Node.warn.apply(AST_Node, arguments);
  16110. }
  16111. }
  16112. },
  16113. clear_warnings: function() {
  16114. this.warnings_produced = {};
  16115. },
  16116. before: function(node, descend, in_list) {
  16117. if (node._squeezed) return node;
  16118. var was_scope = false;
  16119. if (node instanceof AST_Scope) {
  16120. node = node.hoist_declarations(this);
  16121. was_scope = true;
  16122. }
  16123. descend(node, this);
  16124. node = node.optimize(this);
  16125. if (was_scope && node instanceof AST_Scope) {
  16126. node.drop_unused(this);
  16127. descend(node, this);
  16128. }
  16129. node._squeezed = true;
  16130. return node;
  16131. }
  16132. });
  16133. (function(){
  16134. function OPT(node, optimizer) {
  16135. node.DEFMETHOD("optimize", function(compressor){
  16136. var self = this;
  16137. if (self._optimized) return self;
  16138. if (compressor.has_directive("use asm")) return self;
  16139. var opt = optimizer(self, compressor);
  16140. opt._optimized = true;
  16141. if (opt === self) return opt;
  16142. return opt.transform(compressor);
  16143. });
  16144. };
  16145. OPT(AST_Node, function(self, compressor){
  16146. return self;
  16147. });
  16148. AST_Node.DEFMETHOD("equivalent_to", function(node){
  16149. // XXX: this is a rather expensive way to test two node's equivalence:
  16150. return this.print_to_string() == node.print_to_string();
  16151. });
  16152. AST_Node.DEFMETHOD("clear_opt_flags", function(){
  16153. this.walk(new TreeWalker(function(node){
  16154. if (!(node instanceof AST_Directive || node instanceof AST_Constant)) {
  16155. node._squeezed = false;
  16156. node._optimized = false;
  16157. }
  16158. }));
  16159. });
  16160. function make_node(ctor, orig, props) {
  16161. if (!props) props = {};
  16162. if (orig) {
  16163. if (!props.start) props.start = orig.start;
  16164. if (!props.end) props.end = orig.end;
  16165. }
  16166. return new ctor(props);
  16167. };
  16168. function make_node_from_constant(compressor, val, orig) {
  16169. // XXX: WIP.
  16170. // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){
  16171. // if (node instanceof AST_SymbolRef) {
  16172. // var scope = compressor.find_parent(AST_Scope);
  16173. // var def = scope.find_variable(node);
  16174. // node.thedef = def;
  16175. // return node;
  16176. // }
  16177. // })).transform(compressor);
  16178. if (val instanceof AST_Node) return val.transform(compressor);
  16179. switch (typeof val) {
  16180. case "string":
  16181. return make_node(AST_String, orig, {
  16182. value: val
  16183. }).optimize(compressor);
  16184. case "number":
  16185. if (isNaN(val)) {
  16186. return make_node(AST_NaN, orig);
  16187. }
  16188. if ((1 / val) < 0) {
  16189. return make_node(AST_UnaryPrefix, orig, {
  16190. operator: "-",
  16191. expression: make_node(AST_Number, orig, { value: -val })
  16192. });
  16193. }
  16194. return make_node(AST_Number, orig, { value: val }).optimize(compressor);
  16195. case "boolean":
  16196. return make_node(val ? AST_True : AST_False, orig).optimize(compressor);
  16197. case "undefined":
  16198. return make_node(AST_Undefined, orig).optimize(compressor);
  16199. default:
  16200. if (val === null) {
  16201. return make_node(AST_Null, orig, { value: null }).optimize(compressor);
  16202. }
  16203. if (val instanceof RegExp) {
  16204. return make_node(AST_RegExp, orig, { value: val }).optimize(compressor);
  16205. }
  16206. throw new Error(string_template("Can't handle constant of type: {type}", {
  16207. type: typeof val
  16208. }));
  16209. }
  16210. };
  16211. // we shouldn't compress (1,func)(something) to
  16212. // func(something) because that changes the meaning of
  16213. // the func (becomes lexical instead of global).
  16214. function maintain_this_binding(parent, orig, val) {
  16215. if (parent instanceof AST_Call && parent.expression === orig) {
  16216. if (val instanceof AST_PropAccess || val instanceof AST_SymbolRef && val.name === "eval") {
  16217. return make_node(AST_Seq, orig, {
  16218. car: make_node(AST_Number, orig, {
  16219. value: 0
  16220. }),
  16221. cdr: val
  16222. });
  16223. }
  16224. }
  16225. return val;
  16226. }
  16227. function as_statement_array(thing) {
  16228. if (thing === null) return [];
  16229. if (thing instanceof AST_BlockStatement) return thing.body;
  16230. if (thing instanceof AST_EmptyStatement) return [];
  16231. if (thing instanceof AST_Statement) return [ thing ];
  16232. throw new Error("Can't convert thing to statement array");
  16233. };
  16234. function is_empty(thing) {
  16235. if (thing === null) return true;
  16236. if (thing instanceof AST_EmptyStatement) return true;
  16237. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  16238. return false;
  16239. };
  16240. function loop_body(x) {
  16241. if (x instanceof AST_Switch) return x;
  16242. if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {
  16243. return (x.body instanceof AST_BlockStatement ? x.body : x);
  16244. }
  16245. return x;
  16246. };
  16247. function tighten_body(statements, compressor) {
  16248. var CHANGED, max_iter = 10;
  16249. do {
  16250. CHANGED = false;
  16251. if (compressor.option("angular")) {
  16252. statements = process_for_angular(statements);
  16253. }
  16254. statements = eliminate_spurious_blocks(statements);
  16255. if (compressor.option("dead_code")) {
  16256. statements = eliminate_dead_code(statements, compressor);
  16257. }
  16258. if (compressor.option("if_return")) {
  16259. statements = handle_if_return(statements, compressor);
  16260. }
  16261. if (compressor.sequences_limit > 0) {
  16262. statements = sequencesize(statements, compressor);
  16263. }
  16264. if (compressor.option("join_vars")) {
  16265. statements = join_consecutive_vars(statements, compressor);
  16266. }
  16267. if (compressor.option("collapse_vars")) {
  16268. statements = collapse_single_use_vars(statements, compressor);
  16269. }
  16270. } while (CHANGED && max_iter-- > 0);
  16271. if (compressor.option("negate_iife")) {
  16272. negate_iifes(statements, compressor);
  16273. }
  16274. return statements;
  16275. function collapse_single_use_vars(statements, compressor) {
  16276. // Iterate statements backwards looking for a statement with a var/const
  16277. // declaration immediately preceding it. Grab the rightmost var definition
  16278. // and if it has exactly one reference then attempt to replace its reference
  16279. // in the statement with the var value and then erase the var definition.
  16280. var self = compressor.self();
  16281. var var_defs_removed = false;
  16282. for (var stat_index = statements.length; --stat_index >= 0;) {
  16283. var stat = statements[stat_index];
  16284. if (stat instanceof AST_Definitions) continue;
  16285. // Process child blocks of statement if present.
  16286. [stat, stat.body, stat.alternative, stat.bcatch, stat.bfinally].forEach(function(node) {
  16287. node && node.body && collapse_single_use_vars(node.body, compressor);
  16288. });
  16289. // The variable definition must precede a statement.
  16290. if (stat_index <= 0) break;
  16291. var prev_stat_index = stat_index - 1;
  16292. var prev_stat = statements[prev_stat_index];
  16293. if (!(prev_stat instanceof AST_Definitions)) continue;
  16294. var var_defs = prev_stat.definitions;
  16295. if (var_defs == null) continue;
  16296. var var_names_seen = {};
  16297. var side_effects_encountered = false;
  16298. var lvalues_encountered = false;
  16299. var lvalues = {};
  16300. // Scan variable definitions from right to left.
  16301. for (var var_defs_index = var_defs.length; --var_defs_index >= 0;) {
  16302. // Obtain var declaration and var name with basic sanity check.
  16303. var var_decl = var_defs[var_defs_index];
  16304. if (var_decl.value == null) break;
  16305. var var_name = var_decl.name.name;
  16306. if (!var_name || !var_name.length) break;
  16307. // Bail if we've seen a var definition of same name before.
  16308. if (var_name in var_names_seen) break;
  16309. var_names_seen[var_name] = true;
  16310. // Only interested in cases with just one reference to the variable.
  16311. var def = self.find_variable && self.find_variable(var_name);
  16312. if (!def || !def.references || def.references.length !== 1 || var_name == "arguments") {
  16313. side_effects_encountered = true;
  16314. continue;
  16315. }
  16316. var ref = def.references[0];
  16317. // Don't replace ref if eval() or with statement in scope.
  16318. if (ref.scope.uses_eval || ref.scope.uses_with) break;
  16319. // Constant single use vars can be replaced in any scope.
  16320. if (!(var_decl.value instanceof AST_RegExp) && var_decl.value.is_constant(compressor)) {
  16321. var ctt = new TreeTransformer(function(node) {
  16322. if (node === ref)
  16323. return replace_var(node, ctt.parent(), true);
  16324. });
  16325. stat.transform(ctt);
  16326. continue;
  16327. }
  16328. // Restrict var replacement to constants if side effects encountered.
  16329. if (side_effects_encountered |= lvalues_encountered) continue;
  16330. // Non-constant single use vars can only be replaced in same scope.
  16331. if (ref.scope !== self) {
  16332. side_effects_encountered |= var_decl.value.has_side_effects(compressor);
  16333. continue;
  16334. }
  16335. // Detect lvalues in var value.
  16336. var tw = new TreeWalker(function(node){
  16337. if (node instanceof AST_SymbolRef && is_lvalue(node, tw.parent())) {
  16338. lvalues[node.name] = lvalues_encountered = true;
  16339. }
  16340. });
  16341. var_decl.value.walk(tw);
  16342. // Replace the non-constant single use var in statement if side effect free.
  16343. var unwind = false;
  16344. var tt = new TreeTransformer(
  16345. function preorder(node) {
  16346. if (unwind) return node;
  16347. var parent = tt.parent();
  16348. if (node instanceof AST_Lambda
  16349. || node instanceof AST_Try
  16350. || node instanceof AST_With
  16351. || node instanceof AST_Case
  16352. || node instanceof AST_IterationStatement
  16353. || (parent instanceof AST_If && node !== parent.condition)
  16354. || (parent instanceof AST_Conditional && node !== parent.condition)
  16355. || (parent instanceof AST_Binary
  16356. && (parent.operator == "&&" || parent.operator == "||")
  16357. && node === parent.right)
  16358. || (parent instanceof AST_Switch && node !== parent.expression)) {
  16359. return side_effects_encountered = unwind = true, node;
  16360. }
  16361. },
  16362. function postorder(node) {
  16363. if (unwind) return node;
  16364. if (node === ref)
  16365. return unwind = true, replace_var(node, tt.parent(), false);
  16366. if (side_effects_encountered |= node.has_side_effects(compressor))
  16367. return unwind = true, node;
  16368. if (lvalues_encountered && node instanceof AST_SymbolRef && node.name in lvalues) {
  16369. side_effects_encountered = true;
  16370. return unwind = true, node;
  16371. }
  16372. }
  16373. );
  16374. stat.transform(tt);
  16375. }
  16376. }
  16377. // Remove extraneous empty statments in block after removing var definitions.
  16378. // Leave at least one statement in `statements`.
  16379. if (var_defs_removed) for (var i = statements.length; --i >= 0;) {
  16380. if (statements.length > 1 && statements[i] instanceof AST_EmptyStatement)
  16381. statements.splice(i, 1);
  16382. }
  16383. return statements;
  16384. function is_lvalue(node, parent) {
  16385. return node instanceof AST_SymbolRef && (
  16386. (parent instanceof AST_Assign && node === parent.left)
  16387. || (parent instanceof AST_Unary && parent.expression === node
  16388. && (parent.operator == "++" || parent.operator == "--")));
  16389. }
  16390. function replace_var(node, parent, is_constant) {
  16391. if (is_lvalue(node, parent)) return node;
  16392. // Remove var definition and return its value to the TreeTransformer to replace.
  16393. var value = maintain_this_binding(parent, node, var_decl.value);
  16394. var_decl.value = null;
  16395. var_defs.splice(var_defs_index, 1);
  16396. if (var_defs.length === 0) {
  16397. statements[prev_stat_index] = make_node(AST_EmptyStatement, self);
  16398. var_defs_removed = true;
  16399. }
  16400. // Further optimize statement after substitution.
  16401. stat.clear_opt_flags();
  16402. compressor.warn("Replacing " + (is_constant ? "constant" : "variable") +
  16403. " " + var_name + " [{file}:{line},{col}]", node.start);
  16404. CHANGED = true;
  16405. return value;
  16406. }
  16407. }
  16408. function process_for_angular(statements) {
  16409. function has_inject(comment) {
  16410. return /@ngInject/.test(comment.value);
  16411. }
  16412. function make_arguments_names_list(func) {
  16413. return func.argnames.map(function(sym){
  16414. return make_node(AST_String, sym, { value: sym.name });
  16415. });
  16416. }
  16417. function make_array(orig, elements) {
  16418. return make_node(AST_Array, orig, { elements: elements });
  16419. }
  16420. function make_injector(func, name) {
  16421. return make_node(AST_SimpleStatement, func, {
  16422. body: make_node(AST_Assign, func, {
  16423. operator: "=",
  16424. left: make_node(AST_Dot, name, {
  16425. expression: make_node(AST_SymbolRef, name, name),
  16426. property: "$inject"
  16427. }),
  16428. right: make_array(func, make_arguments_names_list(func))
  16429. })
  16430. });
  16431. }
  16432. function check_expression(body) {
  16433. if (body && body.args) {
  16434. // if this is a function call check all of arguments passed
  16435. body.args.forEach(function(argument, index, array) {
  16436. var comments = argument.start.comments_before;
  16437. // if the argument is function preceded by @ngInject
  16438. if (argument instanceof AST_Lambda && comments.length && has_inject(comments[0])) {
  16439. // replace the function with an array of names of its parameters and function at the end
  16440. array[index] = make_array(argument, make_arguments_names_list(argument).concat(argument));
  16441. }
  16442. });
  16443. // if this is chained call check previous one recursively
  16444. if (body.expression && body.expression.expression) {
  16445. check_expression(body.expression.expression);
  16446. }
  16447. }
  16448. }
  16449. return statements.reduce(function(a, stat){
  16450. a.push(stat);
  16451. if (stat.body && stat.body.args) {
  16452. check_expression(stat.body);
  16453. } else {
  16454. var token = stat.start;
  16455. var comments = token.comments_before;
  16456. if (comments && comments.length > 0) {
  16457. var last = comments.pop();
  16458. if (has_inject(last)) {
  16459. // case 1: defun
  16460. if (stat instanceof AST_Defun) {
  16461. a.push(make_injector(stat, stat.name));
  16462. }
  16463. else if (stat instanceof AST_Definitions) {
  16464. stat.definitions.forEach(function(def) {
  16465. if (def.value && def.value instanceof AST_Lambda) {
  16466. a.push(make_injector(def.value, def.name));
  16467. }
  16468. });
  16469. }
  16470. else {
  16471. compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token);
  16472. }
  16473. }
  16474. }
  16475. }
  16476. return a;
  16477. }, []);
  16478. }
  16479. function eliminate_spurious_blocks(statements) {
  16480. var seen_dirs = [];
  16481. return statements.reduce(function(a, stat){
  16482. if (stat instanceof AST_BlockStatement) {
  16483. CHANGED = true;
  16484. a.push.apply(a, eliminate_spurious_blocks(stat.body));
  16485. } else if (stat instanceof AST_EmptyStatement) {
  16486. CHANGED = true;
  16487. } else if (stat instanceof AST_Directive) {
  16488. if (seen_dirs.indexOf(stat.value) < 0) {
  16489. a.push(stat);
  16490. seen_dirs.push(stat.value);
  16491. } else {
  16492. CHANGED = true;
  16493. }
  16494. } else {
  16495. a.push(stat);
  16496. }
  16497. return a;
  16498. }, []);
  16499. };
  16500. function handle_if_return(statements, compressor) {
  16501. var self = compressor.self();
  16502. var multiple_if_returns = has_multiple_if_returns(statements);
  16503. var in_lambda = self instanceof AST_Lambda;
  16504. var ret = [];
  16505. loop: for (var i = statements.length; --i >= 0;) {
  16506. var stat = statements[i];
  16507. switch (true) {
  16508. case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0):
  16509. CHANGED = true;
  16510. // note, ret.length is probably always zero
  16511. // because we drop unreachable code before this
  16512. // step. nevertheless, it's good to check.
  16513. continue loop;
  16514. case stat instanceof AST_If:
  16515. if (stat.body instanceof AST_Return) {
  16516. //---
  16517. // pretty silly case, but:
  16518. // if (foo()) return; return; ==> foo(); return;
  16519. if (((in_lambda && ret.length == 0)
  16520. || (ret[0] instanceof AST_Return && !ret[0].value))
  16521. && !stat.body.value && !stat.alternative) {
  16522. CHANGED = true;
  16523. var cond = make_node(AST_SimpleStatement, stat.condition, {
  16524. body: stat.condition
  16525. });
  16526. ret.unshift(cond);
  16527. continue loop;
  16528. }
  16529. //---
  16530. // if (foo()) return x; return y; ==> return foo() ? x : y;
  16531. if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) {
  16532. CHANGED = true;
  16533. stat = stat.clone();
  16534. stat.alternative = ret[0];
  16535. ret[0] = stat.transform(compressor);
  16536. continue loop;
  16537. }
  16538. //---
  16539. // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
  16540. if (multiple_if_returns && (ret.length == 0 || ret[0] instanceof AST_Return)
  16541. && stat.body.value && !stat.alternative && in_lambda) {
  16542. CHANGED = true;
  16543. stat = stat.clone();
  16544. stat.alternative = ret[0] || make_node(AST_Return, stat, {
  16545. value: make_node(AST_Undefined, stat)
  16546. });
  16547. ret[0] = stat.transform(compressor);
  16548. continue loop;
  16549. }
  16550. //---
  16551. // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... }
  16552. if (!stat.body.value && in_lambda) {
  16553. CHANGED = true;
  16554. stat = stat.clone();
  16555. stat.condition = stat.condition.negate(compressor);
  16556. var body = as_statement_array(stat.alternative).concat(ret);
  16557. var funs = extract_functions_from_statement_array(body);
  16558. stat.body = make_node(AST_BlockStatement, stat, {
  16559. body: body
  16560. });
  16561. stat.alternative = null;
  16562. ret = funs.concat([ stat.transform(compressor) ]);
  16563. continue loop;
  16564. }
  16565. //---
  16566. // XXX: what was the intention of this case?
  16567. // if sequences is not enabled, this can lead to an endless loop (issue #866).
  16568. // however, with sequences on this helps producing slightly better output for
  16569. // the example code.
  16570. if (compressor.option("sequences")
  16571. && ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement
  16572. && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) {
  16573. CHANGED = true;
  16574. ret.push(make_node(AST_Return, ret[0], {
  16575. value: make_node(AST_Undefined, ret[0])
  16576. }).transform(compressor));
  16577. ret = as_statement_array(stat.alternative).concat(ret);
  16578. ret.unshift(stat);
  16579. continue loop;
  16580. }
  16581. }
  16582. var ab = aborts(stat.body);
  16583. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  16584. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  16585. || (ab instanceof AST_Continue && self === loop_body(lct))
  16586. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  16587. if (ab.label) {
  16588. remove(ab.label.thedef.references, ab);
  16589. }
  16590. CHANGED = true;
  16591. var body = as_statement_array(stat.body).slice(0, -1);
  16592. stat = stat.clone();
  16593. stat.condition = stat.condition.negate(compressor);
  16594. stat.body = make_node(AST_BlockStatement, stat, {
  16595. body: as_statement_array(stat.alternative).concat(ret)
  16596. });
  16597. stat.alternative = make_node(AST_BlockStatement, stat, {
  16598. body: body
  16599. });
  16600. ret = [ stat.transform(compressor) ];
  16601. continue loop;
  16602. }
  16603. var ab = aborts(stat.alternative);
  16604. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  16605. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  16606. || (ab instanceof AST_Continue && self === loop_body(lct))
  16607. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  16608. if (ab.label) {
  16609. remove(ab.label.thedef.references, ab);
  16610. }
  16611. CHANGED = true;
  16612. stat = stat.clone();
  16613. stat.body = make_node(AST_BlockStatement, stat.body, {
  16614. body: as_statement_array(stat.body).concat(ret)
  16615. });
  16616. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  16617. body: as_statement_array(stat.alternative).slice(0, -1)
  16618. });
  16619. ret = [ stat.transform(compressor) ];
  16620. continue loop;
  16621. }
  16622. ret.unshift(stat);
  16623. break;
  16624. default:
  16625. ret.unshift(stat);
  16626. break;
  16627. }
  16628. }
  16629. return ret;
  16630. function has_multiple_if_returns(statements) {
  16631. var n = 0;
  16632. for (var i = statements.length; --i >= 0;) {
  16633. var stat = statements[i];
  16634. if (stat instanceof AST_If && stat.body instanceof AST_Return) {
  16635. if (++n > 1) return true;
  16636. }
  16637. }
  16638. return false;
  16639. }
  16640. };
  16641. function eliminate_dead_code(statements, compressor) {
  16642. var has_quit = false;
  16643. var orig = statements.length;
  16644. var self = compressor.self();
  16645. statements = statements.reduce(function(a, stat){
  16646. if (has_quit) {
  16647. extract_declarations_from_unreachable_code(compressor, stat, a);
  16648. } else {
  16649. if (stat instanceof AST_LoopControl) {
  16650. var lct = compressor.loopcontrol_target(stat.label);
  16651. if ((stat instanceof AST_Break
  16652. && lct instanceof AST_BlockStatement
  16653. && loop_body(lct) === self) || (stat instanceof AST_Continue
  16654. && loop_body(lct) === self)) {
  16655. if (stat.label) {
  16656. remove(stat.label.thedef.references, stat);
  16657. }
  16658. } else {
  16659. a.push(stat);
  16660. }
  16661. } else {
  16662. a.push(stat);
  16663. }
  16664. if (aborts(stat)) has_quit = true;
  16665. }
  16666. return a;
  16667. }, []);
  16668. CHANGED = statements.length != orig;
  16669. return statements;
  16670. };
  16671. function sequencesize(statements, compressor) {
  16672. if (statements.length < 2) return statements;
  16673. var seq = [], ret = [];
  16674. function push_seq() {
  16675. seq = AST_Seq.from_array(seq);
  16676. if (seq) ret.push(make_node(AST_SimpleStatement, seq, {
  16677. body: seq
  16678. }));
  16679. seq = [];
  16680. };
  16681. statements.forEach(function(stat){
  16682. if (stat instanceof AST_SimpleStatement && seqLength(seq) < compressor.sequences_limit) {
  16683. seq.push(stat.body);
  16684. } else {
  16685. push_seq();
  16686. ret.push(stat);
  16687. }
  16688. });
  16689. push_seq();
  16690. ret = sequencesize_2(ret, compressor);
  16691. CHANGED = ret.length != statements.length;
  16692. return ret;
  16693. };
  16694. function seqLength(a) {
  16695. for (var len = 0, i = 0; i < a.length; ++i) {
  16696. var stat = a[i];
  16697. if (stat instanceof AST_Seq) {
  16698. len += stat.len();
  16699. } else {
  16700. len++;
  16701. }
  16702. }
  16703. return len;
  16704. };
  16705. function sequencesize_2(statements, compressor) {
  16706. function cons_seq(right) {
  16707. ret.pop();
  16708. var left = prev.body;
  16709. if (left instanceof AST_Seq) {
  16710. left.add(right);
  16711. } else {
  16712. left = AST_Seq.cons(left, right);
  16713. }
  16714. return left.transform(compressor);
  16715. };
  16716. var ret = [], prev = null;
  16717. statements.forEach(function(stat){
  16718. if (prev) {
  16719. if (stat instanceof AST_For) {
  16720. var opera = {};
  16721. try {
  16722. prev.body.walk(new TreeWalker(function(node){
  16723. if (node instanceof AST_Binary && node.operator == "in")
  16724. throw opera;
  16725. }));
  16726. if (stat.init && !(stat.init instanceof AST_Definitions)) {
  16727. stat.init = cons_seq(stat.init);
  16728. }
  16729. else if (!stat.init) {
  16730. stat.init = prev.body;
  16731. ret.pop();
  16732. }
  16733. } catch(ex) {
  16734. if (ex !== opera) throw ex;
  16735. }
  16736. }
  16737. else if (stat instanceof AST_If) {
  16738. stat.condition = cons_seq(stat.condition);
  16739. }
  16740. else if (stat instanceof AST_With) {
  16741. stat.expression = cons_seq(stat.expression);
  16742. }
  16743. else if (stat instanceof AST_Exit && stat.value) {
  16744. stat.value = cons_seq(stat.value);
  16745. }
  16746. else if (stat instanceof AST_Exit) {
  16747. stat.value = cons_seq(make_node(AST_Undefined, stat));
  16748. }
  16749. else if (stat instanceof AST_Switch) {
  16750. stat.expression = cons_seq(stat.expression);
  16751. }
  16752. }
  16753. ret.push(stat);
  16754. prev = stat instanceof AST_SimpleStatement ? stat : null;
  16755. });
  16756. return ret;
  16757. };
  16758. function join_consecutive_vars(statements, compressor) {
  16759. var prev = null;
  16760. return statements.reduce(function(a, stat){
  16761. if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) {
  16762. prev.definitions = prev.definitions.concat(stat.definitions);
  16763. CHANGED = true;
  16764. }
  16765. else if (stat instanceof AST_For
  16766. && prev instanceof AST_Var
  16767. && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  16768. CHANGED = true;
  16769. a.pop();
  16770. if (stat.init) {
  16771. stat.init.definitions = prev.definitions.concat(stat.init.definitions);
  16772. } else {
  16773. stat.init = prev;
  16774. }
  16775. a.push(stat);
  16776. prev = stat;
  16777. }
  16778. else {
  16779. prev = stat;
  16780. a.push(stat);
  16781. }
  16782. return a;
  16783. }, []);
  16784. };
  16785. function negate_iifes(statements, compressor) {
  16786. function is_iife_call(node) {
  16787. if (node instanceof AST_Call) {
  16788. return node.expression instanceof AST_Function || is_iife_call(node.expression);
  16789. }
  16790. return false;
  16791. }
  16792. statements.forEach(function(stat){
  16793. if (stat instanceof AST_SimpleStatement) {
  16794. stat.body = (function transform(thing) {
  16795. return thing.transform(new TreeTransformer(function(node){
  16796. if (node instanceof AST_New) {
  16797. return node;
  16798. }
  16799. if (is_iife_call(node)) {
  16800. return make_node(AST_UnaryPrefix, node, {
  16801. operator: "!",
  16802. expression: node
  16803. });
  16804. }
  16805. else if (node instanceof AST_Call) {
  16806. node.expression = transform(node.expression);
  16807. }
  16808. else if (node instanceof AST_Seq) {
  16809. node.car = transform(node.car);
  16810. }
  16811. else if (node instanceof AST_Conditional) {
  16812. var expr = transform(node.condition);
  16813. if (expr !== node.condition) {
  16814. // it has been negated, reverse
  16815. node.condition = expr;
  16816. var tmp = node.consequent;
  16817. node.consequent = node.alternative;
  16818. node.alternative = tmp;
  16819. }
  16820. }
  16821. return node;
  16822. }));
  16823. })(stat.body);
  16824. }
  16825. });
  16826. };
  16827. };
  16828. function extract_functions_from_statement_array(statements) {
  16829. var funs = [];
  16830. for (var i = statements.length - 1; i >= 0; --i) {
  16831. var stat = statements[i];
  16832. if (stat instanceof AST_Defun) {
  16833. statements.splice(i, 1);
  16834. funs.unshift(stat);
  16835. }
  16836. }
  16837. return funs;
  16838. }
  16839. function extract_declarations_from_unreachable_code(compressor, stat, target) {
  16840. if (!(stat instanceof AST_Defun)) {
  16841. compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
  16842. }
  16843. stat.walk(new TreeWalker(function(node){
  16844. if (node instanceof AST_Definitions) {
  16845. compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
  16846. node.remove_initializers();
  16847. target.push(node);
  16848. return true;
  16849. }
  16850. if (node instanceof AST_Defun) {
  16851. target.push(node);
  16852. return true;
  16853. }
  16854. if (node instanceof AST_Scope) {
  16855. return true;
  16856. }
  16857. }));
  16858. };
  16859. /* -----[ boolean/negation helpers ]----- */
  16860. // methods to determine whether an expression has a boolean result type
  16861. (function (def){
  16862. var unary_bool = [ "!", "delete" ];
  16863. var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ];
  16864. def(AST_Node, function(){ return false });
  16865. def(AST_UnaryPrefix, function(){
  16866. return member(this.operator, unary_bool);
  16867. });
  16868. def(AST_Binary, function(){
  16869. return member(this.operator, binary_bool) ||
  16870. ( (this.operator == "&&" || this.operator == "||") &&
  16871. this.left.is_boolean() && this.right.is_boolean() );
  16872. });
  16873. def(AST_Conditional, function(){
  16874. return this.consequent.is_boolean() && this.alternative.is_boolean();
  16875. });
  16876. def(AST_Assign, function(){
  16877. return this.operator == "=" && this.right.is_boolean();
  16878. });
  16879. def(AST_Seq, function(){
  16880. return this.cdr.is_boolean();
  16881. });
  16882. def(AST_True, function(){ return true });
  16883. def(AST_False, function(){ return true });
  16884. })(function(node, func){
  16885. node.DEFMETHOD("is_boolean", func);
  16886. });
  16887. // methods to determine if an expression has a string result type
  16888. (function (def){
  16889. def(AST_Node, function(){ return false });
  16890. def(AST_String, function(){ return true });
  16891. def(AST_UnaryPrefix, function(){
  16892. return this.operator == "typeof";
  16893. });
  16894. def(AST_Binary, function(compressor){
  16895. return this.operator == "+" &&
  16896. (this.left.is_string(compressor) || this.right.is_string(compressor));
  16897. });
  16898. def(AST_Assign, function(compressor){
  16899. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  16900. });
  16901. def(AST_Seq, function(compressor){
  16902. return this.cdr.is_string(compressor);
  16903. });
  16904. def(AST_Conditional, function(compressor){
  16905. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  16906. });
  16907. def(AST_Call, function(compressor){
  16908. return compressor.option("unsafe")
  16909. && this.expression instanceof AST_SymbolRef
  16910. && this.expression.name == "String"
  16911. && this.expression.undeclared();
  16912. });
  16913. })(function(node, func){
  16914. node.DEFMETHOD("is_string", func);
  16915. });
  16916. function best_of(ast1, ast2) {
  16917. return ast1.print_to_string().length >
  16918. ast2.print_to_string().length
  16919. ? ast2 : ast1;
  16920. };
  16921. // methods to evaluate a constant expression
  16922. (function (def){
  16923. // The evaluate method returns an array with one or two
  16924. // elements. If the node has been successfully reduced to a
  16925. // constant, then the second element tells us the value;
  16926. // otherwise the second element is missing. The first element
  16927. // of the array is always an AST_Node descendant; if
  16928. // evaluation was successful it's a node that represents the
  16929. // constant; otherwise it's the original or a replacement node.
  16930. AST_Node.DEFMETHOD("evaluate", function(compressor){
  16931. if (!compressor.option("evaluate")) return [ this ];
  16932. try {
  16933. var val = this._eval(compressor);
  16934. return [ best_of(make_node_from_constant(compressor, val, this), this), val ];
  16935. } catch(ex) {
  16936. if (ex !== def) throw ex;
  16937. return [ this ];
  16938. }
  16939. });
  16940. AST_Node.DEFMETHOD("is_constant", function(compressor){
  16941. // Accomodate when compress option evaluate=false
  16942. // as well as the common constant expressions !0 and !1
  16943. return this instanceof AST_Constant
  16944. || (this instanceof AST_UnaryPrefix && this.operator == "!"
  16945. && this.expression instanceof AST_Constant)
  16946. || this.evaluate(compressor).length > 1;
  16947. });
  16948. // Obtain the constant value of an expression already known to be constant.
  16949. // Result only valid iff this.is_constant(compressor) is true.
  16950. AST_Node.DEFMETHOD("constant_value", function(compressor){
  16951. // Accomodate when option evaluate=false.
  16952. if (this instanceof AST_Constant) return this.value;
  16953. // Accomodate the common constant expressions !0 and !1 when option evaluate=false.
  16954. if (this instanceof AST_UnaryPrefix
  16955. && this.operator == "!"
  16956. && this.expression instanceof AST_Constant) {
  16957. return !this.expression.value;
  16958. }
  16959. var result = this.evaluate(compressor)
  16960. if (result.length > 1) {
  16961. return result[1];
  16962. }
  16963. // should never be reached
  16964. return undefined;
  16965. });
  16966. def(AST_Statement, function(){
  16967. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  16968. });
  16969. def(AST_Function, function(){
  16970. // XXX: AST_Function inherits from AST_Scope, which itself
  16971. // inherits from AST_Statement; however, an AST_Function
  16972. // isn't really a statement. This could byte in other
  16973. // places too. :-( Wish JS had multiple inheritance.
  16974. throw def;
  16975. });
  16976. function ev(node, compressor) {
  16977. if (!compressor) throw new Error("Compressor must be passed");
  16978. return node._eval(compressor);
  16979. };
  16980. def(AST_Node, function(){
  16981. throw def; // not constant
  16982. });
  16983. def(AST_Constant, function(){
  16984. return this.getValue();
  16985. });
  16986. def(AST_UnaryPrefix, function(compressor){
  16987. var e = this.expression;
  16988. switch (this.operator) {
  16989. case "!": return !ev(e, compressor);
  16990. case "typeof":
  16991. // Function would be evaluated to an array and so typeof would
  16992. // incorrectly return 'object'. Hence making is a special case.
  16993. if (e instanceof AST_Function) return typeof function(){};
  16994. e = ev(e, compressor);
  16995. // typeof <RegExp> returns "object" or "function" on different platforms
  16996. // so cannot evaluate reliably
  16997. if (e instanceof RegExp) throw def;
  16998. return typeof e;
  16999. case "void": return void ev(e, compressor);
  17000. case "~": return ~ev(e, compressor);
  17001. case "-": return -ev(e, compressor);
  17002. case "+": return +ev(e, compressor);
  17003. }
  17004. throw def;
  17005. });
  17006. def(AST_Binary, function(c){
  17007. var left = this.left, right = this.right, result;
  17008. switch (this.operator) {
  17009. case "&&" : result = ev(left, c) && ev(right, c); break;
  17010. case "||" : result = ev(left, c) || ev(right, c); break;
  17011. case "|" : result = ev(left, c) | ev(right, c); break;
  17012. case "&" : result = ev(left, c) & ev(right, c); break;
  17013. case "^" : result = ev(left, c) ^ ev(right, c); break;
  17014. case "+" : result = ev(left, c) + ev(right, c); break;
  17015. case "*" : result = ev(left, c) * ev(right, c); break;
  17016. case "/" : result = ev(left, c) / ev(right, c); break;
  17017. case "%" : result = ev(left, c) % ev(right, c); break;
  17018. case "-" : result = ev(left, c) - ev(right, c); break;
  17019. case "<<" : result = ev(left, c) << ev(right, c); break;
  17020. case ">>" : result = ev(left, c) >> ev(right, c); break;
  17021. case ">>>" : result = ev(left, c) >>> ev(right, c); break;
  17022. case "==" : result = ev(left, c) == ev(right, c); break;
  17023. case "===" : result = ev(left, c) === ev(right, c); break;
  17024. case "!=" : result = ev(left, c) != ev(right, c); break;
  17025. case "!==" : result = ev(left, c) !== ev(right, c); break;
  17026. case "<" : result = ev(left, c) < ev(right, c); break;
  17027. case "<=" : result = ev(left, c) <= ev(right, c); break;
  17028. case ">" : result = ev(left, c) > ev(right, c); break;
  17029. case ">=" : result = ev(left, c) >= ev(right, c); break;
  17030. default:
  17031. throw def;
  17032. }
  17033. if (isNaN(result) && c.find_parent(AST_With)) {
  17034. // leave original expression as is
  17035. throw def;
  17036. }
  17037. return result;
  17038. });
  17039. def(AST_Conditional, function(compressor){
  17040. return ev(this.condition, compressor)
  17041. ? ev(this.consequent, compressor)
  17042. : ev(this.alternative, compressor);
  17043. });
  17044. def(AST_SymbolRef, function(compressor){
  17045. if (this._evaluating) throw def;
  17046. this._evaluating = true;
  17047. try {
  17048. var d = this.definition();
  17049. if (d && d.constant && d.init) {
  17050. return ev(d.init, compressor);
  17051. }
  17052. } finally {
  17053. this._evaluating = false;
  17054. }
  17055. throw def;
  17056. });
  17057. def(AST_Dot, function(compressor){
  17058. if (compressor.option("unsafe") && this.property == "length") {
  17059. var str = ev(this.expression, compressor);
  17060. if (typeof str == "string")
  17061. return str.length;
  17062. }
  17063. throw def;
  17064. });
  17065. })(function(node, func){
  17066. node.DEFMETHOD("_eval", func);
  17067. });
  17068. // method to negate an expression
  17069. (function(def){
  17070. function basic_negation(exp) {
  17071. return make_node(AST_UnaryPrefix, exp, {
  17072. operator: "!",
  17073. expression: exp
  17074. });
  17075. };
  17076. def(AST_Node, function(){
  17077. return basic_negation(this);
  17078. });
  17079. def(AST_Statement, function(){
  17080. throw new Error("Cannot negate a statement");
  17081. });
  17082. def(AST_Function, function(){
  17083. return basic_negation(this);
  17084. });
  17085. def(AST_UnaryPrefix, function(){
  17086. if (this.operator == "!")
  17087. return this.expression;
  17088. return basic_negation(this);
  17089. });
  17090. def(AST_Seq, function(compressor){
  17091. var self = this.clone();
  17092. self.cdr = self.cdr.negate(compressor);
  17093. return self;
  17094. });
  17095. def(AST_Conditional, function(compressor){
  17096. var self = this.clone();
  17097. self.consequent = self.consequent.negate(compressor);
  17098. self.alternative = self.alternative.negate(compressor);
  17099. return best_of(basic_negation(this), self);
  17100. });
  17101. def(AST_Binary, function(compressor){
  17102. var self = this.clone(), op = this.operator;
  17103. if (compressor.option("unsafe_comps")) {
  17104. switch (op) {
  17105. case "<=" : self.operator = ">" ; return self;
  17106. case "<" : self.operator = ">=" ; return self;
  17107. case ">=" : self.operator = "<" ; return self;
  17108. case ">" : self.operator = "<=" ; return self;
  17109. }
  17110. }
  17111. switch (op) {
  17112. case "==" : self.operator = "!="; return self;
  17113. case "!=" : self.operator = "=="; return self;
  17114. case "===": self.operator = "!=="; return self;
  17115. case "!==": self.operator = "==="; return self;
  17116. case "&&":
  17117. self.operator = "||";
  17118. self.left = self.left.negate(compressor);
  17119. self.right = self.right.negate(compressor);
  17120. return best_of(basic_negation(this), self);
  17121. case "||":
  17122. self.operator = "&&";
  17123. self.left = self.left.negate(compressor);
  17124. self.right = self.right.negate(compressor);
  17125. return best_of(basic_negation(this), self);
  17126. }
  17127. return basic_negation(this);
  17128. });
  17129. })(function(node, func){
  17130. node.DEFMETHOD("negate", function(compressor){
  17131. return func.call(this, compressor);
  17132. });
  17133. });
  17134. // determine if expression has side effects
  17135. (function(def){
  17136. def(AST_Node, function(compressor){ return true });
  17137. def(AST_EmptyStatement, function(compressor){ return false });
  17138. def(AST_Constant, function(compressor){ return false });
  17139. def(AST_This, function(compressor){ return false });
  17140. def(AST_Call, function(compressor){
  17141. var pure = compressor.option("pure_funcs");
  17142. if (!pure) return true;
  17143. if (typeof pure == "function") return pure(this);
  17144. return pure.indexOf(this.expression.print_to_string()) < 0;
  17145. });
  17146. def(AST_Block, function(compressor){
  17147. for (var i = this.body.length; --i >= 0;) {
  17148. if (this.body[i].has_side_effects(compressor))
  17149. return true;
  17150. }
  17151. return false;
  17152. });
  17153. def(AST_SimpleStatement, function(compressor){
  17154. return this.body.has_side_effects(compressor);
  17155. });
  17156. def(AST_Defun, function(compressor){ return true });
  17157. def(AST_Function, function(compressor){ return false });
  17158. def(AST_Binary, function(compressor){
  17159. return this.left.has_side_effects(compressor)
  17160. || this.right.has_side_effects(compressor);
  17161. });
  17162. def(AST_Assign, function(compressor){ return true });
  17163. def(AST_Conditional, function(compressor){
  17164. return this.condition.has_side_effects(compressor)
  17165. || this.consequent.has_side_effects(compressor)
  17166. || this.alternative.has_side_effects(compressor);
  17167. });
  17168. def(AST_Unary, function(compressor){
  17169. return this.operator == "delete"
  17170. || this.operator == "++"
  17171. || this.operator == "--"
  17172. || this.expression.has_side_effects(compressor);
  17173. });
  17174. def(AST_SymbolRef, function(compressor){
  17175. return this.global() && this.undeclared();
  17176. });
  17177. def(AST_Object, function(compressor){
  17178. for (var i = this.properties.length; --i >= 0;)
  17179. if (this.properties[i].has_side_effects(compressor))
  17180. return true;
  17181. return false;
  17182. });
  17183. def(AST_ObjectProperty, function(compressor){
  17184. return this.value.has_side_effects(compressor);
  17185. });
  17186. def(AST_Array, function(compressor){
  17187. for (var i = this.elements.length; --i >= 0;)
  17188. if (this.elements[i].has_side_effects(compressor))
  17189. return true;
  17190. return false;
  17191. });
  17192. def(AST_Dot, function(compressor){
  17193. if (!compressor.option("pure_getters")) return true;
  17194. return this.expression.has_side_effects(compressor);
  17195. });
  17196. def(AST_Sub, function(compressor){
  17197. if (!compressor.option("pure_getters")) return true;
  17198. return this.expression.has_side_effects(compressor)
  17199. || this.property.has_side_effects(compressor);
  17200. });
  17201. def(AST_PropAccess, function(compressor){
  17202. return !compressor.option("pure_getters");
  17203. });
  17204. def(AST_Seq, function(compressor){
  17205. return this.car.has_side_effects(compressor)
  17206. || this.cdr.has_side_effects(compressor);
  17207. });
  17208. })(function(node, func){
  17209. node.DEFMETHOD("has_side_effects", func);
  17210. });
  17211. // tell me if a statement aborts
  17212. function aborts(thing) {
  17213. return thing && thing.aborts();
  17214. };
  17215. (function(def){
  17216. def(AST_Statement, function(){ return null });
  17217. def(AST_Jump, function(){ return this });
  17218. function block_aborts(){
  17219. var n = this.body.length;
  17220. return n > 0 && aborts(this.body[n - 1]);
  17221. };
  17222. def(AST_BlockStatement, block_aborts);
  17223. def(AST_SwitchBranch, block_aborts);
  17224. def(AST_If, function(){
  17225. return this.alternative && aborts(this.body) && aborts(this.alternative) && this;
  17226. });
  17227. })(function(node, func){
  17228. node.DEFMETHOD("aborts", func);
  17229. });
  17230. /* -----[ optimizers ]----- */
  17231. OPT(AST_Directive, function(self, compressor){
  17232. if (compressor.has_directive(self.value) === "up") {
  17233. return make_node(AST_EmptyStatement, self);
  17234. }
  17235. return self;
  17236. });
  17237. OPT(AST_Debugger, function(self, compressor){
  17238. if (compressor.option("drop_debugger"))
  17239. return make_node(AST_EmptyStatement, self);
  17240. return self;
  17241. });
  17242. OPT(AST_LabeledStatement, function(self, compressor){
  17243. if (self.body instanceof AST_Break
  17244. && compressor.loopcontrol_target(self.body.label) === self.body) {
  17245. return make_node(AST_EmptyStatement, self);
  17246. }
  17247. return self.label.references.length == 0 ? self.body : self;
  17248. });
  17249. OPT(AST_Block, function(self, compressor){
  17250. self.body = tighten_body(self.body, compressor);
  17251. return self;
  17252. });
  17253. OPT(AST_BlockStatement, function(self, compressor){
  17254. self.body = tighten_body(self.body, compressor);
  17255. switch (self.body.length) {
  17256. case 1: return self.body[0];
  17257. case 0: return make_node(AST_EmptyStatement, self);
  17258. }
  17259. return self;
  17260. });
  17261. AST_Scope.DEFMETHOD("drop_unused", function(compressor){
  17262. var self = this;
  17263. if (compressor.has_directive("use asm")) return self;
  17264. if (compressor.option("unused")
  17265. && !(self instanceof AST_Toplevel)
  17266. && !self.uses_eval
  17267. && !self.uses_with
  17268. ) {
  17269. var in_use = [];
  17270. var in_use_ids = {}; // avoid expensive linear scans of in_use
  17271. var initializations = new Dictionary();
  17272. // pass 1: find out which symbols are directly used in
  17273. // this scope (not in nested scopes).
  17274. var scope = this;
  17275. var tw = new TreeWalker(function(node, descend){
  17276. if (node !== self) {
  17277. if (node instanceof AST_Defun) {
  17278. initializations.add(node.name.name, node);
  17279. return true; // don't go in nested scopes
  17280. }
  17281. if (node instanceof AST_Definitions && scope === self) {
  17282. node.definitions.forEach(function(def){
  17283. if (def.value) {
  17284. initializations.add(def.name.name, def.value);
  17285. if (def.value.has_side_effects(compressor)) {
  17286. def.value.walk(tw);
  17287. }
  17288. }
  17289. });
  17290. return true;
  17291. }
  17292. if (node instanceof AST_SymbolRef) {
  17293. var node_def = node.definition();
  17294. if (!(node_def.id in in_use_ids)) {
  17295. in_use_ids[node_def.id] = true;
  17296. in_use.push(node_def);
  17297. }
  17298. return true;
  17299. }
  17300. if (node instanceof AST_Scope) {
  17301. var save_scope = scope;
  17302. scope = node;
  17303. descend();
  17304. scope = save_scope;
  17305. return true;
  17306. }
  17307. }
  17308. });
  17309. self.walk(tw);
  17310. // pass 2: for every used symbol we need to walk its
  17311. // initialization code to figure out if it uses other
  17312. // symbols (that may not be in_use).
  17313. for (var i = 0; i < in_use.length; ++i) {
  17314. in_use[i].orig.forEach(function(decl){
  17315. // undeclared globals will be instanceof AST_SymbolRef
  17316. var init = initializations.get(decl.name);
  17317. if (init) init.forEach(function(init){
  17318. var tw = new TreeWalker(function(node){
  17319. if (node instanceof AST_SymbolRef) {
  17320. var node_def = node.definition();
  17321. if (!(node_def.id in in_use_ids)) {
  17322. in_use_ids[node_def.id] = true;
  17323. in_use.push(node_def);
  17324. }
  17325. }
  17326. });
  17327. init.walk(tw);
  17328. });
  17329. });
  17330. }
  17331. // pass 3: we should drop declarations not in_use
  17332. var tt = new TreeTransformer(
  17333. function before(node, descend, in_list) {
  17334. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  17335. if (!compressor.option("keep_fargs")) {
  17336. for (var a = node.argnames, i = a.length; --i >= 0;) {
  17337. var sym = a[i];
  17338. if (sym.unreferenced()) {
  17339. a.pop();
  17340. compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", {
  17341. name : sym.name,
  17342. file : sym.start.file,
  17343. line : sym.start.line,
  17344. col : sym.start.col
  17345. });
  17346. }
  17347. else break;
  17348. }
  17349. }
  17350. }
  17351. if (node instanceof AST_Defun && node !== self) {
  17352. if (!(node.name.definition().id in in_use_ids)) {
  17353. compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", {
  17354. name : node.name.name,
  17355. file : node.name.start.file,
  17356. line : node.name.start.line,
  17357. col : node.name.start.col
  17358. });
  17359. return make_node(AST_EmptyStatement, node);
  17360. }
  17361. return node;
  17362. }
  17363. if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) {
  17364. var def = node.definitions.filter(function(def){
  17365. if (def.name.definition().id in in_use_ids) return true;
  17366. var w = {
  17367. name : def.name.name,
  17368. file : def.name.start.file,
  17369. line : def.name.start.line,
  17370. col : def.name.start.col
  17371. };
  17372. if (def.value && def.value.has_side_effects(compressor)) {
  17373. def._unused_side_effects = true;
  17374. compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w);
  17375. return true;
  17376. }
  17377. compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w);
  17378. return false;
  17379. });
  17380. // place uninitialized names at the start
  17381. def = mergeSort(def, function(a, b){
  17382. if (!a.value && b.value) return -1;
  17383. if (!b.value && a.value) return 1;
  17384. return 0;
  17385. });
  17386. // for unused names whose initialization has
  17387. // side effects, we can cascade the init. code
  17388. // into the next one, or next statement.
  17389. var side_effects = [];
  17390. for (var i = 0; i < def.length;) {
  17391. var x = def[i];
  17392. if (x._unused_side_effects) {
  17393. side_effects.push(x.value);
  17394. def.splice(i, 1);
  17395. } else {
  17396. if (side_effects.length > 0) {
  17397. side_effects.push(x.value);
  17398. x.value = AST_Seq.from_array(side_effects);
  17399. side_effects = [];
  17400. }
  17401. ++i;
  17402. }
  17403. }
  17404. if (side_effects.length > 0) {
  17405. side_effects = make_node(AST_BlockStatement, node, {
  17406. body: [ make_node(AST_SimpleStatement, node, {
  17407. body: AST_Seq.from_array(side_effects)
  17408. }) ]
  17409. });
  17410. } else {
  17411. side_effects = null;
  17412. }
  17413. if (def.length == 0 && !side_effects) {
  17414. return make_node(AST_EmptyStatement, node);
  17415. }
  17416. if (def.length == 0) {
  17417. return in_list ? MAP.splice(side_effects.body) : side_effects;
  17418. }
  17419. node.definitions = def;
  17420. if (side_effects) {
  17421. side_effects.body.unshift(node);
  17422. return in_list ? MAP.splice(side_effects.body) : side_effects;
  17423. }
  17424. return node;
  17425. }
  17426. if (node instanceof AST_For) {
  17427. descend(node, this);
  17428. if (node.init instanceof AST_BlockStatement) {
  17429. // certain combination of unused name + side effect leads to:
  17430. // https://github.com/mishoo/UglifyJS2/issues/44
  17431. // that's an invalid AST.
  17432. // We fix it at this stage by moving the `var` outside the `for`.
  17433. var body = node.init.body.slice(0, -1);
  17434. node.init = node.init.body.slice(-1)[0].body;
  17435. body.push(node);
  17436. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  17437. body: body
  17438. });
  17439. }
  17440. }
  17441. if (node instanceof AST_Scope && node !== self)
  17442. return node;
  17443. }
  17444. );
  17445. self.transform(tt);
  17446. }
  17447. });
  17448. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){
  17449. var self = this;
  17450. if (compressor.has_directive("use asm")) return self;
  17451. var hoist_funs = compressor.option("hoist_funs");
  17452. var hoist_vars = compressor.option("hoist_vars");
  17453. if (hoist_funs || hoist_vars) {
  17454. var dirs = [];
  17455. var hoisted = [];
  17456. var vars = new Dictionary(), vars_found = 0, var_decl = 0;
  17457. // let's count var_decl first, we seem to waste a lot of
  17458. // space if we hoist `var` when there's only one.
  17459. self.walk(new TreeWalker(function(node){
  17460. if (node instanceof AST_Scope && node !== self)
  17461. return true;
  17462. if (node instanceof AST_Var) {
  17463. ++var_decl;
  17464. return true;
  17465. }
  17466. }));
  17467. hoist_vars = hoist_vars && var_decl > 1;
  17468. var tt = new TreeTransformer(
  17469. function before(node) {
  17470. if (node !== self) {
  17471. if (node instanceof AST_Directive) {
  17472. dirs.push(node);
  17473. return make_node(AST_EmptyStatement, node);
  17474. }
  17475. if (node instanceof AST_Defun && hoist_funs) {
  17476. hoisted.push(node);
  17477. return make_node(AST_EmptyStatement, node);
  17478. }
  17479. if (node instanceof AST_Var && hoist_vars) {
  17480. node.definitions.forEach(function(def){
  17481. vars.set(def.name.name, def);
  17482. ++vars_found;
  17483. });
  17484. var seq = node.to_assignments();
  17485. var p = tt.parent();
  17486. if (p instanceof AST_ForIn && p.init === node) {
  17487. if (seq == null) {
  17488. var def = node.definitions[0].name;
  17489. return make_node(AST_SymbolRef, def, def);
  17490. }
  17491. return seq;
  17492. }
  17493. if (p instanceof AST_For && p.init === node) {
  17494. return seq;
  17495. }
  17496. if (!seq) return make_node(AST_EmptyStatement, node);
  17497. return make_node(AST_SimpleStatement, node, {
  17498. body: seq
  17499. });
  17500. }
  17501. if (node instanceof AST_Scope)
  17502. return node; // to avoid descending in nested scopes
  17503. }
  17504. }
  17505. );
  17506. self = self.transform(tt);
  17507. if (vars_found > 0) {
  17508. // collect only vars which don't show up in self's arguments list
  17509. var defs = [];
  17510. vars.each(function(def, name){
  17511. if (self instanceof AST_Lambda
  17512. && find_if(function(x){ return x.name == def.name.name },
  17513. self.argnames)) {
  17514. vars.del(name);
  17515. } else {
  17516. def = def.clone();
  17517. def.value = null;
  17518. defs.push(def);
  17519. vars.set(name, def);
  17520. }
  17521. });
  17522. if (defs.length > 0) {
  17523. // try to merge in assignments
  17524. for (var i = 0; i < self.body.length;) {
  17525. if (self.body[i] instanceof AST_SimpleStatement) {
  17526. var expr = self.body[i].body, sym, assign;
  17527. if (expr instanceof AST_Assign
  17528. && expr.operator == "="
  17529. && (sym = expr.left) instanceof AST_Symbol
  17530. && vars.has(sym.name))
  17531. {
  17532. var def = vars.get(sym.name);
  17533. if (def.value) break;
  17534. def.value = expr.right;
  17535. remove(defs, def);
  17536. defs.push(def);
  17537. self.body.splice(i, 1);
  17538. continue;
  17539. }
  17540. if (expr instanceof AST_Seq
  17541. && (assign = expr.car) instanceof AST_Assign
  17542. && assign.operator == "="
  17543. && (sym = assign.left) instanceof AST_Symbol
  17544. && vars.has(sym.name))
  17545. {
  17546. var def = vars.get(sym.name);
  17547. if (def.value) break;
  17548. def.value = assign.right;
  17549. remove(defs, def);
  17550. defs.push(def);
  17551. self.body[i].body = expr.cdr;
  17552. continue;
  17553. }
  17554. }
  17555. if (self.body[i] instanceof AST_EmptyStatement) {
  17556. self.body.splice(i, 1);
  17557. continue;
  17558. }
  17559. if (self.body[i] instanceof AST_BlockStatement) {
  17560. var tmp = [ i, 1 ].concat(self.body[i].body);
  17561. self.body.splice.apply(self.body, tmp);
  17562. continue;
  17563. }
  17564. break;
  17565. }
  17566. defs = make_node(AST_Var, self, {
  17567. definitions: defs
  17568. });
  17569. hoisted.push(defs);
  17570. };
  17571. }
  17572. self.body = dirs.concat(hoisted, self.body);
  17573. }
  17574. return self;
  17575. });
  17576. OPT(AST_SimpleStatement, function(self, compressor){
  17577. if (compressor.option("side_effects")) {
  17578. if (!self.body.has_side_effects(compressor)) {
  17579. compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
  17580. return make_node(AST_EmptyStatement, self);
  17581. }
  17582. }
  17583. return self;
  17584. });
  17585. OPT(AST_DWLoop, function(self, compressor){
  17586. var cond = self.condition.evaluate(compressor);
  17587. self.condition = cond[0];
  17588. if (!compressor.option("loops")) return self;
  17589. if (cond.length > 1) {
  17590. if (cond[1]) {
  17591. return make_node(AST_For, self, {
  17592. body: self.body
  17593. });
  17594. } else if (self instanceof AST_While) {
  17595. if (compressor.option("dead_code")) {
  17596. var a = [];
  17597. extract_declarations_from_unreachable_code(compressor, self.body, a);
  17598. return make_node(AST_BlockStatement, self, { body: a });
  17599. }
  17600. }
  17601. }
  17602. return self;
  17603. });
  17604. function if_break_in_loop(self, compressor) {
  17605. function drop_it(rest) {
  17606. rest = as_statement_array(rest);
  17607. if (self.body instanceof AST_BlockStatement) {
  17608. self.body = self.body.clone();
  17609. self.body.body = rest.concat(self.body.body.slice(1));
  17610. self.body = self.body.transform(compressor);
  17611. } else {
  17612. self.body = make_node(AST_BlockStatement, self.body, {
  17613. body: rest
  17614. }).transform(compressor);
  17615. }
  17616. if_break_in_loop(self, compressor);
  17617. }
  17618. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  17619. if (first instanceof AST_If) {
  17620. if (first.body instanceof AST_Break
  17621. && compressor.loopcontrol_target(first.body.label) === self) {
  17622. if (self.condition) {
  17623. self.condition = make_node(AST_Binary, self.condition, {
  17624. left: self.condition,
  17625. operator: "&&",
  17626. right: first.condition.negate(compressor),
  17627. });
  17628. } else {
  17629. self.condition = first.condition.negate(compressor);
  17630. }
  17631. drop_it(first.alternative);
  17632. }
  17633. else if (first.alternative instanceof AST_Break
  17634. && compressor.loopcontrol_target(first.alternative.label) === self) {
  17635. if (self.condition) {
  17636. self.condition = make_node(AST_Binary, self.condition, {
  17637. left: self.condition,
  17638. operator: "&&",
  17639. right: first.condition,
  17640. });
  17641. } else {
  17642. self.condition = first.condition;
  17643. }
  17644. drop_it(first.body);
  17645. }
  17646. }
  17647. };
  17648. OPT(AST_While, function(self, compressor) {
  17649. if (!compressor.option("loops")) return self;
  17650. self = AST_DWLoop.prototype.optimize.call(self, compressor);
  17651. if (self instanceof AST_While) {
  17652. if_break_in_loop(self, compressor);
  17653. self = make_node(AST_For, self, self).transform(compressor);
  17654. }
  17655. return self;
  17656. });
  17657. OPT(AST_For, function(self, compressor){
  17658. var cond = self.condition;
  17659. if (cond) {
  17660. cond = cond.evaluate(compressor);
  17661. self.condition = cond[0];
  17662. }
  17663. if (!compressor.option("loops")) return self;
  17664. if (cond) {
  17665. if (cond.length > 1 && !cond[1]) {
  17666. if (compressor.option("dead_code")) {
  17667. var a = [];
  17668. if (self.init instanceof AST_Statement) {
  17669. a.push(self.init);
  17670. }
  17671. else if (self.init) {
  17672. a.push(make_node(AST_SimpleStatement, self.init, {
  17673. body: self.init
  17674. }));
  17675. }
  17676. extract_declarations_from_unreachable_code(compressor, self.body, a);
  17677. return make_node(AST_BlockStatement, self, { body: a });
  17678. }
  17679. }
  17680. }
  17681. if_break_in_loop(self, compressor);
  17682. return self;
  17683. });
  17684. OPT(AST_If, function(self, compressor){
  17685. if (!compressor.option("conditionals")) return self;
  17686. // if condition can be statically determined, warn and drop
  17687. // one of the blocks. note, statically determined implies
  17688. // “has no side effects”; also it doesn't work for cases like
  17689. // `x && true`, though it probably should.
  17690. var cond = self.condition.evaluate(compressor);
  17691. self.condition = cond[0];
  17692. if (cond.length > 1) {
  17693. if (cond[1]) {
  17694. compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
  17695. if (compressor.option("dead_code")) {
  17696. var a = [];
  17697. if (self.alternative) {
  17698. extract_declarations_from_unreachable_code(compressor, self.alternative, a);
  17699. }
  17700. a.push(self.body);
  17701. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  17702. }
  17703. } else {
  17704. compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
  17705. if (compressor.option("dead_code")) {
  17706. var a = [];
  17707. extract_declarations_from_unreachable_code(compressor, self.body, a);
  17708. if (self.alternative) a.push(self.alternative);
  17709. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  17710. }
  17711. }
  17712. }
  17713. if (is_empty(self.alternative)) self.alternative = null;
  17714. var negated = self.condition.negate(compressor);
  17715. var self_condition_length = self.condition.print_to_string().length;
  17716. var negated_length = negated.print_to_string().length;
  17717. var negated_is_best = negated_length < self_condition_length;
  17718. if (self.alternative && negated_is_best) {
  17719. negated_is_best = false; // because we already do the switch here.
  17720. // no need to swap values of self_condition_length and negated_length
  17721. // here because they are only used in an equality comparison later on.
  17722. self.condition = negated;
  17723. var tmp = self.body;
  17724. self.body = self.alternative || make_node(AST_EmptyStatement);
  17725. self.alternative = tmp;
  17726. }
  17727. if (is_empty(self.body) && is_empty(self.alternative)) {
  17728. return make_node(AST_SimpleStatement, self.condition, {
  17729. body: self.condition
  17730. }).transform(compressor);
  17731. }
  17732. if (self.body instanceof AST_SimpleStatement
  17733. && self.alternative instanceof AST_SimpleStatement) {
  17734. return make_node(AST_SimpleStatement, self, {
  17735. body: make_node(AST_Conditional, self, {
  17736. condition : self.condition,
  17737. consequent : self.body.body,
  17738. alternative : self.alternative.body
  17739. })
  17740. }).transform(compressor);
  17741. }
  17742. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  17743. if (self_condition_length === negated_length && !negated_is_best
  17744. && self.condition instanceof AST_Binary && self.condition.operator == "||") {
  17745. // although the code length of self.condition and negated are the same,
  17746. // negated does not require additional surrounding parentheses.
  17747. // see https://github.com/mishoo/UglifyJS2/issues/979
  17748. negated_is_best = true;
  17749. }
  17750. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  17751. body: make_node(AST_Binary, self, {
  17752. operator : "||",
  17753. left : negated,
  17754. right : self.body.body
  17755. })
  17756. }).transform(compressor);
  17757. return make_node(AST_SimpleStatement, self, {
  17758. body: make_node(AST_Binary, self, {
  17759. operator : "&&",
  17760. left : self.condition,
  17761. right : self.body.body
  17762. })
  17763. }).transform(compressor);
  17764. }
  17765. if (self.body instanceof AST_EmptyStatement
  17766. && self.alternative
  17767. && self.alternative instanceof AST_SimpleStatement) {
  17768. return make_node(AST_SimpleStatement, self, {
  17769. body: make_node(AST_Binary, self, {
  17770. operator : "||",
  17771. left : self.condition,
  17772. right : self.alternative.body
  17773. })
  17774. }).transform(compressor);
  17775. }
  17776. if (self.body instanceof AST_Exit
  17777. && self.alternative instanceof AST_Exit
  17778. && self.body.TYPE == self.alternative.TYPE) {
  17779. return make_node(self.body.CTOR, self, {
  17780. value: make_node(AST_Conditional, self, {
  17781. condition : self.condition,
  17782. consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor),
  17783. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor)
  17784. })
  17785. }).transform(compressor);
  17786. }
  17787. if (self.body instanceof AST_If
  17788. && !self.body.alternative
  17789. && !self.alternative) {
  17790. self.condition = make_node(AST_Binary, self.condition, {
  17791. operator: "&&",
  17792. left: self.condition,
  17793. right: self.body.condition
  17794. }).transform(compressor);
  17795. self.body = self.body.body;
  17796. }
  17797. if (aborts(self.body)) {
  17798. if (self.alternative) {
  17799. var alt = self.alternative;
  17800. self.alternative = null;
  17801. return make_node(AST_BlockStatement, self, {
  17802. body: [ self, alt ]
  17803. }).transform(compressor);
  17804. }
  17805. }
  17806. if (aborts(self.alternative)) {
  17807. var body = self.body;
  17808. self.body = self.alternative;
  17809. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  17810. self.alternative = null;
  17811. return make_node(AST_BlockStatement, self, {
  17812. body: [ self, body ]
  17813. }).transform(compressor);
  17814. }
  17815. return self;
  17816. });
  17817. OPT(AST_Switch, function(self, compressor){
  17818. if (self.body.length == 0 && compressor.option("conditionals")) {
  17819. return make_node(AST_SimpleStatement, self, {
  17820. body: self.expression
  17821. }).transform(compressor);
  17822. }
  17823. for(;;) {
  17824. var last_branch = self.body[self.body.length - 1];
  17825. if (last_branch) {
  17826. var stat = last_branch.body[last_branch.body.length - 1]; // last statement
  17827. if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self)
  17828. last_branch.body.pop();
  17829. if (last_branch instanceof AST_Default && last_branch.body.length == 0) {
  17830. self.body.pop();
  17831. continue;
  17832. }
  17833. }
  17834. break;
  17835. }
  17836. var exp = self.expression.evaluate(compressor);
  17837. out: if (exp.length == 2) try {
  17838. // constant expression
  17839. self.expression = exp[0];
  17840. if (!compressor.option("dead_code")) break out;
  17841. var value = exp[1];
  17842. var in_if = false;
  17843. var in_block = false;
  17844. var started = false;
  17845. var stopped = false;
  17846. var ruined = false;
  17847. var tt = new TreeTransformer(function(node, descend, in_list){
  17848. if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) {
  17849. // no need to descend these node types
  17850. return node;
  17851. }
  17852. else if (node instanceof AST_Switch && node === self) {
  17853. node = node.clone();
  17854. descend(node, this);
  17855. return ruined ? node : make_node(AST_BlockStatement, node, {
  17856. body: node.body.reduce(function(a, branch){
  17857. return a.concat(branch.body);
  17858. }, [])
  17859. }).transform(compressor);
  17860. }
  17861. else if (node instanceof AST_If || node instanceof AST_Try) {
  17862. var save = in_if;
  17863. in_if = !in_block;
  17864. descend(node, this);
  17865. in_if = save;
  17866. return node;
  17867. }
  17868. else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) {
  17869. var save = in_block;
  17870. in_block = true;
  17871. descend(node, this);
  17872. in_block = save;
  17873. return node;
  17874. }
  17875. else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) {
  17876. if (in_if) {
  17877. ruined = true;
  17878. return node;
  17879. }
  17880. if (in_block) return node;
  17881. stopped = true;
  17882. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  17883. }
  17884. else if (node instanceof AST_SwitchBranch && this.parent() === self) {
  17885. if (stopped) return MAP.skip;
  17886. if (node instanceof AST_Case) {
  17887. var exp = node.expression.evaluate(compressor);
  17888. if (exp.length < 2) {
  17889. // got a case with non-constant expression, baling out
  17890. throw self;
  17891. }
  17892. if (exp[1] === value || started) {
  17893. started = true;
  17894. if (aborts(node)) stopped = true;
  17895. descend(node, this);
  17896. return node;
  17897. }
  17898. return MAP.skip;
  17899. }
  17900. descend(node, this);
  17901. return node;
  17902. }
  17903. });
  17904. tt.stack = compressor.stack.slice(); // so that's able to see parent nodes
  17905. self = self.transform(tt);
  17906. } catch(ex) {
  17907. if (ex !== self) throw ex;
  17908. }
  17909. return self;
  17910. });
  17911. OPT(AST_Case, function(self, compressor){
  17912. self.body = tighten_body(self.body, compressor);
  17913. return self;
  17914. });
  17915. OPT(AST_Try, function(self, compressor){
  17916. self.body = tighten_body(self.body, compressor);
  17917. return self;
  17918. });
  17919. AST_Definitions.DEFMETHOD("remove_initializers", function(){
  17920. this.definitions.forEach(function(def){ def.value = null });
  17921. });
  17922. AST_Definitions.DEFMETHOD("to_assignments", function(){
  17923. var assignments = this.definitions.reduce(function(a, def){
  17924. if (def.value) {
  17925. var name = make_node(AST_SymbolRef, def.name, def.name);
  17926. a.push(make_node(AST_Assign, def, {
  17927. operator : "=",
  17928. left : name,
  17929. right : def.value
  17930. }));
  17931. }
  17932. return a;
  17933. }, []);
  17934. if (assignments.length == 0) return null;
  17935. return AST_Seq.from_array(assignments);
  17936. });
  17937. OPT(AST_Definitions, function(self, compressor){
  17938. if (self.definitions.length == 0)
  17939. return make_node(AST_EmptyStatement, self);
  17940. return self;
  17941. });
  17942. OPT(AST_Function, function(self, compressor){
  17943. self = AST_Lambda.prototype.optimize.call(self, compressor);
  17944. if (compressor.option("unused") && !compressor.option("keep_fnames")) {
  17945. if (self.name && self.name.unreferenced()) {
  17946. self.name = null;
  17947. }
  17948. }
  17949. return self;
  17950. });
  17951. OPT(AST_Call, function(self, compressor){
  17952. if (compressor.option("unsafe")) {
  17953. var exp = self.expression;
  17954. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  17955. switch (exp.name) {
  17956. case "Array":
  17957. if (self.args.length != 1) {
  17958. return make_node(AST_Array, self, {
  17959. elements: self.args
  17960. }).transform(compressor);
  17961. }
  17962. break;
  17963. case "Object":
  17964. if (self.args.length == 0) {
  17965. return make_node(AST_Object, self, {
  17966. properties: []
  17967. });
  17968. }
  17969. break;
  17970. case "String":
  17971. if (self.args.length == 0) return make_node(AST_String, self, {
  17972. value: ""
  17973. });
  17974. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  17975. left: self.args[0],
  17976. operator: "+",
  17977. right: make_node(AST_String, self, { value: "" })
  17978. }).transform(compressor);
  17979. break;
  17980. case "Number":
  17981. if (self.args.length == 0) return make_node(AST_Number, self, {
  17982. value: 0
  17983. });
  17984. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  17985. expression: self.args[0],
  17986. operator: "+"
  17987. }).transform(compressor);
  17988. case "Boolean":
  17989. if (self.args.length == 0) return make_node(AST_False, self);
  17990. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  17991. expression: make_node(AST_UnaryPrefix, null, {
  17992. expression: self.args[0],
  17993. operator: "!"
  17994. }),
  17995. operator: "!"
  17996. }).transform(compressor);
  17997. break;
  17998. case "Function":
  17999. // new Function() => function(){}
  18000. if (self.args.length == 0) return make_node(AST_Function, self, {
  18001. argnames: [],
  18002. body: []
  18003. });
  18004. if (all(self.args, function(x){ return x instanceof AST_String })) {
  18005. // quite a corner-case, but we can handle it:
  18006. // https://github.com/mishoo/UglifyJS2/issues/203
  18007. // if the code argument is a constant, then we can minify it.
  18008. try {
  18009. var code = "(function(" + self.args.slice(0, -1).map(function(arg){
  18010. return arg.value;
  18011. }).join(",") + "){" + self.args[self.args.length - 1].value + "})()";
  18012. var ast = parse(code);
  18013. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  18014. var comp = new Compressor(compressor.options);
  18015. ast = ast.transform(comp);
  18016. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  18017. ast.mangle_names();
  18018. var fun;
  18019. try {
  18020. ast.walk(new TreeWalker(function(node){
  18021. if (node instanceof AST_Lambda) {
  18022. fun = node;
  18023. throw ast;
  18024. }
  18025. }));
  18026. } catch(ex) {
  18027. if (ex !== ast) throw ex;
  18028. };
  18029. if (!fun) return self;
  18030. var args = fun.argnames.map(function(arg, i){
  18031. return make_node(AST_String, self.args[i], {
  18032. value: arg.print_to_string()
  18033. });
  18034. });
  18035. var code = OutputStream();
  18036. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  18037. code = code.toString().replace(/^\{|\}$/g, "");
  18038. args.push(make_node(AST_String, self.args[self.args.length - 1], {
  18039. value: code
  18040. }));
  18041. self.args = args;
  18042. return self;
  18043. } catch(ex) {
  18044. if (ex instanceof JS_Parse_Error) {
  18045. compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start);
  18046. compressor.warn(ex.toString());
  18047. } else {
  18048. console.log(ex);
  18049. throw ex;
  18050. }
  18051. }
  18052. }
  18053. break;
  18054. }
  18055. }
  18056. else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) {
  18057. return make_node(AST_Binary, self, {
  18058. left: make_node(AST_String, self, { value: "" }),
  18059. operator: "+",
  18060. right: exp.expression
  18061. }).transform(compressor);
  18062. }
  18063. else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: {
  18064. var separator = self.args.length == 0 ? "," : self.args[0].evaluate(compressor)[1];
  18065. if (separator == null) break EXIT; // not a constant
  18066. var elements = exp.expression.elements.reduce(function(a, el){
  18067. el = el.evaluate(compressor);
  18068. if (a.length == 0 || el.length == 1) {
  18069. a.push(el);
  18070. } else {
  18071. var last = a[a.length - 1];
  18072. if (last.length == 2) {
  18073. // it's a constant
  18074. var val = "" + last[1] + separator + el[1];
  18075. a[a.length - 1] = [ make_node_from_constant(compressor, val, last[0]), val ];
  18076. } else {
  18077. a.push(el);
  18078. }
  18079. }
  18080. return a;
  18081. }, []);
  18082. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  18083. if (elements.length == 1) return elements[0][0];
  18084. if (separator == "") {
  18085. var first;
  18086. if (elements[0][0] instanceof AST_String
  18087. || elements[1][0] instanceof AST_String) {
  18088. first = elements.shift()[0];
  18089. } else {
  18090. first = make_node(AST_String, self, { value: "" });
  18091. }
  18092. return elements.reduce(function(prev, el){
  18093. return make_node(AST_Binary, el[0], {
  18094. operator : "+",
  18095. left : prev,
  18096. right : el[0],
  18097. });
  18098. }, first).transform(compressor);
  18099. }
  18100. // need this awkward cloning to not affect original element
  18101. // best_of will decide which one to get through.
  18102. var node = self.clone();
  18103. node.expression = node.expression.clone();
  18104. node.expression.expression = node.expression.expression.clone();
  18105. node.expression.expression.elements = elements.map(function(el){
  18106. return el[0];
  18107. });
  18108. return best_of(self, node);
  18109. }
  18110. }
  18111. if (compressor.option("side_effects")) {
  18112. if (self.expression instanceof AST_Function
  18113. && self.args.length == 0
  18114. && !AST_Block.prototype.has_side_effects.call(self.expression, compressor)) {
  18115. return make_node(AST_Undefined, self).transform(compressor);
  18116. }
  18117. }
  18118. if (compressor.option("drop_console")) {
  18119. if (self.expression instanceof AST_PropAccess) {
  18120. var name = self.expression.expression;
  18121. while (name.expression) {
  18122. name = name.expression;
  18123. }
  18124. if (name instanceof AST_SymbolRef
  18125. && name.name == "console"
  18126. && name.undeclared()) {
  18127. return make_node(AST_Undefined, self).transform(compressor);
  18128. }
  18129. }
  18130. }
  18131. return self.evaluate(compressor)[0];
  18132. });
  18133. OPT(AST_New, function(self, compressor){
  18134. if (compressor.option("unsafe")) {
  18135. var exp = self.expression;
  18136. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  18137. switch (exp.name) {
  18138. case "Object":
  18139. case "RegExp":
  18140. case "Function":
  18141. case "Error":
  18142. case "Array":
  18143. return make_node(AST_Call, self, self).transform(compressor);
  18144. }
  18145. }
  18146. }
  18147. return self;
  18148. });
  18149. OPT(AST_Seq, function(self, compressor){
  18150. if (!compressor.option("side_effects"))
  18151. return self;
  18152. if (!self.car.has_side_effects(compressor)) {
  18153. return maintain_this_binding(compressor.parent(), self, self.cdr);
  18154. }
  18155. if (compressor.option("cascade")) {
  18156. if (self.car instanceof AST_Assign
  18157. && !self.car.left.has_side_effects(compressor)) {
  18158. if (self.car.left.equivalent_to(self.cdr)) {
  18159. return self.car;
  18160. }
  18161. if (self.cdr instanceof AST_Call
  18162. && self.cdr.expression.equivalent_to(self.car.left)) {
  18163. self.cdr.expression = self.car;
  18164. return self.cdr;
  18165. }
  18166. }
  18167. if (!self.car.has_side_effects(compressor)
  18168. && !self.cdr.has_side_effects(compressor)
  18169. && self.car.equivalent_to(self.cdr)) {
  18170. return self.car;
  18171. }
  18172. }
  18173. if (self.cdr instanceof AST_UnaryPrefix
  18174. && self.cdr.operator == "void"
  18175. && !self.cdr.expression.has_side_effects(compressor)) {
  18176. self.cdr.expression = self.car;
  18177. return self.cdr;
  18178. }
  18179. if (self.cdr instanceof AST_Undefined) {
  18180. return make_node(AST_UnaryPrefix, self, {
  18181. operator : "void",
  18182. expression : self.car
  18183. });
  18184. }
  18185. return self;
  18186. });
  18187. AST_Unary.DEFMETHOD("lift_sequences", function(compressor){
  18188. if (compressor.option("sequences")) {
  18189. if (this.expression instanceof AST_Seq) {
  18190. var seq = this.expression;
  18191. var x = seq.to_array();
  18192. this.expression = x.pop();
  18193. x.push(this);
  18194. seq = AST_Seq.from_array(x).transform(compressor);
  18195. return seq;
  18196. }
  18197. }
  18198. return this;
  18199. });
  18200. OPT(AST_UnaryPostfix, function(self, compressor){
  18201. return self.lift_sequences(compressor);
  18202. });
  18203. OPT(AST_UnaryPrefix, function(self, compressor){
  18204. self = self.lift_sequences(compressor);
  18205. var e = self.expression;
  18206. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  18207. switch (self.operator) {
  18208. case "!":
  18209. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  18210. // !!foo ==> foo, if we're in boolean context
  18211. return e.expression;
  18212. }
  18213. break;
  18214. case "typeof":
  18215. // typeof always returns a non-empty string, thus it's
  18216. // always true in booleans
  18217. compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
  18218. return make_node(AST_True, self);
  18219. }
  18220. if (e instanceof AST_Binary && self.operator == "!") {
  18221. self = best_of(self, e.negate(compressor));
  18222. }
  18223. }
  18224. return self.evaluate(compressor)[0];
  18225. });
  18226. function has_side_effects_or_prop_access(node, compressor) {
  18227. var save_pure_getters = compressor.option("pure_getters");
  18228. compressor.options.pure_getters = false;
  18229. var ret = node.has_side_effects(compressor);
  18230. compressor.options.pure_getters = save_pure_getters;
  18231. return ret;
  18232. }
  18233. AST_Binary.DEFMETHOD("lift_sequences", function(compressor){
  18234. if (compressor.option("sequences")) {
  18235. if (this.left instanceof AST_Seq) {
  18236. var seq = this.left;
  18237. var x = seq.to_array();
  18238. this.left = x.pop();
  18239. x.push(this);
  18240. seq = AST_Seq.from_array(x).transform(compressor);
  18241. return seq;
  18242. }
  18243. if (this.right instanceof AST_Seq
  18244. && this instanceof AST_Assign
  18245. && !has_side_effects_or_prop_access(this.left, compressor)) {
  18246. var seq = this.right;
  18247. var x = seq.to_array();
  18248. this.right = x.pop();
  18249. x.push(this);
  18250. seq = AST_Seq.from_array(x).transform(compressor);
  18251. return seq;
  18252. }
  18253. }
  18254. return this;
  18255. });
  18256. var commutativeOperators = makePredicate("== === != !== * & | ^");
  18257. OPT(AST_Binary, function(self, compressor){
  18258. function reverse(op, force) {
  18259. if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) {
  18260. if (op) self.operator = op;
  18261. var tmp = self.left;
  18262. self.left = self.right;
  18263. self.right = tmp;
  18264. }
  18265. }
  18266. if (commutativeOperators(self.operator)) {
  18267. if (self.right instanceof AST_Constant
  18268. && !(self.left instanceof AST_Constant)) {
  18269. // if right is a constant, whatever side effects the
  18270. // left side might have could not influence the
  18271. // result. hence, force switch.
  18272. if (!(self.left instanceof AST_Binary
  18273. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  18274. reverse(null, true);
  18275. }
  18276. }
  18277. if (/^[!=]==?$/.test(self.operator)) {
  18278. if (self.left instanceof AST_SymbolRef && self.right instanceof AST_Conditional) {
  18279. if (self.right.consequent instanceof AST_SymbolRef
  18280. && self.right.consequent.definition() === self.left.definition()) {
  18281. if (/^==/.test(self.operator)) return self.right.condition;
  18282. if (/^!=/.test(self.operator)) return self.right.condition.negate(compressor);
  18283. }
  18284. if (self.right.alternative instanceof AST_SymbolRef
  18285. && self.right.alternative.definition() === self.left.definition()) {
  18286. if (/^==/.test(self.operator)) return self.right.condition.negate(compressor);
  18287. if (/^!=/.test(self.operator)) return self.right.condition;
  18288. }
  18289. }
  18290. if (self.right instanceof AST_SymbolRef && self.left instanceof AST_Conditional) {
  18291. if (self.left.consequent instanceof AST_SymbolRef
  18292. && self.left.consequent.definition() === self.right.definition()) {
  18293. if (/^==/.test(self.operator)) return self.left.condition;
  18294. if (/^!=/.test(self.operator)) return self.left.condition.negate(compressor);
  18295. }
  18296. if (self.left.alternative instanceof AST_SymbolRef
  18297. && self.left.alternative.definition() === self.right.definition()) {
  18298. if (/^==/.test(self.operator)) return self.left.condition.negate(compressor);
  18299. if (/^!=/.test(self.operator)) return self.left.condition;
  18300. }
  18301. }
  18302. }
  18303. }
  18304. self = self.lift_sequences(compressor);
  18305. if (compressor.option("comparisons")) switch (self.operator) {
  18306. case "===":
  18307. case "!==":
  18308. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  18309. (self.left.is_boolean() && self.right.is_boolean())) {
  18310. self.operator = self.operator.substr(0, 2);
  18311. }
  18312. // XXX: intentionally falling down to the next case
  18313. case "==":
  18314. case "!=":
  18315. if (self.left instanceof AST_String
  18316. && self.left.value == "undefined"
  18317. && self.right instanceof AST_UnaryPrefix
  18318. && self.right.operator == "typeof"
  18319. && compressor.option("unsafe")) {
  18320. if (!(self.right.expression instanceof AST_SymbolRef)
  18321. || !self.right.expression.undeclared()) {
  18322. self.right = self.right.expression;
  18323. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  18324. if (self.operator.length == 2) self.operator += "=";
  18325. }
  18326. }
  18327. break;
  18328. }
  18329. if (compressor.option("conditionals")) {
  18330. if (self.operator == "&&") {
  18331. var ll = self.left.evaluate(compressor);
  18332. if (ll.length > 1) {
  18333. if (ll[1]) {
  18334. compressor.warn("Condition left of && always true [{file}:{line},{col}]", self.start);
  18335. return maintain_this_binding(compressor.parent(), self, self.right.evaluate(compressor)[0]);
  18336. } else {
  18337. compressor.warn("Condition left of && always false [{file}:{line},{col}]", self.start);
  18338. return maintain_this_binding(compressor.parent(), self, ll[0]);
  18339. }
  18340. }
  18341. }
  18342. else if (self.operator == "||") {
  18343. var ll = self.left.evaluate(compressor);
  18344. if (ll.length > 1) {
  18345. if (ll[1]) {
  18346. compressor.warn("Condition left of || always true [{file}:{line},{col}]", self.start);
  18347. return maintain_this_binding(compressor.parent(), self, ll[0]);
  18348. } else {
  18349. compressor.warn("Condition left of || always false [{file}:{line},{col}]", self.start);
  18350. return maintain_this_binding(compressor.parent(), self, self.right.evaluate(compressor)[0]);
  18351. }
  18352. }
  18353. }
  18354. }
  18355. if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) {
  18356. case "&&":
  18357. var ll = self.left.evaluate(compressor);
  18358. var rr = self.right.evaluate(compressor);
  18359. if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) {
  18360. compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
  18361. if (self.left.has_side_effects(compressor)) {
  18362. return make_node(AST_Seq, self, {
  18363. car: self.left,
  18364. cdr: make_node(AST_False)
  18365. }).optimize(compressor);
  18366. }
  18367. return make_node(AST_False, self);
  18368. }
  18369. if (ll.length > 1 && ll[1]) {
  18370. return rr[0];
  18371. }
  18372. if (rr.length > 1 && rr[1]) {
  18373. return ll[0];
  18374. }
  18375. break;
  18376. case "||":
  18377. var ll = self.left.evaluate(compressor);
  18378. var rr = self.right.evaluate(compressor);
  18379. if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) {
  18380. compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
  18381. if (self.left.has_side_effects(compressor)) {
  18382. return make_node(AST_Seq, self, {
  18383. car: self.left,
  18384. cdr: make_node(AST_True)
  18385. }).optimize(compressor);
  18386. }
  18387. return make_node(AST_True, self);
  18388. }
  18389. if (ll.length > 1 && !ll[1]) {
  18390. return rr[0];
  18391. }
  18392. if (rr.length > 1 && !rr[1]) {
  18393. return ll[0];
  18394. }
  18395. break;
  18396. case "+":
  18397. var ll = self.left.evaluate(compressor);
  18398. var rr = self.right.evaluate(compressor);
  18399. if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) ||
  18400. (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) {
  18401. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  18402. return make_node(AST_True, self);
  18403. }
  18404. break;
  18405. }
  18406. if (compressor.option("comparisons") && self.is_boolean()) {
  18407. if (!(compressor.parent() instanceof AST_Binary)
  18408. || compressor.parent() instanceof AST_Assign) {
  18409. var negated = make_node(AST_UnaryPrefix, self, {
  18410. operator: "!",
  18411. expression: self.negate(compressor)
  18412. });
  18413. self = best_of(self, negated);
  18414. }
  18415. if (compressor.option("unsafe_comps")) {
  18416. switch (self.operator) {
  18417. case "<": reverse(">"); break;
  18418. case "<=": reverse(">="); break;
  18419. }
  18420. }
  18421. }
  18422. if (self.operator == "+" && self.right instanceof AST_String
  18423. && self.right.getValue() === "" && self.left instanceof AST_Binary
  18424. && self.left.operator == "+" && self.left.is_string(compressor)) {
  18425. return self.left;
  18426. }
  18427. if (compressor.option("evaluate")) {
  18428. if (self.operator == "+") {
  18429. if (self.left instanceof AST_Constant
  18430. && self.right instanceof AST_Binary
  18431. && self.right.operator == "+"
  18432. && self.right.left instanceof AST_Constant
  18433. && self.right.is_string(compressor)) {
  18434. self = make_node(AST_Binary, self, {
  18435. operator: "+",
  18436. left: make_node(AST_String, null, {
  18437. value: "" + self.left.getValue() + self.right.left.getValue(),
  18438. start: self.left.start,
  18439. end: self.right.left.end
  18440. }),
  18441. right: self.right.right
  18442. });
  18443. }
  18444. if (self.right instanceof AST_Constant
  18445. && self.left instanceof AST_Binary
  18446. && self.left.operator == "+"
  18447. && self.left.right instanceof AST_Constant
  18448. && self.left.is_string(compressor)) {
  18449. self = make_node(AST_Binary, self, {
  18450. operator: "+",
  18451. left: self.left.left,
  18452. right: make_node(AST_String, null, {
  18453. value: "" + self.left.right.getValue() + self.right.getValue(),
  18454. start: self.left.right.start,
  18455. end: self.right.end
  18456. })
  18457. });
  18458. }
  18459. if (self.left instanceof AST_Binary
  18460. && self.left.operator == "+"
  18461. && self.left.is_string(compressor)
  18462. && self.left.right instanceof AST_Constant
  18463. && self.right instanceof AST_Binary
  18464. && self.right.operator == "+"
  18465. && self.right.left instanceof AST_Constant
  18466. && self.right.is_string(compressor)) {
  18467. self = make_node(AST_Binary, self, {
  18468. operator: "+",
  18469. left: make_node(AST_Binary, self.left, {
  18470. operator: "+",
  18471. left: self.left.left,
  18472. right: make_node(AST_String, null, {
  18473. value: "" + self.left.right.getValue() + self.right.left.getValue(),
  18474. start: self.left.right.start,
  18475. end: self.right.left.end
  18476. })
  18477. }),
  18478. right: self.right.right
  18479. });
  18480. }
  18481. }
  18482. }
  18483. // x && (y && z) ==> x && y && z
  18484. // x || (y || z) ==> x || y || z
  18485. if (self.right instanceof AST_Binary
  18486. && self.right.operator == self.operator
  18487. && (self.operator == "&&" || self.operator == "||"))
  18488. {
  18489. self.left = make_node(AST_Binary, self.left, {
  18490. operator : self.operator,
  18491. left : self.left,
  18492. right : self.right.left
  18493. });
  18494. self.right = self.right.right;
  18495. return self.transform(compressor);
  18496. }
  18497. return self.evaluate(compressor)[0];
  18498. });
  18499. OPT(AST_SymbolRef, function(self, compressor){
  18500. function isLHS(symbol, parent) {
  18501. return (
  18502. parent instanceof AST_Binary &&
  18503. parent.operator === '=' &&
  18504. parent.left === symbol
  18505. );
  18506. }
  18507. if (self.undeclared() && !isLHS(self, compressor.parent())) {
  18508. var defines = compressor.option("global_defs");
  18509. if (defines && HOP(defines, self.name)) {
  18510. return make_node_from_constant(compressor, defines[self.name], self);
  18511. }
  18512. // testing against !self.scope.uses_with first is an optimization
  18513. if (!self.scope.uses_with || !compressor.find_parent(AST_With)) {
  18514. switch (self.name) {
  18515. case "undefined":
  18516. return make_node(AST_Undefined, self);
  18517. case "NaN":
  18518. return make_node(AST_NaN, self).transform(compressor);
  18519. case "Infinity":
  18520. return make_node(AST_Infinity, self).transform(compressor);
  18521. }
  18522. }
  18523. }
  18524. return self;
  18525. });
  18526. OPT(AST_Infinity, function (self, compressor) {
  18527. return make_node(AST_Binary, self, {
  18528. operator : '/',
  18529. left : make_node(AST_Number, self, {value: 1}),
  18530. right : make_node(AST_Number, self, {value: 0})
  18531. });
  18532. });
  18533. OPT(AST_Undefined, function(self, compressor){
  18534. if (compressor.option("unsafe")) {
  18535. var scope = compressor.find_parent(AST_Scope);
  18536. var undef = scope.find_variable("undefined");
  18537. if (undef) {
  18538. var ref = make_node(AST_SymbolRef, self, {
  18539. name : "undefined",
  18540. scope : scope,
  18541. thedef : undef
  18542. });
  18543. ref.reference();
  18544. return ref;
  18545. }
  18546. }
  18547. return self;
  18548. });
  18549. var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  18550. OPT(AST_Assign, function(self, compressor){
  18551. self = self.lift_sequences(compressor);
  18552. if (self.operator == "="
  18553. && self.left instanceof AST_SymbolRef
  18554. && self.right instanceof AST_Binary
  18555. && self.right.left instanceof AST_SymbolRef
  18556. && self.right.left.name == self.left.name
  18557. && member(self.right.operator, ASSIGN_OPS)) {
  18558. self.operator = self.right.operator + "=";
  18559. self.right = self.right.right;
  18560. }
  18561. return self;
  18562. });
  18563. OPT(AST_Conditional, function(self, compressor){
  18564. if (!compressor.option("conditionals")) return self;
  18565. if (self.condition instanceof AST_Seq) {
  18566. var car = self.condition.car;
  18567. self.condition = self.condition.cdr;
  18568. return AST_Seq.cons(car, self);
  18569. }
  18570. var cond = self.condition.evaluate(compressor);
  18571. if (cond.length > 1) {
  18572. if (cond[1]) {
  18573. compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
  18574. return maintain_this_binding(compressor.parent(), self, self.consequent);
  18575. } else {
  18576. compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
  18577. return maintain_this_binding(compressor.parent(), self, self.alternative);
  18578. }
  18579. }
  18580. var negated = cond[0].negate(compressor);
  18581. if (best_of(cond[0], negated) === negated) {
  18582. self = make_node(AST_Conditional, self, {
  18583. condition: negated,
  18584. consequent: self.alternative,
  18585. alternative: self.consequent
  18586. });
  18587. }
  18588. var consequent = self.consequent;
  18589. var alternative = self.alternative;
  18590. if (consequent instanceof AST_Assign
  18591. && alternative instanceof AST_Assign
  18592. && consequent.operator == alternative.operator
  18593. && consequent.left.equivalent_to(alternative.left)
  18594. && !consequent.left.has_side_effects(compressor)
  18595. ) {
  18596. /*
  18597. * Stuff like this:
  18598. * if (foo) exp = something; else exp = something_else;
  18599. * ==>
  18600. * exp = foo ? something : something_else;
  18601. */
  18602. return make_node(AST_Assign, self, {
  18603. operator: consequent.operator,
  18604. left: consequent.left,
  18605. right: make_node(AST_Conditional, self, {
  18606. condition: self.condition,
  18607. consequent: consequent.right,
  18608. alternative: alternative.right
  18609. })
  18610. });
  18611. }
  18612. if (consequent instanceof AST_Call
  18613. && alternative.TYPE === consequent.TYPE
  18614. && consequent.args.length == alternative.args.length
  18615. && !consequent.expression.has_side_effects(compressor)
  18616. && consequent.expression.equivalent_to(alternative.expression)) {
  18617. if (consequent.args.length == 0) {
  18618. return make_node(AST_Seq, self, {
  18619. car: self.condition,
  18620. cdr: consequent
  18621. });
  18622. }
  18623. if (consequent.args.length == 1) {
  18624. consequent.args[0] = make_node(AST_Conditional, self, {
  18625. condition: self.condition,
  18626. consequent: consequent.args[0],
  18627. alternative: alternative.args[0]
  18628. });
  18629. return consequent;
  18630. }
  18631. }
  18632. // x?y?z:a:a --> x&&y?z:a
  18633. if (consequent instanceof AST_Conditional
  18634. && consequent.alternative.equivalent_to(alternative)) {
  18635. return make_node(AST_Conditional, self, {
  18636. condition: make_node(AST_Binary, self, {
  18637. left: self.condition,
  18638. operator: "&&",
  18639. right: consequent.condition
  18640. }),
  18641. consequent: consequent.consequent,
  18642. alternative: alternative
  18643. });
  18644. }
  18645. // y?1:1 --> 1
  18646. if (consequent.is_constant(compressor)
  18647. && alternative.is_constant(compressor)
  18648. && consequent.equivalent_to(alternative)) {
  18649. var consequent_value = consequent.constant_value(compressor);
  18650. if (self.condition.has_side_effects(compressor)) {
  18651. return AST_Seq.from_array([self.condition, make_node_from_constant(compressor, consequent_value, self)]);
  18652. } else {
  18653. return make_node_from_constant(compressor, consequent_value, self);
  18654. }
  18655. }
  18656. if (is_true(self.consequent)) {
  18657. if (is_false(self.alternative)) {
  18658. // c ? true : false ---> !!c
  18659. return booleanize(self.condition);
  18660. }
  18661. // c ? true : x ---> !!c || x
  18662. return make_node(AST_Binary, self, {
  18663. operator: "||",
  18664. left: booleanize(self.condition),
  18665. right: self.alternative
  18666. });
  18667. }
  18668. if (is_false(self.consequent)) {
  18669. if (is_true(self.alternative)) {
  18670. // c ? false : true ---> !c
  18671. return booleanize(self.condition.negate(compressor));
  18672. }
  18673. // c ? false : x ---> !c && x
  18674. return make_node(AST_Binary, self, {
  18675. operator: "&&",
  18676. left: booleanize(self.condition.negate(compressor)),
  18677. right: self.alternative
  18678. });
  18679. }
  18680. if (is_true(self.alternative)) {
  18681. // c ? x : true ---> !c || x
  18682. return make_node(AST_Binary, self, {
  18683. operator: "||",
  18684. left: booleanize(self.condition.negate(compressor)),
  18685. right: self.consequent
  18686. });
  18687. }
  18688. if (is_false(self.alternative)) {
  18689. // c ? x : false ---> !!c && x
  18690. return make_node(AST_Binary, self, {
  18691. operator: "&&",
  18692. left: booleanize(self.condition),
  18693. right: self.consequent
  18694. });
  18695. }
  18696. return self;
  18697. function booleanize(node) {
  18698. if (node.is_boolean()) return node;
  18699. // !!expression
  18700. return make_node(AST_UnaryPrefix, node, {
  18701. operator: "!",
  18702. expression: node.negate(compressor)
  18703. });
  18704. }
  18705. // AST_True or !0
  18706. function is_true(node) {
  18707. return node instanceof AST_True
  18708. || (node instanceof AST_UnaryPrefix
  18709. && node.operator == "!"
  18710. && node.expression instanceof AST_Constant
  18711. && !node.expression.value);
  18712. }
  18713. // AST_False or !1
  18714. function is_false(node) {
  18715. return node instanceof AST_False
  18716. || (node instanceof AST_UnaryPrefix
  18717. && node.operator == "!"
  18718. && node.expression instanceof AST_Constant
  18719. && !!node.expression.value);
  18720. }
  18721. });
  18722. OPT(AST_Boolean, function(self, compressor){
  18723. if (compressor.option("booleans")) {
  18724. var p = compressor.parent();
  18725. if (p instanceof AST_Binary && (p.operator == "=="
  18726. || p.operator == "!=")) {
  18727. compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
  18728. operator : p.operator,
  18729. value : self.value,
  18730. file : p.start.file,
  18731. line : p.start.line,
  18732. col : p.start.col,
  18733. });
  18734. return make_node(AST_Number, self, {
  18735. value: +self.value
  18736. });
  18737. }
  18738. return make_node(AST_UnaryPrefix, self, {
  18739. operator: "!",
  18740. expression: make_node(AST_Number, self, {
  18741. value: 1 - self.value
  18742. })
  18743. });
  18744. }
  18745. return self;
  18746. });
  18747. OPT(AST_Sub, function(self, compressor){
  18748. var prop = self.property;
  18749. if (prop instanceof AST_String && compressor.option("properties")) {
  18750. prop = prop.getValue();
  18751. if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) {
  18752. return make_node(AST_Dot, self, {
  18753. expression : self.expression,
  18754. property : prop
  18755. }).optimize(compressor);
  18756. }
  18757. var v = parseFloat(prop);
  18758. if (!isNaN(v) && v.toString() == prop) {
  18759. self.property = make_node(AST_Number, self.property, {
  18760. value: v
  18761. });
  18762. }
  18763. }
  18764. return self;
  18765. });
  18766. OPT(AST_Dot, function(self, compressor){
  18767. var prop = self.property;
  18768. if (RESERVED_WORDS(prop) && !compressor.option("screw_ie8")) {
  18769. return make_node(AST_Sub, self, {
  18770. expression : self.expression,
  18771. property : make_node(AST_String, self, {
  18772. value: prop
  18773. })
  18774. }).optimize(compressor);
  18775. }
  18776. return self.evaluate(compressor)[0];
  18777. });
  18778. function literals_in_boolean_context(self, compressor) {
  18779. if (compressor.option("booleans") && compressor.in_boolean_context() && !self.has_side_effects(compressor)) {
  18780. return make_node(AST_True, self);
  18781. }
  18782. return self;
  18783. };
  18784. OPT(AST_Array, literals_in_boolean_context);
  18785. OPT(AST_Object, literals_in_boolean_context);
  18786. OPT(AST_RegExp, literals_in_boolean_context);
  18787. OPT(AST_Return, function(self, compressor){
  18788. if (self.value instanceof AST_Undefined) {
  18789. self.value = null;
  18790. }
  18791. return self;
  18792. });
  18793. })();
  18794. /***********************************************************************
  18795. A JavaScript tokenizer / parser / beautifier / compressor.
  18796. https://github.com/mishoo/UglifyJS2
  18797. -------------------------------- (C) ---------------------------------
  18798. Author: Mihai Bazon
  18799. <mihai.bazon@gmail.com>
  18800. http://mihai.bazon.net/blog
  18801. Distributed under the BSD license:
  18802. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  18803. Redistribution and use in source and binary forms, with or without
  18804. modification, are permitted provided that the following conditions
  18805. are met:
  18806. * Redistributions of source code must retain the above
  18807. copyright notice, this list of conditions and the following
  18808. disclaimer.
  18809. * Redistributions in binary form must reproduce the above
  18810. copyright notice, this list of conditions and the following
  18811. disclaimer in the documentation and/or other materials
  18812. provided with the distribution.
  18813. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  18814. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18815. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  18816. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  18817. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  18818. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  18819. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  18820. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  18821. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  18822. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  18823. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  18824. SUCH DAMAGE.
  18825. ***********************************************************************/
  18826. "use strict";
  18827. // a small wrapper around fitzgen's source-map library
  18828. function SourceMap(options) {
  18829. options = defaults(options, {
  18830. file : null,
  18831. root : null,
  18832. orig : null,
  18833. orig_line_diff : 0,
  18834. dest_line_diff : 0,
  18835. });
  18836. var generator = new MOZ_SourceMap.SourceMapGenerator({
  18837. file : options.file,
  18838. sourceRoot : options.root
  18839. });
  18840. var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);
  18841. if (orig_map && Array.isArray(options.orig.sources)) {
  18842. options.orig.sources.forEach(function(source) {
  18843. var sourceContent = orig_map.sourceContentFor(source, true);
  18844. if (sourceContent) {
  18845. generator.setSourceContent(source, sourceContent);
  18846. }
  18847. });
  18848. }
  18849. function add(source, gen_line, gen_col, orig_line, orig_col, name) {
  18850. if (orig_map) {
  18851. var info = orig_map.originalPositionFor({
  18852. line: orig_line,
  18853. column: orig_col
  18854. });
  18855. if (info.source === null) {
  18856. return;
  18857. }
  18858. source = info.source;
  18859. orig_line = info.line;
  18860. orig_col = info.column;
  18861. name = info.name || name;
  18862. }
  18863. generator.addMapping({
  18864. generated : { line: gen_line + options.dest_line_diff, column: gen_col },
  18865. original : { line: orig_line + options.orig_line_diff, column: orig_col },
  18866. source : source,
  18867. name : name
  18868. });
  18869. };
  18870. return {
  18871. add : add,
  18872. get : function() { return generator },
  18873. toString : function() { return JSON.stringify(generator.toJSON()); }
  18874. };
  18875. };
  18876. /***********************************************************************
  18877. A JavaScript tokenizer / parser / beautifier / compressor.
  18878. https://github.com/mishoo/UglifyJS2
  18879. -------------------------------- (C) ---------------------------------
  18880. Author: Mihai Bazon
  18881. <mihai.bazon@gmail.com>
  18882. http://mihai.bazon.net/blog
  18883. Distributed under the BSD license:
  18884. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  18885. Redistribution and use in source and binary forms, with or without
  18886. modification, are permitted provided that the following conditions
  18887. are met:
  18888. * Redistributions of source code must retain the above
  18889. copyright notice, this list of conditions and the following
  18890. disclaimer.
  18891. * Redistributions in binary form must reproduce the above
  18892. copyright notice, this list of conditions and the following
  18893. disclaimer in the documentation and/or other materials
  18894. provided with the distribution.
  18895. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  18896. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18897. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  18898. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  18899. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  18900. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  18901. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  18902. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  18903. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  18904. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  18905. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  18906. SUCH DAMAGE.
  18907. ***********************************************************************/
  18908. "use strict";
  18909. (function(){
  18910. var normalize_directives = function(body) {
  18911. var in_directive = true;
  18912. for (var i = 0; i < body.length; i++) {
  18913. if (in_directive && body[i] instanceof AST_Statement && body[i].body instanceof AST_String) {
  18914. body[i] = new AST_Directive({
  18915. start: body[i].start,
  18916. end: body[i].end,
  18917. value: body[i].body.value
  18918. });
  18919. } else if (in_directive && !(body[i] instanceof AST_Statement && body[i].body instanceof AST_String)) {
  18920. in_directive = false;
  18921. }
  18922. }
  18923. return body;
  18924. };
  18925. var MOZ_TO_ME = {
  18926. Program: function(M) {
  18927. return new AST_Toplevel({
  18928. start: my_start_token(M),
  18929. end: my_end_token(M),
  18930. body: normalize_directives(M.body.map(from_moz))
  18931. });
  18932. },
  18933. FunctionDeclaration: function(M) {
  18934. return new AST_Defun({
  18935. start: my_start_token(M),
  18936. end: my_end_token(M),
  18937. name: from_moz(M.id),
  18938. argnames: M.params.map(from_moz),
  18939. body: normalize_directives(from_moz(M.body).body)
  18940. });
  18941. },
  18942. FunctionExpression: function(M) {
  18943. return new AST_Function({
  18944. start: my_start_token(M),
  18945. end: my_end_token(M),
  18946. name: from_moz(M.id),
  18947. argnames: M.params.map(from_moz),
  18948. body: normalize_directives(from_moz(M.body).body)
  18949. });
  18950. },
  18951. ExpressionStatement: function(M) {
  18952. return new AST_SimpleStatement({
  18953. start: my_start_token(M),
  18954. end: my_end_token(M),
  18955. body: from_moz(M.expression)
  18956. });
  18957. },
  18958. TryStatement: function(M) {
  18959. var handlers = M.handlers || [M.handler];
  18960. if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) {
  18961. throw new Error("Multiple catch clauses are not supported.");
  18962. }
  18963. return new AST_Try({
  18964. start : my_start_token(M),
  18965. end : my_end_token(M),
  18966. body : from_moz(M.block).body,
  18967. bcatch : from_moz(handlers[0]),
  18968. bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
  18969. });
  18970. },
  18971. Property: function(M) {
  18972. var key = M.key;
  18973. var name = key.type == "Identifier" ? key.name : key.value;
  18974. var args = {
  18975. start : my_start_token(key),
  18976. end : my_end_token(M.value),
  18977. key : name,
  18978. value : from_moz(M.value)
  18979. };
  18980. switch (M.kind) {
  18981. case "init":
  18982. return new AST_ObjectKeyVal(args);
  18983. case "set":
  18984. args.value.name = from_moz(key);
  18985. return new AST_ObjectSetter(args);
  18986. case "get":
  18987. args.value.name = from_moz(key);
  18988. return new AST_ObjectGetter(args);
  18989. }
  18990. },
  18991. ArrayExpression: function(M) {
  18992. return new AST_Array({
  18993. start : my_start_token(M),
  18994. end : my_end_token(M),
  18995. elements : M.elements.map(function(elem){
  18996. return elem === null ? new AST_Hole() : from_moz(elem);
  18997. })
  18998. });
  18999. },
  19000. ObjectExpression: function(M) {
  19001. return new AST_Object({
  19002. start : my_start_token(M),
  19003. end : my_end_token(M),
  19004. properties : M.properties.map(function(prop){
  19005. prop.type = "Property";
  19006. return from_moz(prop)
  19007. })
  19008. });
  19009. },
  19010. SequenceExpression: function(M) {
  19011. return AST_Seq.from_array(M.expressions.map(from_moz));
  19012. },
  19013. MemberExpression: function(M) {
  19014. return new (M.computed ? AST_Sub : AST_Dot)({
  19015. start : my_start_token(M),
  19016. end : my_end_token(M),
  19017. property : M.computed ? from_moz(M.property) : M.property.name,
  19018. expression : from_moz(M.object)
  19019. });
  19020. },
  19021. SwitchCase: function(M) {
  19022. return new (M.test ? AST_Case : AST_Default)({
  19023. start : my_start_token(M),
  19024. end : my_end_token(M),
  19025. expression : from_moz(M.test),
  19026. body : M.consequent.map(from_moz)
  19027. });
  19028. },
  19029. VariableDeclaration: function(M) {
  19030. return new (M.kind === "const" ? AST_Const : AST_Var)({
  19031. start : my_start_token(M),
  19032. end : my_end_token(M),
  19033. definitions : M.declarations.map(from_moz)
  19034. });
  19035. },
  19036. Literal: function(M) {
  19037. var val = M.value, args = {
  19038. start : my_start_token(M),
  19039. end : my_end_token(M)
  19040. };
  19041. if (val === null) return new AST_Null(args);
  19042. switch (typeof val) {
  19043. case "string":
  19044. args.value = val;
  19045. return new AST_String(args);
  19046. case "number":
  19047. args.value = val;
  19048. return new AST_Number(args);
  19049. case "boolean":
  19050. return new (val ? AST_True : AST_False)(args);
  19051. default:
  19052. var rx = M.regex;
  19053. if (rx && rx.pattern) {
  19054. // RegExpLiteral as per ESTree AST spec
  19055. args.value = new RegExp(rx.pattern, rx.flags).toString();
  19056. } else {
  19057. // support legacy RegExp
  19058. args.value = M.regex && M.raw ? M.raw : val;
  19059. }
  19060. return new AST_RegExp(args);
  19061. }
  19062. },
  19063. Identifier: function(M) {
  19064. var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
  19065. return new ( p.type == "LabeledStatement" ? AST_Label
  19066. : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar)
  19067. : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
  19068. : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
  19069. : p.type == "CatchClause" ? AST_SymbolCatch
  19070. : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
  19071. : AST_SymbolRef)({
  19072. start : my_start_token(M),
  19073. end : my_end_token(M),
  19074. name : M.name
  19075. });
  19076. }
  19077. };
  19078. MOZ_TO_ME.UpdateExpression =
  19079. MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) {
  19080. var prefix = "prefix" in M ? M.prefix
  19081. : M.type == "UnaryExpression" ? true : false;
  19082. return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  19083. start : my_start_token(M),
  19084. end : my_end_token(M),
  19085. operator : M.operator,
  19086. expression : from_moz(M.argument)
  19087. });
  19088. };
  19089. map("EmptyStatement", AST_EmptyStatement);
  19090. map("BlockStatement", AST_BlockStatement, "body@body");
  19091. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  19092. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  19093. map("BreakStatement", AST_Break, "label>label");
  19094. map("ContinueStatement", AST_Continue, "label>label");
  19095. map("WithStatement", AST_With, "object>expression, body>body");
  19096. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  19097. map("ReturnStatement", AST_Return, "argument>value");
  19098. map("ThrowStatement", AST_Throw, "argument>value");
  19099. map("WhileStatement", AST_While, "test>condition, body>body");
  19100. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  19101. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  19102. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  19103. map("DebuggerStatement", AST_Debugger);
  19104. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  19105. map("CatchClause", AST_Catch, "param>argname, body%body");
  19106. map("ThisExpression", AST_This);
  19107. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  19108. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  19109. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  19110. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  19111. map("NewExpression", AST_New, "callee>expression, arguments@args");
  19112. map("CallExpression", AST_Call, "callee>expression, arguments@args");
  19113. def_to_moz(AST_Toplevel, function To_Moz_Program(M) {
  19114. return {
  19115. type: "Program",
  19116. body: M.body.map(to_moz)
  19117. };
  19118. });
  19119. def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) {
  19120. return {
  19121. type: "FunctionDeclaration",
  19122. id: to_moz(M.name),
  19123. params: M.argnames.map(to_moz),
  19124. body: to_moz_block(M)
  19125. }
  19126. });
  19127. def_to_moz(AST_Function, function To_Moz_FunctionExpression(M) {
  19128. return {
  19129. type: "FunctionExpression",
  19130. id: to_moz(M.name),
  19131. params: M.argnames.map(to_moz),
  19132. body: to_moz_block(M)
  19133. }
  19134. });
  19135. def_to_moz(AST_Directive, function To_Moz_Directive(M) {
  19136. return {
  19137. type: "ExpressionStatement",
  19138. expression: {
  19139. type: "Literal",
  19140. value: M.value
  19141. }
  19142. };
  19143. });
  19144. def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) {
  19145. return {
  19146. type: "ExpressionStatement",
  19147. expression: to_moz(M.body)
  19148. };
  19149. });
  19150. def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) {
  19151. return {
  19152. type: "SwitchCase",
  19153. test: to_moz(M.expression),
  19154. consequent: M.body.map(to_moz)
  19155. };
  19156. });
  19157. def_to_moz(AST_Try, function To_Moz_TryStatement(M) {
  19158. return {
  19159. type: "TryStatement",
  19160. block: to_moz_block(M),
  19161. handler: to_moz(M.bcatch),
  19162. guardedHandlers: [],
  19163. finalizer: to_moz(M.bfinally)
  19164. };
  19165. });
  19166. def_to_moz(AST_Catch, function To_Moz_CatchClause(M) {
  19167. return {
  19168. type: "CatchClause",
  19169. param: to_moz(M.argname),
  19170. guard: null,
  19171. body: to_moz_block(M)
  19172. };
  19173. });
  19174. def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) {
  19175. return {
  19176. type: "VariableDeclaration",
  19177. kind: M instanceof AST_Const ? "const" : "var",
  19178. declarations: M.definitions.map(to_moz)
  19179. };
  19180. });
  19181. def_to_moz(AST_Seq, function To_Moz_SequenceExpression(M) {
  19182. return {
  19183. type: "SequenceExpression",
  19184. expressions: M.to_array().map(to_moz)
  19185. };
  19186. });
  19187. def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) {
  19188. var isComputed = M instanceof AST_Sub;
  19189. return {
  19190. type: "MemberExpression",
  19191. object: to_moz(M.expression),
  19192. computed: isComputed,
  19193. property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}
  19194. };
  19195. });
  19196. def_to_moz(AST_Unary, function To_Moz_Unary(M) {
  19197. return {
  19198. type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression",
  19199. operator: M.operator,
  19200. prefix: M instanceof AST_UnaryPrefix,
  19201. argument: to_moz(M.expression)
  19202. };
  19203. });
  19204. def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) {
  19205. return {
  19206. type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression",
  19207. left: to_moz(M.left),
  19208. operator: M.operator,
  19209. right: to_moz(M.right)
  19210. };
  19211. });
  19212. def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) {
  19213. return {
  19214. type: "ArrayExpression",
  19215. elements: M.elements.map(to_moz)
  19216. };
  19217. });
  19218. def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) {
  19219. return {
  19220. type: "ObjectExpression",
  19221. properties: M.properties.map(to_moz)
  19222. };
  19223. });
  19224. def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) {
  19225. var key = (
  19226. is_identifier(M.key)
  19227. ? {type: "Identifier", name: M.key}
  19228. : {type: "Literal", value: M.key}
  19229. );
  19230. var kind;
  19231. if (M instanceof AST_ObjectKeyVal) {
  19232. kind = "init";
  19233. } else
  19234. if (M instanceof AST_ObjectGetter) {
  19235. kind = "get";
  19236. } else
  19237. if (M instanceof AST_ObjectSetter) {
  19238. kind = "set";
  19239. }
  19240. return {
  19241. type: "Property",
  19242. kind: kind,
  19243. key: key,
  19244. value: to_moz(M.value)
  19245. };
  19246. });
  19247. def_to_moz(AST_Symbol, function To_Moz_Identifier(M) {
  19248. var def = M.definition();
  19249. return {
  19250. type: "Identifier",
  19251. name: def ? def.mangled_name || def.name : M.name
  19252. };
  19253. });
  19254. def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) {
  19255. var value = M.value;
  19256. return {
  19257. type: "Literal",
  19258. value: value,
  19259. raw: value.toString(),
  19260. regex: {
  19261. pattern: value.source,
  19262. flags: value.toString().match(/[gimuy]*$/)[0]
  19263. }
  19264. };
  19265. });
  19266. def_to_moz(AST_Constant, function To_Moz_Literal(M) {
  19267. var value = M.value;
  19268. if (typeof value === 'number' && (value < 0 || (value === 0 && 1 / value < 0))) {
  19269. return {
  19270. type: "UnaryExpression",
  19271. operator: "-",
  19272. prefix: true,
  19273. argument: {
  19274. type: "Literal",
  19275. value: -value,
  19276. raw: M.start.raw
  19277. }
  19278. };
  19279. }
  19280. return {
  19281. type: "Literal",
  19282. value: value,
  19283. raw: M.start.raw
  19284. };
  19285. });
  19286. def_to_moz(AST_Atom, function To_Moz_Atom(M) {
  19287. return {
  19288. type: "Identifier",
  19289. name: String(M.value)
  19290. };
  19291. });
  19292. AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  19293. AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  19294. AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null });
  19295. AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast);
  19296. AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast);
  19297. /* -----[ tools ]----- */
  19298. function raw_token(moznode) {
  19299. if (moznode.type == "Literal") {
  19300. return moznode.raw != null ? moznode.raw : moznode.value + "";
  19301. }
  19302. }
  19303. function my_start_token(moznode) {
  19304. var loc = moznode.loc, start = loc && loc.start;
  19305. var range = moznode.range;
  19306. return new AST_Token({
  19307. file : loc && loc.source,
  19308. line : start && start.line,
  19309. col : start && start.column,
  19310. pos : range ? range[0] : moznode.start,
  19311. endline : start && start.line,
  19312. endcol : start && start.column,
  19313. endpos : range ? range[0] : moznode.start,
  19314. raw : raw_token(moznode),
  19315. });
  19316. };
  19317. function my_end_token(moznode) {
  19318. var loc = moznode.loc, end = loc && loc.end;
  19319. var range = moznode.range;
  19320. return new AST_Token({
  19321. file : loc && loc.source,
  19322. line : end && end.line,
  19323. col : end && end.column,
  19324. pos : range ? range[1] : moznode.end,
  19325. endline : end && end.line,
  19326. endcol : end && end.column,
  19327. endpos : range ? range[1] : moznode.end,
  19328. raw : raw_token(moznode),
  19329. });
  19330. };
  19331. function map(moztype, mytype, propmap) {
  19332. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  19333. moz_to_me += "return new U2." + mytype.name + "({\n" +
  19334. "start: my_start_token(M),\n" +
  19335. "end: my_end_token(M)";
  19336. var me_to_moz = "function To_Moz_" + moztype + "(M){\n";
  19337. me_to_moz += "return {\n" +
  19338. "type: " + JSON.stringify(moztype);
  19339. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){
  19340. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  19341. if (!m) throw new Error("Can't understand property map: " + prop);
  19342. var moz = m[1], how = m[2], my = m[3];
  19343. moz_to_me += ",\n" + my + ": ";
  19344. me_to_moz += ",\n" + moz + ": ";
  19345. switch (how) {
  19346. case "@":
  19347. moz_to_me += "M." + moz + ".map(from_moz)";
  19348. me_to_moz += "M." + my + ".map(to_moz)";
  19349. break;
  19350. case ">":
  19351. moz_to_me += "from_moz(M." + moz + ")";
  19352. me_to_moz += "to_moz(M." + my + ")";
  19353. break;
  19354. case "=":
  19355. moz_to_me += "M." + moz;
  19356. me_to_moz += "M." + my;
  19357. break;
  19358. case "%":
  19359. moz_to_me += "from_moz(M." + moz + ").body";
  19360. me_to_moz += "to_moz_block(M)";
  19361. break;
  19362. default:
  19363. throw new Error("Can't understand operator in propmap: " + prop);
  19364. }
  19365. });
  19366. moz_to_me += "\n})\n}";
  19367. me_to_moz += "\n}\n}";
  19368. //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
  19369. //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true });
  19370. //console.log(moz_to_me);
  19371. moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
  19372. exports, my_start_token, my_end_token, from_moz
  19373. );
  19374. me_to_moz = new Function("to_moz", "to_moz_block", "return(" + me_to_moz + ")")(
  19375. to_moz, to_moz_block
  19376. );
  19377. MOZ_TO_ME[moztype] = moz_to_me;
  19378. def_to_moz(mytype, me_to_moz);
  19379. };
  19380. var FROM_MOZ_STACK = null;
  19381. function from_moz(node) {
  19382. FROM_MOZ_STACK.push(node);
  19383. var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
  19384. FROM_MOZ_STACK.pop();
  19385. return ret;
  19386. };
  19387. AST_Node.from_mozilla_ast = function(node){
  19388. var save_stack = FROM_MOZ_STACK;
  19389. FROM_MOZ_STACK = [];
  19390. var ast = from_moz(node);
  19391. FROM_MOZ_STACK = save_stack;
  19392. return ast;
  19393. };
  19394. function set_moz_loc(mynode, moznode, myparent) {
  19395. var start = mynode.start;
  19396. var end = mynode.end;
  19397. if (start.pos != null && end.endpos != null) {
  19398. moznode.range = [start.pos, end.endpos];
  19399. }
  19400. if (start.line) {
  19401. moznode.loc = {
  19402. start: {line: start.line, column: start.col},
  19403. end: end.endline ? {line: end.endline, column: end.endcol} : null
  19404. };
  19405. if (start.file) {
  19406. moznode.loc.source = start.file;
  19407. }
  19408. }
  19409. return moznode;
  19410. };
  19411. function def_to_moz(mytype, handler) {
  19412. mytype.DEFMETHOD("to_mozilla_ast", function() {
  19413. return set_moz_loc(this, handler(this));
  19414. });
  19415. };
  19416. function to_moz(node) {
  19417. return node != null ? node.to_mozilla_ast() : null;
  19418. };
  19419. function to_moz_block(node) {
  19420. return {
  19421. type: "BlockStatement",
  19422. body: node.body.map(to_moz)
  19423. };
  19424. };
  19425. })();
  19426. /***********************************************************************
  19427. A JavaScript tokenizer / parser / beautifier / compressor.
  19428. https://github.com/mishoo/UglifyJS2
  19429. -------------------------------- (C) ---------------------------------
  19430. Author: Mihai Bazon
  19431. <mihai.bazon@gmail.com>
  19432. http://mihai.bazon.net/blog
  19433. Distributed under the BSD license:
  19434. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  19435. Redistribution and use in source and binary forms, with or without
  19436. modification, are permitted provided that the following conditions
  19437. are met:
  19438. * Redistributions of source code must retain the above
  19439. copyright notice, this list of conditions and the following
  19440. disclaimer.
  19441. * Redistributions in binary form must reproduce the above
  19442. copyright notice, this list of conditions and the following
  19443. disclaimer in the documentation and/or other materials
  19444. provided with the distribution.
  19445. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  19446. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19447. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  19448. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  19449. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  19450. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  19451. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  19452. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  19453. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  19454. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  19455. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  19456. SUCH DAMAGE.
  19457. ***********************************************************************/
  19458. "use strict";
  19459. function find_builtins() {
  19460. var a = [];
  19461. [ Object, Array, Function, Number,
  19462. String, Boolean, Error, Math,
  19463. Date, RegExp
  19464. ].forEach(function(ctor){
  19465. Object.getOwnPropertyNames(ctor).map(add);
  19466. if (ctor.prototype) {
  19467. Object.getOwnPropertyNames(ctor.prototype).map(add);
  19468. }
  19469. });
  19470. function add(name) {
  19471. push_uniq(a, name);
  19472. }
  19473. return a;
  19474. }
  19475. function mangle_properties(ast, options) {
  19476. options = defaults(options, {
  19477. reserved : null,
  19478. cache : null,
  19479. only_cache : false,
  19480. regex : null,
  19481. ignore_quoted : false
  19482. });
  19483. var reserved = options.reserved;
  19484. if (reserved == null)
  19485. reserved = find_builtins();
  19486. var cache = options.cache;
  19487. if (cache == null) {
  19488. cache = {
  19489. cname: -1,
  19490. props: new Dictionary()
  19491. };
  19492. }
  19493. var regex = options.regex;
  19494. var ignore_quoted = options.ignore_quoted;
  19495. var names_to_mangle = [];
  19496. var unmangleable = [];
  19497. var ignored = {};
  19498. // step 1: find candidates to mangle
  19499. ast.walk(new TreeWalker(function(node){
  19500. if (node instanceof AST_ObjectKeyVal) {
  19501. add(node.key, ignore_quoted && node.quote);
  19502. }
  19503. else if (node instanceof AST_ObjectProperty) {
  19504. // setter or getter, since KeyVal is handled above
  19505. add(node.key.name);
  19506. }
  19507. else if (node instanceof AST_Dot) {
  19508. add(node.property);
  19509. }
  19510. else if (node instanceof AST_Sub) {
  19511. addStrings(node.property, ignore_quoted);
  19512. }
  19513. }));
  19514. // step 2: transform the tree, renaming properties
  19515. return ast.transform(new TreeTransformer(function(node){
  19516. if (node instanceof AST_ObjectKeyVal) {
  19517. if (!(ignore_quoted && node.quote))
  19518. node.key = mangle(node.key);
  19519. }
  19520. else if (node instanceof AST_ObjectProperty) {
  19521. // setter or getter
  19522. node.key.name = mangle(node.key.name);
  19523. }
  19524. else if (node instanceof AST_Dot) {
  19525. node.property = mangle(node.property);
  19526. }
  19527. else if (node instanceof AST_Sub) {
  19528. if (!ignore_quoted)
  19529. node.property = mangleStrings(node.property);
  19530. }
  19531. // else if (node instanceof AST_String) {
  19532. // if (should_mangle(node.value)) {
  19533. // AST_Node.warn(
  19534. // "Found \"{prop}\" property candidate for mangling in an arbitrary string [{file}:{line},{col}]", {
  19535. // file : node.start.file,
  19536. // line : node.start.line,
  19537. // col : node.start.col,
  19538. // prop : node.value
  19539. // }
  19540. // );
  19541. // }
  19542. // }
  19543. }));
  19544. // only function declarations after this line
  19545. function can_mangle(name) {
  19546. if (unmangleable.indexOf(name) >= 0) return false;
  19547. if (reserved.indexOf(name) >= 0) return false;
  19548. if (options.only_cache) {
  19549. return cache.props.has(name);
  19550. }
  19551. if (/^[0-9.]+$/.test(name)) return false;
  19552. return true;
  19553. }
  19554. function should_mangle(name) {
  19555. if (ignore_quoted && name in ignored) return false;
  19556. if (regex && !regex.test(name)) return false;
  19557. if (reserved.indexOf(name) >= 0) return false;
  19558. return cache.props.has(name)
  19559. || names_to_mangle.indexOf(name) >= 0;
  19560. }
  19561. function add(name, ignore) {
  19562. if (ignore) {
  19563. ignored[name] = true;
  19564. return;
  19565. }
  19566. if (can_mangle(name))
  19567. push_uniq(names_to_mangle, name);
  19568. if (!should_mangle(name)) {
  19569. push_uniq(unmangleable, name);
  19570. }
  19571. }
  19572. function mangle(name) {
  19573. if (!should_mangle(name)) {
  19574. return name;
  19575. }
  19576. var mangled = cache.props.get(name);
  19577. if (!mangled) {
  19578. do {
  19579. mangled = base54(++cache.cname);
  19580. } while (!can_mangle(mangled));
  19581. cache.props.set(name, mangled);
  19582. }
  19583. return mangled;
  19584. }
  19585. function addStrings(node, ignore) {
  19586. var out = {};
  19587. try {
  19588. (function walk(node){
  19589. node.walk(new TreeWalker(function(node){
  19590. if (node instanceof AST_Seq) {
  19591. walk(node.cdr);
  19592. return true;
  19593. }
  19594. if (node instanceof AST_String) {
  19595. add(node.value, ignore);
  19596. return true;
  19597. }
  19598. if (node instanceof AST_Conditional) {
  19599. walk(node.consequent);
  19600. walk(node.alternative);
  19601. return true;
  19602. }
  19603. throw out;
  19604. }));
  19605. })(node);
  19606. } catch(ex) {
  19607. if (ex !== out) throw ex;
  19608. }
  19609. }
  19610. function mangleStrings(node) {
  19611. return node.transform(new TreeTransformer(function(node){
  19612. if (node instanceof AST_Seq) {
  19613. node.cdr = mangleStrings(node.cdr);
  19614. }
  19615. else if (node instanceof AST_String) {
  19616. node.value = mangle(node.value);
  19617. }
  19618. else if (node instanceof AST_Conditional) {
  19619. node.consequent = mangleStrings(node.consequent);
  19620. node.alternative = mangleStrings(node.alternative);
  19621. }
  19622. return node;
  19623. }));
  19624. }
  19625. }
  19626. AST_Node.warn_function = function(txt) { logger.error("uglifyjs WARN: " + txt); };
  19627. exports.minify = function(files, options, name) {
  19628. options = defaults(options, {
  19629. spidermonkey : false,
  19630. outSourceMap : null,
  19631. sourceRoot : null,
  19632. inSourceMap : null,
  19633. sourceMapUrl : null,
  19634. fromString : false,
  19635. warnings : false,
  19636. mangle : {},
  19637. mangleProperties : false,
  19638. nameCache : null,
  19639. output : null,
  19640. compress : {},
  19641. parse : {}
  19642. });
  19643. base54.reset();
  19644. // 1. parse
  19645. var toplevel = null,
  19646. sourcesContent = {};
  19647. if (options.spidermonkey) {
  19648. toplevel = AST_Node.from_mozilla_ast(files);
  19649. } else {
  19650. var addFile = function(file, fileUrl) {
  19651. var code = options.fromString
  19652. ? file
  19653. : rjsFile.readFile(file, "utf8");
  19654. sourcesContent[fileUrl] = code;
  19655. toplevel = parse(code, {
  19656. filename: fileUrl,
  19657. toplevel: toplevel,
  19658. bare_returns: options.parse ? options.parse.bare_returns : undefined
  19659. });
  19660. }
  19661. if (!options.fromString) files = simple_glob(files);
  19662. [].concat(files).forEach(function (files, i) {
  19663. if (typeof files === 'string') {
  19664. addFile(files, options.fromString ? i : files);
  19665. } else {
  19666. for (var fileUrl in files) {
  19667. addFile(files[fileUrl], fileUrl);
  19668. }
  19669. }
  19670. });
  19671. }
  19672. if (options.wrap) {
  19673. toplevel = toplevel.wrap_commonjs(options.wrap, options.exportAll);
  19674. }
  19675. // 2. compress
  19676. if (options.compress) {
  19677. var compress = { warnings: options.warnings };
  19678. merge(compress, options.compress);
  19679. toplevel.figure_out_scope();
  19680. var sq = Compressor(compress);
  19681. toplevel = sq.compress(toplevel);
  19682. }
  19683. // 3. mangle properties
  19684. if (options.mangleProperties || options.nameCache) {
  19685. options.mangleProperties.cache = readNameCache(options.nameCache, "props");
  19686. toplevel = mangle_properties(toplevel, options.mangleProperties);
  19687. writeNameCache(options.nameCache, "props", options.mangleProperties.cache);
  19688. }
  19689. // 4. mangle
  19690. if (options.mangle) {
  19691. toplevel.figure_out_scope(options.mangle);
  19692. toplevel.compute_char_frequency(options.mangle);
  19693. toplevel.mangle_names(options.mangle);
  19694. }
  19695. // 5. output
  19696. var inMap = options.inSourceMap;
  19697. var output = {};
  19698. if (typeof options.inSourceMap == "string") {
  19699. inMap = JSON.parse(rjsFile.readFile(options.inSourceMap, "utf8"));
  19700. }
  19701. if (options.outSourceMap) {
  19702. output.source_map = SourceMap({
  19703. file: options.outSourceMap,
  19704. orig: inMap,
  19705. root: options.sourceRoot
  19706. });
  19707. if (options.sourceMapIncludeSources) {
  19708. for (var file in sourcesContent) {
  19709. if (sourcesContent.hasOwnProperty(file)) {
  19710. output.source_map.get().setSourceContent(file, sourcesContent[file]);
  19711. }
  19712. }
  19713. }
  19714. }
  19715. if (options.output) {
  19716. merge(output, options.output);
  19717. }
  19718. var stream = OutputStream(output);
  19719. toplevel.print(stream);
  19720. var mappingUrlPrefix = "\n//# sourceMappingURL=";
  19721. if (options.outSourceMap && typeof options.outSourceMap === "string" && options.sourceMapUrl !== false) {
  19722. stream += mappingUrlPrefix + (typeof options.sourceMapUrl === "string" ? options.sourceMapUrl : options.outSourceMap);
  19723. }
  19724. var source_map = output.source_map;
  19725. if (source_map) {
  19726. source_map = source_map + "";
  19727. }
  19728. return {
  19729. code : stream + "",
  19730. map : source_map
  19731. };
  19732. };
  19733. // exports.describe_ast = function() {
  19734. // function doitem(ctor) {
  19735. // var sub = {};
  19736. // ctor.SUBCLASSES.forEach(function(ctor){
  19737. // sub[ctor.TYPE] = doitem(ctor);
  19738. // });
  19739. // var ret = {};
  19740. // if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS;
  19741. // if (ctor.SUBCLASSES.length > 0) ret.sub = sub;
  19742. // return ret;
  19743. // }
  19744. // return doitem(AST_Node).sub;
  19745. // }
  19746. exports.describe_ast = function() {
  19747. var out = OutputStream({ beautify: true });
  19748. function doitem(ctor) {
  19749. out.print("AST_" + ctor.TYPE);
  19750. var props = ctor.SELF_PROPS.filter(function(prop){
  19751. return !/^\$/.test(prop);
  19752. });
  19753. if (props.length > 0) {
  19754. out.space();
  19755. out.with_parens(function(){
  19756. props.forEach(function(prop, i){
  19757. if (i) out.space();
  19758. out.print(prop);
  19759. });
  19760. });
  19761. }
  19762. if (ctor.documentation) {
  19763. out.space();
  19764. out.print_string(ctor.documentation);
  19765. }
  19766. if (ctor.SUBCLASSES.length > 0) {
  19767. out.space();
  19768. out.with_block(function(){
  19769. ctor.SUBCLASSES.forEach(function(ctor, i){
  19770. out.indent();
  19771. doitem(ctor);
  19772. out.newline();
  19773. });
  19774. });
  19775. }
  19776. };
  19777. doitem(AST_Node);
  19778. return out + "";
  19779. };
  19780. });
  19781. /*jslint plusplus: true */
  19782. /*global define: false */
  19783. define('parse', ['./esprimaAdapter', 'lang'], function (esprima, lang) {
  19784. 'use strict';
  19785. function arrayToString(ary) {
  19786. var output = '[';
  19787. if (ary) {
  19788. ary.forEach(function (item, i) {
  19789. output += (i > 0 ? ',' : '') + '"' + lang.jsEscape(item) + '"';
  19790. });
  19791. }
  19792. output += ']';
  19793. return output;
  19794. }
  19795. //This string is saved off because JSLint complains
  19796. //about obj.arguments use, as 'reserved word'
  19797. var argPropName = 'arguments',
  19798. //Default object to use for "scope" checking for UMD identifiers.
  19799. emptyScope = {},
  19800. mixin = lang.mixin,
  19801. hasProp = lang.hasProp;
  19802. //From an esprima example for traversing its ast.
  19803. function traverse(object, visitor) {
  19804. var child;
  19805. if (!object) {
  19806. return;
  19807. }
  19808. if (visitor.call(null, object) === false) {
  19809. return false;
  19810. }
  19811. for (var i = 0, keys = Object.keys(object); i < keys.length; i++) {
  19812. child = object[keys[i]];
  19813. if (typeof child === 'object' && child !== null) {
  19814. if (traverse(child, visitor) === false) {
  19815. return false;
  19816. }
  19817. }
  19818. }
  19819. }
  19820. //Like traverse, but visitor returning false just
  19821. //stops that subtree analysis, not the rest of tree
  19822. //visiting.
  19823. function traverseBroad(object, visitor) {
  19824. var child;
  19825. if (!object) {
  19826. return;
  19827. }
  19828. if (visitor.call(null, object) === false) {
  19829. return false;
  19830. }
  19831. for (var i = 0, keys = Object.keys(object); i < keys.length; i++) {
  19832. child = object[key];
  19833. if (typeof child === 'object' && child !== null) {
  19834. traverseBroad(child, visitor);
  19835. }
  19836. }
  19837. }
  19838. /**
  19839. * Pulls out dependencies from an array literal with just string members.
  19840. * If string literals, will just return those string values in an array,
  19841. * skipping other items in the array.
  19842. *
  19843. * @param {Node} node an AST node.
  19844. *
  19845. * @returns {Array} an array of strings.
  19846. * If null is returned, then it means the input node was not a valid
  19847. * dependency.
  19848. */
  19849. function getValidDeps(node) {
  19850. if (!node || node.type !== 'ArrayExpression' || !node.elements) {
  19851. return;
  19852. }
  19853. var deps = [];
  19854. node.elements.some(function (elem) {
  19855. if (elem.type === 'Literal') {
  19856. deps.push(elem.value);
  19857. }
  19858. });
  19859. return deps.length ? deps : undefined;
  19860. }
  19861. // Detects regular or arrow function expressions as the desired expression
  19862. // type.
  19863. function isFnExpression(node) {
  19864. return (node && (node.type === 'FunctionExpression' ||
  19865. node.type === 'ArrowFunctionExpression'));
  19866. }
  19867. /**
  19868. * Main parse function. Returns a string of any valid require or
  19869. * define/require.def calls as part of one JavaScript source string.
  19870. * @param {String} moduleName the module name that represents this file.
  19871. * It is used to create a default define if there is not one already for the
  19872. * file. This allows properly tracing dependencies for builds. Otherwise, if
  19873. * the file just has a require() call, the file dependencies will not be
  19874. * properly reflected: the file will come before its dependencies.
  19875. * @param {String} moduleName
  19876. * @param {String} fileName
  19877. * @param {String} fileContents
  19878. * @param {Object} options optional options. insertNeedsDefine: true will
  19879. * add calls to require.needsDefine() if appropriate.
  19880. * @returns {String} JS source string or null, if no require or
  19881. * define/require.def calls are found.
  19882. */
  19883. function parse(moduleName, fileName, fileContents, options) {
  19884. options = options || {};
  19885. //Set up source input
  19886. var i, moduleCall, depString,
  19887. moduleDeps = [],
  19888. result = '',
  19889. moduleList = [],
  19890. needsDefine = true,
  19891. astRoot = esprima.parse(fileContents);
  19892. parse.recurse(astRoot, function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) {
  19893. if (!deps) {
  19894. deps = [];
  19895. }
  19896. if (callName === 'define' && (!name || name === moduleName)) {
  19897. needsDefine = false;
  19898. }
  19899. if (!name) {
  19900. //If there is no module name, the dependencies are for
  19901. //this file/default module name.
  19902. moduleDeps = moduleDeps.concat(deps);
  19903. } else {
  19904. moduleList.push({
  19905. name: name,
  19906. deps: deps
  19907. });
  19908. }
  19909. if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) {
  19910. return factoryIdentifier;
  19911. }
  19912. //If define was found, no need to dive deeper, unless
  19913. //the config explicitly wants to dig deeper.
  19914. return !!options.findNestedDependencies;
  19915. }, options);
  19916. if (options.insertNeedsDefine && needsDefine) {
  19917. result += 'require.needsDefine("' + moduleName + '");';
  19918. }
  19919. if (moduleDeps.length || moduleList.length) {
  19920. for (i = 0; i < moduleList.length; i++) {
  19921. moduleCall = moduleList[i];
  19922. if (result) {
  19923. result += '\n';
  19924. }
  19925. //If this is the main module for this file, combine any
  19926. //"anonymous" dependencies (could come from a nested require
  19927. //call) with this module.
  19928. if (moduleCall.name === moduleName) {
  19929. moduleCall.deps = moduleCall.deps.concat(moduleDeps);
  19930. moduleDeps = [];
  19931. }
  19932. depString = arrayToString(moduleCall.deps);
  19933. result += 'define("' + moduleCall.name + '",' +
  19934. depString + ');';
  19935. }
  19936. if (moduleDeps.length) {
  19937. if (result) {
  19938. result += '\n';
  19939. }
  19940. depString = arrayToString(moduleDeps);
  19941. result += 'define("' + moduleName + '",' + depString + ');';
  19942. }
  19943. }
  19944. return result || null;
  19945. }
  19946. parse.traverse = traverse;
  19947. parse.traverseBroad = traverseBroad;
  19948. parse.isFnExpression = isFnExpression;
  19949. /**
  19950. * Handles parsing a file recursively for require calls.
  19951. * @param {Array} parentNode the AST node to start with.
  19952. * @param {Function} onMatch function to call on a parse match.
  19953. * @param {Object} [options] This is normally the build config options if
  19954. * it is passed.
  19955. * @param {Object} [fnExpScope] holds list of function expresssion
  19956. * argument identifiers, set up internally, not passed in
  19957. */
  19958. parse.recurse = function (object, onMatch, options, fnExpScope) {
  19959. //Like traverse, but skips if branches that would not be processed
  19960. //after has application that results in tests of true or false boolean
  19961. //literal values.
  19962. var keys, child, result, i, params, param, tempObject,
  19963. hasHas = options && options.has;
  19964. fnExpScope = fnExpScope || emptyScope;
  19965. if (!object) {
  19966. return;
  19967. }
  19968. //If has replacement has resulted in if(true){} or if(false){}, take
  19969. //the appropriate branch and skip the other one.
  19970. if (hasHas && object.type === 'IfStatement' && object.test.type &&
  19971. object.test.type === 'Literal') {
  19972. if (object.test.value) {
  19973. //Take the if branch
  19974. this.recurse(object.consequent, onMatch, options, fnExpScope);
  19975. } else {
  19976. //Take the else branch
  19977. this.recurse(object.alternate, onMatch, options, fnExpScope);
  19978. }
  19979. } else {
  19980. result = this.parseNode(object, onMatch, fnExpScope);
  19981. if (result === false) {
  19982. return;
  19983. } else if (typeof result === 'string') {
  19984. return result;
  19985. }
  19986. //Build up a "scope" object that informs nested recurse calls if
  19987. //the define call references an identifier that is likely a UMD
  19988. //wrapped function expression argument.
  19989. //Catch (function(a) {... wrappers
  19990. if (object.type === 'ExpressionStatement' && object.expression &&
  19991. object.expression.type === 'CallExpression' && object.expression.callee &&
  19992. isFnExpression(object.expression.callee)) {
  19993. tempObject = object.expression.callee;
  19994. }
  19995. // Catch !function(a) {... wrappers
  19996. if (object.type === 'UnaryExpression' && object.argument &&
  19997. object.argument.type === 'CallExpression' && object.argument.callee &&
  19998. isFnExpression(object.argument.callee)) {
  19999. tempObject = object.argument.callee;
  20000. }
  20001. if (tempObject && tempObject.params && tempObject.params.length) {
  20002. params = tempObject.params;
  20003. fnExpScope = mixin({}, fnExpScope, true);
  20004. for (i = 0; i < params.length; i++) {
  20005. param = params[i];
  20006. if (param.type === 'Identifier') {
  20007. fnExpScope[param.name] = true;
  20008. }
  20009. }
  20010. }
  20011. for (i = 0, keys = Object.keys(object); i < keys.length; i++) {
  20012. child = object[keys[i]];
  20013. if (typeof child === 'object' && child !== null) {
  20014. result = this.recurse(child, onMatch, options, fnExpScope);
  20015. if (typeof result === 'string' && hasProp(fnExpScope, result)) {
  20016. //The result was still in fnExpScope so break. Otherwise,
  20017. //was a return from a a tree that had a UMD definition,
  20018. //but now out of that scope so keep siblings.
  20019. break;
  20020. }
  20021. }
  20022. }
  20023. //Check for an identifier for a factory function identifier being
  20024. //passed in as a function expression, indicating a UMD-type of
  20025. //wrapping.
  20026. if (typeof result === 'string') {
  20027. if (hasProp(fnExpScope, result)) {
  20028. //result still in scope, keep jumping out indicating the
  20029. //identifier still in use.
  20030. return result;
  20031. }
  20032. return;
  20033. }
  20034. }
  20035. };
  20036. /**
  20037. * Determines if the file defines the require/define module API.
  20038. * Specifically, it looks for the `define.amd = ` expression.
  20039. * @param {String} fileName
  20040. * @param {String} fileContents
  20041. * @returns {Boolean}
  20042. */
  20043. parse.definesRequire = function (fileName, fileContents) {
  20044. var foundDefine = false,
  20045. foundDefineAmd = false;
  20046. traverse(esprima.parse(fileContents), function (node) {
  20047. // Look for a top level declaration of a define, like
  20048. // var requirejs, require, define, off Program body.
  20049. if (node.type === 'Program' && node.body && node.body.length) {
  20050. foundDefine = node.body.some(function(bodyNode) {
  20051. // var define
  20052. if (bodyNode.type === 'VariableDeclaration') {
  20053. var decls = bodyNode.declarations;
  20054. if (decls) {
  20055. var hasVarDefine = decls.some(function(declNode) {
  20056. return (declNode.type === 'VariableDeclarator' &&
  20057. declNode.id &&
  20058. declNode.id.type === 'Identifier' &&
  20059. declNode.id.name === 'define');
  20060. });
  20061. if (hasVarDefine) {
  20062. return true;
  20063. }
  20064. }
  20065. }
  20066. // function define() {}
  20067. if (bodyNode.type === 'FunctionDeclaration' &&
  20068. bodyNode.id &&
  20069. bodyNode.id.type === 'Identifier' &&
  20070. bodyNode.id.name === 'define') {
  20071. return true;
  20072. }
  20073. });
  20074. }
  20075. // Need define variable found first, before detecting define.amd.
  20076. if (foundDefine && parse.hasDefineAmd(node)) {
  20077. foundDefineAmd = true;
  20078. //Stop traversal
  20079. return false;
  20080. }
  20081. });
  20082. return foundDefine && foundDefineAmd;
  20083. };
  20084. /**
  20085. * Finds require("") calls inside a CommonJS anonymous module wrapped in a
  20086. * define(function(require, exports, module){}) wrapper. These dependencies
  20087. * will be added to a modified define() call that lists the dependencies
  20088. * on the outside of the function.
  20089. * @param {String} fileName
  20090. * @param {String|Object} fileContents: a string of contents, or an already
  20091. * parsed AST tree.
  20092. * @returns {Array} an array of module names that are dependencies. Always
  20093. * returns an array, but could be of length zero.
  20094. */
  20095. parse.getAnonDeps = function (fileName, fileContents) {
  20096. var astRoot = typeof fileContents === 'string' ?
  20097. esprima.parse(fileContents) : fileContents,
  20098. defFunc = this.findAnonDefineFactory(astRoot);
  20099. return parse.getAnonDepsFromNode(defFunc);
  20100. };
  20101. /**
  20102. * Finds require("") calls inside a CommonJS anonymous module wrapped
  20103. * in a define function, given an AST node for the definition function.
  20104. * @param {Node} node the AST node for the definition function.
  20105. * @returns {Array} and array of dependency names. Can be of zero length.
  20106. */
  20107. parse.getAnonDepsFromNode = function (node) {
  20108. var deps = [],
  20109. funcArgLength;
  20110. if (node) {
  20111. this.findRequireDepNames(node, deps);
  20112. //If no deps, still add the standard CommonJS require, exports,
  20113. //module, in that order, to the deps, but only if specified as
  20114. //function args. In particular, if exports is used, it is favored
  20115. //over the return value of the function, so only add it if asked.
  20116. funcArgLength = node.params && node.params.length;
  20117. if (funcArgLength) {
  20118. deps = (funcArgLength > 1 ? ["require", "exports", "module"] :
  20119. ["require"]).concat(deps);
  20120. }
  20121. }
  20122. return deps;
  20123. };
  20124. parse.isDefineNodeWithArgs = function (node) {
  20125. return node && node.type === 'CallExpression' &&
  20126. node.callee && node.callee.type === 'Identifier' &&
  20127. node.callee.name === 'define' && node[argPropName];
  20128. };
  20129. /**
  20130. * Finds the function in define(function (require, exports, module){});
  20131. * @param {Array} node
  20132. * @returns {Boolean}
  20133. */
  20134. parse.findAnonDefineFactory = function (node) {
  20135. var match;
  20136. traverse(node, function (node) {
  20137. var arg0, arg1;
  20138. if (parse.isDefineNodeWithArgs(node)) {
  20139. //Just the factory function passed to define
  20140. arg0 = node[argPropName][0];
  20141. if (isFnExpression(arg0)) {
  20142. match = arg0;
  20143. return false;
  20144. }
  20145. //A string literal module ID followed by the factory function.
  20146. arg1 = node[argPropName][1];
  20147. if (arg0.type === 'Literal' && isFnExpression(arg1)) {
  20148. match = arg1;
  20149. return false;
  20150. }
  20151. }
  20152. });
  20153. return match;
  20154. };
  20155. /**
  20156. * Finds any config that is passed to requirejs. That includes calls to
  20157. * require/requirejs.config(), as well as require({}, ...) and
  20158. * requirejs({}, ...)
  20159. * @param {String} fileContents
  20160. *
  20161. * @returns {Object} a config details object with the following properties:
  20162. * - config: {Object} the config object found. Can be undefined if no
  20163. * config found.
  20164. * - range: {Array} the start index and end index in the contents where
  20165. * the config was found. Can be undefined if no config found.
  20166. * Can throw an error if the config in the file cannot be evaluated in
  20167. * a build context to valid JavaScript.
  20168. */
  20169. parse.findConfig = function (fileContents) {
  20170. /*jslint evil: true */
  20171. var jsConfig, foundConfig, stringData, foundRange, quote, quoteMatch,
  20172. quoteRegExp = /(:\s|\[\s*)(['"])/,
  20173. astRoot = esprima.parse(fileContents, {
  20174. loc: true
  20175. });
  20176. traverse(astRoot, function (node) {
  20177. var arg,
  20178. requireType = parse.hasRequire(node);
  20179. if (requireType && (requireType === 'require' ||
  20180. requireType === 'requirejs' ||
  20181. requireType === 'requireConfig' ||
  20182. requireType === 'requirejsConfig')) {
  20183. arg = node[argPropName] && node[argPropName][0];
  20184. if (arg && arg.type === 'ObjectExpression') {
  20185. stringData = parse.nodeToString(fileContents, arg);
  20186. jsConfig = stringData.value;
  20187. foundRange = stringData.range;
  20188. return false;
  20189. }
  20190. } else {
  20191. arg = parse.getRequireObjectLiteral(node);
  20192. if (arg) {
  20193. stringData = parse.nodeToString(fileContents, arg);
  20194. jsConfig = stringData.value;
  20195. foundRange = stringData.range;
  20196. return false;
  20197. }
  20198. }
  20199. });
  20200. if (jsConfig) {
  20201. // Eval the config
  20202. quoteMatch = quoteRegExp.exec(jsConfig);
  20203. quote = (quoteMatch && quoteMatch[2]) || '"';
  20204. foundConfig = eval('(' + jsConfig + ')');
  20205. }
  20206. return {
  20207. config: foundConfig,
  20208. range: foundRange,
  20209. quote: quote
  20210. };
  20211. };
  20212. /** Returns the node for the object literal assigned to require/requirejs,
  20213. * for holding a declarative config.
  20214. */
  20215. parse.getRequireObjectLiteral = function (node) {
  20216. if (node.id && node.id.type === 'Identifier' &&
  20217. (node.id.name === 'require' || node.id.name === 'requirejs') &&
  20218. node.init && node.init.type === 'ObjectExpression') {
  20219. return node.init;
  20220. }
  20221. };
  20222. /**
  20223. * Renames require/requirejs/define calls to be ns + '.' + require/requirejs/define
  20224. * Does *not* do .config calls though. See pragma.namespace for the complete
  20225. * set of namespace transforms. This function is used because require calls
  20226. * inside a define() call should not be renamed, so a simple regexp is not
  20227. * good enough.
  20228. * @param {String} fileContents the contents to transform.
  20229. * @param {String} ns the namespace, *not* including trailing dot.
  20230. * @return {String} the fileContents with the namespace applied
  20231. */
  20232. parse.renameNamespace = function (fileContents, ns) {
  20233. var lines,
  20234. locs = [],
  20235. astRoot = esprima.parse(fileContents, {
  20236. loc: true
  20237. });
  20238. parse.recurse(astRoot, function (callName, config, name, deps, node) {
  20239. locs.push(node.loc);
  20240. //Do not recurse into define functions, they should be using
  20241. //local defines.
  20242. return callName !== 'define';
  20243. }, {});
  20244. if (locs.length) {
  20245. lines = fileContents.split('\n');
  20246. //Go backwards through the found locs, adding in the namespace name
  20247. //in front.
  20248. locs.reverse();
  20249. locs.forEach(function (loc) {
  20250. var startIndex = loc.start.column,
  20251. //start.line is 1-based, not 0 based.
  20252. lineIndex = loc.start.line - 1,
  20253. line = lines[lineIndex];
  20254. lines[lineIndex] = line.substring(0, startIndex) +
  20255. ns + '.' +
  20256. line.substring(startIndex,
  20257. line.length);
  20258. });
  20259. fileContents = lines.join('\n');
  20260. }
  20261. return fileContents;
  20262. };
  20263. /**
  20264. * Finds all dependencies specified in dependency arrays and inside
  20265. * simplified commonjs wrappers.
  20266. * @param {String} fileName
  20267. * @param {String} fileContents
  20268. *
  20269. * @returns {Array} an array of dependency strings. The dependencies
  20270. * have not been normalized, they may be relative IDs.
  20271. */
  20272. parse.findDependencies = function (fileName, fileContents, options) {
  20273. var dependencies = [],
  20274. astRoot = esprima.parse(fileContents);
  20275. parse.recurse(astRoot, function (callName, config, name, deps) {
  20276. if (deps) {
  20277. dependencies = dependencies.concat(deps);
  20278. }
  20279. }, options);
  20280. return dependencies;
  20281. };
  20282. /**
  20283. * Finds only CJS dependencies, ones that are the form
  20284. * require('stringLiteral')
  20285. */
  20286. parse.findCjsDependencies = function (fileName, fileContents) {
  20287. var dependencies = [];
  20288. traverse(esprima.parse(fileContents), function (node) {
  20289. var arg;
  20290. if (node && node.type === 'CallExpression' && node.callee &&
  20291. node.callee.type === 'Identifier' &&
  20292. node.callee.name === 'require' && node[argPropName] &&
  20293. node[argPropName].length === 1) {
  20294. arg = node[argPropName][0];
  20295. if (arg.type === 'Literal') {
  20296. dependencies.push(arg.value);
  20297. }
  20298. }
  20299. });
  20300. return dependencies;
  20301. };
  20302. //function define() {}
  20303. parse.hasDefDefine = function (node) {
  20304. return node.type === 'FunctionDeclaration' && node.id &&
  20305. node.id.type === 'Identifier' && node.id.name === 'define';
  20306. };
  20307. //define.amd = ...
  20308. parse.hasDefineAmd = function (node) {
  20309. return node && node.type === 'AssignmentExpression' &&
  20310. node.left && node.left.type === 'MemberExpression' &&
  20311. node.left.object && node.left.object.name === 'define' &&
  20312. node.left.property && node.left.property.name === 'amd';
  20313. };
  20314. //define.amd reference, as in: if (define.amd)
  20315. parse.refsDefineAmd = function (node) {
  20316. return node && node.type === 'MemberExpression' &&
  20317. node.object && node.object.name === 'define' &&
  20318. node.object.type === 'Identifier' &&
  20319. node.property && node.property.name === 'amd' &&
  20320. node.property.type === 'Identifier';
  20321. };
  20322. //require(), requirejs(), require.config() and requirejs.config()
  20323. parse.hasRequire = function (node) {
  20324. var callName,
  20325. c = node && node.callee;
  20326. if (node && node.type === 'CallExpression' && c) {
  20327. if (c.type === 'Identifier' &&
  20328. (c.name === 'require' ||
  20329. c.name === 'requirejs')) {
  20330. //A require/requirejs({}, ...) call
  20331. callName = c.name;
  20332. } else if (c.type === 'MemberExpression' &&
  20333. c.object &&
  20334. c.object.type === 'Identifier' &&
  20335. (c.object.name === 'require' ||
  20336. c.object.name === 'requirejs') &&
  20337. c.property && c.property.name === 'config') {
  20338. // require/requirejs.config({}) call
  20339. callName = c.object.name + 'Config';
  20340. }
  20341. }
  20342. return callName;
  20343. };
  20344. //define()
  20345. parse.hasDefine = function (node) {
  20346. return node && node.type === 'CallExpression' && node.callee &&
  20347. node.callee.type === 'Identifier' &&
  20348. node.callee.name === 'define';
  20349. };
  20350. /**
  20351. * If there is a named define in the file, returns the name. Does not
  20352. * scan for mulitple names, just the first one.
  20353. */
  20354. parse.getNamedDefine = function (fileContents) {
  20355. var name;
  20356. traverse(esprima.parse(fileContents), function (node) {
  20357. if (node && node.type === 'CallExpression' && node.callee &&
  20358. node.callee.type === 'Identifier' &&
  20359. node.callee.name === 'define' &&
  20360. node[argPropName] && node[argPropName][0] &&
  20361. node[argPropName][0].type === 'Literal') {
  20362. name = node[argPropName][0].value;
  20363. return false;
  20364. }
  20365. });
  20366. return name;
  20367. };
  20368. /**
  20369. * Finds all the named define module IDs in a file.
  20370. */
  20371. parse.getAllNamedDefines = function (fileContents, excludeMap) {
  20372. var names = [];
  20373. parse.recurse(esprima.parse(fileContents),
  20374. function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) {
  20375. if (callName === 'define' && name) {
  20376. if (!excludeMap.hasOwnProperty(name)) {
  20377. names.push(name);
  20378. }
  20379. }
  20380. //If a UMD definition that points to a factory that is an Identifier,
  20381. //indicate processing should not traverse inside the UMD definition.
  20382. if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) {
  20383. return factoryIdentifier;
  20384. }
  20385. //If define was found, no need to dive deeper, unless
  20386. //the config explicitly wants to dig deeper.
  20387. return true;
  20388. }, {});
  20389. return names;
  20390. };
  20391. /**
  20392. * Determines if define(), require({}|[]) or requirejs was called in the
  20393. * file. Also finds out if define() is declared and if define.amd is called.
  20394. */
  20395. parse.usesAmdOrRequireJs = function (fileName, fileContents) {
  20396. var uses;
  20397. traverse(esprima.parse(fileContents), function (node) {
  20398. var type, callName, arg;
  20399. if (parse.hasDefDefine(node)) {
  20400. //function define() {}
  20401. type = 'declaresDefine';
  20402. } else if (parse.hasDefineAmd(node)) {
  20403. type = 'defineAmd';
  20404. } else {
  20405. callName = parse.hasRequire(node);
  20406. if (callName) {
  20407. arg = node[argPropName] && node[argPropName][0];
  20408. if (arg && (arg.type === 'ObjectExpression' ||
  20409. arg.type === 'ArrayExpression')) {
  20410. type = callName;
  20411. }
  20412. } else if (parse.hasDefine(node)) {
  20413. type = 'define';
  20414. }
  20415. }
  20416. if (type) {
  20417. if (!uses) {
  20418. uses = {};
  20419. }
  20420. uses[type] = true;
  20421. }
  20422. });
  20423. return uses;
  20424. };
  20425. /**
  20426. * Determines if require(''), exports.x =, module.exports =,
  20427. * __dirname, __filename are used. So, not strictly traditional CommonJS,
  20428. * also checks for Node variants.
  20429. */
  20430. parse.usesCommonJs = function (fileName, fileContents) {
  20431. var uses = null,
  20432. assignsExports = false;
  20433. traverse(esprima.parse(fileContents), function (node) {
  20434. var type,
  20435. exp = node.expression || node.init;
  20436. if (node.type === 'Identifier' &&
  20437. (node.name === '__dirname' || node.name === '__filename')) {
  20438. type = node.name.substring(2);
  20439. } else if (node.type === 'VariableDeclarator' && node.id &&
  20440. node.id.type === 'Identifier' &&
  20441. node.id.name === 'exports') {
  20442. //Hmm, a variable assignment for exports, so does not use cjs
  20443. //exports.
  20444. type = 'varExports';
  20445. } else if (exp && exp.type === 'AssignmentExpression' && exp.left &&
  20446. exp.left.type === 'MemberExpression' && exp.left.object) {
  20447. if (exp.left.object.name === 'module' && exp.left.property &&
  20448. exp.left.property.name === 'exports') {
  20449. type = 'moduleExports';
  20450. } else if (exp.left.object.name === 'exports' &&
  20451. exp.left.property) {
  20452. type = 'exports';
  20453. } else if (exp.left.object.type === 'MemberExpression' &&
  20454. exp.left.object.object.name === 'module' &&
  20455. exp.left.object.property.name === 'exports' &&
  20456. exp.left.object.property.type === 'Identifier') {
  20457. type = 'moduleExports';
  20458. }
  20459. } else if (node && node.type === 'CallExpression' && node.callee &&
  20460. node.callee.type === 'Identifier' &&
  20461. node.callee.name === 'require' && node[argPropName] &&
  20462. node[argPropName].length === 1 &&
  20463. node[argPropName][0].type === 'Literal') {
  20464. type = 'require';
  20465. }
  20466. if (type) {
  20467. if (type === 'varExports') {
  20468. assignsExports = true;
  20469. } else if (type !== 'exports' || !assignsExports) {
  20470. if (!uses) {
  20471. uses = {};
  20472. }
  20473. uses[type] = true;
  20474. }
  20475. }
  20476. });
  20477. return uses;
  20478. };
  20479. parse.findRequireDepNames = function (node, deps) {
  20480. traverse(node, function (node) {
  20481. var arg;
  20482. if (node && node.type === 'CallExpression' && node.callee &&
  20483. node.callee.type === 'Identifier' &&
  20484. node.callee.name === 'require' &&
  20485. node[argPropName] && node[argPropName].length === 1) {
  20486. arg = node[argPropName][0];
  20487. if (arg.type === 'Literal') {
  20488. deps.push(arg.value);
  20489. }
  20490. }
  20491. });
  20492. };
  20493. /**
  20494. * Determines if a specific node is a valid require or define/require.def
  20495. * call.
  20496. * @param {Array} node
  20497. * @param {Function} onMatch a function to call when a match is found.
  20498. * It is passed the match name, and the config, name, deps possible args.
  20499. * The config, name and deps args are not normalized.
  20500. * @param {Object} fnExpScope an object whose keys are all function
  20501. * expression identifiers that should be in scope. Useful for UMD wrapper
  20502. * detection to avoid parsing more into the wrapped UMD code.
  20503. *
  20504. * @returns {String} a JS source string with the valid require/define call.
  20505. * Otherwise null.
  20506. */
  20507. parse.parseNode = function (node, onMatch, fnExpScope) {
  20508. var name, deps, cjsDeps, arg, factory, exp, refsDefine, bodyNode,
  20509. args = node && node[argPropName],
  20510. callName = parse.hasRequire(node),
  20511. isUmd = false;
  20512. if (callName === 'require' || callName === 'requirejs') {
  20513. //A plain require/requirejs call
  20514. arg = node[argPropName] && node[argPropName][0];
  20515. if (arg && arg.type !== 'ArrayExpression') {
  20516. if (arg.type === 'ObjectExpression') {
  20517. //A config call, try the second arg.
  20518. arg = node[argPropName][1];
  20519. }
  20520. }
  20521. deps = getValidDeps(arg);
  20522. if (!deps) {
  20523. return;
  20524. }
  20525. return onMatch("require", null, null, deps, node);
  20526. } else if (parse.hasDefine(node) && args && args.length) {
  20527. name = args[0];
  20528. deps = args[1];
  20529. factory = args[2];
  20530. if (name.type === 'ArrayExpression') {
  20531. //No name, adjust args
  20532. factory = deps;
  20533. deps = name;
  20534. name = null;
  20535. } else if (isFnExpression(name)) {
  20536. //Just the factory, no name or deps
  20537. factory = name;
  20538. name = deps = null;
  20539. } else if (name.type === 'Identifier' && args.length === 1 &&
  20540. hasProp(fnExpScope, name.name)) {
  20541. //define(e) where e is a UMD identifier for the factory
  20542. //function.
  20543. isUmd = true;
  20544. factory = name;
  20545. name = null;
  20546. } else if (name.type !== 'Literal') {
  20547. //An object literal, just null out
  20548. name = deps = factory = null;
  20549. }
  20550. if (name && name.type === 'Literal' && deps) {
  20551. if (isFnExpression(deps)) {
  20552. //deps is the factory
  20553. factory = deps;
  20554. deps = null;
  20555. } else if (deps.type === 'ObjectExpression') {
  20556. //deps is object literal, null out
  20557. deps = factory = null;
  20558. } else if (deps.type === 'Identifier') {
  20559. if (args.length === 2) {
  20560. //define('id', factory)
  20561. deps = factory = null;
  20562. } else if (args.length === 3 && isFnExpression(factory)) {
  20563. //define('id', depsIdentifier, factory)
  20564. //Since identifier, cannot know the deps, but do not
  20565. //error out, assume they are taken care of outside of
  20566. //static parsing.
  20567. deps = null;
  20568. }
  20569. }
  20570. }
  20571. if (deps && deps.type === 'ArrayExpression') {
  20572. deps = getValidDeps(deps);
  20573. } else if (isFnExpression(factory)) {
  20574. //If no deps and a factory function, could be a commonjs sugar
  20575. //wrapper, scan the function for dependencies.
  20576. cjsDeps = parse.getAnonDepsFromNode(factory);
  20577. if (cjsDeps.length) {
  20578. deps = cjsDeps;
  20579. }
  20580. } else if (deps || (factory && !isUmd)) {
  20581. //Does not match the shape of an AMD call.
  20582. return;
  20583. }
  20584. //Just save off the name as a string instead of an AST object.
  20585. if (name && name.type === 'Literal') {
  20586. name = name.value;
  20587. }
  20588. return onMatch("define", null, name, deps, node,
  20589. (factory && factory.type === 'Identifier' ? factory.name : undefined),
  20590. fnExpScope);
  20591. } else if (node.type === 'CallExpression' && node.callee &&
  20592. isFnExpression(node.callee) &&
  20593. node.callee.body && node.callee.body.body &&
  20594. node.callee.body.body.length === 1 &&
  20595. node.callee.body.body[0].type === 'IfStatement') {
  20596. bodyNode = node.callee.body.body[0];
  20597. //Look for a define(Identifier) case, but only if inside an
  20598. //if that has a define.amd test
  20599. if (bodyNode.consequent && bodyNode.consequent.body) {
  20600. exp = bodyNode.consequent.body[0];
  20601. if (exp.type === 'ExpressionStatement' && exp.expression &&
  20602. parse.hasDefine(exp.expression) &&
  20603. exp.expression.arguments &&
  20604. exp.expression.arguments.length === 1 &&
  20605. exp.expression.arguments[0].type === 'Identifier') {
  20606. //Calls define(Identifier) as first statement in body.
  20607. //Confirm the if test references define.amd
  20608. traverse(bodyNode.test, function (node) {
  20609. if (parse.refsDefineAmd(node)) {
  20610. refsDefine = true;
  20611. return false;
  20612. }
  20613. });
  20614. if (refsDefine) {
  20615. return onMatch("define", null, null, null, exp.expression,
  20616. exp.expression.arguments[0].name, fnExpScope);
  20617. }
  20618. }
  20619. }
  20620. }
  20621. };
  20622. /**
  20623. * Converts an AST node into a JS source string by extracting
  20624. * the node's location from the given contents string. Assumes
  20625. * esprima.parse() with loc was done.
  20626. * @param {String} contents
  20627. * @param {Object} node
  20628. * @returns {String} a JS source string.
  20629. */
  20630. parse.nodeToString = function (contents, node) {
  20631. var extracted,
  20632. loc = node.loc,
  20633. lines = contents.split('\n'),
  20634. firstLine = loc.start.line > 1 ?
  20635. lines.slice(0, loc.start.line - 1).join('\n') + '\n' :
  20636. '',
  20637. preamble = firstLine +
  20638. lines[loc.start.line - 1].substring(0, loc.start.column);
  20639. if (loc.start.line === loc.end.line) {
  20640. extracted = lines[loc.start.line - 1].substring(loc.start.column,
  20641. loc.end.column);
  20642. } else {
  20643. extracted = lines[loc.start.line - 1].substring(loc.start.column) +
  20644. '\n' +
  20645. lines.slice(loc.start.line, loc.end.line - 1).join('\n') +
  20646. '\n' +
  20647. lines[loc.end.line - 1].substring(0, loc.end.column);
  20648. }
  20649. return {
  20650. value: extracted,
  20651. range: [
  20652. preamble.length,
  20653. preamble.length + extracted.length
  20654. ]
  20655. };
  20656. };
  20657. /**
  20658. * Extracts license comments from JS text.
  20659. * @param {String} fileName
  20660. * @param {String} contents
  20661. * @returns {String} a string of license comments.
  20662. */
  20663. parse.getLicenseComments = function (fileName, contents) {
  20664. var commentNode, refNode, subNode, value, i, j,
  20665. //xpconnect's Reflect does not support comment or range, but
  20666. //prefer continued operation vs strict parity of operation,
  20667. //as license comments can be expressed in other ways, like
  20668. //via wrap args, or linked via sourcemaps.
  20669. ast = esprima.parse(contents, {
  20670. comment: true,
  20671. range: true
  20672. }),
  20673. result = '',
  20674. existsMap = {},
  20675. lineEnd = contents.indexOf('\r') === -1 ? '\n' : '\r\n';
  20676. if (ast.comments) {
  20677. for (i = 0; i < ast.comments.length; i++) {
  20678. commentNode = ast.comments[i];
  20679. if (commentNode.type === 'Line') {
  20680. value = '//' + commentNode.value + lineEnd;
  20681. refNode = commentNode;
  20682. if (i + 1 >= ast.comments.length) {
  20683. value += lineEnd;
  20684. } else {
  20685. //Look for immediately adjacent single line comments
  20686. //since it could from a multiple line comment made out
  20687. //of single line comments. Like this comment.
  20688. for (j = i + 1; j < ast.comments.length; j++) {
  20689. subNode = ast.comments[j];
  20690. if (subNode.type === 'Line' &&
  20691. subNode.range[0] === refNode.range[1] + 1) {
  20692. //Adjacent single line comment. Collect it.
  20693. value += '//' + subNode.value + lineEnd;
  20694. refNode = subNode;
  20695. } else {
  20696. //No more single line comment blocks. Break out
  20697. //and continue outer looping.
  20698. break;
  20699. }
  20700. }
  20701. value += lineEnd;
  20702. i = j - 1;
  20703. }
  20704. } else {
  20705. value = '/*' + commentNode.value + '*/' + lineEnd + lineEnd;
  20706. }
  20707. if (!existsMap[value] && (value.indexOf('license') !== -1 ||
  20708. (commentNode.type === 'Block' &&
  20709. value.indexOf('/*!') === 0) ||
  20710. value.indexOf('opyright') !== -1 ||
  20711. value.indexOf('(c)') !== -1)) {
  20712. result += value;
  20713. existsMap[value] = true;
  20714. }
  20715. }
  20716. }
  20717. return result;
  20718. };
  20719. return parse;
  20720. });
  20721. /*global define */
  20722. define('transform', [ './esprimaAdapter', './parse', 'logger', 'lang'],
  20723. function (esprima, parse, logger, lang) {
  20724. 'use strict';
  20725. var transform,
  20726. baseIndentRegExp = /^([ \t]+)/,
  20727. indentRegExp = /\{[\r\n]+([ \t]+)/,
  20728. keyRegExp = /^[_A-Za-z]([A-Za-z\d_]*)$/,
  20729. bulkIndentRegExps = {
  20730. '\n': /\n/g,
  20731. '\r\n': /\r\n/g
  20732. };
  20733. function applyIndent(str, indent, lineReturn) {
  20734. var regExp = bulkIndentRegExps[lineReturn];
  20735. return str.replace(regExp, '$&' + indent);
  20736. }
  20737. transform = {
  20738. toTransport: function (namespace, moduleName, path, contents, onFound, options) {
  20739. options = options || {};
  20740. var astRoot, contentLines, modLine,
  20741. foundAnon,
  20742. scanCount = 0,
  20743. scanReset = false,
  20744. defineInfos = [],
  20745. applySourceUrl = function (contents) {
  20746. if (options.useSourceUrl) {
  20747. contents = 'eval("' + lang.jsEscape(contents) +
  20748. '\\n//# sourceURL=' + (path.indexOf('/') === 0 ? '' : '/') +
  20749. path +
  20750. '");\n';
  20751. }
  20752. return contents;
  20753. };
  20754. try {
  20755. astRoot = esprima.parse(contents, {
  20756. loc: true
  20757. });
  20758. } catch (e) {
  20759. logger.trace('toTransport skipping ' + path + ': ' +
  20760. e.toString());
  20761. return contents;
  20762. }
  20763. //Find the define calls and their position in the files.
  20764. parse.traverse(astRoot, function (node) {
  20765. var args, firstArg, firstArgLoc, factoryNode,
  20766. needsId, depAction, foundId, init,
  20767. sourceUrlData, range,
  20768. namespaceExists = false;
  20769. // If a bundle script with a define declaration, do not
  20770. // parse any further at this level. Likely a built layerobj
  20771. // by some other tool.
  20772. if (node.type === 'VariableDeclarator' &&
  20773. node.id && node.id.name === 'define' &&
  20774. node.id.type === 'Identifier') {
  20775. init = node.init;
  20776. if (init && init.callee &&
  20777. init.callee.type === 'CallExpression' &&
  20778. init.callee.callee &&
  20779. init.callee.callee.type === 'Identifier' &&
  20780. init.callee.callee.name === 'require' &&
  20781. init.callee.arguments && init.callee.arguments.length === 1 &&
  20782. init.callee.arguments[0].type === 'Literal' &&
  20783. init.callee.arguments[0].value &&
  20784. init.callee.arguments[0].value.indexOf('amdefine') !== -1) {
  20785. // the var define = require('amdefine')(module) case,
  20786. // keep going in that case.
  20787. } else {
  20788. return false;
  20789. }
  20790. }
  20791. namespaceExists = namespace &&
  20792. node.type === 'CallExpression' &&
  20793. node.callee && node.callee.object &&
  20794. node.callee.object.type === 'Identifier' &&
  20795. node.callee.object.name === namespace &&
  20796. node.callee.property.type === 'Identifier' &&
  20797. node.callee.property.name === 'define';
  20798. if (namespaceExists || parse.isDefineNodeWithArgs(node)) {
  20799. //The arguments are where its at.
  20800. args = node.arguments;
  20801. if (!args || !args.length) {
  20802. return;
  20803. }
  20804. firstArg = args[0];
  20805. firstArgLoc = firstArg.loc;
  20806. if (args.length === 1) {
  20807. if (firstArg.type === 'Identifier') {
  20808. //The define(factory) case, but
  20809. //only allow it if one Identifier arg,
  20810. //to limit impact of false positives.
  20811. needsId = true;
  20812. depAction = 'empty';
  20813. } else if (parse.isFnExpression(firstArg)) {
  20814. //define(function(){})
  20815. factoryNode = firstArg;
  20816. needsId = true;
  20817. depAction = 'scan';
  20818. } else if (firstArg.type === 'ObjectExpression') {
  20819. //define({});
  20820. needsId = true;
  20821. depAction = 'skip';
  20822. } else if (firstArg.type === 'Literal' &&
  20823. typeof firstArg.value === 'number') {
  20824. //define('12345');
  20825. needsId = true;
  20826. depAction = 'skip';
  20827. } else if (firstArg.type === 'UnaryExpression' &&
  20828. firstArg.operator === '-' &&
  20829. firstArg.argument &&
  20830. firstArg.argument.type === 'Literal' &&
  20831. typeof firstArg.argument.value === 'number') {
  20832. //define('-12345');
  20833. needsId = true;
  20834. depAction = 'skip';
  20835. } else if (firstArg.type === 'MemberExpression' &&
  20836. firstArg.object &&
  20837. firstArg.property &&
  20838. firstArg.property.type === 'Identifier') {
  20839. //define(this.key);
  20840. needsId = true;
  20841. depAction = 'empty';
  20842. }
  20843. } else if (firstArg.type === 'ArrayExpression') {
  20844. //define([], ...);
  20845. needsId = true;
  20846. depAction = 'skip';
  20847. } else if (firstArg.type === 'Literal' &&
  20848. typeof firstArg.value === 'string') {
  20849. //define('string', ....)
  20850. //Already has an ID.
  20851. needsId = false;
  20852. if (args.length === 2 &&
  20853. parse.isFnExpression(args[1])) {
  20854. //Needs dependency scanning.
  20855. factoryNode = args[1];
  20856. depAction = 'scan';
  20857. } else {
  20858. depAction = 'skip';
  20859. }
  20860. } else {
  20861. //Unknown define entity, keep looking, even
  20862. //in the subtree for this node.
  20863. return;
  20864. }
  20865. range = {
  20866. foundId: foundId,
  20867. needsId: needsId,
  20868. depAction: depAction,
  20869. namespaceExists: namespaceExists,
  20870. node: node,
  20871. defineLoc: node.loc,
  20872. firstArgLoc: firstArgLoc,
  20873. factoryNode: factoryNode,
  20874. sourceUrlData: sourceUrlData
  20875. };
  20876. //Only transform ones that do not have IDs. If it has an
  20877. //ID but no dependency array, assume it is something like
  20878. //a phonegap implementation, that has its own internal
  20879. //define that cannot handle dependency array constructs,
  20880. //and if it is a named module, then it means it has been
  20881. //set for transport form.
  20882. if (range.needsId) {
  20883. if (foundAnon) {
  20884. logger.trace(path + ' has more than one anonymous ' +
  20885. 'define. May be a built file from another ' +
  20886. 'build system like, Ender. Skipping normalization.');
  20887. defineInfos = [];
  20888. return false;
  20889. } else {
  20890. foundAnon = range;
  20891. defineInfos.push(range);
  20892. }
  20893. } else if (depAction === 'scan') {
  20894. scanCount += 1;
  20895. if (scanCount > 1) {
  20896. //Just go back to an array that just has the
  20897. //anon one, since this is an already optimized
  20898. //file like the phonegap one.
  20899. if (!scanReset) {
  20900. defineInfos = foundAnon ? [foundAnon] : [];
  20901. scanReset = true;
  20902. }
  20903. } else {
  20904. defineInfos.push(range);
  20905. }
  20906. }
  20907. }
  20908. });
  20909. if (!defineInfos.length) {
  20910. return applySourceUrl(contents);
  20911. }
  20912. //Reverse the matches, need to start from the bottom of
  20913. //the file to modify it, so that the ranges are still true
  20914. //further up.
  20915. defineInfos.reverse();
  20916. contentLines = contents.split('\n');
  20917. modLine = function (loc, contentInsertion) {
  20918. var startIndex = loc.start.column,
  20919. //start.line is 1-based, not 0 based.
  20920. lineIndex = loc.start.line - 1,
  20921. line = contentLines[lineIndex];
  20922. contentLines[lineIndex] = line.substring(0, startIndex) +
  20923. contentInsertion +
  20924. line.substring(startIndex,
  20925. line.length);
  20926. };
  20927. defineInfos.forEach(function (info) {
  20928. var deps,
  20929. contentInsertion = '',
  20930. depString = '';
  20931. //Do the modifications "backwards", in other words, start with the
  20932. //one that is farthest down and work up, so that the ranges in the
  20933. //defineInfos still apply. So that means deps, id, then namespace.
  20934. if (info.needsId && moduleName) {
  20935. contentInsertion += "'" + moduleName + "',";
  20936. }
  20937. if (info.depAction === 'scan') {
  20938. deps = parse.getAnonDepsFromNode(info.factoryNode);
  20939. if (deps.length) {
  20940. depString = '[' + deps.map(function (dep) {
  20941. return "'" + dep + "'";
  20942. }) + ']';
  20943. } else {
  20944. depString = '[]';
  20945. }
  20946. depString += ',';
  20947. if (info.factoryNode) {
  20948. //Already have a named module, need to insert the
  20949. //dependencies after the name.
  20950. modLine(info.factoryNode.loc, depString);
  20951. } else {
  20952. contentInsertion += depString;
  20953. }
  20954. }
  20955. if (contentInsertion) {
  20956. modLine(info.firstArgLoc, contentInsertion);
  20957. }
  20958. //Do namespace last so that ui does not mess upthe parenRange
  20959. //used above.
  20960. if (namespace && !info.namespaceExists) {
  20961. modLine(info.defineLoc, namespace + '.');
  20962. }
  20963. //Notify any listener for the found info
  20964. if (onFound) {
  20965. onFound(info);
  20966. }
  20967. });
  20968. contents = contentLines.join('\n');
  20969. return applySourceUrl(contents);
  20970. },
  20971. /**
  20972. * Modify the contents of a require.config/requirejs.config call. This
  20973. * call will LOSE any existing comments that are in the config string.
  20974. *
  20975. * @param {String} fileContents String that may contain a config call
  20976. * @param {Function} onConfig Function called when the first config
  20977. * call is found. It will be passed an Object which is the current
  20978. * config, and the onConfig function should return an Object to use
  20979. * as the config.
  20980. * @return {String} the fileContents with the config changes applied.
  20981. */
  20982. modifyConfig: function (fileContents, onConfig) {
  20983. var details = parse.findConfig(fileContents),
  20984. config = details.config;
  20985. if (config) {
  20986. config = onConfig(config);
  20987. if (config) {
  20988. return transform.serializeConfig(config,
  20989. fileContents,
  20990. details.range[0],
  20991. details.range[1],
  20992. {
  20993. quote: details.quote
  20994. });
  20995. }
  20996. }
  20997. return fileContents;
  20998. },
  20999. serializeConfig: function (config, fileContents, start, end, options) {
  21000. //Calculate base level of indent
  21001. var indent, match, configString, outDentRegExp,
  21002. baseIndent = '',
  21003. startString = fileContents.substring(0, start),
  21004. existingConfigString = fileContents.substring(start, end),
  21005. lineReturn = existingConfigString.indexOf('\r') === -1 ? '\n' : '\r\n',
  21006. lastReturnIndex = startString.lastIndexOf('\n');
  21007. //Get the basic amount of indent for the require config call.
  21008. if (lastReturnIndex === -1) {
  21009. lastReturnIndex = 0;
  21010. }
  21011. match = baseIndentRegExp.exec(startString.substring(lastReturnIndex + 1, start));
  21012. if (match && match[1]) {
  21013. baseIndent = match[1];
  21014. }
  21015. //Calculate internal indentation for config
  21016. match = indentRegExp.exec(existingConfigString);
  21017. if (match && match[1]) {
  21018. indent = match[1];
  21019. }
  21020. if (!indent || indent.length < baseIndent) {
  21021. indent = ' ';
  21022. } else {
  21023. indent = indent.substring(baseIndent.length);
  21024. }
  21025. outDentRegExp = new RegExp('(' + lineReturn + ')' + indent, 'g');
  21026. configString = transform.objectToString(config, {
  21027. indent: indent,
  21028. lineReturn: lineReturn,
  21029. outDentRegExp: outDentRegExp,
  21030. quote: options && options.quote
  21031. });
  21032. //Add in the base indenting level.
  21033. configString = applyIndent(configString, baseIndent, lineReturn);
  21034. return startString + configString + fileContents.substring(end);
  21035. },
  21036. /**
  21037. * Tries converting a JS object to a string. This will likely suck, and
  21038. * is tailored to the type of config expected in a loader config call.
  21039. * So, hasOwnProperty fields, strings, numbers, arrays and functions,
  21040. * no weird recursively referenced stuff.
  21041. * @param {Object} obj the object to convert
  21042. * @param {Object} options options object with the following values:
  21043. * {String} indent the indentation to use for each level
  21044. * {String} lineReturn the type of line return to use
  21045. * {outDentRegExp} outDentRegExp the regexp to use to outdent functions
  21046. * {String} quote the quote type to use, ' or ". Optional. Default is "
  21047. * @param {String} totalIndent the total indent to print for this level
  21048. * @return {String} a string representation of the object.
  21049. */
  21050. objectToString: function (obj, options, totalIndent) {
  21051. var startBrace, endBrace, nextIndent,
  21052. first = true,
  21053. value = '',
  21054. lineReturn = options.lineReturn,
  21055. indent = options.indent,
  21056. outDentRegExp = options.outDentRegExp,
  21057. quote = options.quote || '"';
  21058. totalIndent = totalIndent || '';
  21059. nextIndent = totalIndent + indent;
  21060. if (obj === null) {
  21061. value = 'null';
  21062. } else if (obj === undefined) {
  21063. value = 'undefined';
  21064. } else if (typeof obj === 'number' || typeof obj === 'boolean') {
  21065. value = obj;
  21066. } else if (typeof obj === 'string') {
  21067. //Use double quotes in case the config may also work as JSON.
  21068. value = quote + lang.jsEscape(obj) + quote;
  21069. } else if (lang.isArray(obj)) {
  21070. lang.each(obj, function (item, i) {
  21071. value += (i !== 0 ? ',' + lineReturn : '' ) +
  21072. nextIndent +
  21073. transform.objectToString(item,
  21074. options,
  21075. nextIndent);
  21076. });
  21077. startBrace = '[';
  21078. endBrace = ']';
  21079. } else if (lang.isFunction(obj) || lang.isRegExp(obj)) {
  21080. //The outdent regexp just helps pretty up the conversion
  21081. //just in node. Rhino strips comments and does a different
  21082. //indent scheme for Function toString, so not really helpful
  21083. //there.
  21084. value = obj.toString().replace(outDentRegExp, '$1');
  21085. } else {
  21086. //An object
  21087. lang.eachProp(obj, function (v, prop) {
  21088. value += (first ? '': ',' + lineReturn) +
  21089. nextIndent +
  21090. (keyRegExp.test(prop) ? prop : quote + lang.jsEscape(prop) + quote )+
  21091. ': ' +
  21092. transform.objectToString(v,
  21093. options,
  21094. nextIndent);
  21095. first = false;
  21096. });
  21097. startBrace = '{';
  21098. endBrace = '}';
  21099. }
  21100. if (startBrace) {
  21101. value = startBrace +
  21102. lineReturn +
  21103. value +
  21104. lineReturn + totalIndent +
  21105. endBrace;
  21106. }
  21107. return value;
  21108. }
  21109. };
  21110. return transform;
  21111. });
  21112. /*jslint regexp: true, plusplus: true */
  21113. /*global define: false */
  21114. define('pragma', ['parse', 'logger'], function (parse, logger) {
  21115. 'use strict';
  21116. function Temp() {}
  21117. function create(obj, mixin) {
  21118. Temp.prototype = obj;
  21119. var temp = new Temp(), prop;
  21120. //Avoid any extra memory hanging around
  21121. Temp.prototype = null;
  21122. if (mixin) {
  21123. for (prop in mixin) {
  21124. if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) {
  21125. temp[prop] = mixin[prop];
  21126. }
  21127. }
  21128. }
  21129. return temp; // Object
  21130. }
  21131. var pragma = {
  21132. conditionalRegExp: /(exclude|include)Start\s*\(\s*["'](\w+)["']\s*,(.*)\)/,
  21133. useStrictRegExp: /(^|[^{]\r?\n)['"]use strict['"];/g,
  21134. hasRegExp: /has\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
  21135. configRegExp: /(^|[^\.])(requirejs|require)(\.config)\s*\(/g,
  21136. nsWrapRegExp: /\/\*requirejs namespace: true \*\//,
  21137. apiDefRegExp: /var requirejs,\s*require,\s*define;/,
  21138. defineCheckRegExp: /typeof(\s+|\s*\(\s*)define(\s*\))?\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd/g,
  21139. defineStringCheckRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\[\s*["']amd["']\s*\]/g,
  21140. defineTypeFirstCheckRegExp: /\s*["']function["']\s*==(=?)\s*typeof\s+define\s*&&\s*define\s*\.\s*amd/g,
  21141. defineJQueryRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd\s*&&\s*define\s*\.\s*amd\s*\.\s*jQuery/g,
  21142. defineHasRegExp: /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g,
  21143. defineTernaryRegExp: /typeof\s+define\s*===?\s*['"]function["']\s*&&\s*define\s*\.\s*amd\s*\?\s*define/,
  21144. defineExistsRegExp: /\s+typeof\s+define\s*!==?\s*['"]undefined["']\s*/,
  21145. defineExistsAndAmdRegExp: /typeof\s+define\s*!==?\s*['"]undefined["']\s*&&\s*define\s*\.\s*amd\s*/,
  21146. amdefineRegExp: /if\s*\(\s*typeof define\s*\!==\s*['"]function['"]\s*\)\s*\{\s*[^\{\}]+amdefine[^\{\}]+\}/g,
  21147. removeStrict: function (contents, config) {
  21148. return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '$1');
  21149. },
  21150. namespace: function (fileContents, ns, onLifecycleName) {
  21151. if (ns) {
  21152. //Namespace require/define calls
  21153. fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3(');
  21154. fileContents = parse.renameNamespace(fileContents, ns);
  21155. //Namespace define ternary use:
  21156. fileContents = fileContents.replace(pragma.defineTernaryRegExp,
  21157. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd ? " + ns + ".define");
  21158. //Namespace define jquery use:
  21159. fileContents = fileContents.replace(pragma.defineJQueryRegExp,
  21160. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd && " + ns + ".define.amd.jQuery");
  21161. //Namespace has.js define use:
  21162. fileContents = fileContents.replace(pragma.defineHasRegExp,
  21163. "typeof " + ns + ".define === 'function' && typeof " + ns + ".define.amd === 'object' && " + ns + ".define.amd");
  21164. //Namespace async.js define use:
  21165. fileContents = fileContents.replace(pragma.defineExistsAndAmdRegExp,
  21166. "typeof " + ns + ".define !== 'undefined' && " + ns + ".define.amd");
  21167. //Namespace define checks.
  21168. //Do these ones last, since they are a subset of the more specific
  21169. //checks above.
  21170. fileContents = fileContents.replace(pragma.defineCheckRegExp,
  21171. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd");
  21172. fileContents = fileContents.replace(pragma.defineStringCheckRegExp,
  21173. "typeof " + ns + ".define === 'function' && " + ns + ".define['amd']");
  21174. fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp,
  21175. "'function' === typeof " + ns + ".define && " + ns + ".define.amd");
  21176. fileContents = fileContents.replace(pragma.defineExistsRegExp,
  21177. "typeof " + ns + ".define !== 'undefined'");
  21178. //Check for require.js with the require/define definitions
  21179. if (pragma.apiDefRegExp.test(fileContents) &&
  21180. fileContents.indexOf("if (!" + ns + " || !" + ns + ".requirejs)") === -1) {
  21181. //Wrap the file contents in a typeof check, and a function
  21182. //to contain the API globals.
  21183. fileContents = "var " + ns + ";(function () { if (!" + ns + " || !" + ns + ".requirejs) {\n" +
  21184. "if (!" + ns + ") { " + ns + ' = {}; } else { require = ' + ns + '; }\n' +
  21185. fileContents +
  21186. "\n" +
  21187. ns + ".requirejs = requirejs;" +
  21188. ns + ".require = require;" +
  21189. ns + ".define = define;\n" +
  21190. "}\n}());";
  21191. }
  21192. //Finally, if the file wants a special wrapper because it ties
  21193. //in to the requirejs internals in a way that would not fit
  21194. //the above matches, do that. Look for /*requirejs namespace: true*/
  21195. if (pragma.nsWrapRegExp.test(fileContents)) {
  21196. //Remove the pragma.
  21197. fileContents = fileContents.replace(pragma.nsWrapRegExp, '');
  21198. //Alter the contents.
  21199. fileContents = '(function () {\n' +
  21200. 'var require = ' + ns + '.require,' +
  21201. 'requirejs = ' + ns + '.requirejs,' +
  21202. 'define = ' + ns + '.define;\n' +
  21203. fileContents +
  21204. '\n}());';
  21205. }
  21206. }
  21207. return fileContents;
  21208. },
  21209. /**
  21210. * processes the fileContents for some //>> conditional statements
  21211. */
  21212. process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) {
  21213. /*jslint evil: true */
  21214. var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine,
  21215. matches, type, marker, condition, isTrue, endRegExp, endMatches,
  21216. endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps,
  21217. i, dep, moduleName, collectorMod,
  21218. lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has,
  21219. //Legacy arg defined to help in dojo conversion script. Remove later
  21220. //when dojo no longer needs conversion:
  21221. kwArgs = pragmas;
  21222. //Mix in a specific lifecycle scoped object, to allow targeting
  21223. //some pragmas/has tests to only when files are saved, or at different
  21224. //lifecycle events. Do not bother with kwArgs in this section, since
  21225. //the old dojo kwArgs were for all points in the build lifecycle.
  21226. if (onLifecycleName) {
  21227. lifecyclePragmas = config['pragmas' + onLifecycleName];
  21228. lifecycleHas = config['has' + onLifecycleName];
  21229. if (lifecyclePragmas) {
  21230. pragmas = create(pragmas || {}, lifecyclePragmas);
  21231. }
  21232. if (lifecycleHas) {
  21233. hasConfig = create(hasConfig || {}, lifecycleHas);
  21234. }
  21235. }
  21236. //Replace has references if desired
  21237. if (hasConfig) {
  21238. fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) {
  21239. if (hasConfig.hasOwnProperty(test)) {
  21240. return !!hasConfig[test];
  21241. }
  21242. return match;
  21243. });
  21244. }
  21245. if (!config.skipPragmas) {
  21246. while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) {
  21247. //Found a conditional. Get the conditional line.
  21248. lineEndIndex = fileContents.indexOf("\n", foundIndex);
  21249. if (lineEndIndex === -1) {
  21250. lineEndIndex = fileContents.length - 1;
  21251. }
  21252. //Increment startIndex past the line so the next conditional search can be done.
  21253. startIndex = lineEndIndex + 1;
  21254. //Break apart the conditional.
  21255. conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1);
  21256. matches = conditionLine.match(pragma.conditionalRegExp);
  21257. if (matches) {
  21258. type = matches[1];
  21259. marker = matches[2];
  21260. condition = matches[3];
  21261. isTrue = false;
  21262. //See if the condition is true.
  21263. try {
  21264. isTrue = !!eval("(" + condition + ")");
  21265. } catch (e) {
  21266. throw "Error in file: " +
  21267. fileName +
  21268. ". Conditional comment: " +
  21269. conditionLine +
  21270. " failed with this error: " + e;
  21271. }
  21272. //Find the endpoint marker.
  21273. endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g");
  21274. endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length));
  21275. if (endMatches) {
  21276. endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length;
  21277. //Find the next line return based on the match position.
  21278. lineEndIndex = fileContents.indexOf("\n", endMarkerIndex);
  21279. if (lineEndIndex === -1) {
  21280. lineEndIndex = fileContents.length - 1;
  21281. }
  21282. //Should we include the segment?
  21283. shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue));
  21284. //Remove the conditional comments, and optionally remove the content inside
  21285. //the conditional comments.
  21286. startLength = startIndex - foundIndex;
  21287. fileContents = fileContents.substring(0, foundIndex) +
  21288. (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") +
  21289. fileContents.substring(lineEndIndex + 1, fileContents.length);
  21290. //Move startIndex to foundIndex, since that is the new position in the file
  21291. //where we need to look for more conditionals in the next while loop pass.
  21292. startIndex = foundIndex;
  21293. } else {
  21294. throw "Error in file: " +
  21295. fileName +
  21296. ". Cannot find end marker for conditional comment: " +
  21297. conditionLine;
  21298. }
  21299. }
  21300. }
  21301. }
  21302. //If need to find all plugin resources to optimize, do that now,
  21303. //before namespacing, since the namespacing will change the API
  21304. //names.
  21305. //If there is a plugin collector, scan the file for plugin resources.
  21306. if (config.optimizeAllPluginResources && pluginCollector) {
  21307. try {
  21308. deps = parse.findDependencies(fileName, fileContents);
  21309. if (deps.length) {
  21310. for (i = 0; i < deps.length; i++) {
  21311. dep = deps[i];
  21312. if (dep.indexOf('!') !== -1) {
  21313. moduleName = dep.split('!')[0];
  21314. collectorMod = pluginCollector[moduleName];
  21315. if (!collectorMod) {
  21316. collectorMod = pluginCollector[moduleName] = [];
  21317. }
  21318. collectorMod.push(dep);
  21319. }
  21320. }
  21321. }
  21322. } catch (eDep) {
  21323. logger.error('Parse error looking for plugin resources in ' +
  21324. fileName + ', skipping.');
  21325. }
  21326. }
  21327. //Strip amdefine use for node-shared modules.
  21328. if (!config.keepAmdefine) {
  21329. fileContents = fileContents.replace(pragma.amdefineRegExp, '');
  21330. }
  21331. //Do namespacing
  21332. if (onLifecycleName === 'OnSave' && config.namespace) {
  21333. fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName);
  21334. }
  21335. return pragma.removeStrict(fileContents, config);
  21336. }
  21337. };
  21338. return pragma;
  21339. });
  21340. if(env === 'browser') {
  21341. /*jslint strict: false */
  21342. /*global define: false */
  21343. define('browser/optimize', {});
  21344. }
  21345. if(env === 'node') {
  21346. /*jslint strict: false */
  21347. /*global define: false */
  21348. define('node/optimize', {});
  21349. }
  21350. if(env === 'rhino') {
  21351. /*jslint sloppy: true, plusplus: true */
  21352. /*global define, java, Packages, com */
  21353. define('rhino/optimize', ['logger', 'env!env/file'], function (logger, file) {
  21354. //Add .reduce to Rhino so UglifyJS can run in Rhino,
  21355. //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
  21356. //but rewritten for brevity, and to be good enough for use by UglifyJS.
  21357. if (!Array.prototype.reduce) {
  21358. Array.prototype.reduce = function (fn /*, initialValue */) {
  21359. var i = 0,
  21360. length = this.length,
  21361. accumulator;
  21362. if (arguments.length >= 2) {
  21363. accumulator = arguments[1];
  21364. } else {
  21365. if (length) {
  21366. while (!(i in this)) {
  21367. i++;
  21368. }
  21369. accumulator = this[i++];
  21370. }
  21371. }
  21372. for (; i < length; i++) {
  21373. if (i in this) {
  21374. accumulator = fn.call(undefined, accumulator, this[i], i, this);
  21375. }
  21376. }
  21377. return accumulator;
  21378. };
  21379. }
  21380. var JSSourceFilefromCode, optimize,
  21381. mapRegExp = /"file":"[^"]+"/;
  21382. //Bind to Closure compiler, but if it is not available, do not sweat it.
  21383. try {
  21384. // Try older closure compiler that worked on Java 6
  21385. JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
  21386. } catch (e) {
  21387. try {
  21388. // Try for newer closure compiler that needs Java 7+
  21389. JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.SourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
  21390. } catch (e) {
  21391. try {
  21392. // Try Nashorn style
  21393. var stringClass = Java.type("java.lang.String").class;
  21394. JSSourceFilefromCode = Java.type("com.google.javascript.jscomp.SourceFile").class.getMethod("fromCode", [stringClass, stringClass]);
  21395. } catch (e) {}
  21396. }
  21397. }
  21398. //Helper for closure compiler, because of weird Java-JavaScript interactions.
  21399. function closurefromCode(filename, content) {
  21400. return JSSourceFilefromCode.invoke(null, [filename, content]);
  21401. }
  21402. function getFileWriter(fileName, encoding) {
  21403. var outFile = new java.io.File(fileName), outWriter, parentDir;
  21404. parentDir = outFile.getAbsoluteFile().getParentFile();
  21405. if (!parentDir.exists()) {
  21406. if (!parentDir.mkdirs()) {
  21407. throw "Could not create directory: " + parentDir.getAbsolutePath();
  21408. }
  21409. }
  21410. if (encoding) {
  21411. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  21412. } else {
  21413. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  21414. }
  21415. return new java.io.BufferedWriter(outWriter);
  21416. }
  21417. optimize = {
  21418. closure: function (fileName, fileContents, outFileName, keepLines, config) {
  21419. config = config || {};
  21420. var result, mappings, optimized, compressed, baseName, writer,
  21421. outBaseName, outFileNameMap, outFileNameMapContent,
  21422. srcOutFileName, concatNameMap,
  21423. jscomp = Packages.com.google.javascript.jscomp,
  21424. flags = Packages.com.google.common.flags,
  21425. //Set up source input
  21426. jsSourceFile = closurefromCode(String(fileName), String(fileContents)),
  21427. sourceListArray = new java.util.ArrayList(),
  21428. externList = new java.util.ArrayList(),
  21429. options, option, FLAG_compilation_level, compiler, externExportsPath,
  21430. Compiler = Packages.com.google.javascript.jscomp.Compiler,
  21431. CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner;
  21432. logger.trace("Minifying file: " + fileName);
  21433. baseName = (new java.io.File(fileName)).getName();
  21434. //Set up options
  21435. options = new jscomp.CompilerOptions();
  21436. for (option in config.CompilerOptions) {
  21437. // options are false by default and jslint wanted an if statement in this for loop
  21438. if (config.CompilerOptions[option]) {
  21439. options[option] = config.CompilerOptions[option];
  21440. }
  21441. }
  21442. options.prettyPrint = keepLines || options.prettyPrint;
  21443. FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS'];
  21444. FLAG_compilation_level.setOptionsForCompilationLevel(options);
  21445. if (config.generateSourceMaps) {
  21446. mappings = new java.util.ArrayList();
  21447. mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js"));
  21448. options.setSourceMapLocationMappings(mappings);
  21449. options.setSourceMapOutputPath(fileName + ".map");
  21450. }
  21451. //If we need to pass an externs file to Closure so that it does not create aliases
  21452. //for certain symbols, do so here.
  21453. externList.addAll(CommandLineRunner.getDefaultExterns());
  21454. if (config.externExportsPath) {
  21455. externExportsPath = config.externExportsPath;
  21456. externList.add(jscomp.SourceFile.fromFile(externExportsPath));
  21457. }
  21458. //Trigger the compiler
  21459. Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']);
  21460. compiler = new Compiler();
  21461. //fill the sourceArrrayList; we need the ArrayList because the only overload of compile
  21462. //accepting the getDefaultExterns return value (a List) also wants the sources as a List
  21463. sourceListArray.add(jsSourceFile);
  21464. result = compiler.compile(externList, sourceListArray, options);
  21465. if (result.success) {
  21466. optimized = String(compiler.toSource());
  21467. if (config.generateSourceMaps && result.sourceMap && outFileName) {
  21468. outBaseName = (new java.io.File(outFileName)).getName();
  21469. srcOutFileName = outFileName + ".src.js";
  21470. outFileNameMap = outFileName + ".map";
  21471. //If previous .map file exists, move it to the ".src.js"
  21472. //location. Need to update the sourceMappingURL part in the
  21473. //src.js file too.
  21474. if (file.exists(outFileNameMap)) {
  21475. concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map');
  21476. file.saveFile(concatNameMap, file.readFile(outFileNameMap));
  21477. file.saveFile(srcOutFileName,
  21478. fileContents.replace(/\/\# sourceMappingURL=(.+).map/,
  21479. '/# sourceMappingURL=$1.src.js.map'));
  21480. } else {
  21481. file.saveUtf8File(srcOutFileName, fileContents);
  21482. }
  21483. writer = getFileWriter(outFileNameMap, "utf-8");
  21484. result.sourceMap.appendTo(writer, outFileName);
  21485. writer.close();
  21486. //Not sure how better to do this, but right now the .map file
  21487. //leaks the full OS path in the "file" property. Manually
  21488. //modify it to not do that.
  21489. file.saveFile(outFileNameMap,
  21490. file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"'));
  21491. fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map";
  21492. } else {
  21493. fileContents = optimized;
  21494. }
  21495. return fileContents;
  21496. } else {
  21497. throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.');
  21498. }
  21499. return fileContents;
  21500. }
  21501. };
  21502. return optimize;
  21503. });
  21504. }
  21505. if(env === 'xpconnect') {
  21506. define('xpconnect/optimize', {});
  21507. }
  21508. /*jslint plusplus: true, nomen: true, regexp: true */
  21509. /*global define: false */
  21510. define('optimize', [ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse',
  21511. 'pragma', 'uglifyjs',
  21512. 'source-map'],
  21513. function (lang, logger, envOptimize, file, parse,
  21514. pragma, uglify,
  21515. sourceMap) {
  21516. 'use strict';
  21517. var optimize,
  21518. cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig,
  21519. cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g,
  21520. cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g,
  21521. protocolRegExp = /^\w+:/,
  21522. SourceMapGenerator = sourceMap.SourceMapGenerator,
  21523. SourceMapConsumer =sourceMap.SourceMapConsumer;
  21524. /**
  21525. * If an URL from a CSS url value contains start/end quotes, remove them.
  21526. * This is not done in the regexp, since my regexp fu is not that strong,
  21527. * and the CSS spec allows for ' and " in the URL if they are backslash escaped.
  21528. * @param {String} url
  21529. */
  21530. function cleanCssUrlQuotes(url) {
  21531. //Make sure we are not ending in whitespace.
  21532. //Not very confident of the css regexps above that there will not be ending
  21533. //whitespace.
  21534. url = url.replace(/\s+$/, "");
  21535. if (url.charAt(0) === "'" || url.charAt(0) === "\"") {
  21536. url = url.substring(1, url.length - 1);
  21537. }
  21538. return url;
  21539. }
  21540. function fixCssUrlPaths(fileName, path, contents, cssPrefix) {
  21541. return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) {
  21542. var firstChar, hasProtocol, parts, i,
  21543. fixedUrlMatch = cleanCssUrlQuotes(urlMatch);
  21544. fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/");
  21545. //Only do the work for relative URLs. Skip things that start with / or #, or have
  21546. //a protocol.
  21547. firstChar = fixedUrlMatch.charAt(0);
  21548. hasProtocol = protocolRegExp.test(fixedUrlMatch);
  21549. if (firstChar !== "/" && firstChar !== "#" && !hasProtocol) {
  21550. //It is a relative URL, tack on the cssPrefix and path prefix
  21551. urlMatch = cssPrefix + path + fixedUrlMatch;
  21552. } else if (!hasProtocol) {
  21553. logger.trace(fileName + "\n URL not a relative URL, skipping: " + urlMatch);
  21554. }
  21555. //Collapse .. and .
  21556. parts = urlMatch.split("/");
  21557. for (i = parts.length - 1; i > 0; i--) {
  21558. if (parts[i] === ".") {
  21559. parts.splice(i, 1);
  21560. } else if (parts[i] === "..") {
  21561. if (i !== 0 && parts[i - 1] !== "..") {
  21562. parts.splice(i - 1, 2);
  21563. i -= 1;
  21564. }
  21565. }
  21566. }
  21567. return "url(" + parts.join("/") + ")";
  21568. });
  21569. }
  21570. /**
  21571. * Inlines nested stylesheets that have @import calls in them.
  21572. * @param {String} fileName the file name
  21573. * @param {String} fileContents the file contents
  21574. * @param {String} cssImportIgnore comma delimited string of files to ignore
  21575. * @param {String} cssPrefix string to be prefixed before relative URLs
  21576. * @param {Object} included an object used to track the files already imported
  21577. */
  21578. function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) {
  21579. //Find the last slash in the name.
  21580. fileName = fileName.replace(lang.backSlashRegExp, "/");
  21581. var endIndex = fileName.lastIndexOf("/"),
  21582. //Make a file path based on the last slash.
  21583. //If no slash, so must be just a file name. Use empty string then.
  21584. filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "",
  21585. //store a list of merged files
  21586. importList = [],
  21587. skippedList = [];
  21588. //First make a pass by removing any commented out @import calls.
  21589. fileContents = fileContents.replace(cssCommentImportRegExp, '');
  21590. //Make sure we have a delimited ignore list to make matching faster
  21591. if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") {
  21592. cssImportIgnore += ",";
  21593. }
  21594. fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) {
  21595. //Only process media type "all" or empty media type rules.
  21596. if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) {
  21597. skippedList.push(fileName);
  21598. return fullMatch;
  21599. }
  21600. importFileName = cleanCssUrlQuotes(importFileName);
  21601. //Ignore the file import if it is part of an ignore list.
  21602. if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) {
  21603. return fullMatch;
  21604. }
  21605. //Make sure we have a unix path for the rest of the operation.
  21606. importFileName = importFileName.replace(lang.backSlashRegExp, "/");
  21607. try {
  21608. //if a relative path, then tack on the filePath.
  21609. //If it is not a relative path, then the readFile below will fail,
  21610. //and we will just skip that import.
  21611. var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName,
  21612. importContents = file.readFile(fullImportFileName),
  21613. importEndIndex, importPath, flat;
  21614. //Skip the file if it has already been included.
  21615. if (included[fullImportFileName]) {
  21616. return '';
  21617. }
  21618. included[fullImportFileName] = true;
  21619. //Make sure to flatten any nested imports.
  21620. flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included);
  21621. importContents = flat.fileContents;
  21622. if (flat.importList.length) {
  21623. importList.push.apply(importList, flat.importList);
  21624. }
  21625. if (flat.skippedList.length) {
  21626. skippedList.push.apply(skippedList, flat.skippedList);
  21627. }
  21628. //Make the full import path
  21629. importEndIndex = importFileName.lastIndexOf("/");
  21630. //Make a file path based on the last slash.
  21631. //If no slash, so must be just a file name. Use empty string then.
  21632. importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : "";
  21633. //fix url() on relative import (#5)
  21634. importPath = importPath.replace(/^\.\//, '');
  21635. //Modify URL paths to match the path represented by this file.
  21636. importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix);
  21637. importList.push(fullImportFileName);
  21638. return importContents;
  21639. } catch (e) {
  21640. logger.warn(fileName + "\n Cannot inline css import, skipping: " + importFileName);
  21641. return fullMatch;
  21642. }
  21643. });
  21644. if (cssPrefix && topLevel) {
  21645. //Modify URL paths to match the path represented by this file.
  21646. fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix);
  21647. }
  21648. return {
  21649. importList : importList,
  21650. skippedList: skippedList,
  21651. fileContents : fileContents
  21652. };
  21653. }
  21654. optimize = {
  21655. /**
  21656. * Optimizes a file that contains JavaScript content. Optionally collects
  21657. * plugin resources mentioned in a file, and then passes the content
  21658. * through an minifier if one is specified via config.optimize.
  21659. *
  21660. * @param {String} fileName the name of the file to optimize
  21661. * @param {String} fileContents the contents to optimize. If this is
  21662. * a null value, then fileName will be used to read the fileContents.
  21663. * @param {String} outFileName the name of the file to use for the
  21664. * saved optimized content.
  21665. * @param {Object} config the build config object.
  21666. * @param {Array} [pluginCollector] storage for any plugin resources
  21667. * found.
  21668. */
  21669. jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) {
  21670. if (!fileContents) {
  21671. fileContents = file.readFile(fileName);
  21672. }
  21673. fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector);
  21674. file.saveUtf8File(outFileName, fileContents);
  21675. },
  21676. /**
  21677. * Optimizes a file that contains JavaScript content. Optionally collects
  21678. * plugin resources mentioned in a file, and then passes the content
  21679. * through an minifier if one is specified via config.optimize.
  21680. *
  21681. * @param {String} fileName the name of the file that matches the
  21682. * fileContents.
  21683. * @param {String} fileContents the string of JS to optimize.
  21684. * @param {Object} [config] the build config object.
  21685. * @param {Array} [pluginCollector] storage for any plugin resources
  21686. * found.
  21687. */
  21688. js: function (fileName, fileContents, outFileName, config, pluginCollector) {
  21689. var optFunc, optConfig,
  21690. parts = (String(config.optimize)).split('.'),
  21691. optimizerName = parts[0],
  21692. keepLines = parts[1] === 'keepLines',
  21693. licenseContents = '';
  21694. config = config || {};
  21695. //Apply pragmas/namespace renaming
  21696. fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector);
  21697. //Optimize the JS files if asked.
  21698. if (optimizerName && optimizerName !== 'none') {
  21699. optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName];
  21700. if (!optFunc) {
  21701. throw new Error('optimizer with name of "' +
  21702. optimizerName +
  21703. '" not found for this environment');
  21704. }
  21705. optConfig = config[optimizerName] || {};
  21706. if (config.generateSourceMaps) {
  21707. optConfig.generateSourceMaps = !!config.generateSourceMaps;
  21708. optConfig._buildSourceMap = config._buildSourceMap;
  21709. }
  21710. try {
  21711. if (config.preserveLicenseComments) {
  21712. //Pull out any license comments for prepending after optimization.
  21713. try {
  21714. licenseContents = parse.getLicenseComments(fileName, fileContents);
  21715. } catch (e) {
  21716. throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString());
  21717. }
  21718. }
  21719. if (config.generateSourceMaps && licenseContents) {
  21720. optConfig.preamble = licenseContents;
  21721. licenseContents = '';
  21722. }
  21723. fileContents = licenseContents + optFunc(fileName,
  21724. fileContents,
  21725. outFileName,
  21726. keepLines,
  21727. optConfig);
  21728. if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) {
  21729. config._buildSourceMap = optConfig._buildSourceMap;
  21730. }
  21731. } catch (e) {
  21732. if (config.throwWhen && config.throwWhen.optimize) {
  21733. throw e;
  21734. } else {
  21735. logger.error(e);
  21736. }
  21737. }
  21738. } else {
  21739. if (config._buildSourceMap) {
  21740. config._buildSourceMap = null;
  21741. }
  21742. }
  21743. return fileContents;
  21744. },
  21745. /**
  21746. * Optimizes one CSS file, inlining @import calls, stripping comments, and
  21747. * optionally removes line returns.
  21748. * @param {String} fileName the path to the CSS file to optimize
  21749. * @param {String} outFileName the path to save the optimized file.
  21750. * @param {Object} config the config object with the optimizeCss and
  21751. * cssImportIgnore options.
  21752. */
  21753. cssFile: function (fileName, outFileName, config) {
  21754. //Read in the file. Make sure we have a JS string.
  21755. var originalFileContents = file.readFile(fileName),
  21756. flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true),
  21757. //Do not use the flattened CSS if there was one that was skipped.
  21758. fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents,
  21759. startIndex, endIndex, buildText, comment;
  21760. if (flat.skippedList.length) {
  21761. logger.warn('Cannot inline @imports for ' + fileName +
  21762. ',\nthe following files had media queries in them:\n' +
  21763. flat.skippedList.join('\n'));
  21764. }
  21765. //Do comment removal.
  21766. try {
  21767. if (config.optimizeCss.indexOf(".keepComments") === -1) {
  21768. startIndex = 0;
  21769. //Get rid of comments.
  21770. while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) {
  21771. endIndex = fileContents.indexOf("*/", startIndex + 2);
  21772. if (endIndex === -1) {
  21773. throw "Improper comment in CSS file: " + fileName;
  21774. }
  21775. comment = fileContents.substring(startIndex, endIndex);
  21776. if (config.preserveLicenseComments &&
  21777. (comment.indexOf('license') !== -1 ||
  21778. comment.indexOf('opyright') !== -1 ||
  21779. comment.indexOf('(c)') !== -1)) {
  21780. //Keep the comment, just increment the startIndex
  21781. startIndex = endIndex;
  21782. } else {
  21783. fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length);
  21784. startIndex = 0;
  21785. }
  21786. }
  21787. }
  21788. //Get rid of newlines.
  21789. if (config.optimizeCss.indexOf(".keepLines") === -1) {
  21790. fileContents = fileContents.replace(/[\r\n]/g, " ");
  21791. fileContents = fileContents.replace(/\s+/g, " ");
  21792. fileContents = fileContents.replace(/\{\s/g, "{");
  21793. fileContents = fileContents.replace(/\s\}/g, "}");
  21794. } else {
  21795. //Remove multiple empty lines.
  21796. fileContents = fileContents.replace(/(\r\n)+/g, "\r\n");
  21797. fileContents = fileContents.replace(/(\n)+/g, "\n");
  21798. }
  21799. //Remove unnecessary whitespace
  21800. if (config.optimizeCss.indexOf(".keepWhitespace") === -1) {
  21801. //Remove leading and trailing whitespace from lines
  21802. fileContents = fileContents.replace(/^[ \t]+/gm, "");
  21803. fileContents = fileContents.replace(/[ \t]+$/gm, "");
  21804. //Remove whitespace after semicolon, colon, curly brackets and commas
  21805. fileContents = fileContents.replace(/(;|:|\{|}|,)[ \t]+/g, "$1");
  21806. //Remove whitespace before opening curly brackets
  21807. fileContents = fileContents.replace(/[ \t]+(\{)/g, "$1");
  21808. //Truncate double whitespace
  21809. fileContents = fileContents.replace(/([ \t])+/g, "$1");
  21810. //Remove empty lines
  21811. fileContents = fileContents.replace(/^[ \t]*[\r\n]/gm,'');
  21812. }
  21813. } catch (e) {
  21814. fileContents = originalFileContents;
  21815. logger.error("Could not optimized CSS file: " + fileName + ", error: " + e);
  21816. }
  21817. file.saveUtf8File(outFileName, fileContents);
  21818. //text output to stdout and/or written to build.txt file
  21819. buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n";
  21820. flat.importList.push(fileName);
  21821. buildText += flat.importList.map(function(path){
  21822. return path.replace(config.dir, "");
  21823. }).join("\n");
  21824. return {
  21825. importList: flat.importList,
  21826. buildText: buildText +"\n"
  21827. };
  21828. },
  21829. /**
  21830. * Optimizes CSS files, inlining @import calls, stripping comments, and
  21831. * optionally removes line returns.
  21832. * @param {String} startDir the path to the top level directory
  21833. * @param {Object} config the config object with the optimizeCss and
  21834. * cssImportIgnore options.
  21835. */
  21836. css: function (startDir, config) {
  21837. var buildText = "",
  21838. importList = [],
  21839. shouldRemove = config.dir && config.removeCombined,
  21840. i, fileName, result, fileList;
  21841. if (config.optimizeCss.indexOf("standard") !== -1) {
  21842. fileList = file.getFilteredFileList(startDir, /\.css$/, true);
  21843. if (fileList) {
  21844. for (i = 0; i < fileList.length; i++) {
  21845. fileName = fileList[i];
  21846. logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName);
  21847. result = optimize.cssFile(fileName, fileName, config);
  21848. buildText += result.buildText;
  21849. if (shouldRemove) {
  21850. result.importList.pop();
  21851. importList = importList.concat(result.importList);
  21852. }
  21853. }
  21854. }
  21855. if (shouldRemove) {
  21856. importList.forEach(function (path) {
  21857. if (file.exists(path)) {
  21858. file.deleteFile(path);
  21859. }
  21860. });
  21861. }
  21862. }
  21863. return buildText;
  21864. },
  21865. optimizers: {
  21866. uglify: function (fileName, fileContents, outFileName, keepLines, config) {
  21867. var result, existingMap, resultMap, finalMap, sourceIndex,
  21868. uconfig = {},
  21869. existingMapPath = outFileName + '.map',
  21870. preamble = config.preamble || "",
  21871. baseName = fileName && fileName.split('/').pop();
  21872. config = config || {};
  21873. lang.mixin(uconfig, config, true);
  21874. uconfig.fromString = true;
  21875. if (config.preamble) {
  21876. uconfig.output = {preamble: config.preamble};
  21877. }
  21878. if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) {
  21879. uconfig.outSourceMap = baseName + '.map';
  21880. if (config._buildSourceMap) {
  21881. existingMap = JSON.parse(config._buildSourceMap);
  21882. uconfig.inSourceMap = existingMap;
  21883. } else if (file.exists(existingMapPath)) {
  21884. uconfig.inSourceMap = existingMapPath;
  21885. existingMap = JSON.parse(file.readFile(existingMapPath));
  21886. }
  21887. }
  21888. logger.trace("Uglify file: " + fileName);
  21889. try {
  21890. //var tempContents = fileContents.replace(/\/\/\# sourceMappingURL=.*$/, '');
  21891. result = uglify.minify(fileContents, uconfig, baseName + '.src.js');
  21892. if (uconfig.outSourceMap && result.map) {
  21893. resultMap = result.map;
  21894. if (!existingMap && !config._buildSourceMap) {
  21895. file.saveFile(outFileName + '.src.js', fileContents);
  21896. }
  21897. fileContents = result.code;
  21898. if (config._buildSourceMap) {
  21899. config._buildSourceMap = resultMap;
  21900. } else {
  21901. file.saveFile(outFileName + '.map', resultMap);
  21902. }
  21903. } else {
  21904. fileContents = result.code;
  21905. }
  21906. } catch (e) {
  21907. throw new Error('Cannot uglify file: ' + fileName + '. Skipping it. Error is:\n' + e.toString());
  21908. }
  21909. return preamble + fileContents;
  21910. }
  21911. }
  21912. };
  21913. return optimize;
  21914. });
  21915. /*
  21916. * This file patches require.js to communicate with the build system.
  21917. */
  21918. //Using sloppy since this uses eval for some code like plugins,
  21919. //which may not be strict mode compliant. So if use strict is used
  21920. //below they will have strict rules applied and may cause an error.
  21921. /*jslint sloppy: true, nomen: true, plusplus: true, regexp: true */
  21922. /*global require, define: true */
  21923. //NOT asking for require as a dependency since the goal is to modify the
  21924. //global require below
  21925. define('requirePatch', [ 'env!env/file', 'pragma', 'parse', 'lang', 'logger', 'commonJs', 'prim'], function (
  21926. file,
  21927. pragma,
  21928. parse,
  21929. lang,
  21930. logger,
  21931. commonJs,
  21932. prim
  21933. ) {
  21934. var allowRun = true,
  21935. hasProp = lang.hasProp,
  21936. falseProp = lang.falseProp,
  21937. getOwn = lang.getOwn,
  21938. // Used to strip out use strict from toString()'d functions for the
  21939. // shim config since they will explicitly want to not be bound by strict,
  21940. // but some envs, explicitly xpcshell, adds a use strict.
  21941. useStrictRegExp = /['"]use strict['"];/g,
  21942. //Absolute path if starts with /, \, or x:
  21943. absoluteUrlRegExp = /^[\/\\]|^\w:/;
  21944. //Turn off throwing on resolution conflict, that was just an older prim
  21945. //idea about finding errors early, but does not comply with how promises
  21946. //should operate.
  21947. prim.hideResolutionConflict = true;
  21948. //This method should be called when the patches to require should take hold.
  21949. return function () {
  21950. if (!allowRun) {
  21951. return;
  21952. }
  21953. allowRun = false;
  21954. var layerobj,
  21955. pluginBuilderRegExp = /(["']?)pluginBuilder(["']?)\s*[=\:]\s*["']([^'"\s]+)["']/,
  21956. oldNewContext = require.s.newContext,
  21957. oldDef,
  21958. //create local undefined values for module and exports,
  21959. //so that when files are evaled in this function they do not
  21960. //see the node values used for r.js
  21961. exports,
  21962. module;
  21963. /**
  21964. * Reset "global" build caches that are kept around between
  21965. * build layerobj builds. Useful to do when there are multiple
  21966. * top level requirejs.optimize() calls.
  21967. */
  21968. require._cacheReset = function () {
  21969. //Stored raw text caches, used by browser use.
  21970. require._cachedRawText = {};
  21971. //Stored cached file contents for reuse in other layerobjs.
  21972. require._cachedFileContents = {};
  21973. //Store which cached files contain a require definition.
  21974. require._cachedDefinesRequireUrls = {};
  21975. };
  21976. require._cacheReset();
  21977. /**
  21978. * Makes sure the URL is something that can be supported by the
  21979. * optimization tool.
  21980. * @param {String} url
  21981. * @returns {Boolean}
  21982. */
  21983. require._isSupportedBuildUrl = function (url) {
  21984. //Ignore URLs with protocols, hosts or question marks, means either network
  21985. //access is needed to fetch it or it is too dynamic. Note that
  21986. //on Windows, full paths are used for some urls, which include
  21987. //the drive, like c:/something, so need to test for something other
  21988. //than just a colon.
  21989. if (url.indexOf("://") === -1 && url.indexOf("?") === -1 &&
  21990. url.indexOf('empty:') !== 0 && url.indexOf('//') !== 0) {
  21991. return true;
  21992. } else {
  21993. if (!layerobj.ignoredUrls[url]) {
  21994. if (url.indexOf('empty:') === -1) {
  21995. logger.info('Cannot optimize network URL, skipping: ' + url);
  21996. }
  21997. layerobj.ignoredUrls[url] = true;
  21998. }
  21999. return false;
  22000. }
  22001. };
  22002. function normalizeUrlWithBase(context, moduleName, url) {
  22003. //Adjust the URL if it was not transformed to use baseUrl, but only
  22004. //if the URL is not already an absolute path.
  22005. if (require.jsExtRegExp.test(moduleName) &&
  22006. !absoluteUrlRegExp.test(url)) {
  22007. url = (context.config.dir || context.config.dirBaseUrl) + url;
  22008. }
  22009. return url;
  22010. }
  22011. //Overrides the new context call to add existing tracking features.
  22012. require.s.newContext = function (name) {
  22013. var context = oldNewContext(name),
  22014. oldEnable = context.enable,
  22015. moduleProto = context.Module.prototype,
  22016. oldInit = moduleProto.init,
  22017. oldCallPlugin = moduleProto.callPlugin;
  22018. //Only do this for the context used for building.
  22019. if (name === '_') {
  22020. //For build contexts, do everything sync
  22021. context.nextTick = function (fn) {
  22022. fn();
  22023. };
  22024. context.needFullExec = {};
  22025. context.fullExec = {};
  22026. context.plugins = {};
  22027. context.buildShimExports = {};
  22028. //Override the shim exports function generator to just
  22029. //spit out strings that can be used in the stringified
  22030. //build output.
  22031. context.makeShimExports = function (value) {
  22032. var fn;
  22033. if (context.config.wrapShim) {
  22034. fn = function () {
  22035. var str = 'return ';
  22036. // If specifies an export that is just a global
  22037. // name, no dot for a `this.` and such, then also
  22038. // attach to the global, for `var a = {}` files
  22039. // where the function closure would hide that from
  22040. // the global object.
  22041. if (value.exports && value.exports.indexOf('.') === -1) {
  22042. str += 'root.' + value.exports + ' = ';
  22043. }
  22044. if (value.init) {
  22045. str += '(' + value.init.toString()
  22046. .replace(useStrictRegExp, '') + '.apply(this, arguments))';
  22047. }
  22048. if (value.init && value.exports) {
  22049. str += ' || ';
  22050. }
  22051. if (value.exports) {
  22052. str += value.exports;
  22053. }
  22054. str += ';';
  22055. return str;
  22056. };
  22057. } else {
  22058. fn = function () {
  22059. return '(function (global) {\n' +
  22060. ' return function () {\n' +
  22061. ' var ret, fn;\n' +
  22062. (value.init ?
  22063. (' fn = ' + value.init.toString()
  22064. .replace(useStrictRegExp, '') + ';\n' +
  22065. ' ret = fn.apply(global, arguments);\n') : '') +
  22066. (value.exports ?
  22067. ' return ret || global.' + value.exports + ';\n' :
  22068. ' return ret;\n') +
  22069. ' };\n' +
  22070. '}(this))';
  22071. };
  22072. }
  22073. return fn;
  22074. };
  22075. context.enable = function (depMap, parent) {
  22076. var id = depMap.id,
  22077. parentId = parent && parent.map.id,
  22078. needFullExec = context.needFullExec,
  22079. fullExec = context.fullExec,
  22080. mod = getOwn(context.registry, id);
  22081. if (mod && !mod.defined) {
  22082. if (parentId && getOwn(needFullExec, parentId)) {
  22083. needFullExec[id] = depMap;
  22084. }
  22085. } else if ((getOwn(needFullExec, id) && falseProp(fullExec, id)) ||
  22086. (parentId && getOwn(needFullExec, parentId) &&
  22087. falseProp(fullExec, id))) {
  22088. context.require.undef(id);
  22089. }
  22090. return oldEnable.apply(context, arguments);
  22091. };
  22092. //Override load so that the file paths can be collected.
  22093. context.load = function (moduleName, url) {
  22094. /*jslint evil: true */
  22095. var contents, pluginBuilderMatch, builderName,
  22096. shim, shimExports;
  22097. //Do not mark the url as fetched if it is
  22098. //not an empty: URL, used by the optimizer.
  22099. //In that case we need to be sure to call
  22100. //load() for each module that is mapped to
  22101. //empty: so that dependencies are satisfied
  22102. //correctly.
  22103. if (url.indexOf('empty:') === 0) {
  22104. delete context.urlFetched[url];
  22105. }
  22106. //Only handle urls that can be inlined, so that means avoiding some
  22107. //URLs like ones that require network access or may be too dynamic,
  22108. //like JSONP
  22109. if (require._isSupportedBuildUrl(url)) {
  22110. //Adjust the URL if it was not transformed to use baseUrl.
  22111. url = normalizeUrlWithBase(context, moduleName, url);
  22112. //Save the module name to path and path to module name mappings.
  22113. layerobj.buildPathMap[moduleName] = url;
  22114. layerobj.buildFileToModule[url] = moduleName;
  22115. if (hasProp(context.plugins, moduleName)) {
  22116. //plugins need to have their source evaled as-is.
  22117. context.needFullExec[moduleName] = true;
  22118. }
  22119. prim().start(function () {
  22120. if (hasProp(require._cachedFileContents, url) &&
  22121. (falseProp(context.needFullExec, moduleName) ||
  22122. getOwn(context.fullExec, moduleName))) {
  22123. contents = require._cachedFileContents[url];
  22124. //If it defines require, mark it so it can be hoisted.
  22125. //Done here and in the else below, before the
  22126. //else block removes code from the contents.
  22127. //Related to #263
  22128. if (!layerobj.existingRequireUrl && require._cachedDefinesRequireUrls[url]) {
  22129. layerobj.existingRequireUrl = url;
  22130. }
  22131. } else {
  22132. //Load the file contents, process for conditionals, then
  22133. //evaluate it.
  22134. return require._cacheReadAsync(url).then(function (text) {
  22135. contents = text;
  22136. if (context.config.cjsTranslate &&
  22137. (!context.config.shim || !lang.hasProp(context.config.shim, moduleName))) {
  22138. contents = commonJs.convert(url, contents);
  22139. }
  22140. //If there is a read filter, run it now.
  22141. if (context.config.onBuildRead) {
  22142. contents = context.config.onBuildRead(moduleName, url, contents);
  22143. }
  22144. contents = pragma.process(url, contents, context.config, 'OnExecute');
  22145. //Find out if the file contains a require() definition. Need to know
  22146. //this so we can inject plugins right after it, but before they are needed,
  22147. //and to make sure this file is first, so that define calls work.
  22148. try {
  22149. if (!layerobj.existingRequireUrl && parse.definesRequire(url, contents)) {
  22150. layerobj.existingRequireUrl = url;
  22151. require._cachedDefinesRequireUrls[url] = true;
  22152. }
  22153. } catch (e1) {
  22154. throw new Error('Parse error using esprima ' +
  22155. 'for file: ' + url + '\n' + e1);
  22156. }
  22157. }).then(function () {
  22158. if (hasProp(context.plugins, moduleName)) {
  22159. //This is a loader plugin, check to see if it has a build extension,
  22160. //otherwise the plugin will act as the plugin builder too.
  22161. pluginBuilderMatch = pluginBuilderRegExp.exec(contents);
  22162. if (pluginBuilderMatch) {
  22163. //Load the plugin builder for the plugin contents.
  22164. builderName = context.makeModuleMap(pluginBuilderMatch[3],
  22165. context.makeModuleMap(moduleName),
  22166. null,
  22167. true).id;
  22168. return require._cacheReadAsync(context.nameToUrl(builderName));
  22169. }
  22170. }
  22171. return contents;
  22172. }).then(function (text) {
  22173. contents = text;
  22174. //Parse out the require and define calls.
  22175. //Do this even for plugins in case they have their own
  22176. //dependencies that may be separate to how the pluginBuilder works.
  22177. try {
  22178. if (falseProp(context.needFullExec, moduleName)) {
  22179. contents = parse(moduleName, url, contents, {
  22180. insertNeedsDefine: true,
  22181. has: context.config.has,
  22182. findNestedDependencies: context.config.findNestedDependencies
  22183. });
  22184. }
  22185. } catch (e2) {
  22186. throw new Error('Parse error using esprima ' +
  22187. 'for file: ' + url + '\n' + e2);
  22188. }
  22189. require._cachedFileContents[url] = contents;
  22190. });
  22191. }
  22192. }).then(function () {
  22193. if (contents) {
  22194. eval(contents);
  22195. }
  22196. try {
  22197. //If have a string shim config, and this is
  22198. //a fully executed module, try to see if
  22199. //it created a variable in this eval scope
  22200. if (getOwn(context.needFullExec, moduleName)) {
  22201. shim = getOwn(context.config.shim, moduleName);
  22202. if (shim && shim.exports) {
  22203. shimExports = eval(shim.exports);
  22204. if (typeof shimExports !== 'undefined') {
  22205. context.buildShimExports[moduleName] = shimExports;
  22206. }
  22207. }
  22208. }
  22209. //Need to close out completion of this module
  22210. //so that listeners will get notified that it is available.
  22211. context.completeLoad(moduleName);
  22212. } catch (e) {
  22213. //Track which module could not complete loading.
  22214. if (!e.moduleTree) {
  22215. e.moduleTree = [];
  22216. }
  22217. e.moduleTree.push(moduleName);
  22218. throw e;
  22219. }
  22220. }).then(null, function (eOuter) {
  22221. if (!eOuter.fileName) {
  22222. eOuter.fileName = url;
  22223. }
  22224. throw eOuter;
  22225. }).end();
  22226. } else {
  22227. //With unsupported URLs still need to call completeLoad to
  22228. //finish loading.
  22229. context.completeLoad(moduleName);
  22230. }
  22231. };
  22232. //Marks module has having a name, and optionally executes the
  22233. //callback, but only if it meets certain criteria.
  22234. context.execCb = function (name, cb, args, exports) {
  22235. var buildShimExports = getOwn(layerobj.context.buildShimExports, name);
  22236. if (buildShimExports) {
  22237. return buildShimExports;
  22238. } else if (cb.__requireJsBuild || getOwn(layerobj.context.needFullExec, name)) {
  22239. return cb.apply(exports, args);
  22240. }
  22241. return undefined;
  22242. };
  22243. moduleProto.init = function (depMaps) {
  22244. if (context.needFullExec[this.map.id]) {
  22245. lang.each(depMaps, lang.bind(this, function (depMap) {
  22246. if (typeof depMap === 'string') {
  22247. depMap = context.makeModuleMap(depMap,
  22248. (this.map.isDefine ? this.map : this.map.parentMap));
  22249. }
  22250. if (!context.fullExec[depMap.id]) {
  22251. context.require.undef(depMap.id);
  22252. }
  22253. }));
  22254. }
  22255. return oldInit.apply(this, arguments);
  22256. };
  22257. moduleProto.callPlugin = function () {
  22258. var map = this.map,
  22259. pluginMap = context.makeModuleMap(map.prefix),
  22260. pluginId = pluginMap.id,
  22261. pluginMod = getOwn(context.registry, pluginId);
  22262. context.plugins[pluginId] = true;
  22263. context.needFullExec[pluginId] = map;
  22264. //If the module is not waiting to finish being defined,
  22265. //undef it and start over, to get full execution.
  22266. if (falseProp(context.fullExec, pluginId) && (!pluginMod || pluginMod.defined)) {
  22267. context.require.undef(pluginMap.id);
  22268. }
  22269. return oldCallPlugin.apply(this, arguments);
  22270. };
  22271. }
  22272. return context;
  22273. };
  22274. //Clear up the existing context so that the newContext modifications
  22275. //above will be active.
  22276. delete require.s.contexts._;
  22277. /** Reset state for each build layerobj pass. */
  22278. require._buildReset = function () {
  22279. var oldContext = require.s.contexts._;
  22280. //Clear up the existing context.
  22281. delete require.s.contexts._;
  22282. //Set up new context, so the layerobj object can hold onto it.
  22283. require({});
  22284. layerobj = require._layerobj = {
  22285. buildPathMap: {},
  22286. buildFileToModule: {},
  22287. buildFilePaths: [],
  22288. pathAdded: {},
  22289. modulesWithNames: {},
  22290. needsDefine: {},
  22291. existingRequireUrl: "",
  22292. ignoredUrls: {},
  22293. context: require.s.contexts._
  22294. };
  22295. //Return the previous context in case it is needed, like for
  22296. //the basic config object.
  22297. return oldContext;
  22298. };
  22299. require._buildReset();
  22300. //Override define() to catch modules that just define an object, so that
  22301. //a dummy define call is not put in the build file for them. They do
  22302. //not end up getting defined via context.execCb, so we need to catch them
  22303. //at the define call.
  22304. oldDef = define;
  22305. //This function signature does not have to be exact, just match what we
  22306. //are looking for.
  22307. define = function (name) {
  22308. if (typeof name === "string" && falseProp(layerobj.needsDefine, name)) {
  22309. layerobj.modulesWithNames[name] = true;
  22310. }
  22311. return oldDef.apply(require, arguments);
  22312. };
  22313. define.amd = oldDef.amd;
  22314. //Add some utilities for plugins
  22315. require._readFile = file.readFile;
  22316. require._fileExists = function (path) {
  22317. return file.exists(path);
  22318. };
  22319. //Called when execManager runs for a dependency. Used to figure out
  22320. //what order of execution.
  22321. require.onResourceLoad = function (context, map) {
  22322. var id = map.id,
  22323. url;
  22324. // Fix up any maps that need to be normalized as part of the fullExec
  22325. // plumbing for plugins to participate in the build.
  22326. if (context.plugins && lang.hasProp(context.plugins, id)) {
  22327. lang.eachProp(context.needFullExec, function(value, prop) {
  22328. // For plugin entries themselves, they do not have a map
  22329. // value in needFullExec, just a "true" entry.
  22330. if (value !== true && value.prefix === id && value.unnormalized) {
  22331. var map = context.makeModuleMap(value.originalName, value.parentMap);
  22332. context.needFullExec[map.id] = map;
  22333. }
  22334. });
  22335. }
  22336. //If build needed a full execution, indicate it
  22337. //has been done now. But only do it if the context is tracking
  22338. //that. Only valid for the context used in a build, not for
  22339. //other contexts being run, like for useLib, plain requirejs
  22340. //use in node/rhino.
  22341. if (context.needFullExec && getOwn(context.needFullExec, id)) {
  22342. context.fullExec[id] = map;
  22343. }
  22344. //A plugin.
  22345. if (map.prefix) {
  22346. if (falseProp(layerobj.pathAdded, id)) {
  22347. layerobj.buildFilePaths.push(id);
  22348. //For plugins the real path is not knowable, use the name
  22349. //for both module to file and file to module mappings.
  22350. layerobj.buildPathMap[id] = id;
  22351. layerobj.buildFileToModule[id] = id;
  22352. layerobj.modulesWithNames[id] = true;
  22353. layerobj.pathAdded[id] = true;
  22354. }
  22355. } else if (map.url && require._isSupportedBuildUrl(map.url)) {
  22356. //If the url has not been added to the layerobj yet, and it
  22357. //is from an actual file that was loaded, add it now.
  22358. url = normalizeUrlWithBase(context, id, map.url);
  22359. if (!layerobj.pathAdded[url] && getOwn(layerobj.buildPathMap, id)) {
  22360. //Remember the list of dependencies for this layerobj.
  22361. layerobj.buildFilePaths.push(url);
  22362. layerobj.pathAdded[url] = true;
  22363. }
  22364. }
  22365. };
  22366. //Called by output of the parse() function, when a file does not
  22367. //explicitly call define, probably just require, but the parse()
  22368. //function normalizes on define() for dependency mapping and file
  22369. //ordering works correctly.
  22370. require.needsDefine = function (moduleName) {
  22371. layerobj.needsDefine[moduleName] = true;
  22372. };
  22373. };
  22374. });
  22375. /*jslint */
  22376. /*global define: false, console: false */
  22377. define('commonJs', ['env!env/file', 'parse'], function (file, parse) {
  22378. 'use strict';
  22379. var commonJs = {
  22380. //Set to false if you do not want this file to log. Useful in environments
  22381. //like node where you want the work to happen without noise.
  22382. useLog: true,
  22383. convertDir: function (commonJsPath, savePath) {
  22384. var fileList, i,
  22385. jsFileRegExp = /\.js$/,
  22386. fileName, convertedFileName, fileContents;
  22387. //Get list of files to convert.
  22388. fileList = file.getFilteredFileList(commonJsPath, /\w/, true);
  22389. //Normalize on front slashes and make sure the paths do not end in a slash.
  22390. commonJsPath = commonJsPath.replace(/\\/g, "/");
  22391. savePath = savePath.replace(/\\/g, "/");
  22392. if (commonJsPath.charAt(commonJsPath.length - 1) === "/") {
  22393. commonJsPath = commonJsPath.substring(0, commonJsPath.length - 1);
  22394. }
  22395. if (savePath.charAt(savePath.length - 1) === "/") {
  22396. savePath = savePath.substring(0, savePath.length - 1);
  22397. }
  22398. //Cycle through all the JS files and convert them.
  22399. if (!fileList || !fileList.length) {
  22400. if (commonJs.useLog) {
  22401. if (commonJsPath === "convert") {
  22402. //A request just to convert one file.
  22403. console.log('\n\n' + commonJs.convert(savePath, file.readFile(savePath)));
  22404. } else {
  22405. console.log("No files to convert in directory: " + commonJsPath);
  22406. }
  22407. }
  22408. } else {
  22409. for (i = 0; i < fileList.length; i++) {
  22410. fileName = fileList[i];
  22411. convertedFileName = fileName.replace(commonJsPath, savePath);
  22412. //Handle JS files.
  22413. if (jsFileRegExp.test(fileName)) {
  22414. fileContents = file.readFile(fileName);
  22415. fileContents = commonJs.convert(fileName, fileContents);
  22416. file.saveUtf8File(convertedFileName, fileContents);
  22417. } else {
  22418. //Just copy the file over.
  22419. file.copyFile(fileName, convertedFileName, true);
  22420. }
  22421. }
  22422. }
  22423. },
  22424. /**
  22425. * Does the actual file conversion.
  22426. *
  22427. * @param {String} fileName the name of the file.
  22428. *
  22429. * @param {String} fileContents the contents of a file :)
  22430. *
  22431. * @returns {String} the converted contents
  22432. */
  22433. convert: function (fileName, fileContents) {
  22434. //Strip out comments.
  22435. try {
  22436. var preamble = '',
  22437. commonJsProps = parse.usesCommonJs(fileName, fileContents);
  22438. //First see if the module is not already RequireJS-formatted.
  22439. if (parse.usesAmdOrRequireJs(fileName, fileContents) || !commonJsProps) {
  22440. return fileContents;
  22441. }
  22442. if (commonJsProps.dirname || commonJsProps.filename) {
  22443. preamble = 'var __filename = module.uri || "", ' +
  22444. '__dirname = __filename.substring(0, __filename.lastIndexOf("/") + 1); ';
  22445. }
  22446. //Construct the wrapper boilerplate.
  22447. fileContents = 'define(function (require, exports, module) {' +
  22448. preamble +
  22449. fileContents +
  22450. '\n});\n';
  22451. } catch (e) {
  22452. console.log("commonJs.convert: COULD NOT CONVERT: " + fileName + ", so skipping it. Error was: " + e);
  22453. return fileContents;
  22454. }
  22455. return fileContents;
  22456. }
  22457. };
  22458. return commonJs;
  22459. });
  22460. /*jslint plusplus: true, nomen: true, regexp: true */
  22461. /*global define, requirejs, java, process, console */
  22462. define('build', function (require) {
  22463. 'use strict';
  22464. var build,
  22465. lang = require('lang'),
  22466. prim = require('prim'),
  22467. logger = require('logger'),
  22468. file = require('env!env/file'),
  22469. parse = require('parse'),
  22470. optimize = require('optimize'),
  22471. pragma = require('pragma'),
  22472. transform = require('transform'),
  22473. requirePatch = require('requirePatch'),
  22474. env = require('env'),
  22475. commonJs = require('commonJs'),
  22476. SourceMapGenerator = require('source-map').SourceMapGenerator,
  22477. hasProp = lang.hasProp,
  22478. getOwn = lang.getOwn,
  22479. falseProp = lang.falseProp,
  22480. endsWithSemiColonRegExp = /;\s*$/,
  22481. endsWithSlashRegExp = /[\/\\]$/,
  22482. resourceIsModuleIdRegExp = /^[\w\/\\\.]+$/,
  22483. deepCopyProps = {
  22484. layerobj: true
  22485. };
  22486. //Deep copy a config object, but do not copy over the "layerobj" property,
  22487. //as it can be a deeply nested structure with a full requirejs context.
  22488. function copyConfig(obj) {
  22489. return lang.deeplikeCopy(obj, deepCopyProps);
  22490. }
  22491. prim.nextTick = function (fn) {
  22492. fn();
  22493. };
  22494. //Now map require to the outermost requirejs, now that we have
  22495. //local dependencies for this module. The rest of the require use is
  22496. //manipulating the requirejs loader.
  22497. require = requirejs;
  22498. //Caching function for performance. Attached to
  22499. //require so it can be reused in requirePatch.js. _cachedRawText
  22500. //set up by requirePatch.js
  22501. require._cacheReadAsync = function (path, encoding) {
  22502. var d;
  22503. if (lang.hasProp(require._cachedRawText, path)) {
  22504. d = prim();
  22505. d.resolve(require._cachedRawText[path]);
  22506. return d.promise;
  22507. } else {
  22508. return file.readFileAsync(path, encoding).then(function (text) {
  22509. require._cachedRawText[path] = text;
  22510. return text;
  22511. });
  22512. }
  22513. };
  22514. function makeBuildBaseConfig() {
  22515. return {
  22516. appDir: "",
  22517. pragmas: {},
  22518. paths: {},
  22519. optimize: "uglify",
  22520. optimizeCss: "standard.keepLines.keepWhitespace",
  22521. inlineText: true,
  22522. isBuild: true,
  22523. optimizeAllPluginResources: false,
  22524. findNestedDependencies: false,
  22525. preserveLicenseComments: true,
  22526. writeBuildTxt: true,
  22527. //Some builds can take a while, up the default limit.
  22528. waitSeconds: 30,
  22529. //By default, all files/directories are copied, unless
  22530. //they match this regexp, by default just excludes .folders
  22531. dirExclusionRegExp: file.dirExclusionRegExp,
  22532. _buildPathToModuleIndex: {}
  22533. };
  22534. }
  22535. /**
  22536. * Some JS may not be valid if concatenated with other JS, in particular
  22537. * the style of omitting semicolons and rely on ASI. Add a semicolon in
  22538. * those cases.
  22539. */
  22540. function addSemiColon(text, config) {
  22541. if (config.skipSemiColonInsertion || endsWithSemiColonRegExp.test(text)) {
  22542. return text;
  22543. } else {
  22544. return text + ";";
  22545. }
  22546. }
  22547. function endsWithSlash(dirName) {
  22548. if (dirName.charAt(dirName.length - 1) !== "/") {
  22549. dirName += "/";
  22550. }
  22551. return dirName;
  22552. }
  22553. function endsWithNewLine(text) {
  22554. if (text.charAt(text.length - 1) !== "\n") {
  22555. text += "\n";
  22556. }
  22557. return text;
  22558. }
  22559. //Method used by plugin writeFile calls, defined up here to avoid
  22560. //jslint warning about "making a function in a loop".
  22561. function makeWriteFile(namespace, layerobj) {
  22562. function writeFile(name, contents) {
  22563. logger.trace('Saving plugin-optimized file: ' + name);
  22564. file.saveUtf8File(name, contents);
  22565. }
  22566. writeFile.asModule = function (moduleName, fileName, contents) {
  22567. writeFile(fileName,
  22568. build.toTransport(namespace, moduleName, fileName, contents, layerobj));
  22569. };
  22570. return writeFile;
  22571. }
  22572. /**
  22573. * Appends singleContents to fileContents and returns the result. If a sourceMapGenerator
  22574. * is provided, adds singleContents to the source map.
  22575. *
  22576. * @param {string} fileContents - The file contents to which to append singleContents
  22577. * @param {string} singleContents - The additional contents to append to fileContents
  22578. * @param {string} path - An absolute path of a file whose name to use in the source map.
  22579. * The file need not actually exist if the code in singleContents is generated.
  22580. * @param {{out: ?string, baseUrl: ?string}} config - The build configuration object.
  22581. * @param {?{_buildPath: ?string}} module - An object with module information.
  22582. * @param {?SourceMapGenerator} sourceMapGenerator - An instance of Mozilla's SourceMapGenerator,
  22583. * or null if no source map is being generated.
  22584. * @returns {string} fileContents with singleContents appended
  22585. */
  22586. function appendToFileContents(fileContents, singleContents, path, config, module, sourceMapGenerator) {
  22587. var refPath, sourceMapPath, resourcePath, pluginId, sourceMapLineNumber, lineCount, parts, i;
  22588. if (sourceMapGenerator) {
  22589. if (config.out) {
  22590. refPath = config.baseUrl;
  22591. } else if (module && module._buildPath) {
  22592. refPath = module._buildPath;
  22593. } else {
  22594. refPath = "";
  22595. }
  22596. parts = path.split('!');
  22597. if (parts.length === 1) {
  22598. //Not a plugin resource, fix the path
  22599. sourceMapPath = build.makeRelativeFilePath(refPath, path);
  22600. } else {
  22601. //Plugin resource. If it looks like just a plugin
  22602. //followed by a module ID, pull off the plugin
  22603. //and put it at the end of the name, otherwise
  22604. //just leave it alone.
  22605. pluginId = parts.shift();
  22606. resourcePath = parts.join('!');
  22607. if (resourceIsModuleIdRegExp.test(resourcePath)) {
  22608. sourceMapPath = build.makeRelativeFilePath(refPath, require.toUrl(resourcePath)) +
  22609. '!' + pluginId;
  22610. } else {
  22611. sourceMapPath = path;
  22612. }
  22613. }
  22614. sourceMapLineNumber = fileContents.split('\n').length - 1;
  22615. lineCount = singleContents.split('\n').length;
  22616. for (i = 1; i <= lineCount; i += 1) {
  22617. sourceMapGenerator.addMapping({
  22618. generated: {
  22619. line: sourceMapLineNumber + i,
  22620. column: 0
  22621. },
  22622. original: {
  22623. line: i,
  22624. column: 0
  22625. },
  22626. source: sourceMapPath
  22627. });
  22628. }
  22629. //Store the content of the original in the source
  22630. //map since other transforms later like minification
  22631. //can mess up translating back to the original
  22632. //source.
  22633. sourceMapGenerator.setSourceContent(sourceMapPath, singleContents);
  22634. }
  22635. fileContents += singleContents;
  22636. return fileContents;
  22637. }
  22638. /**
  22639. * Main API entry point into the build. The args argument can either be
  22640. * an array of arguments (like the onese passed on a command-line),
  22641. * or it can be a JavaScript object that has the format of a build profile
  22642. * file.
  22643. *
  22644. * If it is an object, then in addition to the normal properties allowed in
  22645. * a build profile file, the object should contain one other property:
  22646. *
  22647. * The object could also contain a "buildFile" property, which is a string
  22648. * that is the file path to a build profile that contains the rest
  22649. * of the build profile directives.
  22650. *
  22651. * This function does not return a status, it should throw an error if
  22652. * there is a problem completing the build.
  22653. */
  22654. build = function (args) {
  22655. var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree,
  22656. i, j, errorMod,
  22657. stackRegExp = /( {4}at[^\n]+)\n/,
  22658. standardIndent = ' ';
  22659. return prim().start(function () {
  22660. if (!args || lang.isArray(args)) {
  22661. if (!args || args.length < 1) {
  22662. logger.error("build.js buildProfile.js\n" +
  22663. "where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file).");
  22664. return undefined;
  22665. }
  22666. //Next args can include a build file path as well as other build args.
  22667. //build file path comes first. If it does not contain an = then it is
  22668. //a build file path. Otherwise, just all build args.
  22669. if (args[0].indexOf("=") === -1) {
  22670. buildFile = args[0];
  22671. args.splice(0, 1);
  22672. }
  22673. //Remaining args are options to the build
  22674. cmdConfig = build.convertArrayToObject(args);
  22675. cmdConfig.buildFile = buildFile;
  22676. } else {
  22677. cmdConfig = args;
  22678. }
  22679. return build._run(cmdConfig);
  22680. }).then(null, function (e) {
  22681. var err;
  22682. errorMsg = e.toString();
  22683. errorTree = e.moduleTree;
  22684. stackMatch = stackRegExp.exec(errorMsg);
  22685. if (stackMatch) {
  22686. errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1);
  22687. }
  22688. //If a module tree that shows what module triggered the error,
  22689. //print it out.
  22690. if (errorTree && errorTree.length > 0) {
  22691. errorMsg += '\nIn module tree:\n';
  22692. for (i = errorTree.length - 1; i > -1; i--) {
  22693. errorMod = errorTree[i];
  22694. if (errorMod) {
  22695. for (j = errorTree.length - i; j > -1; j--) {
  22696. errorMsg += standardIndent;
  22697. }
  22698. errorMsg += errorMod + '\n';
  22699. }
  22700. }
  22701. logger.error(errorMsg);
  22702. }
  22703. errorStack = e.stack;
  22704. if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) {
  22705. errorMsg += '\n' + errorStack;
  22706. } else {
  22707. if (!stackMatch && errorStack) {
  22708. //Just trim out the first "at" in the stack.
  22709. stackMatch = stackRegExp.exec(errorStack);
  22710. if (stackMatch) {
  22711. errorMsg += '\n' + stackMatch[0] || '';
  22712. }
  22713. }
  22714. }
  22715. err = new Error(errorMsg);
  22716. err.originalError = e;
  22717. throw err;
  22718. });
  22719. };
  22720. build._run = function (cmdConfig) {
  22721. var buildPaths, fileName, fileNames,
  22722. paths, i,
  22723. baseConfig, config,
  22724. modules, srcPath, buildContext,
  22725. destPath, moduleMap, parentModuleMap, context,
  22726. resources, resource, plugin, fileContents,
  22727. pluginProcessed = {},
  22728. buildFileContents = "",
  22729. pluginCollector = {};
  22730. return prim().start(function () {
  22731. var prop;
  22732. //Can now run the patches to require.js to allow it to be used for
  22733. //build generation. Do it here instead of at the top of the module
  22734. //because we want normal require behavior to load the build tool
  22735. //then want to switch to build mode.
  22736. requirePatch();
  22737. config = build.createConfig(cmdConfig);
  22738. paths = config.paths;
  22739. //Remove the previous build dir, in case it contains source transforms,
  22740. //like the ones done with onBuildRead and onBuildWrite.
  22741. if (config.dir && !config.keepBuildDir && file.exists(config.dir)) {
  22742. file.deleteFile(config.dir);
  22743. }
  22744. if (!config.out && !config.cssIn) {
  22745. //This is not just a one-off file build but a full build profile, with
  22746. //lots of files to process.
  22747. //First copy all the baseUrl content
  22748. file.copyDir((config.appDir || config.baseUrl), config.dir, /\w/, true);
  22749. //Adjust baseUrl if config.appDir is in play, and set up build output paths.
  22750. buildPaths = {};
  22751. if (config.appDir) {
  22752. //All the paths should be inside the appDir, so just adjust
  22753. //the paths to use the dirBaseUrl
  22754. for (prop in paths) {
  22755. if (hasProp(paths, prop)) {
  22756. buildPaths[prop] = paths[prop].replace(config.appDir, config.dir);
  22757. }
  22758. }
  22759. } else {
  22760. //If no appDir, then make sure to copy the other paths to this directory.
  22761. for (prop in paths) {
  22762. if (hasProp(paths, prop)) {
  22763. //Set up build path for each path prefix, but only do so
  22764. //if the path falls out of the current baseUrl
  22765. if (paths[prop].indexOf(config.baseUrl) === 0) {
  22766. buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl);
  22767. } else {
  22768. buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop;
  22769. //Make sure source path is fully formed with baseUrl,
  22770. //if it is a relative URL.
  22771. srcPath = paths[prop];
  22772. if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) {
  22773. srcPath = config.baseUrl + srcPath;
  22774. }
  22775. destPath = config.dirBaseUrl + buildPaths[prop];
  22776. //Skip empty: paths
  22777. if (srcPath !== 'empty:') {
  22778. //If the srcPath is a directory, copy the whole directory.
  22779. if (file.exists(srcPath) && file.isDirectory(srcPath)) {
  22780. //Copy files to build area. Copy all files (the /\w/ regexp)
  22781. file.copyDir(srcPath, destPath, /\w/, true);
  22782. } else {
  22783. //Try a .js extension
  22784. srcPath += '.js';
  22785. destPath += '.js';
  22786. file.copyFile(srcPath, destPath);
  22787. }
  22788. }
  22789. }
  22790. }
  22791. }
  22792. }
  22793. }
  22794. //Figure out source file location for each module layerobj. Do this by seeding require
  22795. //with source area configuration. This is needed so that later the module layerobjs
  22796. //can be manually copied over to the source area, since the build may be
  22797. //require multiple times and the above copyDir call only copies newer files.
  22798. require({
  22799. baseUrl: config.baseUrl,
  22800. paths: paths,
  22801. packagePaths: config.packagePaths,
  22802. packages: config.packages
  22803. });
  22804. buildContext = require.s.contexts._;
  22805. modules = config.modules;
  22806. if (modules) {
  22807. modules.forEach(function (module) {
  22808. if (module.name) {
  22809. module._sourcePath = buildContext.nameToUrl(module.name);
  22810. //If the module does not exist, and this is not a "new" module layerobj,
  22811. //as indicated by a true "create" property on the module, and
  22812. //it is not a plugin-loaded resource, and there is no
  22813. //'rawText' containing the module's source then throw an error.
  22814. if (!file.exists(module._sourcePath) && !module.create &&
  22815. module.name.indexOf('!') === -1 &&
  22816. (!config.rawText || !lang.hasProp(config.rawText, module.name))) {
  22817. throw new Error("ERROR: module path does not exist: " +
  22818. module._sourcePath + " for module named: " + module.name +
  22819. ". Path is relative to: " + file.absPath('.'));
  22820. }
  22821. }
  22822. });
  22823. }
  22824. if (config.out) {
  22825. //Just set up the _buildPath for the module layerobj.
  22826. require(config);
  22827. if (!config.cssIn) {
  22828. config.modules[0]._buildPath = typeof config.out === 'function' ?
  22829. 'FUNCTION' : config.out;
  22830. }
  22831. } else if (!config.cssIn) {
  22832. //Now set up the config for require to use the build area, and calculate the
  22833. //build file locations. Pass along any config info too.
  22834. baseConfig = {
  22835. baseUrl: config.dirBaseUrl,
  22836. paths: buildPaths
  22837. };
  22838. lang.mixin(baseConfig, config);
  22839. require(baseConfig);
  22840. if (modules) {
  22841. modules.forEach(function (module) {
  22842. if (module.name) {
  22843. module._buildPath = buildContext.nameToUrl(module.name, null);
  22844. //If buildPath and sourcePath are the same, throw since this
  22845. //would result in modifying source. This condition can happen
  22846. //with some more tricky paths: config and appDir/baseUrl
  22847. //setting, which is a sign of incorrect config.
  22848. if (module._buildPath === module._sourcePath &&
  22849. !config.allowSourceOverwrites) {
  22850. throw new Error('Module ID \'' + module.name +
  22851. '\' has a source path that is same as output path: ' +
  22852. module._sourcePath +
  22853. '. Stopping, config is malformed.');
  22854. }
  22855. // Copy the file, but only if it is not provided in rawText.
  22856. if (!module.create && (!config.rawText || !lang.hasProp(config.rawText, module.name))) {
  22857. file.copyFile(module._sourcePath, module._buildPath);
  22858. }
  22859. }
  22860. });
  22861. }
  22862. }
  22863. //Run CSS optimizations before doing JS module tracing, to allow
  22864. //things like text loader plugins loading CSS to get the optimized
  22865. //CSS.
  22866. if (config.optimizeCss && config.optimizeCss !== "none" && config.dir) {
  22867. buildFileContents += optimize.css(config.dir, config);
  22868. }
  22869. }).then(function() {
  22870. baseConfig = copyConfig(require.s.contexts._.config);
  22871. }).then(function () {
  22872. var actions = [];
  22873. if (modules) {
  22874. actions = modules.map(function (module, i) {
  22875. return function () {
  22876. //Save off buildPath to module index in a hash for quicker
  22877. //lookup later.
  22878. config._buildPathToModuleIndex[file.normalize(module._buildPath)] = i;
  22879. //Call require to calculate dependencies.
  22880. return build.traceDependencies(module, config, baseConfig)
  22881. .then(function (layerobj) {
  22882. module.layerobj = layerobj;
  22883. });
  22884. };
  22885. });
  22886. return prim.serial(actions);
  22887. }
  22888. }).then(function () {
  22889. var actions;
  22890. if (modules) {
  22891. //Now build up shadow layerobjs for anything that should be excluded.
  22892. //Do this after tracing dependencies for each module, in case one
  22893. //of those modules end up being one of the excluded values.
  22894. actions = modules.map(function (module) {
  22895. return function () {
  22896. if (module.exclude) {
  22897. module.excludeLayers = [];
  22898. return prim.serial(module.exclude.map(function (exclude, i) {
  22899. return function () {
  22900. //See if it is already in the list of modules.
  22901. //If not trace dependencies for it.
  22902. var found = build.findBuildModule(exclude, modules);
  22903. if (found) {
  22904. module.excludeLayers[i] = found;
  22905. } else {
  22906. return build.traceDependencies({name: exclude}, config, baseConfig)
  22907. .then(function (layerobj) {
  22908. module.excludeLayers[i] = { layerobj: layerobj };
  22909. });
  22910. }
  22911. };
  22912. }));
  22913. }
  22914. };
  22915. });
  22916. return prim.serial(actions);
  22917. }
  22918. }).then(function () {
  22919. if (modules) {
  22920. return prim.serial(modules.map(function (module) {
  22921. return function () {
  22922. if (module.exclude) {
  22923. //module.exclude is an array of module names. For each one,
  22924. //get the nested dependencies for it via a matching entry
  22925. //in the module.excludeLayers array.
  22926. module.exclude.forEach(function (excludeModule, i) {
  22927. var excludeLayer = module.excludeLayers[i].layerobj,
  22928. map = excludeLayer.buildFileToModule;
  22929. excludeLayer.buildFilePaths.forEach(function(filePath){
  22930. build.removeModulePath(map[filePath], filePath, module.layerobj);
  22931. });
  22932. });
  22933. }
  22934. if (module.excludeShallow) {
  22935. //module.excludeShallow is an array of module names.
  22936. //shallow exclusions are just that module itself, and not
  22937. //its nested dependencies.
  22938. module.excludeShallow.forEach(function (excludeShallowModule) {
  22939. var path = getOwn(module.layerobj.buildPathMap, excludeShallowModule);
  22940. if (path) {
  22941. build.removeModulePath(excludeShallowModule, path, module.layerobj);
  22942. }
  22943. });
  22944. }
  22945. //Flatten them and collect the build output for each module.
  22946. return build.flattenModule(module, module.layerobj, config).then(function (builtModule) {
  22947. var finalText, baseName;
  22948. //Save it to a temp file for now, in case there are other layerobjs that
  22949. //contain optimized content that should not be included in later
  22950. //layerobj optimizations. See issue #56.
  22951. if (module._buildPath === 'FUNCTION') {
  22952. module._buildText = builtModule.text;
  22953. module._buildSourceMap = builtModule.sourceMap;
  22954. } else {
  22955. finalText = builtModule.text;
  22956. if (builtModule.sourceMap) {
  22957. baseName = module._buildPath.split('/');
  22958. baseName = baseName.pop();
  22959. finalText += '\n//# sourceMappingURL=' + baseName + '.map';
  22960. file.saveUtf8File(module._buildPath + '.map', builtModule.sourceMap);
  22961. }
  22962. file.saveUtf8File(module._buildPath + '-temp', finalText);
  22963. }
  22964. buildFileContents += builtModule.buildText;
  22965. });
  22966. };
  22967. }));
  22968. }
  22969. }).then(function () {
  22970. var moduleName, outOrigSourceMap,
  22971. bundlesConfig = {},
  22972. bundlesConfigOutFile = config.bundlesConfigOutFile;
  22973. if (modules) {
  22974. //Now move the build layerobjs to their final position.
  22975. modules.forEach(function (module) {
  22976. var entryConfig,
  22977. finalPath = module._buildPath;
  22978. if (finalPath !== 'FUNCTION') {
  22979. if (file.exists(finalPath)) {
  22980. file.deleteFile(finalPath);
  22981. }
  22982. file.renameFile(finalPath + '-temp', finalPath);
  22983. //If bundles config should be written out, scan the
  22984. //built file for module IDs. Favor doing this reparse
  22985. //since tracking the IDs as the file is built has some
  22986. //edge cases around files that had more than one ID in
  22987. //them already, and likely loader plugin-written contents.
  22988. if (bundlesConfigOutFile) {
  22989. entryConfig = bundlesConfig[module.name] = [];
  22990. var bundleContents = file.readFile(finalPath);
  22991. var excludeMap = {};
  22992. excludeMap[module.name] = true;
  22993. var parsedIds = parse.getAllNamedDefines(bundleContents, excludeMap);
  22994. entryConfig.push.apply(entryConfig, parsedIds);
  22995. }
  22996. //And finally, if removeCombined is specified, remove
  22997. //any of the files that were used in this layerobj.
  22998. //Be sure not to remove other build layerobjs.
  22999. if (config.removeCombined && !config.out) {
  23000. module.layerobj.buildFilePaths.forEach(function (path) {
  23001. var isLayer = modules.some(function (mod) {
  23002. return mod._buildPath === path;
  23003. }),
  23004. relPath = build.makeRelativeFilePath(config.dir, path);
  23005. if (file.exists(path) &&
  23006. // not a build layerobj target
  23007. !isLayer &&
  23008. // not outside the build directory
  23009. relPath.indexOf('..') !== 0) {
  23010. file.deleteFile(path);
  23011. }
  23012. });
  23013. }
  23014. }
  23015. //Signal layerobj is done
  23016. if (config.onModuleBundleComplete) {
  23017. config.onModuleBundleComplete(module.onCompleteData);
  23018. }
  23019. });
  23020. //Write out bundles config, if it is wanted.
  23021. if (bundlesConfigOutFile) {
  23022. var text = file.readFile(bundlesConfigOutFile);
  23023. text = transform.modifyConfig(text, function (config) {
  23024. if (!config.bundles) {
  23025. config.bundles = {};
  23026. }
  23027. lang.eachProp(bundlesConfig, function (value, prop) {
  23028. config.bundles[prop] = value;
  23029. });
  23030. return config;
  23031. });
  23032. file.saveUtf8File(bundlesConfigOutFile, text);
  23033. }
  23034. }
  23035. //If removeCombined in play, remove any empty directories that
  23036. //may now exist because of its use
  23037. if (config.removeCombined && !config.out && config.dir) {
  23038. file.deleteEmptyDirs(config.dir);
  23039. }
  23040. //Do other optimizations.
  23041. if (config.out && !config.cssIn) {
  23042. //Just need to worry about one JS file.
  23043. fileName = config.modules[0]._buildPath;
  23044. if (fileName === 'FUNCTION') {
  23045. outOrigSourceMap = config.modules[0]._buildSourceMap;
  23046. config._buildSourceMap = outOrigSourceMap;
  23047. config.modules[0]._buildText = optimize.js((config.modules[0].name ||
  23048. config.modules[0].include[0] ||
  23049. fileName) + '.build.js',
  23050. config.modules[0]._buildText,
  23051. null,
  23052. config);
  23053. if (config._buildSourceMap && config._buildSourceMap !== outOrigSourceMap) {
  23054. config.modules[0]._buildSourceMap = config._buildSourceMap;
  23055. config._buildSourceMap = null;
  23056. }
  23057. } else {
  23058. optimize.jsFile(fileName, null, fileName, config);
  23059. }
  23060. } else if (!config.cssIn) {
  23061. //Normal optimizations across modules.
  23062. //JS optimizations.
  23063. fileNames = file.getFilteredFileList(config.dir, /\.js$/, true);
  23064. fileNames.forEach(function (fileName) {
  23065. var cfg, override, moduleIndex;
  23066. //Generate the module name from the config.dir root.
  23067. moduleName = fileName.replace(config.dir, '');
  23068. //Get rid of the extension
  23069. moduleName = moduleName.substring(0, moduleName.length - 3);
  23070. //If there is an override for a specific layerobj build module,
  23071. //and this file is that module, mix in the override for use
  23072. //by optimize.jsFile.
  23073. moduleIndex = getOwn(config._buildPathToModuleIndex, fileName);
  23074. //Normalize, since getOwn could have returned undefined
  23075. moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1;
  23076. //Try to avoid extra work if the other files do not need to
  23077. //be read. Build layerobjs should be processed at the very
  23078. //least for optimization.
  23079. if (moduleIndex > -1 || !config.skipDirOptimize ||
  23080. config.normalizeDirDefines === "all" ||
  23081. config.cjsTranslate) {
  23082. //Convert the file to transport format, but without a name
  23083. //inserted (by passing null for moduleName) since the files are
  23084. //standalone, one module per file.
  23085. fileContents = file.readFile(fileName);
  23086. //For builds, if wanting cjs translation, do it now, so that
  23087. //the individual modules can be loaded cross domain via
  23088. //plain script tags.
  23089. if (config.cjsTranslate &&
  23090. (!config.shim || !lang.hasProp(config.shim, moduleName))) {
  23091. fileContents = commonJs.convert(fileName, fileContents);
  23092. }
  23093. if (moduleIndex === -1) {
  23094. if (config.onBuildRead) {
  23095. fileContents = config.onBuildRead(moduleName,
  23096. fileName,
  23097. fileContents);
  23098. }
  23099. //Only do transport normalization if this is not a build
  23100. //layerobj (since it was already normalized) and if
  23101. //normalizeDirDefines indicated all should be done.
  23102. if (config.normalizeDirDefines === "all") {
  23103. fileContents = build.toTransport(config.namespace,
  23104. null,
  23105. fileName,
  23106. fileContents);
  23107. }
  23108. if (config.onBuildWrite) {
  23109. fileContents = config.onBuildWrite(moduleName,
  23110. fileName,
  23111. fileContents);
  23112. }
  23113. }
  23114. override = moduleIndex > -1 ?
  23115. config.modules[moduleIndex].override : null;
  23116. if (override) {
  23117. cfg = build.createOverrideConfig(config, override);
  23118. } else {
  23119. cfg = config;
  23120. }
  23121. if (moduleIndex > -1 || !config.skipDirOptimize) {
  23122. optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector);
  23123. }
  23124. }
  23125. });
  23126. //Normalize all the plugin resources.
  23127. context = require.s.contexts._;
  23128. for (moduleName in pluginCollector) {
  23129. if (hasProp(pluginCollector, moduleName)) {
  23130. parentModuleMap = context.makeModuleMap(moduleName);
  23131. resources = pluginCollector[moduleName];
  23132. for (i = 0; i < resources.length; i++) {
  23133. resource = resources[i];
  23134. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  23135. if (falseProp(context.plugins, moduleMap.prefix)) {
  23136. //Set the value in context.plugins so it
  23137. //will be evaluated as a full plugin.
  23138. context.plugins[moduleMap.prefix] = true;
  23139. //Do not bother if the plugin is not available.
  23140. if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) {
  23141. continue;
  23142. }
  23143. //Rely on the require in the build environment
  23144. //to be synchronous
  23145. context.require([moduleMap.prefix]);
  23146. //Now that the plugin is loaded, redo the moduleMap
  23147. //since the plugin will need to normalize part of the path.
  23148. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  23149. }
  23150. //Only bother with plugin resources that can be handled
  23151. //processed by the plugin, via support of the writeFile
  23152. //method.
  23153. if (falseProp(pluginProcessed, moduleMap.id)) {
  23154. //Only do the work if the plugin was really loaded.
  23155. //Using an internal access because the file may
  23156. //not really be loaded.
  23157. plugin = getOwn(context.defined, moduleMap.prefix);
  23158. if (plugin && plugin.writeFile) {
  23159. plugin.writeFile(
  23160. moduleMap.prefix,
  23161. moduleMap.name,
  23162. require,
  23163. makeWriteFile(
  23164. config.namespace
  23165. ),
  23166. context.config
  23167. );
  23168. }
  23169. pluginProcessed[moduleMap.id] = true;
  23170. }
  23171. }
  23172. }
  23173. }
  23174. //console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, " "));
  23175. //All module layerobjs are done, write out the build.txt file.
  23176. if (config.writeBuildTxt) {
  23177. file.saveUtf8File(config.dir + "build.txt", buildFileContents);
  23178. }
  23179. }
  23180. //If just have one CSS file to optimize, do that here.
  23181. if (config.cssIn) {
  23182. buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText;
  23183. }
  23184. if (typeof config.out === 'function') {
  23185. config.out(config.modules[0]._buildText, config.modules[0]._buildSourceMap);
  23186. }
  23187. //Print out what was built into which layerobjs.
  23188. if (buildFileContents) {
  23189. logger.info(buildFileContents);
  23190. return buildFileContents;
  23191. }
  23192. return '';
  23193. });
  23194. };
  23195. /**
  23196. * Converts command line args like "paths.foo=../some/path"
  23197. * result.paths = { foo: '../some/path' } where prop = paths,
  23198. * name = paths.foo and value = ../some/path, so it assumes the
  23199. * name=value splitting has already happened.
  23200. */
  23201. function stringDotToObj(result, name, value) {
  23202. var parts = name.split('.');
  23203. parts.forEach(function (prop, i) {
  23204. if (i === parts.length - 1) {
  23205. result[prop] = value;
  23206. } else {
  23207. if (falseProp(result, prop)) {
  23208. result[prop] = {};
  23209. }
  23210. result = result[prop];
  23211. }
  23212. });
  23213. }
  23214. build.objProps = {
  23215. paths: true,
  23216. wrap: true,
  23217. pragmas: true,
  23218. pragmasOnSave: true,
  23219. has: true,
  23220. hasOnSave: true,
  23221. uglify: true,
  23222. uglify2: true,
  23223. closure: true,
  23224. map: true,
  23225. throwWhen: true
  23226. };
  23227. build.hasDotPropMatch = function (prop) {
  23228. var dotProp,
  23229. index = prop.indexOf('.');
  23230. if (index !== -1) {
  23231. dotProp = prop.substring(0, index);
  23232. return hasProp(build.objProps, dotProp);
  23233. }
  23234. return false;
  23235. };
  23236. /**
  23237. * Converts an array that has String members of "name=value"
  23238. * into an object, where the properties on the object are the names in the array.
  23239. * Also converts the strings "true" and "false" to booleans for the values.
  23240. * member name/value pairs, and converts some comma-separated lists into
  23241. * arrays.
  23242. * @param {Array} ary
  23243. */
  23244. build.convertArrayToObject = function (ary) {
  23245. var result = {}, i, separatorIndex, prop, value,
  23246. needArray = {
  23247. "include": true,
  23248. "exclude": true,
  23249. "excludeShallow": true,
  23250. "insertRequire": true,
  23251. "stubModules": true,
  23252. "deps": true,
  23253. "mainConfigFile": true,
  23254. "wrap.startFile": true,
  23255. "wrap.endFile": true
  23256. };
  23257. for (i = 0; i < ary.length; i++) {
  23258. separatorIndex = ary[i].indexOf("=");
  23259. if (separatorIndex === -1) {
  23260. throw "Malformed name/value pair: [" + ary[i] + "]. Format should be name=value";
  23261. }
  23262. value = ary[i].substring(separatorIndex + 1, ary[i].length);
  23263. if (value === "true") {
  23264. value = true;
  23265. } else if (value === "false") {
  23266. value = false;
  23267. }
  23268. prop = ary[i].substring(0, separatorIndex);
  23269. //Convert to array if necessary
  23270. if (getOwn(needArray, prop)) {
  23271. value = value.split(",");
  23272. }
  23273. if (build.hasDotPropMatch(prop)) {
  23274. stringDotToObj(result, prop, value);
  23275. } else {
  23276. result[prop] = value;
  23277. }
  23278. }
  23279. return result; //Object
  23280. };
  23281. build.makeAbsPath = function (path, absFilePath) {
  23282. if (!absFilePath) {
  23283. return path;
  23284. }
  23285. //Add abspath if necessary. If path starts with a slash or has a colon,
  23286. //then already is an abolute path.
  23287. if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) {
  23288. path = absFilePath +
  23289. (absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') +
  23290. path;
  23291. path = file.normalize(path);
  23292. }
  23293. return path.replace(lang.backSlashRegExp, '/');
  23294. };
  23295. build.makeAbsObject = function (props, obj, absFilePath) {
  23296. var i, prop;
  23297. if (obj) {
  23298. for (i = 0; i < props.length; i++) {
  23299. prop = props[i];
  23300. if (hasProp(obj, prop) && typeof obj[prop] === 'string') {
  23301. obj[prop] = build.makeAbsPath(obj[prop], absFilePath);
  23302. }
  23303. }
  23304. }
  23305. };
  23306. /**
  23307. * For any path in a possible config, make it absolute relative
  23308. * to the absFilePath passed in.
  23309. */
  23310. build.makeAbsConfig = function (config, absFilePath) {
  23311. var props, prop, i;
  23312. props = ["appDir", "dir", "baseUrl"];
  23313. for (i = 0; i < props.length; i++) {
  23314. prop = props[i];
  23315. if (getOwn(config, prop)) {
  23316. //Add abspath if necessary, make sure these paths end in
  23317. //slashes
  23318. if (prop === "baseUrl") {
  23319. config.originalBaseUrl = config.baseUrl;
  23320. if (config.appDir) {
  23321. //If baseUrl with an appDir, the baseUrl is relative to
  23322. //the appDir, *not* the absFilePath. appDir and dir are
  23323. //made absolute before baseUrl, so this will work.
  23324. config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir);
  23325. } else {
  23326. //The dir output baseUrl is same as regular baseUrl, both
  23327. //relative to the absFilePath.
  23328. config.baseUrl = build.makeAbsPath(config[prop], absFilePath);
  23329. }
  23330. } else {
  23331. config[prop] = build.makeAbsPath(config[prop], absFilePath);
  23332. }
  23333. config[prop] = endsWithSlash(config[prop]);
  23334. }
  23335. }
  23336. build.makeAbsObject((config.out === "stdout" ? ["cssIn"] : ["out", "cssIn"]),
  23337. config, absFilePath);
  23338. build.makeAbsObject(["startFile", "endFile"], config.wrap, absFilePath);
  23339. build.makeAbsObject(["externExportsPath"], config.closure, absFilePath);
  23340. };
  23341. /**
  23342. * Creates a relative path to targetPath from refPath.
  23343. * Only deals with file paths, not folders. If folders,
  23344. * make sure paths end in a trailing '/'.
  23345. */
  23346. build.makeRelativeFilePath = function (refPath, targetPath) {
  23347. var i, dotLength, finalParts, length, targetParts, targetName,
  23348. refParts = refPath.split('/'),
  23349. hasEndSlash = endsWithSlashRegExp.test(targetPath),
  23350. dotParts = [];
  23351. targetPath = file.normalize(targetPath);
  23352. if (hasEndSlash && !endsWithSlashRegExp.test(targetPath)) {
  23353. targetPath += '/';
  23354. }
  23355. targetParts = targetPath.split('/');
  23356. //Pull off file name
  23357. targetName = targetParts.pop();
  23358. //Also pop off the ref file name to make the matches against
  23359. //targetParts equivalent.
  23360. refParts.pop();
  23361. length = refParts.length;
  23362. for (i = 0; i < length; i += 1) {
  23363. if (refParts[i] !== targetParts[i]) {
  23364. break;
  23365. }
  23366. }
  23367. //Now i is the index in which they diverge.
  23368. finalParts = targetParts.slice(i);
  23369. dotLength = length - i;
  23370. for (i = 0; i > -1 && i < dotLength; i += 1) {
  23371. dotParts.push('..');
  23372. }
  23373. return dotParts.join('/') + (dotParts.length ? '/' : '') +
  23374. finalParts.join('/') + (finalParts.length ? '/' : '') +
  23375. targetName;
  23376. };
  23377. build.nestedMix = {
  23378. paths: true,
  23379. has: true,
  23380. hasOnSave: true,
  23381. pragmas: true,
  23382. pragmasOnSave: true
  23383. };
  23384. /**
  23385. * Mixes additional source config into target config, and merges some
  23386. * nested config, like paths, correctly.
  23387. */
  23388. function mixConfig(target, source, skipArrays) {
  23389. var prop, value, isArray, targetValue;
  23390. for (prop in source) {
  23391. if (hasProp(source, prop)) {
  23392. //If the value of the property is a plain object, then
  23393. //allow a one-level-deep mixing of it.
  23394. value = source[prop];
  23395. isArray = lang.isArray(value);
  23396. if (typeof value === 'object' && value &&
  23397. !isArray && !lang.isFunction(value) &&
  23398. !lang.isRegExp(value)) {
  23399. // TODO: need to generalize this work, maybe also reuse
  23400. // the work done in requirejs configure, perhaps move to
  23401. // just a deep copy/merge overall. However, given the
  23402. // amount of observable change, wait for a dot release.
  23403. // This change is in relation to #645
  23404. if (prop === 'map') {
  23405. if (!target.map) {
  23406. target.map = {};
  23407. }
  23408. lang.deepMix(target.map, source.map);
  23409. } else {
  23410. target[prop] = lang.mixin({}, target[prop], value, true);
  23411. }
  23412. } else if (isArray) {
  23413. if (!skipArrays) {
  23414. // Some config, like packages, are arrays. For those,
  23415. // just merge the results.
  23416. targetValue = target[prop];
  23417. if (lang.isArray(targetValue)) {
  23418. target[prop] = targetValue.concat(value);
  23419. } else {
  23420. target[prop] = value;
  23421. }
  23422. }
  23423. } else {
  23424. target[prop] = value;
  23425. }
  23426. }
  23427. }
  23428. //Set up log level since it can affect if errors are thrown
  23429. //or caught and passed to errbacks while doing config setup.
  23430. if (lang.hasProp(target, 'logLevel')) {
  23431. logger.logLevel(target.logLevel);
  23432. }
  23433. }
  23434. /**
  23435. * Converts a wrap.startFile or endFile to be start/end as a string.
  23436. * the startFile/endFile values can be arrays.
  23437. */
  23438. function flattenWrapFile(config, keyName, absFilePath) {
  23439. var wrap = config.wrap,
  23440. keyFileName = keyName + 'File',
  23441. keyMapName = '__' + keyName + 'Map';
  23442. if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) {
  23443. wrap[keyName] = '';
  23444. if (typeof wrap[keyFileName] === 'string') {
  23445. wrap[keyFileName] = [wrap[keyFileName]];
  23446. }
  23447. wrap[keyMapName] = [];
  23448. wrap[keyFileName].forEach(function (fileName) {
  23449. var absPath = build.makeAbsPath(fileName, absFilePath),
  23450. fileText = endsWithNewLine(file.readFile(absPath));
  23451. wrap[keyMapName].push(function (fileContents, cfg, sourceMapGenerator) {
  23452. return appendToFileContents(fileContents, fileText, absPath, cfg, null, sourceMapGenerator);
  23453. });
  23454. wrap[keyName] += fileText;
  23455. });
  23456. } else if (wrap[keyName] === null || wrap[keyName] === undefined) {
  23457. //Allow missing one, just set to empty string.
  23458. wrap[keyName] = '';
  23459. } else if (typeof wrap[keyName] === 'string') {
  23460. wrap[keyName] = endsWithNewLine(wrap[keyName]);
  23461. wrap[keyMapName] = [
  23462. function (fileContents, cfg, sourceMapGenerator) {
  23463. var absPath = build.makeAbsPath("config-wrap-" + keyName + "-default.js", absFilePath);
  23464. return appendToFileContents(fileContents, wrap[keyName], absPath, cfg, null, sourceMapGenerator);
  23465. }
  23466. ];
  23467. } else {
  23468. throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed');
  23469. }
  23470. }
  23471. function normalizeWrapConfig(config, absFilePath) {
  23472. //Get any wrap text.
  23473. try {
  23474. if (config.wrap) {
  23475. if (config.wrap === true) {
  23476. //Use default values.
  23477. config.wrap = {
  23478. start: '(function () {\n',
  23479. end: '}());',
  23480. __startMap: [
  23481. function (fileContents, cfg, sourceMapGenerator) {
  23482. return appendToFileContents(fileContents, "(function () {\n",
  23483. build.makeAbsPath("config-wrap-start-default.js",
  23484. absFilePath), cfg, null,
  23485. sourceMapGenerator);
  23486. }
  23487. ],
  23488. __endMap: [
  23489. function (fileContents, cfg, sourceMapGenerator) {
  23490. return appendToFileContents(fileContents, "}());",
  23491. build.makeAbsPath("config-wrap-end-default.js", absFilePath),
  23492. cfg, null, sourceMapGenerator);
  23493. }
  23494. ]
  23495. };
  23496. } else {
  23497. flattenWrapFile(config, 'start', absFilePath);
  23498. flattenWrapFile(config, 'end', absFilePath);
  23499. }
  23500. }
  23501. } catch (wrapError) {
  23502. throw new Error('Malformed wrap config: ' + wrapError.toString());
  23503. }
  23504. }
  23505. /**
  23506. * Creates a config object for an optimization build.
  23507. * It will also read the build profile if it is available, to create
  23508. * the configuration.
  23509. *
  23510. * @param {Object} cfg config options that take priority
  23511. * over defaults and ones in the build file. These options could
  23512. * be from a command line, for instance.
  23513. *
  23514. * @param {Object} the created config object.
  23515. */
  23516. build.createConfig = function (cfg) {
  23517. /*jslint evil: true */
  23518. var buildFileContents, buildFileConfig, mainConfig,
  23519. mainConfigFile, mainConfigPath, buildFile, absFilePath,
  23520. config = {},
  23521. buildBaseConfig = makeBuildBaseConfig();
  23522. //Make sure all paths are relative to current directory.
  23523. absFilePath = file.absPath('.');
  23524. build.makeAbsConfig(cfg, absFilePath);
  23525. build.makeAbsConfig(buildBaseConfig, absFilePath);
  23526. lang.mixin(config, buildBaseConfig);
  23527. lang.mixin(config, cfg, true);
  23528. //Set up log level early since it can affect if errors are thrown
  23529. //or caught and passed to errbacks, even while constructing config.
  23530. if (lang.hasProp(config, 'logLevel')) {
  23531. logger.logLevel(config.logLevel);
  23532. }
  23533. if (config.buildFile) {
  23534. //A build file exists, load it to get more config.
  23535. buildFile = file.absPath(config.buildFile);
  23536. //Find the build file, and make sure it exists, if this is a build
  23537. //that has a build profile, and not just command line args with an in=path
  23538. if (!file.exists(buildFile)) {
  23539. throw new Error("ERROR: build file does not exist: " + buildFile);
  23540. }
  23541. absFilePath = config.baseUrl = file.absPath(file.parent(buildFile));
  23542. //Load build file options.
  23543. buildFileContents = file.readFile(buildFile);
  23544. try {
  23545. //Be a bit lenient in the file ending in a ; or ending with
  23546. //a //# sourceMappingUrl comment, mostly for compiled languages
  23547. //that create a config, like typescript.
  23548. buildFileContents = buildFileContents
  23549. .replace(/\/\/\#[^\n\r]+[\n\r]*$/, '')
  23550. .trim()
  23551. .replace(/;$/, '');
  23552. buildFileConfig = eval("(" + buildFileContents + ")");
  23553. build.makeAbsConfig(buildFileConfig, absFilePath);
  23554. //Mix in the config now so that items in mainConfigFile can
  23555. //be resolved relative to them if necessary, like if appDir
  23556. //is set here, but the baseUrl is in mainConfigFile. Will
  23557. //re-mix in the same build config later after mainConfigFile
  23558. //is processed, since build config should take priority.
  23559. mixConfig(config, buildFileConfig);
  23560. } catch (e) {
  23561. throw new Error("Build file " + buildFile + " is malformed: " + e);
  23562. }
  23563. }
  23564. mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile);
  23565. if (mainConfigFile) {
  23566. if (typeof mainConfigFile === 'string') {
  23567. mainConfigFile = [mainConfigFile];
  23568. }
  23569. mainConfigFile.forEach(function (configFile) {
  23570. configFile = build.makeAbsPath(configFile, absFilePath);
  23571. if (!file.exists(configFile)) {
  23572. throw new Error(configFile + ' does not exist.');
  23573. }
  23574. try {
  23575. mainConfig = parse.findConfig(file.readFile(configFile)).config;
  23576. } catch (configError) {
  23577. throw new Error('The config in mainConfigFile ' +
  23578. configFile +
  23579. ' cannot be used because it cannot be evaluated' +
  23580. ' correctly while running in the optimizer. Try only' +
  23581. ' using a config that is also valid JSON, or do not use' +
  23582. ' mainConfigFile and instead copy the config values needed' +
  23583. ' into a build file or command line arguments given to the optimizer.\n' +
  23584. 'Source error from parsing: ' + configFile + ': ' + configError);
  23585. }
  23586. if (mainConfig) {
  23587. mainConfigPath = configFile.substring(0, configFile.lastIndexOf('/'));
  23588. //Add in some existing config, like appDir, since they can be
  23589. //used inside the configFile -- paths and baseUrl are
  23590. //relative to them.
  23591. if (config.appDir && !mainConfig.appDir) {
  23592. mainConfig.appDir = config.appDir;
  23593. }
  23594. //If no baseUrl, then use the directory holding the main config.
  23595. if (!mainConfig.baseUrl) {
  23596. mainConfig.baseUrl = mainConfigPath;
  23597. }
  23598. build.makeAbsConfig(mainConfig, mainConfigPath);
  23599. mixConfig(config, mainConfig);
  23600. }
  23601. });
  23602. }
  23603. //Mix in build file config, but only after mainConfig has been mixed in.
  23604. //Since this is a re-application, skip array merging.
  23605. if (buildFileConfig) {
  23606. mixConfig(config, buildFileConfig, true);
  23607. }
  23608. //Re-apply the override config values. Command line
  23609. //args should take precedence over build file values.
  23610. //Since this is a re-application, skip array merging.
  23611. mixConfig(config, cfg, true);
  23612. //Fix paths to full paths so that they can be adjusted consistently
  23613. //lately to be in the output area.
  23614. lang.eachProp(config.paths, function (value, prop) {
  23615. if (lang.isArray(value)) {
  23616. throw new Error('paths fallback not supported in optimizer. ' +
  23617. 'Please provide a build config path override ' +
  23618. 'for ' + prop);
  23619. }
  23620. config.paths[prop] = build.makeAbsPath(value, config.baseUrl);
  23621. });
  23622. //Set final output dir
  23623. if (hasProp(config, "baseUrl")) {
  23624. if (config.appDir) {
  23625. if (!config.originalBaseUrl) {
  23626. throw new Error('Please set a baseUrl in the build config');
  23627. }
  23628. config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir);
  23629. } else {
  23630. config.dirBaseUrl = config.dir || config.baseUrl;
  23631. }
  23632. //Make sure dirBaseUrl ends in a slash, since it is
  23633. //concatenated with other strings.
  23634. config.dirBaseUrl = endsWithSlash(config.dirBaseUrl);
  23635. }
  23636. if (config.bundlesConfigOutFile) {
  23637. if (!config.dir) {
  23638. throw new Error('bundlesConfigOutFile can only be used with optimizations ' +
  23639. 'that use "dir".');
  23640. }
  23641. config.bundlesConfigOutFile = build.makeAbsPath(config.bundlesConfigOutFile, config.dir);
  23642. }
  23643. //If out=stdout, write output to STDOUT instead of a file.
  23644. if (config.out && config.out === 'stdout') {
  23645. config.out = function (content) {
  23646. var e = env.get();
  23647. if (e === 'rhino') {
  23648. var out = new java.io.PrintStream(java.lang.System.out, true, 'UTF-8');
  23649. out.println(content);
  23650. } else if (e === 'node') {
  23651. process.stdout.setEncoding('utf8');
  23652. process.stdout.write(content);
  23653. } else {
  23654. console.log(content);
  23655. }
  23656. };
  23657. }
  23658. //Check for errors in config
  23659. if (config.main) {
  23660. throw new Error('"main" passed as an option, but the ' +
  23661. 'supported option is called "name".');
  23662. }
  23663. if (config.out && !config.name && !config.modules && !config.include &&
  23664. !config.cssIn) {
  23665. throw new Error('Missing either a "name", "include" or "modules" ' +
  23666. 'option');
  23667. }
  23668. if (config.cssIn) {
  23669. if (config.dir || config.appDir) {
  23670. throw new Error('cssIn is only for the output of single file ' +
  23671. 'CSS optimizations and is not compatible with "dir" or "appDir" configuration.');
  23672. }
  23673. if (!config.out) {
  23674. throw new Error('"out" option missing.');
  23675. }
  23676. }
  23677. if (!config.cssIn && !config.baseUrl) {
  23678. //Just use the current directory as the baseUrl
  23679. config.baseUrl = './';
  23680. }
  23681. if (!config.out && !config.dir) {
  23682. throw new Error('Missing either an "out" or "dir" config value. ' +
  23683. 'If using "appDir" for a full project optimization, ' +
  23684. 'use "dir". If you want to optimize to one file, ' +
  23685. 'use "out".');
  23686. }
  23687. if (config.appDir && config.out) {
  23688. throw new Error('"appDir" is not compatible with "out". Use "dir" ' +
  23689. 'instead. appDir is used to copy whole projects, ' +
  23690. 'where "out" with "baseUrl" is used to just ' +
  23691. 'optimize to one file.');
  23692. }
  23693. if (config.out && config.dir) {
  23694. throw new Error('The "out" and "dir" options are incompatible.' +
  23695. ' Use "out" if you are targeting a single file' +
  23696. ' for optimization, and "dir" if you want the appDir' +
  23697. ' or baseUrl directories optimized.');
  23698. }
  23699. if (config.dir) {
  23700. // Make sure the output dir is not set to a parent of the
  23701. // source dir or the same dir, as it will result in source
  23702. // code deletion.
  23703. if (!config.allowSourceOverwrites && (config.dir === config.baseUrl ||
  23704. config.dir === config.appDir ||
  23705. (config.baseUrl && build.makeRelativeFilePath(config.dir,
  23706. config.baseUrl).indexOf('..') !== 0) ||
  23707. (config.appDir &&
  23708. build.makeRelativeFilePath(config.dir, config.appDir).indexOf('..') !== 0))) {
  23709. throw new Error('"dir" is set to a parent or same directory as' +
  23710. ' "appDir" or "baseUrl". This can result in' +
  23711. ' the deletion of source code. Stopping. If' +
  23712. ' you want to allow possible overwriting of' +
  23713. ' source code, set "allowSourceOverwrites"' +
  23714. ' to true in the build config, but do so at' +
  23715. ' your own risk. In that case, you may want' +
  23716. ' to also set "keepBuildDir" to true.');
  23717. }
  23718. }
  23719. if (config.insertRequire && !lang.isArray(config.insertRequire)) {
  23720. throw new Error('insertRequire should be a list of module IDs' +
  23721. ' to insert in to a require([]) call.');
  23722. }
  23723. //Support older configs with uglify2 settings, but now that uglify1 has
  23724. //been removed, just translate it to 'uglify' settings.
  23725. if (config.optimize === 'uglify2') {
  23726. config.optimize = 'uglify';
  23727. }
  23728. if (config.uglify2) {
  23729. config.uglify = config.uglify2;
  23730. delete config.uglify2;
  23731. }
  23732. if (config.generateSourceMaps) {
  23733. if (config.preserveLicenseComments && !(config.optimize === 'none' || config.optimize === 'uglify')) {
  23734. throw new Error('Cannot use preserveLicenseComments and ' +
  23735. 'generateSourceMaps together, unless optimize is set ' +
  23736. 'to \'uglify\'. Either explicitly set preserveLicenseComments ' +
  23737. 'to false (default is true) or turn off generateSourceMaps. ' +
  23738. 'If you want source maps with license comments, see: ' +
  23739. 'http://requirejs.org/docs/errors.html#sourcemapcomments');
  23740. } else if (config.optimize !== 'none' &&
  23741. config.optimize !== 'closure' &&
  23742. config.optimize !== 'uglify') {
  23743. //Allow optimize: none to pass, since it is useful when toggling
  23744. //minification on and off to debug something, and it implicitly
  23745. //works, since it does not need a source map.
  23746. throw new Error('optimize: "' + config.optimize +
  23747. '" does not support generateSourceMaps.');
  23748. }
  23749. }
  23750. if ((config.name || config.include) && !config.modules) {
  23751. //Just need to build one file, but may be part of a whole appDir/
  23752. //baseUrl copy, but specified on the command line, so cannot do
  23753. //the modules array setup. So create a modules section in that
  23754. //case.
  23755. config.modules = [
  23756. {
  23757. name: config.name,
  23758. out: config.out,
  23759. create: config.create,
  23760. include: config.include,
  23761. exclude: config.exclude,
  23762. excludeShallow: config.excludeShallow,
  23763. insertRequire: config.insertRequire,
  23764. stubModules: config.stubModules
  23765. }
  23766. ];
  23767. delete config.stubModules;
  23768. } else if (config.modules && config.out) {
  23769. throw new Error('If the "modules" option is used, then there ' +
  23770. 'should be a "dir" option set and "out" should ' +
  23771. 'not be used since "out" is only for single file ' +
  23772. 'optimization output.');
  23773. } else if (config.modules && config.name) {
  23774. throw new Error('"name" and "modules" options are incompatible. ' +
  23775. 'Either use "name" if doing a single file ' +
  23776. 'optimization, or "modules" if you want to target ' +
  23777. 'more than one file for optimization.');
  23778. }
  23779. if (config.out && !config.cssIn) {
  23780. //Just one file to optimize.
  23781. //Does not have a build file, so set up some defaults.
  23782. //Optimizing CSS should not be allowed, unless explicitly
  23783. //asked for on command line. In that case the only task is
  23784. //to optimize a CSS file.
  23785. if (!cfg.optimizeCss) {
  23786. config.optimizeCss = "none";
  23787. }
  23788. }
  23789. //Normalize cssPrefix
  23790. if (config.cssPrefix) {
  23791. //Make sure cssPrefix ends in a slash
  23792. config.cssPrefix = endsWithSlash(config.cssPrefix);
  23793. } else {
  23794. config.cssPrefix = '';
  23795. }
  23796. //Cycle through modules and normalize
  23797. if (config.modules && config.modules.length) {
  23798. config.modules.forEach(function (mod) {
  23799. if (lang.isArray(mod) || typeof mod === 'string' || !mod) {
  23800. throw new Error('modules config item is malformed: it should' +
  23801. ' be an object with a \'name\' property.');
  23802. }
  23803. //Combine any local stubModules with global values.
  23804. if (config.stubModules) {
  23805. mod.stubModules = config.stubModules.concat(mod.stubModules || []);
  23806. }
  23807. //Create a hash lookup for the stubModules config to make lookup
  23808. //cheaper later.
  23809. if (mod.stubModules) {
  23810. mod.stubModules._byName = {};
  23811. mod.stubModules.forEach(function (id) {
  23812. mod.stubModules._byName[id] = true;
  23813. });
  23814. }
  23815. // Legacy command support, which allowed a single string ID
  23816. // for include.
  23817. if (typeof mod.include === 'string') {
  23818. mod.include = [mod.include];
  23819. }
  23820. //Allow wrap config in overrides, but normalize it.
  23821. if (mod.override) {
  23822. normalizeWrapConfig(mod.override, absFilePath);
  23823. }
  23824. });
  23825. }
  23826. normalizeWrapConfig(config, absFilePath);
  23827. //Do final input verification
  23828. if (config.context) {
  23829. throw new Error('The build argument "context" is not supported' +
  23830. ' in a build. It should only be used in web' +
  23831. ' pages.');
  23832. }
  23833. //Set up normalizeDirDefines. If not explicitly set, if optimize "none",
  23834. //set to "skip" otherwise set to "all".
  23835. if (!hasProp(config, 'normalizeDirDefines')) {
  23836. if (config.optimize === 'none' || config.skipDirOptimize) {
  23837. config.normalizeDirDefines = 'skip';
  23838. } else {
  23839. config.normalizeDirDefines = 'all';
  23840. }
  23841. }
  23842. //Set file.fileExclusionRegExp if desired
  23843. if (hasProp(config, 'fileExclusionRegExp')) {
  23844. if (typeof config.fileExclusionRegExp === "string") {
  23845. file.exclusionRegExp = new RegExp(config.fileExclusionRegExp);
  23846. } else {
  23847. file.exclusionRegExp = config.fileExclusionRegExp;
  23848. }
  23849. } else if (hasProp(config, 'dirExclusionRegExp')) {
  23850. //Set file.dirExclusionRegExp if desired, this is the old
  23851. //name for fileExclusionRegExp before 1.0.2. Support for backwards
  23852. //compatibility
  23853. file.exclusionRegExp = config.dirExclusionRegExp;
  23854. }
  23855. //Track the deps, but in a different key, so that they are not loaded
  23856. //as part of config seeding before all config is in play (#648). Was
  23857. //going to merge this in with "include", but include is added after
  23858. //the "name" target. To preserve what r.js has done previously, make
  23859. //sure "deps" comes before the "name".
  23860. if (config.deps) {
  23861. config._depsInclude = config.deps;
  23862. }
  23863. //Remove things that may cause problems in the build.
  23864. //deps already merged above
  23865. delete config.deps;
  23866. delete config.jQuery;
  23867. delete config.enforceDefine;
  23868. delete config.urlArgs;
  23869. return config;
  23870. };
  23871. /**
  23872. * finds the module being built/optimized with the given moduleName,
  23873. * or returns null.
  23874. * @param {String} moduleName
  23875. * @param {Array} modules
  23876. * @returns {Object} the module object from the build profile, or null.
  23877. */
  23878. build.findBuildModule = function (moduleName, modules) {
  23879. var i, module;
  23880. for (i = 0; i < modules.length; i++) {
  23881. module = modules[i];
  23882. if (module.name === moduleName) {
  23883. return module;
  23884. }
  23885. }
  23886. return null;
  23887. };
  23888. /**
  23889. * Removes a module name and path from a layerobj, if it is supposed to be
  23890. * excluded from the layerobj.
  23891. * @param {String} moduleName the name of the module
  23892. * @param {String} path the file path for the module
  23893. * @param {Object} layerobj the layerobj to remove the module/path from
  23894. */
  23895. build.removeModulePath = function (module, path, layerobj) {
  23896. var index = layerobj.buildFilePaths.indexOf(path);
  23897. if (index !== -1) {
  23898. layerobj.buildFilePaths.splice(index, 1);
  23899. }
  23900. };
  23901. /**
  23902. * Uses the module build config object to trace the dependencies for the
  23903. * given module.
  23904. *
  23905. * @param {Object} module the module object from the build config info.
  23906. * @param {Object} config the build config object.
  23907. * @param {Object} [baseLoaderConfig] the base loader config to use for env resets.
  23908. *
  23909. * @returns {Object} layerobj information about what paths and modules should
  23910. * be in the flattened module.
  23911. */
  23912. build.traceDependencies = function (module, config, baseLoaderConfig) {
  23913. var include, override, layerobj, context, oldContext,
  23914. rawTextByIds,
  23915. syncChecks = {
  23916. rhino: true,
  23917. node: true,
  23918. xpconnect: true
  23919. },
  23920. deferred = prim();
  23921. //Reset some state set up in requirePatch.js, and clean up require's
  23922. //current context.
  23923. oldContext = require._buildReset();
  23924. //Grab the reset layerobj and context after the reset, but keep the
  23925. //old config to reuse in the new context.
  23926. layerobj = require._layerobj;
  23927. context = layerobj.context;
  23928. //Put back basic config, use a fresh object for it.
  23929. if (baseLoaderConfig) {
  23930. require(copyConfig(baseLoaderConfig));
  23931. }
  23932. logger.trace("\nTracing dependencies for: " + (module.name ||
  23933. (typeof module.out === 'function' ? 'FUNCTION' : module.out)));
  23934. include = config._depsInclude || [];
  23935. include = include.concat(module.name && !module.create ? [module.name] : []);
  23936. if (module.include) {
  23937. include = include.concat(module.include);
  23938. }
  23939. //If there are overrides to basic config, set that up now.;
  23940. if (module.override) {
  23941. if (baseLoaderConfig) {
  23942. override = build.createOverrideConfig(baseLoaderConfig, module.override);
  23943. } else {
  23944. override = copyConfig(module.override);
  23945. }
  23946. require(override);
  23947. }
  23948. //Now, populate the rawText cache with any values explicitly passed in
  23949. //via config.
  23950. rawTextByIds = require.s.contexts._.config.rawText;
  23951. if (rawTextByIds) {
  23952. lang.eachProp(rawTextByIds, function (contents, id) {
  23953. var url = require.toUrl(id) + '.js';
  23954. require._cachedRawText[url] = contents;
  23955. });
  23956. }
  23957. //Configure the callbacks to be called.
  23958. deferred.reject.__requireJsBuild = true;
  23959. //Use a wrapping function so can check for errors.
  23960. function includeFinished(value) {
  23961. //If a sync build environment, check for errors here, instead of
  23962. //in the then callback below, since some errors, like two IDs pointed
  23963. //to same URL but only one anon ID will leave the loader in an
  23964. //unresolved state since a setTimeout cannot be used to check for
  23965. //timeout.
  23966. var hasError = false;
  23967. if (syncChecks[env.get()]) {
  23968. try {
  23969. build.checkForErrors(context, layerobj);
  23970. } catch (e) {
  23971. hasError = true;
  23972. deferred.reject(e);
  23973. }
  23974. }
  23975. if (!hasError) {
  23976. deferred.resolve(value);
  23977. }
  23978. }
  23979. includeFinished.__requireJsBuild = true;
  23980. //Figure out module layerobj dependencies by calling require to do the work.
  23981. require(include, includeFinished, deferred.reject);
  23982. // If a sync env, then with the "two IDs to same anon module path"
  23983. // issue, the require never completes, need to check for errors
  23984. // here.
  23985. if (syncChecks[env.get()]) {
  23986. build.checkForErrors(context, layerobj);
  23987. }
  23988. return deferred.promise.then(function () {
  23989. //Reset config
  23990. if (module.override && baseLoaderConfig) {
  23991. require(copyConfig(baseLoaderConfig));
  23992. }
  23993. build.checkForErrors(context, layerobj);
  23994. return layerobj;
  23995. });
  23996. };
  23997. build.checkForErrors = function (context, layerobj) {
  23998. //Check to see if it all loaded. If not, then throw, and give
  23999. //a message on what is left.
  24000. var id, prop, mod, idParts, pluginId, pluginResources,
  24001. errMessage = '',
  24002. failedPluginMap = {},
  24003. failedPluginIds = [],
  24004. errIds = [],
  24005. errUrlMap = {},
  24006. errUrlConflicts = {},
  24007. hasErrUrl = false,
  24008. hasUndefined = false,
  24009. defined = context.defined,
  24010. registry = context.registry;
  24011. function populateErrUrlMap(id, errUrl, skipNew) {
  24012. // Loader plugins do not have an errUrl, so skip them.
  24013. if (!errUrl) {
  24014. return;
  24015. }
  24016. if (!skipNew) {
  24017. errIds.push(id);
  24018. }
  24019. if (errUrlMap[errUrl]) {
  24020. hasErrUrl = true;
  24021. //This error module has the same URL as another
  24022. //error module, could be misconfiguration.
  24023. if (!errUrlConflicts[errUrl]) {
  24024. errUrlConflicts[errUrl] = [];
  24025. //Store the original module that had the same URL.
  24026. errUrlConflicts[errUrl].push(errUrlMap[errUrl]);
  24027. }
  24028. errUrlConflicts[errUrl].push(id);
  24029. } else if (!skipNew) {
  24030. errUrlMap[errUrl] = id;
  24031. }
  24032. }
  24033. for (id in registry) {
  24034. if (hasProp(registry, id) && id.indexOf('_@r') !== 0) {
  24035. hasUndefined = true;
  24036. mod = getOwn(registry, id);
  24037. idParts = id.split('!');
  24038. pluginId = idParts[0];
  24039. if (id.indexOf('_unnormalized') === -1 && mod && mod.enabled) {
  24040. populateErrUrlMap(id, mod.map.url);
  24041. }
  24042. //Look for plugins that did not call load()
  24043. //But skip plugin IDs that were already inlined and called
  24044. //define() with a name.
  24045. if (!hasProp(layerobj.modulesWithNames, id) && idParts.length > 1) {
  24046. if (falseProp(failedPluginMap, pluginId)) {
  24047. failedPluginIds.push(pluginId);
  24048. }
  24049. pluginResources = failedPluginMap[pluginId];
  24050. if (!pluginResources) {
  24051. pluginResources = failedPluginMap[pluginId] = [];
  24052. }
  24053. pluginResources.push(id + (mod.error ? ': ' + mod.error : ''));
  24054. }
  24055. }
  24056. }
  24057. // If have some modules that are not defined/stuck in the registry,
  24058. // then check defined modules for URL overlap.
  24059. if (hasUndefined) {
  24060. for (id in defined) {
  24061. if (hasProp(defined, id) && id.indexOf('!') === -1) {
  24062. populateErrUrlMap(id, require.toUrl(id) + '.js', true);
  24063. }
  24064. }
  24065. }
  24066. if (errIds.length || failedPluginIds.length) {
  24067. if (failedPluginIds.length) {
  24068. errMessage += 'Loader plugin' +
  24069. (failedPluginIds.length === 1 ? '' : 's') +
  24070. ' did not call ' +
  24071. 'the load callback in the build:\n' +
  24072. failedPluginIds.map(function (pluginId) {
  24073. var pluginResources = failedPluginMap[pluginId];
  24074. return pluginId + ':\n ' + pluginResources.join('\n ');
  24075. }).join('\n') + '\n';
  24076. }
  24077. errMessage += 'Module loading did not complete for: ' + errIds.join(', ');
  24078. if (hasErrUrl) {
  24079. errMessage += '\nThe following modules share the same URL. This ' +
  24080. 'could be a misconfiguration if that URL only has ' +
  24081. 'one anonymous module in it:';
  24082. for (prop in errUrlConflicts) {
  24083. if (hasProp(errUrlConflicts, prop)) {
  24084. errMessage += '\n' + prop + ': ' +
  24085. errUrlConflicts[prop].join(', ');
  24086. }
  24087. }
  24088. }
  24089. throw new Error(errMessage);
  24090. }
  24091. };
  24092. build.createOverrideConfig = function (config, override) {
  24093. var cfg = copyConfig(config),
  24094. oride = copyConfig(override);
  24095. lang.eachProp(oride, function (value, prop) {
  24096. if (hasProp(build.objProps, prop)) {
  24097. //An object property, merge keys. Start a new object
  24098. //so that source object in config does not get modified.
  24099. cfg[prop] = {};
  24100. lang.mixin(cfg[prop], config[prop], true);
  24101. lang.mixin(cfg[prop], override[prop], true);
  24102. } else {
  24103. cfg[prop] = override[prop];
  24104. }
  24105. });
  24106. return cfg;
  24107. };
  24108. /**
  24109. * Uses the module build config object to create an flattened version
  24110. * of the module, with deep dependencies included.
  24111. *
  24112. * @param {Object} module the module object from the build config info.
  24113. *
  24114. * @param {Object} layerobj the layerobj object returned from build.traceDependencies.
  24115. *
  24116. * @param {Object} the build config object.
  24117. *
  24118. * @returns {Object} with two properties: "text", the text of the flattened
  24119. * module, and "buildText", a string of text representing which files were
  24120. * included in the flattened module text.
  24121. */
  24122. build.flattenModule = function (module, layerobj, config) {
  24123. var fileContents, sourceMapGenerator,
  24124. sourceMapBase,
  24125. buildFileContents = '';
  24126. return prim().start(function () {
  24127. var reqIndex, currContents, fileForSourceMap,
  24128. moduleName, shim, packageName,
  24129. parts, builder, writeApi,
  24130. namespace, namespaceWithDot, stubModulesByName,
  24131. context = layerobj.context,
  24132. onLayerEnds = [],
  24133. onLayerEndAdded = {},
  24134. pkgsMainMap = {};
  24135. //Use override settings, particularly for pragmas
  24136. //Do this before the var readings since it reads config values.
  24137. if (module.override) {
  24138. config = build.createOverrideConfig(config, module.override);
  24139. }
  24140. namespace = config.namespace || '';
  24141. namespaceWithDot = namespace ? namespace + '.' : '';
  24142. stubModulesByName = (module.stubModules && module.stubModules._byName) || {};
  24143. //Start build output for the module.
  24144. module.onCompleteData = {
  24145. name: module.name,
  24146. path: (config.dir ? module._buildPath.replace(config.dir, "") : module._buildPath),
  24147. included: []
  24148. };
  24149. buildFileContents += "\n" +
  24150. module.onCompleteData.path +
  24151. "\n----------------\n";
  24152. //If there was an existing file with require in it, hoist to the top.
  24153. if (layerobj.existingRequireUrl) {
  24154. reqIndex = layerobj.buildFilePaths.indexOf(layerobj.existingRequireUrl);
  24155. if (reqIndex !== -1) {
  24156. layerobj.buildFilePaths.splice(reqIndex, 1);
  24157. layerobj.buildFilePaths.unshift(layerobj.existingRequireUrl);
  24158. }
  24159. }
  24160. if (config.generateSourceMaps) {
  24161. sourceMapBase = config.dir || config.baseUrl;
  24162. if (module._buildPath === 'FUNCTION') {
  24163. fileForSourceMap = (module.name || module.include[0] || 'FUNCTION') + '.build.js';
  24164. } else if (config.out) {
  24165. fileForSourceMap = module._buildPath.split('/').pop();
  24166. } else {
  24167. fileForSourceMap = module._buildPath.replace(sourceMapBase, '');
  24168. }
  24169. sourceMapGenerator = new SourceMapGenerator({
  24170. file: fileForSourceMap
  24171. });
  24172. }
  24173. //Create a reverse lookup for packages main module IDs to their package
  24174. //names, useful for knowing when to write out define() package main ID
  24175. //adapters.
  24176. lang.eachProp(layerobj.context.config.pkgs, function(value, prop) {
  24177. pkgsMainMap[value] = prop;
  24178. });
  24179. //Write the built module to disk, and build up the build output.
  24180. fileContents = "";
  24181. if (config.wrap && config.wrap.__startMap) {
  24182. config.wrap.__startMap.forEach(function (wrapFunction) {
  24183. fileContents = wrapFunction(fileContents, config, sourceMapGenerator);
  24184. });
  24185. }
  24186. return prim.serial(layerobj.buildFilePaths.map(function (path) {
  24187. return function () {
  24188. var singleContents = '';
  24189. moduleName = layerobj.buildFileToModule[path];
  24190. //If the moduleName is a package main, then hold on to the
  24191. //packageName in case an adapter needs to be written.
  24192. packageName = getOwn(pkgsMainMap, moduleName);
  24193. return prim().start(function () {
  24194. //Figure out if the module is a result of a build plugin, and if so,
  24195. //then delegate to that plugin.
  24196. parts = context.makeModuleMap(moduleName);
  24197. builder = parts.prefix && getOwn(context.defined, parts.prefix);
  24198. if (builder) {
  24199. if (builder.onLayerEnd && falseProp(onLayerEndAdded, parts.prefix)) {
  24200. onLayerEnds.push(builder);
  24201. onLayerEndAdded[parts.prefix] = true;
  24202. }
  24203. if (builder.write) {
  24204. writeApi = function (input) {
  24205. singleContents += "\n" + addSemiColon(input, config);
  24206. if (config.onBuildWrite) {
  24207. singleContents = config.onBuildWrite(moduleName, path, singleContents);
  24208. }
  24209. };
  24210. writeApi.asModule = function (moduleName, input) {
  24211. singleContents += "\n" +
  24212. addSemiColon(build.toTransport(namespace, moduleName, path, input, layerobj, {
  24213. useSourceUrl: layerobj.context.config.useSourceUrl
  24214. }), config);
  24215. if (config.onBuildWrite) {
  24216. singleContents = config.onBuildWrite(moduleName, path, singleContents);
  24217. }
  24218. };
  24219. builder.write(parts.prefix, parts.name, writeApi);
  24220. }
  24221. return;
  24222. } else {
  24223. return prim().start(function () {
  24224. if (hasProp(stubModulesByName, moduleName)) {
  24225. //Just want to insert a simple module definition instead
  24226. //of the source module. Useful for plugins that inline
  24227. //all their resources.
  24228. if (hasProp(layerobj.context.plugins, moduleName)) {
  24229. //Slightly different content for plugins, to indicate
  24230. //that dynamic loading will not work.
  24231. return 'define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}});';
  24232. } else {
  24233. return 'define({});';
  24234. }
  24235. } else {
  24236. return require._cacheReadAsync(path);
  24237. }
  24238. }).then(function (text) {
  24239. var hasPackageName;
  24240. currContents = text;
  24241. if (config.cjsTranslate &&
  24242. (!config.shim || !lang.hasProp(config.shim, moduleName))) {
  24243. currContents = commonJs.convert(path, currContents);
  24244. }
  24245. if (config.onBuildRead) {
  24246. currContents = config.onBuildRead(moduleName, path, currContents);
  24247. }
  24248. if (packageName) {
  24249. hasPackageName = (packageName === parse.getNamedDefine(currContents));
  24250. }
  24251. if (namespace) {
  24252. currContents = pragma.namespace(currContents, namespace);
  24253. }
  24254. currContents = build.toTransport(namespace, moduleName, path, currContents, layerobj, {
  24255. useSourceUrl: config.useSourceUrl
  24256. });
  24257. if (packageName && !hasPackageName) {
  24258. currContents = addSemiColon(currContents, config) + '\n';
  24259. currContents += namespaceWithDot + "define('" +
  24260. packageName + "', ['" + moduleName +
  24261. "'], function (main) { return main; });\n";
  24262. }
  24263. if (config.onBuildWrite) {
  24264. currContents = config.onBuildWrite(moduleName, path, currContents);
  24265. }
  24266. //Semicolon is for files that are not well formed when
  24267. //concatenated with other content.
  24268. singleContents += addSemiColon(currContents, config);
  24269. });
  24270. }
  24271. }).then(function () {
  24272. var shimDeps, shortPath = path.replace(config.dir, "");
  24273. module.onCompleteData.included.push(shortPath);
  24274. buildFileContents += shortPath + "\n";
  24275. //Some files may not have declared a require module, and if so,
  24276. //put in a placeholder call so the require does not try to load them
  24277. //after the module is processed.
  24278. //If we have a name, but no defined module, then add in the placeholder.
  24279. if (moduleName && falseProp(layerobj.modulesWithNames, moduleName) && !config.skipModuleInsertion) {
  24280. shim = config.shim && (getOwn(config.shim, moduleName) || (packageName && getOwn(config.shim, packageName)));
  24281. if (shim) {
  24282. shimDeps = lang.isArray(shim) ? shim : shim.deps;
  24283. if (config.wrapShim) {
  24284. singleContents = '(function(root) {\n' +
  24285. namespaceWithDot + 'define("' + moduleName + '", ' +
  24286. (shimDeps && shimDeps.length ?
  24287. build.makeJsArrayString(shimDeps) + ', ' : '[], ') +
  24288. 'function() {\n' +
  24289. ' return (function() {\n' +
  24290. singleContents +
  24291. // Start with a \n in case last line is a comment
  24292. // in the singleContents, like a sourceURL comment.
  24293. '\n' + (shim.exportsFn ? shim.exportsFn() : '') +
  24294. '\n' +
  24295. ' }).apply(root, arguments);\n' +
  24296. '});\n' +
  24297. '}(this));\n';
  24298. } else {
  24299. singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", ' +
  24300. (shimDeps && shimDeps.length ?
  24301. build.makeJsArrayString(shimDeps) + ', ' : '') +
  24302. (shim.exportsFn ? shim.exportsFn() : 'function(){}') +
  24303. ');\n';
  24304. }
  24305. } else {
  24306. singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", function(){});\n';
  24307. }
  24308. }
  24309. //Add line break at end of file, instead of at beginning,
  24310. //so source map line numbers stay correct, but still allow
  24311. //for some space separation between files in case ASI issues
  24312. //for concatenation would cause an error otherwise.
  24313. singleContents += '\n';
  24314. //Add to the source map and to the final contents
  24315. fileContents = appendToFileContents(fileContents, singleContents, path, config, module,
  24316. sourceMapGenerator);
  24317. });
  24318. };
  24319. })).then(function () {
  24320. if (onLayerEnds.length) {
  24321. onLayerEnds.forEach(function (builder, index) {
  24322. var path;
  24323. if (typeof module.out === 'string') {
  24324. path = module.out;
  24325. } else if (typeof module._buildPath === 'string') {
  24326. path = module._buildPath;
  24327. }
  24328. builder.onLayerEnd(function (input) {
  24329. fileContents =
  24330. appendToFileContents(fileContents, "\n" + addSemiColon(input, config),
  24331. 'onLayerEnd' + index + '.js', config, module, sourceMapGenerator);
  24332. }, {
  24333. name: module.name,
  24334. path: path
  24335. });
  24336. });
  24337. }
  24338. if (module.create) {
  24339. //The ID is for a created layerobj. Write out
  24340. //a module definition for it in case the
  24341. //built file is used with enforceDefine
  24342. //(#432)
  24343. fileContents =
  24344. appendToFileContents(fileContents, '\n' + namespaceWithDot + 'define("' + module.name +
  24345. '", function(){});\n', 'module-create.js', config, module,
  24346. sourceMapGenerator);
  24347. }
  24348. //Add a require at the end to kick start module execution, if that
  24349. //was desired. Usually this is only specified when using small shim
  24350. //loaders like almond.
  24351. if (module.insertRequire) {
  24352. fileContents =
  24353. appendToFileContents(fileContents, '\n' + namespaceWithDot + 'require(["' + module.insertRequire.join('", "') +
  24354. '"]);\n', 'module-insertRequire.js', config, module,
  24355. sourceMapGenerator);
  24356. }
  24357. });
  24358. }).then(function () {
  24359. if (config.wrap && config.wrap.__endMap) {
  24360. config.wrap.__endMap.forEach(function (wrapFunction) {
  24361. fileContents = wrapFunction(fileContents, config, sourceMapGenerator);
  24362. });
  24363. }
  24364. return {
  24365. text: fileContents,
  24366. buildText: buildFileContents,
  24367. sourceMap: sourceMapGenerator ?
  24368. JSON.stringify(sourceMapGenerator.toJSON(), null, ' ') :
  24369. undefined
  24370. };
  24371. });
  24372. };
  24373. //Converts an JS array of strings to a string representation.
  24374. //Not using JSON.stringify() for Rhino's sake.
  24375. build.makeJsArrayString = function (ary) {
  24376. return '["' + ary.map(function (item) {
  24377. //Escape any double quotes, backslashes
  24378. return lang.jsEscape(item);
  24379. }).join('","') + '"]';
  24380. };
  24381. build.toTransport = function (namespace, moduleName, path, contents, layerobj, options) {
  24382. var baseUrl = layerobj && layerobj.context.config.baseUrl;
  24383. function onFound(info) {
  24384. //Only mark this module as having a name if not a named module,
  24385. //or if a named module and the name matches expectations.
  24386. if (layerobj && (info.needsId || info.foundId === moduleName)) {
  24387. layerobj.modulesWithNames[moduleName] = true;
  24388. }
  24389. }
  24390. //Convert path to be a local one to the baseUrl, useful for
  24391. //useSourceUrl.
  24392. if (baseUrl) {
  24393. path = path.replace(baseUrl, '');
  24394. }
  24395. return transform.toTransport(namespace, moduleName, path, contents, onFound, options);
  24396. };
  24397. return build;
  24398. });
  24399. }
  24400. /**
  24401. * Sets the default baseUrl for requirejs to be directory of top level
  24402. * script.
  24403. */
  24404. function setBaseUrl(fileName) {
  24405. //Use the file name's directory as the baseUrl if available.
  24406. dir = fileName.replace(/\\/g, '/');
  24407. if (dir.indexOf('/') !== -1) {
  24408. dir = dir.split('/');
  24409. dir.pop();
  24410. dir = dir.join('/');
  24411. //Make sure dir is JS-escaped, since it will be part of a JS string.
  24412. exec("require({baseUrl: '" + dir.replace(/[\\"']/g, '\\$&') + "'});");
  24413. }
  24414. }
  24415. function createRjsApi() {
  24416. //Create a method that will run the optimzer given an object
  24417. //config.
  24418. requirejs.optimize = function (config, callback, errback) {
  24419. if (!loadedOptimizedLib) {
  24420. loadLib();
  24421. loadedOptimizedLib = true;
  24422. }
  24423. //Create the function that will be called once build modules
  24424. //have been loaded.
  24425. var runBuild = function (build, logger, quit) {
  24426. //Make sure config has a log level, and if not,
  24427. //make it "silent" by default.
  24428. config.logLevel = config.hasOwnProperty('logLevel') ?
  24429. config.logLevel : logger.SILENT;
  24430. //Reset build internals first in case this is part
  24431. //of a long-running server process that could have
  24432. //exceptioned out in a bad state. It is only defined
  24433. //after the first call though.
  24434. if (requirejs._buildReset) {
  24435. requirejs._buildReset();
  24436. requirejs._cacheReset();
  24437. }
  24438. function done(result) {
  24439. //And clean up, in case something else triggers
  24440. //a build in another pathway.
  24441. if (requirejs._buildReset) {
  24442. requirejs._buildReset();
  24443. requirejs._cacheReset();
  24444. }
  24445. // Ensure errors get propagated to the errback
  24446. if (result instanceof Error) {
  24447. throw result;
  24448. }
  24449. return result;
  24450. }
  24451. errback = errback || function (err) {
  24452. // Using console here since logger may have
  24453. // turned off error logging. Since quit is
  24454. // called want to be sure a message is printed.
  24455. console.log(err);
  24456. quit(1);
  24457. };
  24458. build(config).then(done, done).then(callback, errback);
  24459. };
  24460. requirejs({
  24461. context: 'build'
  24462. }, ['build', 'logger', 'env!env/quit'], runBuild);
  24463. };
  24464. requirejs.tools = {
  24465. useLib: function (contextName, callback) {
  24466. if (!callback) {
  24467. callback = contextName;
  24468. contextName = 'uselib';
  24469. }
  24470. if (!useLibLoaded[contextName]) {
  24471. loadLib();
  24472. useLibLoaded[contextName] = true;
  24473. }
  24474. var req = requirejs({
  24475. context: contextName
  24476. });
  24477. req(['build'], function () {
  24478. callback(req);
  24479. });
  24480. }
  24481. };
  24482. requirejs.define = define;
  24483. }
  24484. //If in Node, and included via a require('requirejs'), just export and
  24485. //THROW IT ON THE GROUND!
  24486. if (env === 'node' && reqMain !== module) {
  24487. setBaseUrl(path.resolve(reqMain ? reqMain.filename : '.'));
  24488. createRjsApi();
  24489. module.exports = requirejs;
  24490. return;
  24491. } else if (env === 'browser') {
  24492. //Only option is to use the API.
  24493. setBaseUrl(location.href);
  24494. createRjsApi();
  24495. return;
  24496. } else if ((env === 'rhino' || env === 'xpconnect') &&
  24497. //User sets up requirejsAsLib variable to indicate it is loaded
  24498. //via load() to be used as a library.
  24499. typeof requirejsAsLib !== 'undefined' && requirejsAsLib) {
  24500. //This script is loaded via rhino's load() method, expose the
  24501. //API and get out.
  24502. setBaseUrl(fileName);
  24503. createRjsApi();
  24504. return;
  24505. }
  24506. if (commandOption === 'o') {
  24507. //Do the optimizer work.
  24508. loadLib();
  24509. /*
  24510. * Create a build.js file that has the build options you want and pass that
  24511. * build file to this file to do the build. See example.build.js for more information.
  24512. */
  24513. /*jslint strict: false, nomen: false */
  24514. /*global require: false */
  24515. require({
  24516. baseUrl: require.s.contexts._.config.baseUrl,
  24517. //Use a separate context than the default context so that the
  24518. //build can use the default context.
  24519. context: 'build',
  24520. catchError: {
  24521. define: true
  24522. }
  24523. }, ['env!env/args', 'env!env/quit', 'logger', 'build'],
  24524. function (args, quit, logger, build) {
  24525. build(args).then(function () {}, function (err) {
  24526. logger.error(err);
  24527. quit(1);
  24528. });
  24529. });
  24530. } else if (commandOption === 'v') {
  24531. console.log('r.js: ' + version +
  24532. ', RequireJS: ' + this.requirejsVars.require.version +
  24533. ', UglifyJS: 2.7.3');
  24534. } else if (commandOption === 'convert') {
  24535. loadLib();
  24536. this.requirejsVars.require(['env!env/args', 'commonJs', 'env!env/print'],
  24537. function (args, commonJs, print) {
  24538. var srcDir, outDir;
  24539. srcDir = args[0];
  24540. outDir = args[1];
  24541. if (!srcDir || !outDir) {
  24542. print('Usage: path/to/commonjs/modules output/dir');
  24543. return;
  24544. }
  24545. commonJs.convertDir(args[0], args[1]);
  24546. });
  24547. } else {
  24548. //Just run an app
  24549. //Load the bundled libraries for use in the app.
  24550. if (commandOption === 'lib') {
  24551. loadLib();
  24552. }
  24553. setBaseUrl(fileName);
  24554. if (exists(fileName)) {
  24555. exec(readFile(fileName), fileName);
  24556. } else {
  24557. showHelp();
  24558. }
  24559. }
  24560. }((typeof console !== 'undefined' ? console : undefined),
  24561. (typeof Packages !== 'undefined' || (typeof window === 'undefined' &&
  24562. typeof Components !== 'undefined' && Components.interfaces) ?
  24563. Array.prototype.slice.call(arguments, 0) : []),
  24564. (typeof readFile !== 'undefined' ? readFile : undefined)));