omega_target_chromium_extension.min.js 195 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.OmegaTargetChromium = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  3. ;(function (exports) {
  4. 'use strict';
  5. var Arr = (typeof Uint8Array !== 'undefined')
  6. ? Uint8Array
  7. : Array
  8. var PLUS = '+'.charCodeAt(0)
  9. var SLASH = '/'.charCodeAt(0)
  10. var NUMBER = '0'.charCodeAt(0)
  11. var LOWER = 'a'.charCodeAt(0)
  12. var UPPER = 'A'.charCodeAt(0)
  13. var PLUS_URL_SAFE = '-'.charCodeAt(0)
  14. var SLASH_URL_SAFE = '_'.charCodeAt(0)
  15. function decode (elt) {
  16. var code = elt.charCodeAt(0)
  17. if (code === PLUS ||
  18. code === PLUS_URL_SAFE)
  19. return 62 // '+'
  20. if (code === SLASH ||
  21. code === SLASH_URL_SAFE)
  22. return 63 // '/'
  23. if (code < NUMBER)
  24. return -1 //no match
  25. if (code < NUMBER + 10)
  26. return code - NUMBER + 26 + 26
  27. if (code < UPPER + 26)
  28. return code - UPPER
  29. if (code < LOWER + 26)
  30. return code - LOWER + 26
  31. }
  32. function b64ToByteArray (b64) {
  33. var i, j, l, tmp, placeHolders, arr
  34. if (b64.length % 4 > 0) {
  35. throw new Error('Invalid string. Length must be a multiple of 4')
  36. }
  37. // the number of equal signs (place holders)
  38. // if there are two placeholders, than the two characters before it
  39. // represent one byte
  40. // if there is only one, then the three characters before it represent 2 bytes
  41. // this is just a cheap hack to not do indexOf twice
  42. var len = b64.length
  43. placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
  44. // base64 is 4/3 + up to two characters of the original data
  45. arr = new Arr(b64.length * 3 / 4 - placeHolders)
  46. // if there are placeholders, only get up to the last complete 4 chars
  47. l = placeHolders > 0 ? b64.length - 4 : b64.length
  48. var L = 0
  49. function push (v) {
  50. arr[L++] = v
  51. }
  52. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  53. tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
  54. push((tmp & 0xFF0000) >> 16)
  55. push((tmp & 0xFF00) >> 8)
  56. push(tmp & 0xFF)
  57. }
  58. if (placeHolders === 2) {
  59. tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
  60. push(tmp & 0xFF)
  61. } else if (placeHolders === 1) {
  62. tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
  63. push((tmp >> 8) & 0xFF)
  64. push(tmp & 0xFF)
  65. }
  66. return arr
  67. }
  68. function uint8ToBase64 (uint8) {
  69. var i,
  70. extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
  71. output = "",
  72. temp, length
  73. function encode (num) {
  74. return lookup.charAt(num)
  75. }
  76. function tripletToBase64 (num) {
  77. return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
  78. }
  79. // go through the array every three bytes, we'll deal with trailing stuff later
  80. for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
  81. temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  82. output += tripletToBase64(temp)
  83. }
  84. // pad the end with zeros, but make sure to not forget the extra bytes
  85. switch (extraBytes) {
  86. case 1:
  87. temp = uint8[uint8.length - 1]
  88. output += encode(temp >> 2)
  89. output += encode((temp << 4) & 0x3F)
  90. output += '=='
  91. break
  92. case 2:
  93. temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
  94. output += encode(temp >> 10)
  95. output += encode((temp >> 4) & 0x3F)
  96. output += encode((temp << 2) & 0x3F)
  97. output += '='
  98. break
  99. }
  100. return output
  101. }
  102. exports.toByteArray = b64ToByteArray
  103. exports.fromByteArray = uint8ToBase64
  104. }(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
  105. },{}],2:[function(require,module,exports){
  106. (function (global){
  107. /*!
  108. * The buffer module from node.js, for the browser.
  109. *
  110. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  111. * @license MIT
  112. */
  113. /* eslint-disable no-proto */
  114. 'use strict'
  115. var base64 = require('base64-js')
  116. var ieee754 = require('ieee754')
  117. var isArray = require('isarray')
  118. exports.Buffer = Buffer
  119. exports.SlowBuffer = SlowBuffer
  120. exports.INSPECT_MAX_BYTES = 50
  121. Buffer.poolSize = 8192 // not used by this implementation
  122. var rootParent = {}
  123. /**
  124. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  125. * === true Use Uint8Array implementation (fastest)
  126. * === false Use Object implementation (most compatible, even IE6)
  127. *
  128. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  129. * Opera 11.6+, iOS 4.2+.
  130. *
  131. * Due to various browser bugs, sometimes the Object implementation will be used even
  132. * when the browser supports typed arrays.
  133. *
  134. * Note:
  135. *
  136. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  137. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  138. *
  139. * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
  140. * on objects.
  141. *
  142. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  143. *
  144. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  145. * incorrect length in some situations.
  146. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  147. * get the Object implementation, which is slower but behaves correctly.
  148. */
  149. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  150. ? global.TYPED_ARRAY_SUPPORT
  151. : typedArraySupport()
  152. function typedArraySupport () {
  153. function Bar () {}
  154. try {
  155. var arr = new Uint8Array(1)
  156. arr.foo = function () { return 42 }
  157. arr.constructor = Bar
  158. return arr.foo() === 42 && // typed array instances can be augmented
  159. arr.constructor === Bar && // constructor can be set
  160. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  161. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  162. } catch (e) {
  163. return false
  164. }
  165. }
  166. function kMaxLength () {
  167. return Buffer.TYPED_ARRAY_SUPPORT
  168. ? 0x7fffffff
  169. : 0x3fffffff
  170. }
  171. /**
  172. * Class: Buffer
  173. * =============
  174. *
  175. * The Buffer constructor returns instances of `Uint8Array` that are augmented
  176. * with function properties for all the node `Buffer` API functions. We use
  177. * `Uint8Array` so that square bracket notation works as expected -- it returns
  178. * a single octet.
  179. *
  180. * By augmenting the instances, we can avoid modifying the `Uint8Array`
  181. * prototype.
  182. */
  183. function Buffer (arg) {
  184. if (!(this instanceof Buffer)) {
  185. // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
  186. if (arguments.length > 1) return new Buffer(arg, arguments[1])
  187. return new Buffer(arg)
  188. }
  189. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  190. this.length = 0
  191. this.parent = undefined
  192. }
  193. // Common case.
  194. if (typeof arg === 'number') {
  195. return fromNumber(this, arg)
  196. }
  197. // Slightly less common case.
  198. if (typeof arg === 'string') {
  199. return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
  200. }
  201. // Unusual.
  202. return fromObject(this, arg)
  203. }
  204. function fromNumber (that, length) {
  205. that = allocate(that, length < 0 ? 0 : checked(length) | 0)
  206. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  207. for (var i = 0; i < length; i++) {
  208. that[i] = 0
  209. }
  210. }
  211. return that
  212. }
  213. function fromString (that, string, encoding) {
  214. if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
  215. // Assumption: byteLength() return value is always < kMaxLength.
  216. var length = byteLength(string, encoding) | 0
  217. that = allocate(that, length)
  218. that.write(string, encoding)
  219. return that
  220. }
  221. function fromObject (that, object) {
  222. if (Buffer.isBuffer(object)) return fromBuffer(that, object)
  223. if (isArray(object)) return fromArray(that, object)
  224. if (object == null) {
  225. throw new TypeError('must start with number, buffer, array or string')
  226. }
  227. if (typeof ArrayBuffer !== 'undefined') {
  228. if (object.buffer instanceof ArrayBuffer) {
  229. return fromTypedArray(that, object)
  230. }
  231. if (object instanceof ArrayBuffer) {
  232. return fromArrayBuffer(that, object)
  233. }
  234. }
  235. if (object.length) return fromArrayLike(that, object)
  236. return fromJsonObject(that, object)
  237. }
  238. function fromBuffer (that, buffer) {
  239. var length = checked(buffer.length) | 0
  240. that = allocate(that, length)
  241. buffer.copy(that, 0, 0, length)
  242. return that
  243. }
  244. function fromArray (that, array) {
  245. var length = checked(array.length) | 0
  246. that = allocate(that, length)
  247. for (var i = 0; i < length; i += 1) {
  248. that[i] = array[i] & 255
  249. }
  250. return that
  251. }
  252. // Duplicate of fromArray() to keep fromArray() monomorphic.
  253. function fromTypedArray (that, array) {
  254. var length = checked(array.length) | 0
  255. that = allocate(that, length)
  256. // Truncating the elements is probably not what people expect from typed
  257. // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
  258. // of the old Buffer constructor.
  259. for (var i = 0; i < length; i += 1) {
  260. that[i] = array[i] & 255
  261. }
  262. return that
  263. }
  264. function fromArrayBuffer (that, array) {
  265. if (Buffer.TYPED_ARRAY_SUPPORT) {
  266. // Return an augmented `Uint8Array` instance, for best performance
  267. array.byteLength
  268. that = Buffer._augment(new Uint8Array(array))
  269. } else {
  270. // Fallback: Return an object instance of the Buffer class
  271. that = fromTypedArray(that, new Uint8Array(array))
  272. }
  273. return that
  274. }
  275. function fromArrayLike (that, array) {
  276. var length = checked(array.length) | 0
  277. that = allocate(that, length)
  278. for (var i = 0; i < length; i += 1) {
  279. that[i] = array[i] & 255
  280. }
  281. return that
  282. }
  283. // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
  284. // Returns a zero-length buffer for inputs that don't conform to the spec.
  285. function fromJsonObject (that, object) {
  286. var array
  287. var length = 0
  288. if (object.type === 'Buffer' && isArray(object.data)) {
  289. array = object.data
  290. length = checked(array.length) | 0
  291. }
  292. that = allocate(that, length)
  293. for (var i = 0; i < length; i += 1) {
  294. that[i] = array[i] & 255
  295. }
  296. return that
  297. }
  298. if (Buffer.TYPED_ARRAY_SUPPORT) {
  299. Buffer.prototype.__proto__ = Uint8Array.prototype
  300. Buffer.__proto__ = Uint8Array
  301. } else {
  302. // pre-set for values that may exist in the future
  303. Buffer.prototype.length = undefined
  304. Buffer.prototype.parent = undefined
  305. }
  306. function allocate (that, length) {
  307. if (Buffer.TYPED_ARRAY_SUPPORT) {
  308. // Return an augmented `Uint8Array` instance, for best performance
  309. that = Buffer._augment(new Uint8Array(length))
  310. that.__proto__ = Buffer.prototype
  311. } else {
  312. // Fallback: Return an object instance of the Buffer class
  313. that.length = length
  314. that._isBuffer = true
  315. }
  316. var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
  317. if (fromPool) that.parent = rootParent
  318. return that
  319. }
  320. function checked (length) {
  321. // Note: cannot use `length < kMaxLength` here because that fails when
  322. // length is NaN (which is otherwise coerced to zero.)
  323. if (length >= kMaxLength()) {
  324. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  325. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  326. }
  327. return length | 0
  328. }
  329. function SlowBuffer (subject, encoding) {
  330. if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
  331. var buf = new Buffer(subject, encoding)
  332. delete buf.parent
  333. return buf
  334. }
  335. Buffer.isBuffer = function isBuffer (b) {
  336. return !!(b != null && b._isBuffer)
  337. }
  338. Buffer.compare = function compare (a, b) {
  339. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  340. throw new TypeError('Arguments must be Buffers')
  341. }
  342. if (a === b) return 0
  343. var x = a.length
  344. var y = b.length
  345. var i = 0
  346. var len = Math.min(x, y)
  347. while (i < len) {
  348. if (a[i] !== b[i]) break
  349. ++i
  350. }
  351. if (i !== len) {
  352. x = a[i]
  353. y = b[i]
  354. }
  355. if (x < y) return -1
  356. if (y < x) return 1
  357. return 0
  358. }
  359. Buffer.isEncoding = function isEncoding (encoding) {
  360. switch (String(encoding).toLowerCase()) {
  361. case 'hex':
  362. case 'utf8':
  363. case 'utf-8':
  364. case 'ascii':
  365. case 'binary':
  366. case 'base64':
  367. case 'raw':
  368. case 'ucs2':
  369. case 'ucs-2':
  370. case 'utf16le':
  371. case 'utf-16le':
  372. return true
  373. default:
  374. return false
  375. }
  376. }
  377. Buffer.concat = function concat (list, length) {
  378. if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
  379. if (list.length === 0) {
  380. return new Buffer(0)
  381. }
  382. var i
  383. if (length === undefined) {
  384. length = 0
  385. for (i = 0; i < list.length; i++) {
  386. length += list[i].length
  387. }
  388. }
  389. var buf = new Buffer(length)
  390. var pos = 0
  391. for (i = 0; i < list.length; i++) {
  392. var item = list[i]
  393. item.copy(buf, pos)
  394. pos += item.length
  395. }
  396. return buf
  397. }
  398. function byteLength (string, encoding) {
  399. if (typeof string !== 'string') string = '' + string
  400. var len = string.length
  401. if (len === 0) return 0
  402. // Use a for loop to avoid recursion
  403. var loweredCase = false
  404. for (;;) {
  405. switch (encoding) {
  406. case 'ascii':
  407. case 'binary':
  408. // Deprecated
  409. case 'raw':
  410. case 'raws':
  411. return len
  412. case 'utf8':
  413. case 'utf-8':
  414. return utf8ToBytes(string).length
  415. case 'ucs2':
  416. case 'ucs-2':
  417. case 'utf16le':
  418. case 'utf-16le':
  419. return len * 2
  420. case 'hex':
  421. return len >>> 1
  422. case 'base64':
  423. return base64ToBytes(string).length
  424. default:
  425. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  426. encoding = ('' + encoding).toLowerCase()
  427. loweredCase = true
  428. }
  429. }
  430. }
  431. Buffer.byteLength = byteLength
  432. function slowToString (encoding, start, end) {
  433. var loweredCase = false
  434. start = start | 0
  435. end = end === undefined || end === Infinity ? this.length : end | 0
  436. if (!encoding) encoding = 'utf8'
  437. if (start < 0) start = 0
  438. if (end > this.length) end = this.length
  439. if (end <= start) return ''
  440. while (true) {
  441. switch (encoding) {
  442. case 'hex':
  443. return hexSlice(this, start, end)
  444. case 'utf8':
  445. case 'utf-8':
  446. return utf8Slice(this, start, end)
  447. case 'ascii':
  448. return asciiSlice(this, start, end)
  449. case 'binary':
  450. return binarySlice(this, start, end)
  451. case 'base64':
  452. return base64Slice(this, start, end)
  453. case 'ucs2':
  454. case 'ucs-2':
  455. case 'utf16le':
  456. case 'utf-16le':
  457. return utf16leSlice(this, start, end)
  458. default:
  459. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  460. encoding = (encoding + '').toLowerCase()
  461. loweredCase = true
  462. }
  463. }
  464. }
  465. Buffer.prototype.toString = function toString () {
  466. var length = this.length | 0
  467. if (length === 0) return ''
  468. if (arguments.length === 0) return utf8Slice(this, 0, length)
  469. return slowToString.apply(this, arguments)
  470. }
  471. Buffer.prototype.equals = function equals (b) {
  472. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  473. if (this === b) return true
  474. return Buffer.compare(this, b) === 0
  475. }
  476. Buffer.prototype.inspect = function inspect () {
  477. var str = ''
  478. var max = exports.INSPECT_MAX_BYTES
  479. if (this.length > 0) {
  480. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  481. if (this.length > max) str += ' ... '
  482. }
  483. return '<Buffer ' + str + '>'
  484. }
  485. Buffer.prototype.compare = function compare (b) {
  486. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  487. if (this === b) return 0
  488. return Buffer.compare(this, b)
  489. }
  490. Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
  491. if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
  492. else if (byteOffset < -0x80000000) byteOffset = -0x80000000
  493. byteOffset >>= 0
  494. if (this.length === 0) return -1
  495. if (byteOffset >= this.length) return -1
  496. // Negative offsets start from the end of the buffer
  497. if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
  498. if (typeof val === 'string') {
  499. if (val.length === 0) return -1 // special case: looking for empty string always fails
  500. return String.prototype.indexOf.call(this, val, byteOffset)
  501. }
  502. if (Buffer.isBuffer(val)) {
  503. return arrayIndexOf(this, val, byteOffset)
  504. }
  505. if (typeof val === 'number') {
  506. if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
  507. return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
  508. }
  509. return arrayIndexOf(this, [ val ], byteOffset)
  510. }
  511. function arrayIndexOf (arr, val, byteOffset) {
  512. var foundIndex = -1
  513. for (var i = 0; byteOffset + i < arr.length; i++) {
  514. if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
  515. if (foundIndex === -1) foundIndex = i
  516. if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
  517. } else {
  518. foundIndex = -1
  519. }
  520. }
  521. return -1
  522. }
  523. throw new TypeError('val must be string, number or Buffer')
  524. }
  525. // `get` is deprecated
  526. Buffer.prototype.get = function get (offset) {
  527. console.log('.get() is deprecated. Access using array indexes instead.')
  528. return this.readUInt8(offset)
  529. }
  530. // `set` is deprecated
  531. Buffer.prototype.set = function set (v, offset) {
  532. console.log('.set() is deprecated. Access using array indexes instead.')
  533. return this.writeUInt8(v, offset)
  534. }
  535. function hexWrite (buf, string, offset, length) {
  536. offset = Number(offset) || 0
  537. var remaining = buf.length - offset
  538. if (!length) {
  539. length = remaining
  540. } else {
  541. length = Number(length)
  542. if (length > remaining) {
  543. length = remaining
  544. }
  545. }
  546. // must be an even number of digits
  547. var strLen = string.length
  548. if (strLen % 2 !== 0) throw new Error('Invalid hex string')
  549. if (length > strLen / 2) {
  550. length = strLen / 2
  551. }
  552. for (var i = 0; i < length; i++) {
  553. var parsed = parseInt(string.substr(i * 2, 2), 16)
  554. if (isNaN(parsed)) throw new Error('Invalid hex string')
  555. buf[offset + i] = parsed
  556. }
  557. return i
  558. }
  559. function utf8Write (buf, string, offset, length) {
  560. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  561. }
  562. function asciiWrite (buf, string, offset, length) {
  563. return blitBuffer(asciiToBytes(string), buf, offset, length)
  564. }
  565. function binaryWrite (buf, string, offset, length) {
  566. return asciiWrite(buf, string, offset, length)
  567. }
  568. function base64Write (buf, string, offset, length) {
  569. return blitBuffer(base64ToBytes(string), buf, offset, length)
  570. }
  571. function ucs2Write (buf, string, offset, length) {
  572. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  573. }
  574. Buffer.prototype.write = function write (string, offset, length, encoding) {
  575. // Buffer#write(string)
  576. if (offset === undefined) {
  577. encoding = 'utf8'
  578. length = this.length
  579. offset = 0
  580. // Buffer#write(string, encoding)
  581. } else if (length === undefined && typeof offset === 'string') {
  582. encoding = offset
  583. length = this.length
  584. offset = 0
  585. // Buffer#write(string, offset[, length][, encoding])
  586. } else if (isFinite(offset)) {
  587. offset = offset | 0
  588. if (isFinite(length)) {
  589. length = length | 0
  590. if (encoding === undefined) encoding = 'utf8'
  591. } else {
  592. encoding = length
  593. length = undefined
  594. }
  595. // legacy write(string, encoding, offset, length) - remove in v0.13
  596. } else {
  597. var swap = encoding
  598. encoding = offset
  599. offset = length | 0
  600. length = swap
  601. }
  602. var remaining = this.length - offset
  603. if (length === undefined || length > remaining) length = remaining
  604. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  605. throw new RangeError('attempt to write outside buffer bounds')
  606. }
  607. if (!encoding) encoding = 'utf8'
  608. var loweredCase = false
  609. for (;;) {
  610. switch (encoding) {
  611. case 'hex':
  612. return hexWrite(this, string, offset, length)
  613. case 'utf8':
  614. case 'utf-8':
  615. return utf8Write(this, string, offset, length)
  616. case 'ascii':
  617. return asciiWrite(this, string, offset, length)
  618. case 'binary':
  619. return binaryWrite(this, string, offset, length)
  620. case 'base64':
  621. // Warning: maxLength not taken into account in base64Write
  622. return base64Write(this, string, offset, length)
  623. case 'ucs2':
  624. case 'ucs-2':
  625. case 'utf16le':
  626. case 'utf-16le':
  627. return ucs2Write(this, string, offset, length)
  628. default:
  629. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  630. encoding = ('' + encoding).toLowerCase()
  631. loweredCase = true
  632. }
  633. }
  634. }
  635. Buffer.prototype.toJSON = function toJSON () {
  636. return {
  637. type: 'Buffer',
  638. data: Array.prototype.slice.call(this._arr || this, 0)
  639. }
  640. }
  641. function base64Slice (buf, start, end) {
  642. if (start === 0 && end === buf.length) {
  643. return base64.fromByteArray(buf)
  644. } else {
  645. return base64.fromByteArray(buf.slice(start, end))
  646. }
  647. }
  648. function utf8Slice (buf, start, end) {
  649. end = Math.min(buf.length, end)
  650. var res = []
  651. var i = start
  652. while (i < end) {
  653. var firstByte = buf[i]
  654. var codePoint = null
  655. var bytesPerSequence = (firstByte > 0xEF) ? 4
  656. : (firstByte > 0xDF) ? 3
  657. : (firstByte > 0xBF) ? 2
  658. : 1
  659. if (i + bytesPerSequence <= end) {
  660. var secondByte, thirdByte, fourthByte, tempCodePoint
  661. switch (bytesPerSequence) {
  662. case 1:
  663. if (firstByte < 0x80) {
  664. codePoint = firstByte
  665. }
  666. break
  667. case 2:
  668. secondByte = buf[i + 1]
  669. if ((secondByte & 0xC0) === 0x80) {
  670. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  671. if (tempCodePoint > 0x7F) {
  672. codePoint = tempCodePoint
  673. }
  674. }
  675. break
  676. case 3:
  677. secondByte = buf[i + 1]
  678. thirdByte = buf[i + 2]
  679. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  680. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  681. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  682. codePoint = tempCodePoint
  683. }
  684. }
  685. break
  686. case 4:
  687. secondByte = buf[i + 1]
  688. thirdByte = buf[i + 2]
  689. fourthByte = buf[i + 3]
  690. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  691. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  692. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  693. codePoint = tempCodePoint
  694. }
  695. }
  696. }
  697. }
  698. if (codePoint === null) {
  699. // we did not generate a valid codePoint so insert a
  700. // replacement char (U+FFFD) and advance only 1 byte
  701. codePoint = 0xFFFD
  702. bytesPerSequence = 1
  703. } else if (codePoint > 0xFFFF) {
  704. // encode to utf16 (surrogate pair dance)
  705. codePoint -= 0x10000
  706. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  707. codePoint = 0xDC00 | codePoint & 0x3FF
  708. }
  709. res.push(codePoint)
  710. i += bytesPerSequence
  711. }
  712. return decodeCodePointsArray(res)
  713. }
  714. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  715. // the lowest limit is Chrome, with 0x10000 args.
  716. // We go 1 magnitude less, for safety
  717. var MAX_ARGUMENTS_LENGTH = 0x1000
  718. function decodeCodePointsArray (codePoints) {
  719. var len = codePoints.length
  720. if (len <= MAX_ARGUMENTS_LENGTH) {
  721. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  722. }
  723. // Decode in chunks to avoid "call stack size exceeded".
  724. var res = ''
  725. var i = 0
  726. while (i < len) {
  727. res += String.fromCharCode.apply(
  728. String,
  729. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  730. )
  731. }
  732. return res
  733. }
  734. function asciiSlice (buf, start, end) {
  735. var ret = ''
  736. end = Math.min(buf.length, end)
  737. for (var i = start; i < end; i++) {
  738. ret += String.fromCharCode(buf[i] & 0x7F)
  739. }
  740. return ret
  741. }
  742. function binarySlice (buf, start, end) {
  743. var ret = ''
  744. end = Math.min(buf.length, end)
  745. for (var i = start; i < end; i++) {
  746. ret += String.fromCharCode(buf[i])
  747. }
  748. return ret
  749. }
  750. function hexSlice (buf, start, end) {
  751. var len = buf.length
  752. if (!start || start < 0) start = 0
  753. if (!end || end < 0 || end > len) end = len
  754. var out = ''
  755. for (var i = start; i < end; i++) {
  756. out += toHex(buf[i])
  757. }
  758. return out
  759. }
  760. function utf16leSlice (buf, start, end) {
  761. var bytes = buf.slice(start, end)
  762. var res = ''
  763. for (var i = 0; i < bytes.length; i += 2) {
  764. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  765. }
  766. return res
  767. }
  768. Buffer.prototype.slice = function slice (start, end) {
  769. var len = this.length
  770. start = ~~start
  771. end = end === undefined ? len : ~~end
  772. if (start < 0) {
  773. start += len
  774. if (start < 0) start = 0
  775. } else if (start > len) {
  776. start = len
  777. }
  778. if (end < 0) {
  779. end += len
  780. if (end < 0) end = 0
  781. } else if (end > len) {
  782. end = len
  783. }
  784. if (end < start) end = start
  785. var newBuf
  786. if (Buffer.TYPED_ARRAY_SUPPORT) {
  787. newBuf = Buffer._augment(this.subarray(start, end))
  788. } else {
  789. var sliceLen = end - start
  790. newBuf = new Buffer(sliceLen, undefined)
  791. for (var i = 0; i < sliceLen; i++) {
  792. newBuf[i] = this[i + start]
  793. }
  794. }
  795. if (newBuf.length) newBuf.parent = this.parent || this
  796. return newBuf
  797. }
  798. /*
  799. * Need to make sure that buffer isn't trying to write out of bounds.
  800. */
  801. function checkOffset (offset, ext, length) {
  802. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  803. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  804. }
  805. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  806. offset = offset | 0
  807. byteLength = byteLength | 0
  808. if (!noAssert) checkOffset(offset, byteLength, this.length)
  809. var val = this[offset]
  810. var mul = 1
  811. var i = 0
  812. while (++i < byteLength && (mul *= 0x100)) {
  813. val += this[offset + i] * mul
  814. }
  815. return val
  816. }
  817. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  818. offset = offset | 0
  819. byteLength = byteLength | 0
  820. if (!noAssert) {
  821. checkOffset(offset, byteLength, this.length)
  822. }
  823. var val = this[offset + --byteLength]
  824. var mul = 1
  825. while (byteLength > 0 && (mul *= 0x100)) {
  826. val += this[offset + --byteLength] * mul
  827. }
  828. return val
  829. }
  830. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  831. if (!noAssert) checkOffset(offset, 1, this.length)
  832. return this[offset]
  833. }
  834. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  835. if (!noAssert) checkOffset(offset, 2, this.length)
  836. return this[offset] | (this[offset + 1] << 8)
  837. }
  838. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  839. if (!noAssert) checkOffset(offset, 2, this.length)
  840. return (this[offset] << 8) | this[offset + 1]
  841. }
  842. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  843. if (!noAssert) checkOffset(offset, 4, this.length)
  844. return ((this[offset]) |
  845. (this[offset + 1] << 8) |
  846. (this[offset + 2] << 16)) +
  847. (this[offset + 3] * 0x1000000)
  848. }
  849. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  850. if (!noAssert) checkOffset(offset, 4, this.length)
  851. return (this[offset] * 0x1000000) +
  852. ((this[offset + 1] << 16) |
  853. (this[offset + 2] << 8) |
  854. this[offset + 3])
  855. }
  856. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  857. offset = offset | 0
  858. byteLength = byteLength | 0
  859. if (!noAssert) checkOffset(offset, byteLength, this.length)
  860. var val = this[offset]
  861. var mul = 1
  862. var i = 0
  863. while (++i < byteLength && (mul *= 0x100)) {
  864. val += this[offset + i] * mul
  865. }
  866. mul *= 0x80
  867. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  868. return val
  869. }
  870. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  871. offset = offset | 0
  872. byteLength = byteLength | 0
  873. if (!noAssert) checkOffset(offset, byteLength, this.length)
  874. var i = byteLength
  875. var mul = 1
  876. var val = this[offset + --i]
  877. while (i > 0 && (mul *= 0x100)) {
  878. val += this[offset + --i] * mul
  879. }
  880. mul *= 0x80
  881. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  882. return val
  883. }
  884. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  885. if (!noAssert) checkOffset(offset, 1, this.length)
  886. if (!(this[offset] & 0x80)) return (this[offset])
  887. return ((0xff - this[offset] + 1) * -1)
  888. }
  889. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  890. if (!noAssert) checkOffset(offset, 2, this.length)
  891. var val = this[offset] | (this[offset + 1] << 8)
  892. return (val & 0x8000) ? val | 0xFFFF0000 : val
  893. }
  894. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  895. if (!noAssert) checkOffset(offset, 2, this.length)
  896. var val = this[offset + 1] | (this[offset] << 8)
  897. return (val & 0x8000) ? val | 0xFFFF0000 : val
  898. }
  899. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  900. if (!noAssert) checkOffset(offset, 4, this.length)
  901. return (this[offset]) |
  902. (this[offset + 1] << 8) |
  903. (this[offset + 2] << 16) |
  904. (this[offset + 3] << 24)
  905. }
  906. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  907. if (!noAssert) checkOffset(offset, 4, this.length)
  908. return (this[offset] << 24) |
  909. (this[offset + 1] << 16) |
  910. (this[offset + 2] << 8) |
  911. (this[offset + 3])
  912. }
  913. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  914. if (!noAssert) checkOffset(offset, 4, this.length)
  915. return ieee754.read(this, offset, true, 23, 4)
  916. }
  917. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  918. if (!noAssert) checkOffset(offset, 4, this.length)
  919. return ieee754.read(this, offset, false, 23, 4)
  920. }
  921. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  922. if (!noAssert) checkOffset(offset, 8, this.length)
  923. return ieee754.read(this, offset, true, 52, 8)
  924. }
  925. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  926. if (!noAssert) checkOffset(offset, 8, this.length)
  927. return ieee754.read(this, offset, false, 52, 8)
  928. }
  929. function checkInt (buf, value, offset, ext, max, min) {
  930. if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
  931. if (value > max || value < min) throw new RangeError('value is out of bounds')
  932. if (offset + ext > buf.length) throw new RangeError('index out of range')
  933. }
  934. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  935. value = +value
  936. offset = offset | 0
  937. byteLength = byteLength | 0
  938. if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
  939. var mul = 1
  940. var i = 0
  941. this[offset] = value & 0xFF
  942. while (++i < byteLength && (mul *= 0x100)) {
  943. this[offset + i] = (value / mul) & 0xFF
  944. }
  945. return offset + byteLength
  946. }
  947. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  948. value = +value
  949. offset = offset | 0
  950. byteLength = byteLength | 0
  951. if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
  952. var i = byteLength - 1
  953. var mul = 1
  954. this[offset + i] = value & 0xFF
  955. while (--i >= 0 && (mul *= 0x100)) {
  956. this[offset + i] = (value / mul) & 0xFF
  957. }
  958. return offset + byteLength
  959. }
  960. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  961. value = +value
  962. offset = offset | 0
  963. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  964. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  965. this[offset] = (value & 0xff)
  966. return offset + 1
  967. }
  968. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  969. if (value < 0) value = 0xffff + value + 1
  970. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
  971. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  972. (littleEndian ? i : 1 - i) * 8
  973. }
  974. }
  975. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  976. value = +value
  977. offset = offset | 0
  978. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  979. if (Buffer.TYPED_ARRAY_SUPPORT) {
  980. this[offset] = (value & 0xff)
  981. this[offset + 1] = (value >>> 8)
  982. } else {
  983. objectWriteUInt16(this, value, offset, true)
  984. }
  985. return offset + 2
  986. }
  987. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  988. value = +value
  989. offset = offset | 0
  990. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  991. if (Buffer.TYPED_ARRAY_SUPPORT) {
  992. this[offset] = (value >>> 8)
  993. this[offset + 1] = (value & 0xff)
  994. } else {
  995. objectWriteUInt16(this, value, offset, false)
  996. }
  997. return offset + 2
  998. }
  999. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1000. if (value < 0) value = 0xffffffff + value + 1
  1001. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
  1002. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1003. }
  1004. }
  1005. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1006. value = +value
  1007. offset = offset | 0
  1008. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1009. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1010. this[offset + 3] = (value >>> 24)
  1011. this[offset + 2] = (value >>> 16)
  1012. this[offset + 1] = (value >>> 8)
  1013. this[offset] = (value & 0xff)
  1014. } else {
  1015. objectWriteUInt32(this, value, offset, true)
  1016. }
  1017. return offset + 4
  1018. }
  1019. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1020. value = +value
  1021. offset = offset | 0
  1022. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1023. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1024. this[offset] = (value >>> 24)
  1025. this[offset + 1] = (value >>> 16)
  1026. this[offset + 2] = (value >>> 8)
  1027. this[offset + 3] = (value & 0xff)
  1028. } else {
  1029. objectWriteUInt32(this, value, offset, false)
  1030. }
  1031. return offset + 4
  1032. }
  1033. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1034. value = +value
  1035. offset = offset | 0
  1036. if (!noAssert) {
  1037. var limit = Math.pow(2, 8 * byteLength - 1)
  1038. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1039. }
  1040. var i = 0
  1041. var mul = 1
  1042. var sub = value < 0 ? 1 : 0
  1043. this[offset] = value & 0xFF
  1044. while (++i < byteLength && (mul *= 0x100)) {
  1045. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1046. }
  1047. return offset + byteLength
  1048. }
  1049. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1050. value = +value
  1051. offset = offset | 0
  1052. if (!noAssert) {
  1053. var limit = Math.pow(2, 8 * byteLength - 1)
  1054. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1055. }
  1056. var i = byteLength - 1
  1057. var mul = 1
  1058. var sub = value < 0 ? 1 : 0
  1059. this[offset + i] = value & 0xFF
  1060. while (--i >= 0 && (mul *= 0x100)) {
  1061. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1062. }
  1063. return offset + byteLength
  1064. }
  1065. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1066. value = +value
  1067. offset = offset | 0
  1068. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1069. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1070. if (value < 0) value = 0xff + value + 1
  1071. this[offset] = (value & 0xff)
  1072. return offset + 1
  1073. }
  1074. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1075. value = +value
  1076. offset = offset | 0
  1077. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1078. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1079. this[offset] = (value & 0xff)
  1080. this[offset + 1] = (value >>> 8)
  1081. } else {
  1082. objectWriteUInt16(this, value, offset, true)
  1083. }
  1084. return offset + 2
  1085. }
  1086. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1087. value = +value
  1088. offset = offset | 0
  1089. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1090. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1091. this[offset] = (value >>> 8)
  1092. this[offset + 1] = (value & 0xff)
  1093. } else {
  1094. objectWriteUInt16(this, value, offset, false)
  1095. }
  1096. return offset + 2
  1097. }
  1098. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1099. value = +value
  1100. offset = offset | 0
  1101. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1102. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1103. this[offset] = (value & 0xff)
  1104. this[offset + 1] = (value >>> 8)
  1105. this[offset + 2] = (value >>> 16)
  1106. this[offset + 3] = (value >>> 24)
  1107. } else {
  1108. objectWriteUInt32(this, value, offset, true)
  1109. }
  1110. return offset + 4
  1111. }
  1112. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1113. value = +value
  1114. offset = offset | 0
  1115. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1116. if (value < 0) value = 0xffffffff + value + 1
  1117. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1118. this[offset] = (value >>> 24)
  1119. this[offset + 1] = (value >>> 16)
  1120. this[offset + 2] = (value >>> 8)
  1121. this[offset + 3] = (value & 0xff)
  1122. } else {
  1123. objectWriteUInt32(this, value, offset, false)
  1124. }
  1125. return offset + 4
  1126. }
  1127. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1128. if (value > max || value < min) throw new RangeError('value is out of bounds')
  1129. if (offset + ext > buf.length) throw new RangeError('index out of range')
  1130. if (offset < 0) throw new RangeError('index out of range')
  1131. }
  1132. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1133. if (!noAssert) {
  1134. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1135. }
  1136. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1137. return offset + 4
  1138. }
  1139. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1140. return writeFloat(this, value, offset, true, noAssert)
  1141. }
  1142. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1143. return writeFloat(this, value, offset, false, noAssert)
  1144. }
  1145. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1146. if (!noAssert) {
  1147. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1148. }
  1149. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1150. return offset + 8
  1151. }
  1152. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1153. return writeDouble(this, value, offset, true, noAssert)
  1154. }
  1155. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1156. return writeDouble(this, value, offset, false, noAssert)
  1157. }
  1158. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1159. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1160. if (!start) start = 0
  1161. if (!end && end !== 0) end = this.length
  1162. if (targetStart >= target.length) targetStart = target.length
  1163. if (!targetStart) targetStart = 0
  1164. if (end > 0 && end < start) end = start
  1165. // Copy 0 bytes; we're done
  1166. if (end === start) return 0
  1167. if (target.length === 0 || this.length === 0) return 0
  1168. // Fatal error conditions
  1169. if (targetStart < 0) {
  1170. throw new RangeError('targetStart out of bounds')
  1171. }
  1172. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1173. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1174. // Are we oob?
  1175. if (end > this.length) end = this.length
  1176. if (target.length - targetStart < end - start) {
  1177. end = target.length - targetStart + start
  1178. }
  1179. var len = end - start
  1180. var i
  1181. if (this === target && start < targetStart && targetStart < end) {
  1182. // descending copy from end
  1183. for (i = len - 1; i >= 0; i--) {
  1184. target[i + targetStart] = this[i + start]
  1185. }
  1186. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1187. // ascending copy from start
  1188. for (i = 0; i < len; i++) {
  1189. target[i + targetStart] = this[i + start]
  1190. }
  1191. } else {
  1192. target._set(this.subarray(start, start + len), targetStart)
  1193. }
  1194. return len
  1195. }
  1196. // fill(value, start=0, end=buffer.length)
  1197. Buffer.prototype.fill = function fill (value, start, end) {
  1198. if (!value) value = 0
  1199. if (!start) start = 0
  1200. if (!end) end = this.length
  1201. if (end < start) throw new RangeError('end < start')
  1202. // Fill 0 bytes; we're done
  1203. if (end === start) return
  1204. if (this.length === 0) return
  1205. if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
  1206. if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
  1207. var i
  1208. if (typeof value === 'number') {
  1209. for (i = start; i < end; i++) {
  1210. this[i] = value
  1211. }
  1212. } else {
  1213. var bytes = utf8ToBytes(value.toString())
  1214. var len = bytes.length
  1215. for (i = start; i < end; i++) {
  1216. this[i] = bytes[i % len]
  1217. }
  1218. }
  1219. return this
  1220. }
  1221. /**
  1222. * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
  1223. * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
  1224. */
  1225. Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
  1226. if (typeof Uint8Array !== 'undefined') {
  1227. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1228. return (new Buffer(this)).buffer
  1229. } else {
  1230. var buf = new Uint8Array(this.length)
  1231. for (var i = 0, len = buf.length; i < len; i += 1) {
  1232. buf[i] = this[i]
  1233. }
  1234. return buf.buffer
  1235. }
  1236. } else {
  1237. throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
  1238. }
  1239. }
  1240. // HELPER FUNCTIONS
  1241. // ================
  1242. var BP = Buffer.prototype
  1243. /**
  1244. * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
  1245. */
  1246. Buffer._augment = function _augment (arr) {
  1247. arr.constructor = Buffer
  1248. arr._isBuffer = true
  1249. // save reference to original Uint8Array set method before overwriting
  1250. arr._set = arr.set
  1251. // deprecated
  1252. arr.get = BP.get
  1253. arr.set = BP.set
  1254. arr.write = BP.write
  1255. arr.toString = BP.toString
  1256. arr.toLocaleString = BP.toString
  1257. arr.toJSON = BP.toJSON
  1258. arr.equals = BP.equals
  1259. arr.compare = BP.compare
  1260. arr.indexOf = BP.indexOf
  1261. arr.copy = BP.copy
  1262. arr.slice = BP.slice
  1263. arr.readUIntLE = BP.readUIntLE
  1264. arr.readUIntBE = BP.readUIntBE
  1265. arr.readUInt8 = BP.readUInt8
  1266. arr.readUInt16LE = BP.readUInt16LE
  1267. arr.readUInt16BE = BP.readUInt16BE
  1268. arr.readUInt32LE = BP.readUInt32LE
  1269. arr.readUInt32BE = BP.readUInt32BE
  1270. arr.readIntLE = BP.readIntLE
  1271. arr.readIntBE = BP.readIntBE
  1272. arr.readInt8 = BP.readInt8
  1273. arr.readInt16LE = BP.readInt16LE
  1274. arr.readInt16BE = BP.readInt16BE
  1275. arr.readInt32LE = BP.readInt32LE
  1276. arr.readInt32BE = BP.readInt32BE
  1277. arr.readFloatLE = BP.readFloatLE
  1278. arr.readFloatBE = BP.readFloatBE
  1279. arr.readDoubleLE = BP.readDoubleLE
  1280. arr.readDoubleBE = BP.readDoubleBE
  1281. arr.writeUInt8 = BP.writeUInt8
  1282. arr.writeUIntLE = BP.writeUIntLE
  1283. arr.writeUIntBE = BP.writeUIntBE
  1284. arr.writeUInt16LE = BP.writeUInt16LE
  1285. arr.writeUInt16BE = BP.writeUInt16BE
  1286. arr.writeUInt32LE = BP.writeUInt32LE
  1287. arr.writeUInt32BE = BP.writeUInt32BE
  1288. arr.writeIntLE = BP.writeIntLE
  1289. arr.writeIntBE = BP.writeIntBE
  1290. arr.writeInt8 = BP.writeInt8
  1291. arr.writeInt16LE = BP.writeInt16LE
  1292. arr.writeInt16BE = BP.writeInt16BE
  1293. arr.writeInt32LE = BP.writeInt32LE
  1294. arr.writeInt32BE = BP.writeInt32BE
  1295. arr.writeFloatLE = BP.writeFloatLE
  1296. arr.writeFloatBE = BP.writeFloatBE
  1297. arr.writeDoubleLE = BP.writeDoubleLE
  1298. arr.writeDoubleBE = BP.writeDoubleBE
  1299. arr.fill = BP.fill
  1300. arr.inspect = BP.inspect
  1301. arr.toArrayBuffer = BP.toArrayBuffer
  1302. return arr
  1303. }
  1304. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1305. function base64clean (str) {
  1306. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1307. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1308. // Node converts strings with length < 2 to ''
  1309. if (str.length < 2) return ''
  1310. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1311. while (str.length % 4 !== 0) {
  1312. str = str + '='
  1313. }
  1314. return str
  1315. }
  1316. function stringtrim (str) {
  1317. if (str.trim) return str.trim()
  1318. return str.replace(/^\s+|\s+$/g, '')
  1319. }
  1320. function toHex (n) {
  1321. if (n < 16) return '0' + n.toString(16)
  1322. return n.toString(16)
  1323. }
  1324. function utf8ToBytes (string, units) {
  1325. units = units || Infinity
  1326. var codePoint
  1327. var length = string.length
  1328. var leadSurrogate = null
  1329. var bytes = []
  1330. for (var i = 0; i < length; i++) {
  1331. codePoint = string.charCodeAt(i)
  1332. // is surrogate component
  1333. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1334. // last char was a lead
  1335. if (!leadSurrogate) {
  1336. // no lead yet
  1337. if (codePoint > 0xDBFF) {
  1338. // unexpected trail
  1339. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1340. continue
  1341. } else if (i + 1 === length) {
  1342. // unpaired lead
  1343. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1344. continue
  1345. }
  1346. // valid lead
  1347. leadSurrogate = codePoint
  1348. continue
  1349. }
  1350. // 2 leads in a row
  1351. if (codePoint < 0xDC00) {
  1352. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1353. leadSurrogate = codePoint
  1354. continue
  1355. }
  1356. // valid surrogate pair
  1357. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1358. } else if (leadSurrogate) {
  1359. // valid bmp char, but last char was a lead
  1360. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1361. }
  1362. leadSurrogate = null
  1363. // encode utf8
  1364. if (codePoint < 0x80) {
  1365. if ((units -= 1) < 0) break
  1366. bytes.push(codePoint)
  1367. } else if (codePoint < 0x800) {
  1368. if ((units -= 2) < 0) break
  1369. bytes.push(
  1370. codePoint >> 0x6 | 0xC0,
  1371. codePoint & 0x3F | 0x80
  1372. )
  1373. } else if (codePoint < 0x10000) {
  1374. if ((units -= 3) < 0) break
  1375. bytes.push(
  1376. codePoint >> 0xC | 0xE0,
  1377. codePoint >> 0x6 & 0x3F | 0x80,
  1378. codePoint & 0x3F | 0x80
  1379. )
  1380. } else if (codePoint < 0x110000) {
  1381. if ((units -= 4) < 0) break
  1382. bytes.push(
  1383. codePoint >> 0x12 | 0xF0,
  1384. codePoint >> 0xC & 0x3F | 0x80,
  1385. codePoint >> 0x6 & 0x3F | 0x80,
  1386. codePoint & 0x3F | 0x80
  1387. )
  1388. } else {
  1389. throw new Error('Invalid code point')
  1390. }
  1391. }
  1392. return bytes
  1393. }
  1394. function asciiToBytes (str) {
  1395. var byteArray = []
  1396. for (var i = 0; i < str.length; i++) {
  1397. // Node's code seems to be doing this and not & 0x7F..
  1398. byteArray.push(str.charCodeAt(i) & 0xFF)
  1399. }
  1400. return byteArray
  1401. }
  1402. function utf16leToBytes (str, units) {
  1403. var c, hi, lo
  1404. var byteArray = []
  1405. for (var i = 0; i < str.length; i++) {
  1406. if ((units -= 2) < 0) break
  1407. c = str.charCodeAt(i)
  1408. hi = c >> 8
  1409. lo = c % 256
  1410. byteArray.push(lo)
  1411. byteArray.push(hi)
  1412. }
  1413. return byteArray
  1414. }
  1415. function base64ToBytes (str) {
  1416. return base64.toByteArray(base64clean(str))
  1417. }
  1418. function blitBuffer (src, dst, offset, length) {
  1419. for (var i = 0; i < length; i++) {
  1420. if ((i + offset >= dst.length) || (i >= src.length)) break
  1421. dst[i + offset] = src[i]
  1422. }
  1423. return i
  1424. }
  1425. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1426. },{"base64-js":1,"ieee754":8,"isarray":3}],3:[function(require,module,exports){
  1427. var toString = {}.toString;
  1428. module.exports = Array.isArray || function (arr) {
  1429. return toString.call(arr) == '[object Array]';
  1430. };
  1431. },{}],4:[function(require,module,exports){
  1432. 'use strict';
  1433. var isCallable = require('is-callable');
  1434. var toStr = Object.prototype.toString;
  1435. var hasOwnProperty = Object.prototype.hasOwnProperty;
  1436. var forEachArray = function forEachArray(array, iterator, receiver) {
  1437. for (var i = 0, len = array.length; i < len; i++) {
  1438. if (hasOwnProperty.call(array, i)) {
  1439. if (receiver == null) {
  1440. iterator(array[i], i, array);
  1441. } else {
  1442. iterator.call(receiver, array[i], i, array);
  1443. }
  1444. }
  1445. }
  1446. };
  1447. var forEachString = function forEachString(string, iterator, receiver) {
  1448. for (var i = 0, len = string.length; i < len; i++) {
  1449. // no such thing as a sparse string.
  1450. if (receiver == null) {
  1451. iterator(string.charAt(i), i, string);
  1452. } else {
  1453. iterator.call(receiver, string.charAt(i), i, string);
  1454. }
  1455. }
  1456. };
  1457. var forEachObject = function forEachObject(object, iterator, receiver) {
  1458. for (var k in object) {
  1459. if (hasOwnProperty.call(object, k)) {
  1460. if (receiver == null) {
  1461. iterator(object[k], k, object);
  1462. } else {
  1463. iterator.call(receiver, object[k], k, object);
  1464. }
  1465. }
  1466. }
  1467. };
  1468. var forEach = function forEach(list, iterator, thisArg) {
  1469. if (!isCallable(iterator)) {
  1470. throw new TypeError('iterator must be a function');
  1471. }
  1472. var receiver;
  1473. if (arguments.length >= 3) {
  1474. receiver = thisArg;
  1475. }
  1476. if (toStr.call(list) === '[object Array]') {
  1477. forEachArray(list, iterator, receiver);
  1478. } else if (typeof list === 'string') {
  1479. forEachString(list, iterator, receiver);
  1480. } else {
  1481. forEachObject(list, iterator, receiver);
  1482. }
  1483. };
  1484. module.exports = forEach;
  1485. },{"is-callable":9}],5:[function(require,module,exports){
  1486. (function (global){
  1487. var win;
  1488. if (typeof window !== "undefined") {
  1489. win = window;
  1490. } else if (typeof global !== "undefined") {
  1491. win = global;
  1492. } else if (typeof self !== "undefined"){
  1493. win = self;
  1494. } else {
  1495. win = {};
  1496. }
  1497. module.exports = win;
  1498. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1499. },{}],6:[function(require,module,exports){
  1500. module.exports = require('./lib/heap');
  1501. },{"./lib/heap":7}],7:[function(require,module,exports){
  1502. // Generated by CoffeeScript 1.8.0
  1503. (function() {
  1504. var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;
  1505. floor = Math.floor, min = Math.min;
  1506. /*
  1507. Default comparison function to be used
  1508. */
  1509. defaultCmp = function(x, y) {
  1510. if (x < y) {
  1511. return -1;
  1512. }
  1513. if (x > y) {
  1514. return 1;
  1515. }
  1516. return 0;
  1517. };
  1518. /*
  1519. Insert item x in list a, and keep it sorted assuming a is sorted.
  1520. If x is already in a, insert it to the right of the rightmost x.
  1521. Optional args lo (default 0) and hi (default a.length) bound the slice
  1522. of a to be searched.
  1523. */
  1524. insort = function(a, x, lo, hi, cmp) {
  1525. var mid;
  1526. if (lo == null) {
  1527. lo = 0;
  1528. }
  1529. if (cmp == null) {
  1530. cmp = defaultCmp;
  1531. }
  1532. if (lo < 0) {
  1533. throw new Error('lo must be non-negative');
  1534. }
  1535. if (hi == null) {
  1536. hi = a.length;
  1537. }
  1538. while (lo < hi) {
  1539. mid = floor((lo + hi) / 2);
  1540. if (cmp(x, a[mid]) < 0) {
  1541. hi = mid;
  1542. } else {
  1543. lo = mid + 1;
  1544. }
  1545. }
  1546. return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);
  1547. };
  1548. /*
  1549. Push item onto heap, maintaining the heap invariant.
  1550. */
  1551. heappush = function(array, item, cmp) {
  1552. if (cmp == null) {
  1553. cmp = defaultCmp;
  1554. }
  1555. array.push(item);
  1556. return _siftdown(array, 0, array.length - 1, cmp);
  1557. };
  1558. /*
  1559. Pop the smallest item off the heap, maintaining the heap invariant.
  1560. */
  1561. heappop = function(array, cmp) {
  1562. var lastelt, returnitem;
  1563. if (cmp == null) {
  1564. cmp = defaultCmp;
  1565. }
  1566. lastelt = array.pop();
  1567. if (array.length) {
  1568. returnitem = array[0];
  1569. array[0] = lastelt;
  1570. _siftup(array, 0, cmp);
  1571. } else {
  1572. returnitem = lastelt;
  1573. }
  1574. return returnitem;
  1575. };
  1576. /*
  1577. Pop and return the current smallest value, and add the new item.
  1578. This is more efficient than heappop() followed by heappush(), and can be
  1579. more appropriate when using a fixed size heap. Note that the value
  1580. returned may be larger than item! That constrains reasonable use of
  1581. this routine unless written as part of a conditional replacement:
  1582. if item > array[0]
  1583. item = heapreplace(array, item)
  1584. */
  1585. heapreplace = function(array, item, cmp) {
  1586. var returnitem;
  1587. if (cmp == null) {
  1588. cmp = defaultCmp;
  1589. }
  1590. returnitem = array[0];
  1591. array[0] = item;
  1592. _siftup(array, 0, cmp);
  1593. return returnitem;
  1594. };
  1595. /*
  1596. Fast version of a heappush followed by a heappop.
  1597. */
  1598. heappushpop = function(array, item, cmp) {
  1599. var _ref;
  1600. if (cmp == null) {
  1601. cmp = defaultCmp;
  1602. }
  1603. if (array.length && cmp(array[0], item) < 0) {
  1604. _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
  1605. _siftup(array, 0, cmp);
  1606. }
  1607. return item;
  1608. };
  1609. /*
  1610. Transform list into a heap, in-place, in O(array.length) time.
  1611. */
  1612. heapify = function(array, cmp) {
  1613. var i, _i, _j, _len, _ref, _ref1, _results, _results1;
  1614. if (cmp == null) {
  1615. cmp = defaultCmp;
  1616. }
  1617. _ref1 = (function() {
  1618. _results1 = [];
  1619. for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }
  1620. return _results1;
  1621. }).apply(this).reverse();
  1622. _results = [];
  1623. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  1624. i = _ref1[_i];
  1625. _results.push(_siftup(array, i, cmp));
  1626. }
  1627. return _results;
  1628. };
  1629. /*
  1630. Update the position of the given item in the heap.
  1631. This function should be called every time the item is being modified.
  1632. */
  1633. updateItem = function(array, item, cmp) {
  1634. var pos;
  1635. if (cmp == null) {
  1636. cmp = defaultCmp;
  1637. }
  1638. pos = array.indexOf(item);
  1639. if (pos === -1) {
  1640. return;
  1641. }
  1642. _siftdown(array, 0, pos, cmp);
  1643. return _siftup(array, pos, cmp);
  1644. };
  1645. /*
  1646. Find the n largest elements in a dataset.
  1647. */
  1648. nlargest = function(array, n, cmp) {
  1649. var elem, result, _i, _len, _ref;
  1650. if (cmp == null) {
  1651. cmp = defaultCmp;
  1652. }
  1653. result = array.slice(0, n);
  1654. if (!result.length) {
  1655. return result;
  1656. }
  1657. heapify(result, cmp);
  1658. _ref = array.slice(n);
  1659. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  1660. elem = _ref[_i];
  1661. heappushpop(result, elem, cmp);
  1662. }
  1663. return result.sort(cmp).reverse();
  1664. };
  1665. /*
  1666. Find the n smallest elements in a dataset.
  1667. */
  1668. nsmallest = function(array, n, cmp) {
  1669. var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results;
  1670. if (cmp == null) {
  1671. cmp = defaultCmp;
  1672. }
  1673. if (n * 10 <= array.length) {
  1674. result = array.slice(0, n).sort(cmp);
  1675. if (!result.length) {
  1676. return result;
  1677. }
  1678. los = result[result.length - 1];
  1679. _ref = array.slice(n);
  1680. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  1681. elem = _ref[_i];
  1682. if (cmp(elem, los) < 0) {
  1683. insort(result, elem, 0, null, cmp);
  1684. result.pop();
  1685. los = result[result.length - 1];
  1686. }
  1687. }
  1688. return result;
  1689. }
  1690. heapify(array, cmp);
  1691. _results = [];
  1692. for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
  1693. _results.push(heappop(array, cmp));
  1694. }
  1695. return _results;
  1696. };
  1697. _siftdown = function(array, startpos, pos, cmp) {
  1698. var newitem, parent, parentpos;
  1699. if (cmp == null) {
  1700. cmp = defaultCmp;
  1701. }
  1702. newitem = array[pos];
  1703. while (pos > startpos) {
  1704. parentpos = (pos - 1) >> 1;
  1705. parent = array[parentpos];
  1706. if (cmp(newitem, parent) < 0) {
  1707. array[pos] = parent;
  1708. pos = parentpos;
  1709. continue;
  1710. }
  1711. break;
  1712. }
  1713. return array[pos] = newitem;
  1714. };
  1715. _siftup = function(array, pos, cmp) {
  1716. var childpos, endpos, newitem, rightpos, startpos;
  1717. if (cmp == null) {
  1718. cmp = defaultCmp;
  1719. }
  1720. endpos = array.length;
  1721. startpos = pos;
  1722. newitem = array[pos];
  1723. childpos = 2 * pos + 1;
  1724. while (childpos < endpos) {
  1725. rightpos = childpos + 1;
  1726. if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
  1727. childpos = rightpos;
  1728. }
  1729. array[pos] = array[childpos];
  1730. pos = childpos;
  1731. childpos = 2 * pos + 1;
  1732. }
  1733. array[pos] = newitem;
  1734. return _siftdown(array, startpos, pos, cmp);
  1735. };
  1736. Heap = (function() {
  1737. Heap.push = heappush;
  1738. Heap.pop = heappop;
  1739. Heap.replace = heapreplace;
  1740. Heap.pushpop = heappushpop;
  1741. Heap.heapify = heapify;
  1742. Heap.updateItem = updateItem;
  1743. Heap.nlargest = nlargest;
  1744. Heap.nsmallest = nsmallest;
  1745. function Heap(cmp) {
  1746. this.cmp = cmp != null ? cmp : defaultCmp;
  1747. this.nodes = [];
  1748. }
  1749. Heap.prototype.push = function(x) {
  1750. return heappush(this.nodes, x, this.cmp);
  1751. };
  1752. Heap.prototype.pop = function() {
  1753. return heappop(this.nodes, this.cmp);
  1754. };
  1755. Heap.prototype.peek = function() {
  1756. return this.nodes[0];
  1757. };
  1758. Heap.prototype.contains = function(x) {
  1759. return this.nodes.indexOf(x) !== -1;
  1760. };
  1761. Heap.prototype.replace = function(x) {
  1762. return heapreplace(this.nodes, x, this.cmp);
  1763. };
  1764. Heap.prototype.pushpop = function(x) {
  1765. return heappushpop(this.nodes, x, this.cmp);
  1766. };
  1767. Heap.prototype.heapify = function() {
  1768. return heapify(this.nodes, this.cmp);
  1769. };
  1770. Heap.prototype.updateItem = function(x) {
  1771. return updateItem(this.nodes, x, this.cmp);
  1772. };
  1773. Heap.prototype.clear = function() {
  1774. return this.nodes = [];
  1775. };
  1776. Heap.prototype.empty = function() {
  1777. return this.nodes.length === 0;
  1778. };
  1779. Heap.prototype.size = function() {
  1780. return this.nodes.length;
  1781. };
  1782. Heap.prototype.clone = function() {
  1783. var heap;
  1784. heap = new Heap();
  1785. heap.nodes = this.nodes.slice(0);
  1786. return heap;
  1787. };
  1788. Heap.prototype.toArray = function() {
  1789. return this.nodes.slice(0);
  1790. };
  1791. Heap.prototype.insert = Heap.prototype.push;
  1792. Heap.prototype.top = Heap.prototype.peek;
  1793. Heap.prototype.front = Heap.prototype.peek;
  1794. Heap.prototype.has = Heap.prototype.contains;
  1795. Heap.prototype.copy = Heap.prototype.clone;
  1796. return Heap;
  1797. })();
  1798. (function(root, factory) {
  1799. if (typeof define === 'function' && define.amd) {
  1800. return define([], factory);
  1801. } else if (typeof exports === 'object') {
  1802. return module.exports = factory();
  1803. } else {
  1804. return root.Heap = factory();
  1805. }
  1806. })(this, function() {
  1807. return Heap;
  1808. });
  1809. }).call(this);
  1810. },{}],8:[function(require,module,exports){
  1811. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  1812. var e, m
  1813. var eLen = (nBytes * 8) - mLen - 1
  1814. var eMax = (1 << eLen) - 1
  1815. var eBias = eMax >> 1
  1816. var nBits = -7
  1817. var i = isLE ? (nBytes - 1) : 0
  1818. var d = isLE ? -1 : 1
  1819. var s = buffer[offset + i]
  1820. i += d
  1821. e = s & ((1 << (-nBits)) - 1)
  1822. s >>= (-nBits)
  1823. nBits += eLen
  1824. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  1825. m = e & ((1 << (-nBits)) - 1)
  1826. e >>= (-nBits)
  1827. nBits += mLen
  1828. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  1829. if (e === 0) {
  1830. e = 1 - eBias
  1831. } else if (e === eMax) {
  1832. return m ? NaN : ((s ? -1 : 1) * Infinity)
  1833. } else {
  1834. m = m + Math.pow(2, mLen)
  1835. e = e - eBias
  1836. }
  1837. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  1838. }
  1839. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  1840. var e, m, c
  1841. var eLen = (nBytes * 8) - mLen - 1
  1842. var eMax = (1 << eLen) - 1
  1843. var eBias = eMax >> 1
  1844. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  1845. var i = isLE ? 0 : (nBytes - 1)
  1846. var d = isLE ? 1 : -1
  1847. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  1848. value = Math.abs(value)
  1849. if (isNaN(value) || value === Infinity) {
  1850. m = isNaN(value) ? 1 : 0
  1851. e = eMax
  1852. } else {
  1853. e = Math.floor(Math.log(value) / Math.LN2)
  1854. if (value * (c = Math.pow(2, -e)) < 1) {
  1855. e--
  1856. c *= 2
  1857. }
  1858. if (e + eBias >= 1) {
  1859. value += rt / c
  1860. } else {
  1861. value += rt * Math.pow(2, 1 - eBias)
  1862. }
  1863. if (value * c >= 2) {
  1864. e++
  1865. c /= 2
  1866. }
  1867. if (e + eBias >= eMax) {
  1868. m = 0
  1869. e = eMax
  1870. } else if (e + eBias >= 1) {
  1871. m = ((value * c) - 1) * Math.pow(2, mLen)
  1872. e = e + eBias
  1873. } else {
  1874. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  1875. e = 0
  1876. }
  1877. }
  1878. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  1879. e = (e << mLen) | m
  1880. eLen += mLen
  1881. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  1882. buffer[offset + i - d] |= s * 128
  1883. }
  1884. },{}],9:[function(require,module,exports){
  1885. 'use strict';
  1886. var fnToStr = Function.prototype.toString;
  1887. var constructorRegex = /^\s*class\b/;
  1888. var isES6ClassFn = function isES6ClassFunction(value) {
  1889. try {
  1890. var fnStr = fnToStr.call(value);
  1891. return constructorRegex.test(fnStr);
  1892. } catch (e) {
  1893. return false; // not a function
  1894. }
  1895. };
  1896. var tryFunctionObject = function tryFunctionToStr(value) {
  1897. try {
  1898. if (isES6ClassFn(value)) { return false; }
  1899. fnToStr.call(value);
  1900. return true;
  1901. } catch (e) {
  1902. return false;
  1903. }
  1904. };
  1905. var toStr = Object.prototype.toString;
  1906. var fnClass = '[object Function]';
  1907. var genClass = '[object GeneratorFunction]';
  1908. var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
  1909. module.exports = function isCallable(value) {
  1910. if (!value) { return false; }
  1911. if (typeof value !== 'function' && typeof value !== 'object') { return false; }
  1912. if (typeof value === 'function' && !value.prototype) { return true; }
  1913. if (hasToStringTag) { return tryFunctionObject(value); }
  1914. if (isES6ClassFn(value)) { return false; }
  1915. var strClass = toStr.call(value);
  1916. return strClass === fnClass || strClass === genClass;
  1917. };
  1918. },{}],10:[function(require,module,exports){
  1919. module.exports = once
  1920. once.proto = once(function () {
  1921. Object.defineProperty(Function.prototype, 'once', {
  1922. value: function () {
  1923. return once(this)
  1924. },
  1925. configurable: true
  1926. })
  1927. })
  1928. function once (fn) {
  1929. var called = false
  1930. return function () {
  1931. if (called) return
  1932. called = true
  1933. return fn.apply(this, arguments)
  1934. }
  1935. }
  1936. },{}],11:[function(require,module,exports){
  1937. var trim = require('trim')
  1938. , forEach = require('for-each')
  1939. , isArray = function(arg) {
  1940. return Object.prototype.toString.call(arg) === '[object Array]';
  1941. }
  1942. module.exports = function (headers) {
  1943. if (!headers)
  1944. return {}
  1945. var result = {}
  1946. forEach(
  1947. trim(headers).split('\n')
  1948. , function (row) {
  1949. var index = row.indexOf(':')
  1950. , key = trim(row.slice(0, index)).toLowerCase()
  1951. , value = trim(row.slice(index + 1))
  1952. if (typeof(result[key]) === 'undefined') {
  1953. result[key] = value
  1954. } else if (isArray(result[key])) {
  1955. result[key].push(value)
  1956. } else {
  1957. result[key] = [ result[key], value ]
  1958. }
  1959. }
  1960. )
  1961. return result
  1962. }
  1963. },{"for-each":4,"trim":16}],12:[function(require,module,exports){
  1964. (function (global){
  1965. /*! https://mths.be/punycode v1.4.1 by @mathias */
  1966. ;(function(root) {
  1967. /** Detect free variables */
  1968. var freeExports = typeof exports == 'object' && exports &&
  1969. !exports.nodeType && exports;
  1970. var freeModule = typeof module == 'object' && module &&
  1971. !module.nodeType && module;
  1972. var freeGlobal = typeof global == 'object' && global;
  1973. if (
  1974. freeGlobal.global === freeGlobal ||
  1975. freeGlobal.window === freeGlobal ||
  1976. freeGlobal.self === freeGlobal
  1977. ) {
  1978. root = freeGlobal;
  1979. }
  1980. /**
  1981. * The `punycode` object.
  1982. * @name punycode
  1983. * @type Object
  1984. */
  1985. var punycode,
  1986. /** Highest positive signed 32-bit float value */
  1987. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  1988. /** Bootstring parameters */
  1989. base = 36,
  1990. tMin = 1,
  1991. tMax = 26,
  1992. skew = 38,
  1993. damp = 700,
  1994. initialBias = 72,
  1995. initialN = 128, // 0x80
  1996. delimiter = '-', // '\x2D'
  1997. /** Regular expressions */
  1998. regexPunycode = /^xn--/,
  1999. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  2000. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  2001. /** Error messages */
  2002. errors = {
  2003. 'overflow': 'Overflow: input needs wider integers to process',
  2004. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  2005. 'invalid-input': 'Invalid input'
  2006. },
  2007. /** Convenience shortcuts */
  2008. baseMinusTMin = base - tMin,
  2009. floor = Math.floor,
  2010. stringFromCharCode = String.fromCharCode,
  2011. /** Temporary variable */
  2012. key;
  2013. /*--------------------------------------------------------------------------*/
  2014. /**
  2015. * A generic error utility function.
  2016. * @private
  2017. * @param {String} type The error type.
  2018. * @returns {Error} Throws a `RangeError` with the applicable error message.
  2019. */
  2020. function error(type) {
  2021. throw new RangeError(errors[type]);
  2022. }
  2023. /**
  2024. * A generic `Array#map` utility function.
  2025. * @private
  2026. * @param {Array} array The array to iterate over.
  2027. * @param {Function} callback The function that gets called for every array
  2028. * item.
  2029. * @returns {Array} A new array of values returned by the callback function.
  2030. */
  2031. function map(array, fn) {
  2032. var length = array.length;
  2033. var result = [];
  2034. while (length--) {
  2035. result[length] = fn(array[length]);
  2036. }
  2037. return result;
  2038. }
  2039. /**
  2040. * A simple `Array#map`-like wrapper to work with domain name strings or email
  2041. * addresses.
  2042. * @private
  2043. * @param {String} domain The domain name or email address.
  2044. * @param {Function} callback The function that gets called for every
  2045. * character.
  2046. * @returns {Array} A new string of characters returned by the callback
  2047. * function.
  2048. */
  2049. function mapDomain(string, fn) {
  2050. var parts = string.split('@');
  2051. var result = '';
  2052. if (parts.length > 1) {
  2053. // In email addresses, only the domain name should be punycoded. Leave
  2054. // the local part (i.e. everything up to `@`) intact.
  2055. result = parts[0] + '@';
  2056. string = parts[1];
  2057. }
  2058. // Avoid `split(regex)` for IE8 compatibility. See #17.
  2059. string = string.replace(regexSeparators, '\x2E');
  2060. var labels = string.split('.');
  2061. var encoded = map(labels, fn).join('.');
  2062. return result + encoded;
  2063. }
  2064. /**
  2065. * Creates an array containing the numeric code points of each Unicode
  2066. * character in the string. While JavaScript uses UCS-2 internally,
  2067. * this function will convert a pair of surrogate halves (each of which
  2068. * UCS-2 exposes as separate characters) into a single code point,
  2069. * matching UTF-16.
  2070. * @see `punycode.ucs2.encode`
  2071. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  2072. * @memberOf punycode.ucs2
  2073. * @name decode
  2074. * @param {String} string The Unicode input string (UCS-2).
  2075. * @returns {Array} The new array of code points.
  2076. */
  2077. function ucs2decode(string) {
  2078. var output = [],
  2079. counter = 0,
  2080. length = string.length,
  2081. value,
  2082. extra;
  2083. while (counter < length) {
  2084. value = string.charCodeAt(counter++);
  2085. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  2086. // high surrogate, and there is a next character
  2087. extra = string.charCodeAt(counter++);
  2088. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  2089. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  2090. } else {
  2091. // unmatched surrogate; only append this code unit, in case the next
  2092. // code unit is the high surrogate of a surrogate pair
  2093. output.push(value);
  2094. counter--;
  2095. }
  2096. } else {
  2097. output.push(value);
  2098. }
  2099. }
  2100. return output;
  2101. }
  2102. /**
  2103. * Creates a string based on an array of numeric code points.
  2104. * @see `punycode.ucs2.decode`
  2105. * @memberOf punycode.ucs2
  2106. * @name encode
  2107. * @param {Array} codePoints The array of numeric code points.
  2108. * @returns {String} The new Unicode string (UCS-2).
  2109. */
  2110. function ucs2encode(array) {
  2111. return map(array, function(value) {
  2112. var output = '';
  2113. if (value > 0xFFFF) {
  2114. value -= 0x10000;
  2115. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  2116. value = 0xDC00 | value & 0x3FF;
  2117. }
  2118. output += stringFromCharCode(value);
  2119. return output;
  2120. }).join('');
  2121. }
  2122. /**
  2123. * Converts a basic code point into a digit/integer.
  2124. * @see `digitToBasic()`
  2125. * @private
  2126. * @param {Number} codePoint The basic numeric code point value.
  2127. * @returns {Number} The numeric value of a basic code point (for use in
  2128. * representing integers) in the range `0` to `base - 1`, or `base` if
  2129. * the code point does not represent a value.
  2130. */
  2131. function basicToDigit(codePoint) {
  2132. if (codePoint - 48 < 10) {
  2133. return codePoint - 22;
  2134. }
  2135. if (codePoint - 65 < 26) {
  2136. return codePoint - 65;
  2137. }
  2138. if (codePoint - 97 < 26) {
  2139. return codePoint - 97;
  2140. }
  2141. return base;
  2142. }
  2143. /**
  2144. * Converts a digit/integer into a basic code point.
  2145. * @see `basicToDigit()`
  2146. * @private
  2147. * @param {Number} digit The numeric value of a basic code point.
  2148. * @returns {Number} The basic code point whose value (when used for
  2149. * representing integers) is `digit`, which needs to be in the range
  2150. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  2151. * used; else, the lowercase form is used. The behavior is undefined
  2152. * if `flag` is non-zero and `digit` has no uppercase form.
  2153. */
  2154. function digitToBasic(digit, flag) {
  2155. // 0..25 map to ASCII a..z or A..Z
  2156. // 26..35 map to ASCII 0..9
  2157. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  2158. }
  2159. /**
  2160. * Bias adaptation function as per section 3.4 of RFC 3492.
  2161. * https://tools.ietf.org/html/rfc3492#section-3.4
  2162. * @private
  2163. */
  2164. function adapt(delta, numPoints, firstTime) {
  2165. var k = 0;
  2166. delta = firstTime ? floor(delta / damp) : delta >> 1;
  2167. delta += floor(delta / numPoints);
  2168. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  2169. delta = floor(delta / baseMinusTMin);
  2170. }
  2171. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  2172. }
  2173. /**
  2174. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  2175. * symbols.
  2176. * @memberOf punycode
  2177. * @param {String} input The Punycode string of ASCII-only symbols.
  2178. * @returns {String} The resulting string of Unicode symbols.
  2179. */
  2180. function decode(input) {
  2181. // Don't use UCS-2
  2182. var output = [],
  2183. inputLength = input.length,
  2184. out,
  2185. i = 0,
  2186. n = initialN,
  2187. bias = initialBias,
  2188. basic,
  2189. j,
  2190. index,
  2191. oldi,
  2192. w,
  2193. k,
  2194. digit,
  2195. t,
  2196. /** Cached calculation results */
  2197. baseMinusT;
  2198. // Handle the basic code points: let `basic` be the number of input code
  2199. // points before the last delimiter, or `0` if there is none, then copy
  2200. // the first basic code points to the output.
  2201. basic = input.lastIndexOf(delimiter);
  2202. if (basic < 0) {
  2203. basic = 0;
  2204. }
  2205. for (j = 0; j < basic; ++j) {
  2206. // if it's not a basic code point
  2207. if (input.charCodeAt(j) >= 0x80) {
  2208. error('not-basic');
  2209. }
  2210. output.push(input.charCodeAt(j));
  2211. }
  2212. // Main decoding loop: start just after the last delimiter if any basic code
  2213. // points were copied; start at the beginning otherwise.
  2214. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  2215. // `index` is the index of the next character to be consumed.
  2216. // Decode a generalized variable-length integer into `delta`,
  2217. // which gets added to `i`. The overflow checking is easier
  2218. // if we increase `i` as we go, then subtract off its starting
  2219. // value at the end to obtain `delta`.
  2220. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  2221. if (index >= inputLength) {
  2222. error('invalid-input');
  2223. }
  2224. digit = basicToDigit(input.charCodeAt(index++));
  2225. if (digit >= base || digit > floor((maxInt - i) / w)) {
  2226. error('overflow');
  2227. }
  2228. i += digit * w;
  2229. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  2230. if (digit < t) {
  2231. break;
  2232. }
  2233. baseMinusT = base - t;
  2234. if (w > floor(maxInt / baseMinusT)) {
  2235. error('overflow');
  2236. }
  2237. w *= baseMinusT;
  2238. }
  2239. out = output.length + 1;
  2240. bias = adapt(i - oldi, out, oldi == 0);
  2241. // `i` was supposed to wrap around from `out` to `0`,
  2242. // incrementing `n` each time, so we'll fix that now:
  2243. if (floor(i / out) > maxInt - n) {
  2244. error('overflow');
  2245. }
  2246. n += floor(i / out);
  2247. i %= out;
  2248. // Insert `n` at position `i` of the output
  2249. output.splice(i++, 0, n);
  2250. }
  2251. return ucs2encode(output);
  2252. }
  2253. /**
  2254. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  2255. * Punycode string of ASCII-only symbols.
  2256. * @memberOf punycode
  2257. * @param {String} input The string of Unicode symbols.
  2258. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  2259. */
  2260. function encode(input) {
  2261. var n,
  2262. delta,
  2263. handledCPCount,
  2264. basicLength,
  2265. bias,
  2266. j,
  2267. m,
  2268. q,
  2269. k,
  2270. t,
  2271. currentValue,
  2272. output = [],
  2273. /** `inputLength` will hold the number of code points in `input`. */
  2274. inputLength,
  2275. /** Cached calculation results */
  2276. handledCPCountPlusOne,
  2277. baseMinusT,
  2278. qMinusT;
  2279. // Convert the input in UCS-2 to Unicode
  2280. input = ucs2decode(input);
  2281. // Cache the length
  2282. inputLength = input.length;
  2283. // Initialize the state
  2284. n = initialN;
  2285. delta = 0;
  2286. bias = initialBias;
  2287. // Handle the basic code points
  2288. for (j = 0; j < inputLength; ++j) {
  2289. currentValue = input[j];
  2290. if (currentValue < 0x80) {
  2291. output.push(stringFromCharCode(currentValue));
  2292. }
  2293. }
  2294. handledCPCount = basicLength = output.length;
  2295. // `handledCPCount` is the number of code points that have been handled;
  2296. // `basicLength` is the number of basic code points.
  2297. // Finish the basic string - if it is not empty - with a delimiter
  2298. if (basicLength) {
  2299. output.push(delimiter);
  2300. }
  2301. // Main encoding loop:
  2302. while (handledCPCount < inputLength) {
  2303. // All non-basic code points < n have been handled already. Find the next
  2304. // larger one:
  2305. for (m = maxInt, j = 0; j < inputLength; ++j) {
  2306. currentValue = input[j];
  2307. if (currentValue >= n && currentValue < m) {
  2308. m = currentValue;
  2309. }
  2310. }
  2311. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  2312. // but guard against overflow
  2313. handledCPCountPlusOne = handledCPCount + 1;
  2314. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  2315. error('overflow');
  2316. }
  2317. delta += (m - n) * handledCPCountPlusOne;
  2318. n = m;
  2319. for (j = 0; j < inputLength; ++j) {
  2320. currentValue = input[j];
  2321. if (currentValue < n && ++delta > maxInt) {
  2322. error('overflow');
  2323. }
  2324. if (currentValue == n) {
  2325. // Represent delta as a generalized variable-length integer
  2326. for (q = delta, k = base; /* no condition */; k += base) {
  2327. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  2328. if (q < t) {
  2329. break;
  2330. }
  2331. qMinusT = q - t;
  2332. baseMinusT = base - t;
  2333. output.push(
  2334. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  2335. );
  2336. q = floor(qMinusT / baseMinusT);
  2337. }
  2338. output.push(stringFromCharCode(digitToBasic(q, 0)));
  2339. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  2340. delta = 0;
  2341. ++handledCPCount;
  2342. }
  2343. }
  2344. ++delta;
  2345. ++n;
  2346. }
  2347. return output.join('');
  2348. }
  2349. /**
  2350. * Converts a Punycode string representing a domain name or an email address
  2351. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  2352. * it doesn't matter if you call it on a string that has already been
  2353. * converted to Unicode.
  2354. * @memberOf punycode
  2355. * @param {String} input The Punycoded domain name or email address to
  2356. * convert to Unicode.
  2357. * @returns {String} The Unicode representation of the given Punycode
  2358. * string.
  2359. */
  2360. function toUnicode(input) {
  2361. return mapDomain(input, function(string) {
  2362. return regexPunycode.test(string)
  2363. ? decode(string.slice(4).toLowerCase())
  2364. : string;
  2365. });
  2366. }
  2367. /**
  2368. * Converts a Unicode string representing a domain name or an email address to
  2369. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  2370. * i.e. it doesn't matter if you call it with a domain that's already in
  2371. * ASCII.
  2372. * @memberOf punycode
  2373. * @param {String} input The domain name or email address to convert, as a
  2374. * Unicode string.
  2375. * @returns {String} The Punycode representation of the given domain name or
  2376. * email address.
  2377. */
  2378. function toASCII(input) {
  2379. return mapDomain(input, function(string) {
  2380. return regexNonASCII.test(string)
  2381. ? 'xn--' + encode(string)
  2382. : string;
  2383. });
  2384. }
  2385. /*--------------------------------------------------------------------------*/
  2386. /** Define the public API */
  2387. punycode = {
  2388. /**
  2389. * A string representing the current Punycode.js version number.
  2390. * @memberOf punycode
  2391. * @type String
  2392. */
  2393. 'version': '1.4.1',
  2394. /**
  2395. * An object of methods to convert from JavaScript's internal character
  2396. * representation (UCS-2) to Unicode code points, and back.
  2397. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  2398. * @memberOf punycode
  2399. * @type Object
  2400. */
  2401. 'ucs2': {
  2402. 'decode': ucs2decode,
  2403. 'encode': ucs2encode
  2404. },
  2405. 'decode': decode,
  2406. 'encode': encode,
  2407. 'toASCII': toASCII,
  2408. 'toUnicode': toUnicode
  2409. };
  2410. /** Expose `punycode` */
  2411. // Some AMD build optimizers, like r.js, check for specific condition patterns
  2412. // like the following:
  2413. if (
  2414. typeof define == 'function' &&
  2415. typeof define.amd == 'object' &&
  2416. define.amd
  2417. ) {
  2418. define('punycode', function() {
  2419. return punycode;
  2420. });
  2421. } else if (freeExports && freeModule) {
  2422. if (module.exports == freeExports) {
  2423. // in Node.js, io.js, or RingoJS v0.8.0+
  2424. freeModule.exports = punycode;
  2425. } else {
  2426. // in Narwhal or RingoJS v0.7.0-
  2427. for (key in punycode) {
  2428. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  2429. }
  2430. }
  2431. } else {
  2432. // in Rhino or a web browser
  2433. root.punycode = punycode;
  2434. }
  2435. }(this));
  2436. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2437. },{}],13:[function(require,module,exports){
  2438. // Copyright Joyent, Inc. and other Node contributors.
  2439. //
  2440. // Permission is hereby granted, free of charge, to any person obtaining a
  2441. // copy of this software and associated documentation files (the
  2442. // "Software"), to deal in the Software without restriction, including
  2443. // without limitation the rights to use, copy, modify, merge, publish,
  2444. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2445. // persons to whom the Software is furnished to do so, subject to the
  2446. // following conditions:
  2447. //
  2448. // The above copyright notice and this permission notice shall be included
  2449. // in all copies or substantial portions of the Software.
  2450. //
  2451. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2452. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2453. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2454. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2455. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2456. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2457. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2458. 'use strict';
  2459. // If obj.hasOwnProperty has been overridden, then calling
  2460. // obj.hasOwnProperty(prop) will break.
  2461. // See: https://github.com/joyent/node/issues/1707
  2462. function hasOwnProperty(obj, prop) {
  2463. return Object.prototype.hasOwnProperty.call(obj, prop);
  2464. }
  2465. module.exports = function(qs, sep, eq, options) {
  2466. sep = sep || '&';
  2467. eq = eq || '=';
  2468. var obj = {};
  2469. if (typeof qs !== 'string' || qs.length === 0) {
  2470. return obj;
  2471. }
  2472. var regexp = /\+/g;
  2473. qs = qs.split(sep);
  2474. var maxKeys = 1000;
  2475. if (options && typeof options.maxKeys === 'number') {
  2476. maxKeys = options.maxKeys;
  2477. }
  2478. var len = qs.length;
  2479. // maxKeys <= 0 means that we should not limit keys count
  2480. if (maxKeys > 0 && len > maxKeys) {
  2481. len = maxKeys;
  2482. }
  2483. for (var i = 0; i < len; ++i) {
  2484. var x = qs[i].replace(regexp, '%20'),
  2485. idx = x.indexOf(eq),
  2486. kstr, vstr, k, v;
  2487. if (idx >= 0) {
  2488. kstr = x.substr(0, idx);
  2489. vstr = x.substr(idx + 1);
  2490. } else {
  2491. kstr = x;
  2492. vstr = '';
  2493. }
  2494. k = decodeURIComponent(kstr);
  2495. v = decodeURIComponent(vstr);
  2496. if (!hasOwnProperty(obj, k)) {
  2497. obj[k] = v;
  2498. } else if (isArray(obj[k])) {
  2499. obj[k].push(v);
  2500. } else {
  2501. obj[k] = [obj[k], v];
  2502. }
  2503. }
  2504. return obj;
  2505. };
  2506. var isArray = Array.isArray || function (xs) {
  2507. return Object.prototype.toString.call(xs) === '[object Array]';
  2508. };
  2509. },{}],14:[function(require,module,exports){
  2510. // Copyright Joyent, Inc. and other Node contributors.
  2511. //
  2512. // Permission is hereby granted, free of charge, to any person obtaining a
  2513. // copy of this software and associated documentation files (the
  2514. // "Software"), to deal in the Software without restriction, including
  2515. // without limitation the rights to use, copy, modify, merge, publish,
  2516. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2517. // persons to whom the Software is furnished to do so, subject to the
  2518. // following conditions:
  2519. //
  2520. // The above copyright notice and this permission notice shall be included
  2521. // in all copies or substantial portions of the Software.
  2522. //
  2523. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2524. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2525. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2526. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2527. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2528. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2529. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2530. 'use strict';
  2531. var stringifyPrimitive = function(v) {
  2532. switch (typeof v) {
  2533. case 'string':
  2534. return v;
  2535. case 'boolean':
  2536. return v ? 'true' : 'false';
  2537. case 'number':
  2538. return isFinite(v) ? v : '';
  2539. default:
  2540. return '';
  2541. }
  2542. };
  2543. module.exports = function(obj, sep, eq, name) {
  2544. sep = sep || '&';
  2545. eq = eq || '=';
  2546. if (obj === null) {
  2547. obj = undefined;
  2548. }
  2549. if (typeof obj === 'object') {
  2550. return map(objectKeys(obj), function(k) {
  2551. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  2552. if (isArray(obj[k])) {
  2553. return map(obj[k], function(v) {
  2554. return ks + encodeURIComponent(stringifyPrimitive(v));
  2555. }).join(sep);
  2556. } else {
  2557. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  2558. }
  2559. }).join(sep);
  2560. }
  2561. if (!name) return '';
  2562. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  2563. encodeURIComponent(stringifyPrimitive(obj));
  2564. };
  2565. var isArray = Array.isArray || function (xs) {
  2566. return Object.prototype.toString.call(xs) === '[object Array]';
  2567. };
  2568. function map (xs, f) {
  2569. if (xs.map) return xs.map(f);
  2570. var res = [];
  2571. for (var i = 0; i < xs.length; i++) {
  2572. res.push(f(xs[i], i));
  2573. }
  2574. return res;
  2575. }
  2576. var objectKeys = Object.keys || function (obj) {
  2577. var res = [];
  2578. for (var key in obj) {
  2579. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  2580. }
  2581. return res;
  2582. };
  2583. },{}],15:[function(require,module,exports){
  2584. 'use strict';
  2585. exports.decode = exports.parse = require('./decode');
  2586. exports.encode = exports.stringify = require('./encode');
  2587. },{"./decode":13,"./encode":14}],16:[function(require,module,exports){
  2588. exports = module.exports = trim;
  2589. function trim(str){
  2590. return str.replace(/^\s*|\s*$/g, '');
  2591. }
  2592. exports.left = function(str){
  2593. return str.replace(/^\s*/, '');
  2594. };
  2595. exports.right = function(str){
  2596. return str.replace(/\s*$/, '');
  2597. };
  2598. },{}],17:[function(require,module,exports){
  2599. // Copyright Joyent, Inc. and other Node contributors.
  2600. //
  2601. // Permission is hereby granted, free of charge, to any person obtaining a
  2602. // copy of this software and associated documentation files (the
  2603. // "Software"), to deal in the Software without restriction, including
  2604. // without limitation the rights to use, copy, modify, merge, publish,
  2605. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2606. // persons to whom the Software is furnished to do so, subject to the
  2607. // following conditions:
  2608. //
  2609. // The above copyright notice and this permission notice shall be included
  2610. // in all copies or substantial portions of the Software.
  2611. //
  2612. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2613. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2614. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2615. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2616. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2617. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2618. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2619. var punycode = require('punycode');
  2620. exports.parse = urlParse;
  2621. exports.resolve = urlResolve;
  2622. exports.resolveObject = urlResolveObject;
  2623. exports.format = urlFormat;
  2624. exports.Url = Url;
  2625. function Url() {
  2626. this.protocol = null;
  2627. this.slashes = null;
  2628. this.auth = null;
  2629. this.host = null;
  2630. this.port = null;
  2631. this.hostname = null;
  2632. this.hash = null;
  2633. this.search = null;
  2634. this.query = null;
  2635. this.pathname = null;
  2636. this.path = null;
  2637. this.href = null;
  2638. }
  2639. // Reference: RFC 3986, RFC 1808, RFC 2396
  2640. // define these here so at least they only have to be
  2641. // compiled once on the first module load.
  2642. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  2643. portPattern = /:[0-9]*$/,
  2644. // RFC 2396: characters reserved for delimiting URLs.
  2645. // We actually just auto-escape these.
  2646. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  2647. // RFC 2396: characters not allowed for various reasons.
  2648. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  2649. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  2650. autoEscape = ['\''].concat(unwise),
  2651. // Characters that are never ever allowed in a hostname.
  2652. // Note that any invalid chars are also handled, but these
  2653. // are the ones that are *expected* to be seen, so we fast-path
  2654. // them.
  2655. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  2656. hostEndingChars = ['/', '?', '#'],
  2657. hostnameMaxLen = 255,
  2658. hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
  2659. hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
  2660. // protocols that can allow "unsafe" and "unwise" chars.
  2661. unsafeProtocol = {
  2662. 'javascript': true,
  2663. 'javascript:': true
  2664. },
  2665. // protocols that never have a hostname.
  2666. hostlessProtocol = {
  2667. 'javascript': true,
  2668. 'javascript:': true
  2669. },
  2670. // protocols that always contain a // bit.
  2671. slashedProtocol = {
  2672. 'http': true,
  2673. 'https': true,
  2674. 'ftp': true,
  2675. 'gopher': true,
  2676. 'file': true,
  2677. 'http:': true,
  2678. 'https:': true,
  2679. 'ftp:': true,
  2680. 'gopher:': true,
  2681. 'file:': true
  2682. },
  2683. querystring = require('querystring');
  2684. function urlParse(url, parseQueryString, slashesDenoteHost) {
  2685. if (url && isObject(url) && url instanceof Url) return url;
  2686. var u = new Url;
  2687. u.parse(url, parseQueryString, slashesDenoteHost);
  2688. return u;
  2689. }
  2690. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  2691. if (!isString(url)) {
  2692. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  2693. }
  2694. var rest = url;
  2695. // trim before proceeding.
  2696. // This is to support parse stuff like " http://foo.com \n"
  2697. rest = rest.trim();
  2698. var proto = protocolPattern.exec(rest);
  2699. if (proto) {
  2700. proto = proto[0];
  2701. var lowerProto = proto.toLowerCase();
  2702. this.protocol = lowerProto;
  2703. rest = rest.substr(proto.length);
  2704. }
  2705. // figure out if it's got a host
  2706. // user@server is *always* interpreted as a hostname, and url
  2707. // resolution will treat //foo/bar as host=foo,path=bar because that's
  2708. // how the browser resolves relative URLs.
  2709. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  2710. var slashes = rest.substr(0, 2) === '//';
  2711. if (slashes && !(proto && hostlessProtocol[proto])) {
  2712. rest = rest.substr(2);
  2713. this.slashes = true;
  2714. }
  2715. }
  2716. if (!hostlessProtocol[proto] &&
  2717. (slashes || (proto && !slashedProtocol[proto]))) {
  2718. // there's a hostname.
  2719. // the first instance of /, ?, ;, or # ends the host.
  2720. //
  2721. // If there is an @ in the hostname, then non-host chars *are* allowed
  2722. // to the left of the last @ sign, unless some host-ending character
  2723. // comes *before* the @-sign.
  2724. // URLs are obnoxious.
  2725. //
  2726. // ex:
  2727. // http://a@b@c/ => user:a@b host:c
  2728. // http://a@b?@c => user:a host:c path:/?@c
  2729. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  2730. // Review our test case against browsers more comprehensively.
  2731. // find the first instance of any hostEndingChars
  2732. var hostEnd = -1;
  2733. for (var i = 0; i < hostEndingChars.length; i++) {
  2734. var hec = rest.indexOf(hostEndingChars[i]);
  2735. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  2736. hostEnd = hec;
  2737. }
  2738. // at this point, either we have an explicit point where the
  2739. // auth portion cannot go past, or the last @ char is the decider.
  2740. var auth, atSign;
  2741. if (hostEnd === -1) {
  2742. // atSign can be anywhere.
  2743. atSign = rest.lastIndexOf('@');
  2744. } else {
  2745. // atSign must be in auth portion.
  2746. // http://a@b/c@d => host:b auth:a path:/c@d
  2747. atSign = rest.lastIndexOf('@', hostEnd);
  2748. }
  2749. // Now we have a portion which is definitely the auth.
  2750. // Pull that off.
  2751. if (atSign !== -1) {
  2752. auth = rest.slice(0, atSign);
  2753. rest = rest.slice(atSign + 1);
  2754. this.auth = decodeURIComponent(auth);
  2755. }
  2756. // the host is the remaining to the left of the first non-host char
  2757. hostEnd = -1;
  2758. for (var i = 0; i < nonHostChars.length; i++) {
  2759. var hec = rest.indexOf(nonHostChars[i]);
  2760. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  2761. hostEnd = hec;
  2762. }
  2763. // if we still have not hit it, then the entire thing is a host.
  2764. if (hostEnd === -1)
  2765. hostEnd = rest.length;
  2766. this.host = rest.slice(0, hostEnd);
  2767. rest = rest.slice(hostEnd);
  2768. // pull out port.
  2769. this.parseHost();
  2770. // we've indicated that there is a hostname,
  2771. // so even if it's empty, it has to be present.
  2772. this.hostname = this.hostname || '';
  2773. // if hostname begins with [ and ends with ]
  2774. // assume that it's an IPv6 address.
  2775. var ipv6Hostname = this.hostname[0] === '[' &&
  2776. this.hostname[this.hostname.length - 1] === ']';
  2777. // validate a little.
  2778. if (!ipv6Hostname) {
  2779. var hostparts = this.hostname.split(/\./);
  2780. for (var i = 0, l = hostparts.length; i < l; i++) {
  2781. var part = hostparts[i];
  2782. if (!part) continue;
  2783. if (!part.match(hostnamePartPattern)) {
  2784. var newpart = '';
  2785. for (var j = 0, k = part.length; j < k; j++) {
  2786. if (part.charCodeAt(j) > 127) {
  2787. // we replace non-ASCII char with a temporary placeholder
  2788. // we need this to make sure size of hostname is not
  2789. // broken by replacing non-ASCII by nothing
  2790. newpart += 'x';
  2791. } else {
  2792. newpart += part[j];
  2793. }
  2794. }
  2795. // we test again with ASCII char only
  2796. if (!newpart.match(hostnamePartPattern)) {
  2797. var validParts = hostparts.slice(0, i);
  2798. var notHost = hostparts.slice(i + 1);
  2799. var bit = part.match(hostnamePartStart);
  2800. if (bit) {
  2801. validParts.push(bit[1]);
  2802. notHost.unshift(bit[2]);
  2803. }
  2804. if (notHost.length) {
  2805. rest = '/' + notHost.join('.') + rest;
  2806. }
  2807. this.hostname = validParts.join('.');
  2808. break;
  2809. }
  2810. }
  2811. }
  2812. }
  2813. if (this.hostname.length > hostnameMaxLen) {
  2814. this.hostname = '';
  2815. } else {
  2816. // hostnames are always lower case.
  2817. this.hostname = this.hostname.toLowerCase();
  2818. }
  2819. if (!ipv6Hostname) {
  2820. // IDNA Support: Returns a puny coded representation of "domain".
  2821. // It only converts the part of the domain name that
  2822. // has non ASCII characters. I.e. it dosent matter if
  2823. // you call it with a domain that already is in ASCII.
  2824. var domainArray = this.hostname.split('.');
  2825. var newOut = [];
  2826. for (var i = 0; i < domainArray.length; ++i) {
  2827. var s = domainArray[i];
  2828. newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
  2829. 'xn--' + punycode.encode(s) : s);
  2830. }
  2831. this.hostname = newOut.join('.');
  2832. }
  2833. var p = this.port ? ':' + this.port : '';
  2834. var h = this.hostname || '';
  2835. this.host = h + p;
  2836. this.href += this.host;
  2837. // strip [ and ] from the hostname
  2838. // the host field still retains them, though
  2839. if (ipv6Hostname) {
  2840. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  2841. if (rest[0] !== '/') {
  2842. rest = '/' + rest;
  2843. }
  2844. }
  2845. }
  2846. // now rest is set to the post-host stuff.
  2847. // chop off any delim chars.
  2848. if (!unsafeProtocol[lowerProto]) {
  2849. // First, make 100% sure that any "autoEscape" chars get
  2850. // escaped, even if encodeURIComponent doesn't think they
  2851. // need to be.
  2852. for (var i = 0, l = autoEscape.length; i < l; i++) {
  2853. var ae = autoEscape[i];
  2854. var esc = encodeURIComponent(ae);
  2855. if (esc === ae) {
  2856. esc = escape(ae);
  2857. }
  2858. rest = rest.split(ae).join(esc);
  2859. }
  2860. }
  2861. // chop off from the tail first.
  2862. var hash = rest.indexOf('#');
  2863. if (hash !== -1) {
  2864. // got a fragment string.
  2865. this.hash = rest.substr(hash);
  2866. rest = rest.slice(0, hash);
  2867. }
  2868. var qm = rest.indexOf('?');
  2869. if (qm !== -1) {
  2870. this.search = rest.substr(qm);
  2871. this.query = rest.substr(qm + 1);
  2872. if (parseQueryString) {
  2873. this.query = querystring.parse(this.query);
  2874. }
  2875. rest = rest.slice(0, qm);
  2876. } else if (parseQueryString) {
  2877. // no query string, but parseQueryString still requested
  2878. this.search = '';
  2879. this.query = {};
  2880. }
  2881. if (rest) this.pathname = rest;
  2882. if (slashedProtocol[lowerProto] &&
  2883. this.hostname && !this.pathname) {
  2884. this.pathname = '/';
  2885. }
  2886. //to support http.request
  2887. if (this.pathname || this.search) {
  2888. var p = this.pathname || '';
  2889. var s = this.search || '';
  2890. this.path = p + s;
  2891. }
  2892. // finally, reconstruct the href based on what has been validated.
  2893. this.href = this.format();
  2894. return this;
  2895. };
  2896. // format a parsed object into a url string
  2897. function urlFormat(obj) {
  2898. // ensure it's an object, and not a string url.
  2899. // If it's an obj, this is a no-op.
  2900. // this way, you can call url_format() on strings
  2901. // to clean up potentially wonky urls.
  2902. if (isString(obj)) obj = urlParse(obj);
  2903. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  2904. return obj.format();
  2905. }
  2906. Url.prototype.format = function() {
  2907. var auth = this.auth || '';
  2908. if (auth) {
  2909. auth = encodeURIComponent(auth);
  2910. auth = auth.replace(/%3A/i, ':');
  2911. auth += '@';
  2912. }
  2913. var protocol = this.protocol || '',
  2914. pathname = this.pathname || '',
  2915. hash = this.hash || '',
  2916. host = false,
  2917. query = '';
  2918. if (this.host) {
  2919. host = auth + this.host;
  2920. } else if (this.hostname) {
  2921. host = auth + (this.hostname.indexOf(':') === -1 ?
  2922. this.hostname :
  2923. '[' + this.hostname + ']');
  2924. if (this.port) {
  2925. host += ':' + this.port;
  2926. }
  2927. }
  2928. if (this.query &&
  2929. isObject(this.query) &&
  2930. Object.keys(this.query).length) {
  2931. query = querystring.stringify(this.query);
  2932. }
  2933. var search = this.search || (query && ('?' + query)) || '';
  2934. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  2935. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  2936. // unless they had them to begin with.
  2937. if (this.slashes ||
  2938. (!protocol || slashedProtocol[protocol]) && host !== false) {
  2939. host = '//' + (host || '');
  2940. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  2941. } else if (!host) {
  2942. host = '';
  2943. }
  2944. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  2945. if (search && search.charAt(0) !== '?') search = '?' + search;
  2946. pathname = pathname.replace(/[?#]/g, function(match) {
  2947. return encodeURIComponent(match);
  2948. });
  2949. search = search.replace('#', '%23');
  2950. return protocol + host + pathname + search + hash;
  2951. };
  2952. function urlResolve(source, relative) {
  2953. return urlParse(source, false, true).resolve(relative);
  2954. }
  2955. Url.prototype.resolve = function(relative) {
  2956. return this.resolveObject(urlParse(relative, false, true)).format();
  2957. };
  2958. function urlResolveObject(source, relative) {
  2959. if (!source) return relative;
  2960. return urlParse(source, false, true).resolveObject(relative);
  2961. }
  2962. Url.prototype.resolveObject = function(relative) {
  2963. if (isString(relative)) {
  2964. var rel = new Url();
  2965. rel.parse(relative, false, true);
  2966. relative = rel;
  2967. }
  2968. var result = new Url();
  2969. Object.keys(this).forEach(function(k) {
  2970. result[k] = this[k];
  2971. }, this);
  2972. // hash is always overridden, no matter what.
  2973. // even href="" will remove it.
  2974. result.hash = relative.hash;
  2975. // if the relative url is empty, then there's nothing left to do here.
  2976. if (relative.href === '') {
  2977. result.href = result.format();
  2978. return result;
  2979. }
  2980. // hrefs like //foo/bar always cut to the protocol.
  2981. if (relative.slashes && !relative.protocol) {
  2982. // take everything except the protocol from relative
  2983. Object.keys(relative).forEach(function(k) {
  2984. if (k !== 'protocol')
  2985. result[k] = relative[k];
  2986. });
  2987. //urlParse appends trailing / to urls like http://www.example.com
  2988. if (slashedProtocol[result.protocol] &&
  2989. result.hostname && !result.pathname) {
  2990. result.path = result.pathname = '/';
  2991. }
  2992. result.href = result.format();
  2993. return result;
  2994. }
  2995. if (relative.protocol && relative.protocol !== result.protocol) {
  2996. // if it's a known url protocol, then changing
  2997. // the protocol does weird things
  2998. // first, if it's not file:, then we MUST have a host,
  2999. // and if there was a path
  3000. // to begin with, then we MUST have a path.
  3001. // if it is file:, then the host is dropped,
  3002. // because that's known to be hostless.
  3003. // anything else is assumed to be absolute.
  3004. if (!slashedProtocol[relative.protocol]) {
  3005. Object.keys(relative).forEach(function(k) {
  3006. result[k] = relative[k];
  3007. });
  3008. result.href = result.format();
  3009. return result;
  3010. }
  3011. result.protocol = relative.protocol;
  3012. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  3013. var relPath = (relative.pathname || '').split('/');
  3014. while (relPath.length && !(relative.host = relPath.shift()));
  3015. if (!relative.host) relative.host = '';
  3016. if (!relative.hostname) relative.hostname = '';
  3017. if (relPath[0] !== '') relPath.unshift('');
  3018. if (relPath.length < 2) relPath.unshift('');
  3019. result.pathname = relPath.join('/');
  3020. } else {
  3021. result.pathname = relative.pathname;
  3022. }
  3023. result.search = relative.search;
  3024. result.query = relative.query;
  3025. result.host = relative.host || '';
  3026. result.auth = relative.auth;
  3027. result.hostname = relative.hostname || relative.host;
  3028. result.port = relative.port;
  3029. // to support http.request
  3030. if (result.pathname || result.search) {
  3031. var p = result.pathname || '';
  3032. var s = result.search || '';
  3033. result.path = p + s;
  3034. }
  3035. result.slashes = result.slashes || relative.slashes;
  3036. result.href = result.format();
  3037. return result;
  3038. }
  3039. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  3040. isRelAbs = (
  3041. relative.host ||
  3042. relative.pathname && relative.pathname.charAt(0) === '/'
  3043. ),
  3044. mustEndAbs = (isRelAbs || isSourceAbs ||
  3045. (result.host && relative.pathname)),
  3046. removeAllDots = mustEndAbs,
  3047. srcPath = result.pathname && result.pathname.split('/') || [],
  3048. relPath = relative.pathname && relative.pathname.split('/') || [],
  3049. psychotic = result.protocol && !slashedProtocol[result.protocol];
  3050. // if the url is a non-slashed url, then relative
  3051. // links like ../.. should be able
  3052. // to crawl up to the hostname, as well. This is strange.
  3053. // result.protocol has already been set by now.
  3054. // Later on, put the first path part into the host field.
  3055. if (psychotic) {
  3056. result.hostname = '';
  3057. result.port = null;
  3058. if (result.host) {
  3059. if (srcPath[0] === '') srcPath[0] = result.host;
  3060. else srcPath.unshift(result.host);
  3061. }
  3062. result.host = '';
  3063. if (relative.protocol) {
  3064. relative.hostname = null;
  3065. relative.port = null;
  3066. if (relative.host) {
  3067. if (relPath[0] === '') relPath[0] = relative.host;
  3068. else relPath.unshift(relative.host);
  3069. }
  3070. relative.host = null;
  3071. }
  3072. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  3073. }
  3074. if (isRelAbs) {
  3075. // it's absolute.
  3076. result.host = (relative.host || relative.host === '') ?
  3077. relative.host : result.host;
  3078. result.hostname = (relative.hostname || relative.hostname === '') ?
  3079. relative.hostname : result.hostname;
  3080. result.search = relative.search;
  3081. result.query = relative.query;
  3082. srcPath = relPath;
  3083. // fall through to the dot-handling below.
  3084. } else if (relPath.length) {
  3085. // it's relative
  3086. // throw away the existing file, and take the new path instead.
  3087. if (!srcPath) srcPath = [];
  3088. srcPath.pop();
  3089. srcPath = srcPath.concat(relPath);
  3090. result.search = relative.search;
  3091. result.query = relative.query;
  3092. } else if (!isNullOrUndefined(relative.search)) {
  3093. // just pull out the search.
  3094. // like href='?foo'.
  3095. // Put this after the other two cases because it simplifies the booleans
  3096. if (psychotic) {
  3097. result.hostname = result.host = srcPath.shift();
  3098. //occationaly the auth can get stuck only in host
  3099. //this especialy happens in cases like
  3100. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  3101. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  3102. result.host.split('@') : false;
  3103. if (authInHost) {
  3104. result.auth = authInHost.shift();
  3105. result.host = result.hostname = authInHost.shift();
  3106. }
  3107. }
  3108. result.search = relative.search;
  3109. result.query = relative.query;
  3110. //to support http.request
  3111. if (!isNull(result.pathname) || !isNull(result.search)) {
  3112. result.path = (result.pathname ? result.pathname : '') +
  3113. (result.search ? result.search : '');
  3114. }
  3115. result.href = result.format();
  3116. return result;
  3117. }
  3118. if (!srcPath.length) {
  3119. // no path at all. easy.
  3120. // we've already handled the other stuff above.
  3121. result.pathname = null;
  3122. //to support http.request
  3123. if (result.search) {
  3124. result.path = '/' + result.search;
  3125. } else {
  3126. result.path = null;
  3127. }
  3128. result.href = result.format();
  3129. return result;
  3130. }
  3131. // if a url ENDs in . or .., then it must get a trailing slash.
  3132. // however, if it ends in anything else non-slashy,
  3133. // then it must NOT get a trailing slash.
  3134. var last = srcPath.slice(-1)[0];
  3135. var hasTrailingSlash = (
  3136. (result.host || relative.host) && (last === '.' || last === '..') ||
  3137. last === '');
  3138. // strip single dots, resolve double dots to parent dir
  3139. // if the path tries to go above the root, `up` ends up > 0
  3140. var up = 0;
  3141. for (var i = srcPath.length; i >= 0; i--) {
  3142. last = srcPath[i];
  3143. if (last == '.') {
  3144. srcPath.splice(i, 1);
  3145. } else if (last === '..') {
  3146. srcPath.splice(i, 1);
  3147. up++;
  3148. } else if (up) {
  3149. srcPath.splice(i, 1);
  3150. up--;
  3151. }
  3152. }
  3153. // if the path is allowed to go above the root, restore leading ..s
  3154. if (!mustEndAbs && !removeAllDots) {
  3155. for (; up--; up) {
  3156. srcPath.unshift('..');
  3157. }
  3158. }
  3159. if (mustEndAbs && srcPath[0] !== '' &&
  3160. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  3161. srcPath.unshift('');
  3162. }
  3163. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  3164. srcPath.push('');
  3165. }
  3166. var isAbsolute = srcPath[0] === '' ||
  3167. (srcPath[0] && srcPath[0].charAt(0) === '/');
  3168. // put the host back
  3169. if (psychotic) {
  3170. result.hostname = result.host = isAbsolute ? '' :
  3171. srcPath.length ? srcPath.shift() : '';
  3172. //occationaly the auth can get stuck only in host
  3173. //this especialy happens in cases like
  3174. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  3175. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  3176. result.host.split('@') : false;
  3177. if (authInHost) {
  3178. result.auth = authInHost.shift();
  3179. result.host = result.hostname = authInHost.shift();
  3180. }
  3181. }
  3182. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  3183. if (mustEndAbs && !isAbsolute) {
  3184. srcPath.unshift('');
  3185. }
  3186. if (!srcPath.length) {
  3187. result.pathname = null;
  3188. result.path = null;
  3189. } else {
  3190. result.pathname = srcPath.join('/');
  3191. }
  3192. //to support request.http
  3193. if (!isNull(result.pathname) || !isNull(result.search)) {
  3194. result.path = (result.pathname ? result.pathname : '') +
  3195. (result.search ? result.search : '');
  3196. }
  3197. result.auth = relative.auth || result.auth;
  3198. result.slashes = result.slashes || relative.slashes;
  3199. result.href = result.format();
  3200. return result;
  3201. };
  3202. Url.prototype.parseHost = function() {
  3203. var host = this.host;
  3204. var port = portPattern.exec(host);
  3205. if (port) {
  3206. port = port[0];
  3207. if (port !== ':') {
  3208. this.port = port.substr(1);
  3209. }
  3210. host = host.substr(0, host.length - port.length);
  3211. }
  3212. if (host) this.hostname = host;
  3213. };
  3214. function isString(arg) {
  3215. return typeof arg === "string";
  3216. }
  3217. function isObject(arg) {
  3218. return typeof arg === 'object' && arg !== null;
  3219. }
  3220. function isNull(arg) {
  3221. return arg === null;
  3222. }
  3223. function isNullOrUndefined(arg) {
  3224. return arg == null;
  3225. }
  3226. },{"punycode":12,"querystring":15}],18:[function(require,module,exports){
  3227. var window = require("global/window")
  3228. var once = require("once")
  3229. var parseHeaders = require('parse-headers')
  3230. var messages = {
  3231. "0": "Internal XMLHttpRequest Error",
  3232. "4": "4xx Client Error",
  3233. "5": "5xx Server Error"
  3234. }
  3235. var XHR = window.XMLHttpRequest || noop
  3236. var XDR = "withCredentials" in (new XHR()) ? XHR : window.XDomainRequest
  3237. module.exports = createXHR
  3238. function createXHR(options, callback) {
  3239. if (typeof options === "string") {
  3240. options = { uri: options }
  3241. }
  3242. options = options || {}
  3243. callback = once(callback)
  3244. var xhr = options.xhr || null
  3245. if (!xhr) {
  3246. if (options.cors || options.useXDR) {
  3247. xhr = new XDR()
  3248. }else{
  3249. xhr = new XHR()
  3250. }
  3251. }
  3252. var uri = xhr.url = options.uri || options.url
  3253. var method = xhr.method = options.method || "GET"
  3254. var body = options.body || options.data
  3255. var headers = xhr.headers = options.headers || {}
  3256. var sync = !!options.sync
  3257. var isJson = false
  3258. var key
  3259. var load = options.response ? loadResponse : loadXhr
  3260. if ("json" in options) {
  3261. isJson = true
  3262. headers["Accept"] = "application/json"
  3263. if (method !== "GET" && method !== "HEAD") {
  3264. headers["Content-Type"] = "application/json"
  3265. body = JSON.stringify(options.json)
  3266. }
  3267. }
  3268. xhr.onreadystatechange = readystatechange
  3269. xhr.onload = load
  3270. xhr.onerror = error
  3271. // IE9 must have onprogress be set to a unique function.
  3272. xhr.onprogress = function () {
  3273. // IE must die
  3274. }
  3275. // hate IE
  3276. xhr.ontimeout = noop
  3277. xhr.open(method, uri, !sync)
  3278. //backward compatibility
  3279. if (options.withCredentials || (options.cors && options.withCredentials !== false)) {
  3280. xhr.withCredentials = true
  3281. }
  3282. // Cannot set timeout with sync request
  3283. if (!sync) {
  3284. xhr.timeout = "timeout" in options ? options.timeout : 5000
  3285. }
  3286. if (xhr.setRequestHeader) {
  3287. for(key in headers){
  3288. if(headers.hasOwnProperty(key)){
  3289. xhr.setRequestHeader(key, headers[key])
  3290. }
  3291. }
  3292. } else if (options.headers) {
  3293. throw new Error("Headers cannot be set on an XDomainRequest object")
  3294. }
  3295. if ("responseType" in options) {
  3296. xhr.responseType = options.responseType
  3297. }
  3298. if ("beforeSend" in options &&
  3299. typeof options.beforeSend === "function"
  3300. ) {
  3301. options.beforeSend(xhr)
  3302. }
  3303. xhr.send(body)
  3304. return xhr
  3305. function readystatechange() {
  3306. if (xhr.readyState === 4) {
  3307. load()
  3308. }
  3309. }
  3310. function getBody() {
  3311. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  3312. var body = null
  3313. if (xhr.response) {
  3314. body = xhr.response
  3315. } else if (xhr.responseType === 'text' || !xhr.responseType) {
  3316. body = xhr.responseText || xhr.responseXML
  3317. }
  3318. if (isJson) {
  3319. try {
  3320. body = JSON.parse(body)
  3321. } catch (e) {}
  3322. }
  3323. return body
  3324. }
  3325. function getStatusCode() {
  3326. return xhr.status === 1223 ? 204 : xhr.status
  3327. }
  3328. // if we're getting a none-ok statusCode, build & return an error
  3329. function errorFromStatusCode(status, body) {
  3330. var error = null
  3331. if (status === 0 || (status >= 400 && status < 600)) {
  3332. var message = (typeof body === "string" ? body : false) ||
  3333. messages[String(status).charAt(0)]
  3334. error = new Error(message)
  3335. error.statusCode = status
  3336. }
  3337. return error
  3338. }
  3339. // will load the data & process the response in a special response object
  3340. function loadResponse() {
  3341. var status = getStatusCode()
  3342. var body = getBody()
  3343. var error = errorFromStatusCode(status, body)
  3344. var response = {
  3345. body: body,
  3346. statusCode: status,
  3347. statusText: xhr.statusText,
  3348. raw: xhr
  3349. }
  3350. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  3351. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  3352. } else {
  3353. response.headers = {}
  3354. }
  3355. callback(error, response, response.body)
  3356. }
  3357. // will load the data and add some response properties to the source xhr
  3358. // and then respond with that
  3359. function loadXhr() {
  3360. var status = getStatusCode()
  3361. var error = errorFromStatusCode(status)
  3362. xhr.status = xhr.statusCode = status
  3363. xhr.body = getBody()
  3364. xhr.headers = parseHeaders(xhr.getAllResponseHeaders())
  3365. callback(error, xhr, xhr.body)
  3366. }
  3367. function error(evt) {
  3368. callback(evt, xhr)
  3369. }
  3370. }
  3371. function noop() {}
  3372. },{"global/window":5,"once":10,"parse-headers":11}],19:[function(require,module,exports){
  3373. module.exports = OmegaTarget
  3374. },{}],20:[function(require,module,exports){
  3375. var OmegaTarget, Promise,
  3376. slice = [].slice;
  3377. OmegaTarget = require('omega-target');
  3378. Promise = OmegaTarget.Promise;
  3379. exports.chromeApiPromisify = function(target, method) {
  3380. return function() {
  3381. var args;
  3382. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  3383. return new Promise(function(resolve, reject) {
  3384. var callback;
  3385. callback = function() {
  3386. var callbackArgs, error;
  3387. callbackArgs = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  3388. if (chrome.runtime.lastError != null) {
  3389. error = new Error(chrome.runtime.lastError.message);
  3390. error.original = chrome.runtime.lastError;
  3391. return reject(error);
  3392. }
  3393. if (callbackArgs.length <= 1) {
  3394. return resolve(callbackArgs[0]);
  3395. } else {
  3396. return resolve(callbackArgs);
  3397. }
  3398. };
  3399. args.push(callback);
  3400. return target[method].apply(target, args);
  3401. });
  3402. };
  3403. };
  3404. },{"omega-target":19}],21:[function(require,module,exports){
  3405. var ChromePort, TrackedEvent,
  3406. slice = [].slice;
  3407. module.exports = ChromePort = (function() {
  3408. function ChromePort(port) {
  3409. this.port = port;
  3410. this.name = this.port.name;
  3411. this.sender = this.port.sender;
  3412. this.disconnect = this.port.disconnect.bind(this.port);
  3413. this.postMessage = (function(_this) {
  3414. return function() {
  3415. var _, args, ref;
  3416. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  3417. try {
  3418. return (ref = _this.port).postMessage.apply(ref, args);
  3419. } catch (error) {
  3420. _ = error;
  3421. }
  3422. };
  3423. })(this);
  3424. this.onMessage = new TrackedEvent(this.port.onMessage);
  3425. this.onDisconnect = new TrackedEvent(this.port.onDisconnect);
  3426. this.onDisconnect.addListener(this.dispose.bind(this));
  3427. }
  3428. ChromePort.prototype.dispose = function() {
  3429. this.onMessage.dispose();
  3430. return this.onDisconnect.dispose();
  3431. };
  3432. return ChromePort;
  3433. })();
  3434. TrackedEvent = (function() {
  3435. function TrackedEvent(event) {
  3436. var j, len, mes, method, methodName;
  3437. this.event = event;
  3438. this.callbacks = [];
  3439. mes = ['hasListener', 'hasListeners', 'addRules', 'getRules', 'removeRules'];
  3440. for (j = 0, len = mes.length; j < len; j++) {
  3441. methodName = mes[j];
  3442. method = this.event[methodName];
  3443. if (method != null) {
  3444. this[methodName] = method.bind(this.event);
  3445. }
  3446. }
  3447. }
  3448. TrackedEvent.prototype.addListener = function(callback) {
  3449. this.event.addListener(callback);
  3450. this.callbacks.push(callback);
  3451. return this;
  3452. };
  3453. TrackedEvent.prototype.removeListener = function(callback) {
  3454. var i;
  3455. this.event.removeListener(callback);
  3456. i = this.callbacks.indexOf(callback);
  3457. if (i >= 0) {
  3458. this.callbacks.splice(i, 1);
  3459. }
  3460. return this;
  3461. };
  3462. /**
  3463. * Removes all listeners added via this TrackedEvent instance.
  3464. * Note: Won't remove listeners added via other TrackedEvent or raw Event.
  3465. */
  3466. TrackedEvent.prototype.removeAllListeners = function() {
  3467. var callback, j, len, ref;
  3468. ref = this.callbacks;
  3469. for (j = 0, len = ref.length; j < len; j++) {
  3470. callback = ref[j];
  3471. this.event.removeListener(callback);
  3472. }
  3473. this.callbacks = [];
  3474. return this;
  3475. };
  3476. /**
  3477. * Removes all listeners added via this TrackedEvent instance and prevent any
  3478. * further listeners from being added. It is considered safe to nullify any
  3479. * references to this instance and the underlying Event without causing leaks.
  3480. * This should be the last method called in the lifetime of TrackedEvent.
  3481. *
  3482. * Throws if the underlying raw Event object still has listeners. This can
  3483. * happen when listeners have been added via other TrackedEvents or raw Event.
  3484. */
  3485. TrackedEvent.prototype.dispose = function() {
  3486. var base;
  3487. this.removeAllListeners();
  3488. if (typeof (base = this.event).hasListeners === "function" ? base.hasListeners() : void 0) {
  3489. throw new Error("Underlying Event still has listeners!");
  3490. }
  3491. this.event = null;
  3492. return this.callbacks = null;
  3493. };
  3494. return TrackedEvent;
  3495. })();
  3496. },{}],22:[function(require,module,exports){
  3497. var ChromePort, ExternalApi, OmegaPac, OmegaTarget, Promise;
  3498. OmegaTarget = require('omega-target');
  3499. OmegaPac = OmegaTarget.OmegaPac;
  3500. Promise = OmegaTarget.Promise;
  3501. ChromePort = require('./chrome_port');
  3502. module.exports = ExternalApi = (function() {
  3503. function ExternalApi(options) {
  3504. this.options = options;
  3505. }
  3506. ExternalApi.prototype.knownExts = {
  3507. 'padekgcemlokbadohgkifijomclgjgif': 32
  3508. };
  3509. ExternalApi.prototype.disabled = false;
  3510. ExternalApi.prototype.listen = function() {
  3511. if (!chrome.runtime.onConnectExternal) {
  3512. return;
  3513. }
  3514. return chrome.runtime.onConnectExternal.addListener((function(_this) {
  3515. return function(rawPort) {
  3516. var port;
  3517. port = new ChromePort(rawPort);
  3518. port.onMessage.addListener(function(msg) {
  3519. return _this.onMessage(msg, port);
  3520. });
  3521. return port.onDisconnect.addListener(_this.reenable.bind(_this));
  3522. };
  3523. })(this));
  3524. };
  3525. ExternalApi.prototype._previousProfileName = null;
  3526. ExternalApi.prototype.reenable = function() {
  3527. var base;
  3528. if (!this.disabled) {
  3529. return;
  3530. }
  3531. this.options.setProxyNotControllable(null);
  3532. if (typeof (base = chrome.browserAction).setPopup === "function") {
  3533. base.setPopup({
  3534. popup: 'popup/index.html'
  3535. });
  3536. }
  3537. this.options.reloadQuickSwitch();
  3538. this.disabled = false;
  3539. this.options.clearBadge();
  3540. return this.options.applyProfile(this._previousProfileName);
  3541. };
  3542. ExternalApi.prototype.checkPerm = function(port, level) {
  3543. var perm;
  3544. perm = this.knownExts[port.sender.id] || 0;
  3545. if (perm < level) {
  3546. port.postMessage({
  3547. action: 'error',
  3548. error: 'permission'
  3549. });
  3550. return false;
  3551. } else {
  3552. return true;
  3553. }
  3554. };
  3555. ExternalApi.prototype.onMessage = function(msg, port) {
  3556. var base, ref;
  3557. this.options.log.log(port.sender.id + " -> " + msg.action, msg);
  3558. switch (msg.action) {
  3559. case 'disable':
  3560. if (!this.checkPerm(port, 16)) {
  3561. return;
  3562. }
  3563. if (this.disabled) {
  3564. return;
  3565. }
  3566. this.disabled = true;
  3567. this._previousProfileName = ((ref = this.options.currentProfile()) != null ? ref.name : void 0) || 'system';
  3568. this.options.applyProfile('system').then((function(_this) {
  3569. return function() {
  3570. var reason;
  3571. reason = 'disabled';
  3572. if (_this.knownExts[port.sender.id] >= 32) {
  3573. reason = 'upgrade';
  3574. }
  3575. return _this.options.setProxyNotControllable(reason, {
  3576. text: 'X',
  3577. color: '#5ab432'
  3578. });
  3579. };
  3580. })(this));
  3581. if (typeof (base = chrome.browserAction).setPopup === "function") {
  3582. base.setPopup({
  3583. popup: 'popup/index.html'
  3584. });
  3585. }
  3586. return port.postMessage({
  3587. action: 'state',
  3588. state: 'disabled'
  3589. });
  3590. case 'enable':
  3591. this.reenable();
  3592. return port.postMessage({
  3593. action: 'state',
  3594. state: 'enabled'
  3595. });
  3596. case 'getOptions':
  3597. if (!this.checkPerm(port, 8)) {
  3598. return;
  3599. }
  3600. return port.postMessage({
  3601. action: 'options',
  3602. options: this.options.getAll()
  3603. });
  3604. default:
  3605. return port.postMessage({
  3606. action: 'error',
  3607. error: 'noSuchAction',
  3608. action_name: msg.action
  3609. });
  3610. }
  3611. };
  3612. return ExternalApi;
  3613. })();
  3614. },{"./chrome_port":21,"omega-target":19}],23:[function(require,module,exports){
  3615. var ContentTypeRejectedError, Promise, Url, defaultHintHandler, fetchUrl, hintHandlers, xhr, xhrWrapper,
  3616. slice = [].slice;
  3617. Promise = OmegaTarget.Promise;
  3618. xhr = Promise.promisify(require('xhr'));
  3619. Url = require('url');
  3620. ContentTypeRejectedError = OmegaTarget.ContentTypeRejectedError;
  3621. xhrWrapper = function() {
  3622. var args;
  3623. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  3624. return xhr.apply(null, args)["catch"](function(err) {
  3625. if (!err.isOperational) {
  3626. throw err;
  3627. }
  3628. if (!err.statusCode) {
  3629. throw new OmegaTarget.NetworkError(err);
  3630. }
  3631. if (err.statusCode === 404) {
  3632. throw new OmegaTarget.HttpNotFoundError(err);
  3633. }
  3634. if (err.statusCode >= 500 && err.statusCode < 600) {
  3635. throw new OmegaTarget.HttpServerError(err);
  3636. }
  3637. throw new OmegaTarget.HttpError(err);
  3638. });
  3639. };
  3640. fetchUrl = function(dest_url, opt_bypass_cache, opt_type_hints) {
  3641. var dest_url_nocache, getResBody, parsed;
  3642. getResBody = function(arg) {
  3643. var body, contentType, handler, hint, i, len, ref, ref1, response, result;
  3644. response = arg[0], body = arg[1];
  3645. if (!opt_type_hints) {
  3646. return body;
  3647. }
  3648. contentType = (ref = response.headers['content-type']) != null ? ref.toLowerCase() : void 0;
  3649. for (i = 0, len = opt_type_hints.length; i < len; i++) {
  3650. hint = opt_type_hints[i];
  3651. handler = (ref1 = hintHandlers[hint]) != null ? ref1 : defaultHintHandler;
  3652. result = handler(response, body, {
  3653. contentType: contentType,
  3654. hint: hint
  3655. });
  3656. if (result != null) {
  3657. return result;
  3658. }
  3659. }
  3660. throw new ContentTypeRejectedError('Unrecognized Content-Type: ' + contentType);
  3661. return body;
  3662. };
  3663. if (opt_bypass_cache && dest_url.indexOf('?') < 0) {
  3664. parsed = Url.parse(dest_url, true);
  3665. parsed.search = void 0;
  3666. parsed.query['_'] = Date.now();
  3667. dest_url_nocache = Url.format(parsed);
  3668. return xhrWrapper(dest_url_nocache).then(getResBody)["catch"](function() {
  3669. return xhrWrapper(dest_url).then(getResBody);
  3670. });
  3671. } else {
  3672. return xhrWrapper(dest_url).then(getResBody);
  3673. }
  3674. };
  3675. defaultHintHandler = function(response, body, arg) {
  3676. var contentType, hint;
  3677. contentType = arg.contentType, hint = arg.hint;
  3678. if ('!' + contentType === hint) {
  3679. throw new ContentTypeRejectedError('Response Content-Type blacklisted: ' + contentType);
  3680. }
  3681. if (contentType === hint) {
  3682. return body;
  3683. }
  3684. };
  3685. hintHandlers = {
  3686. '*': function(response, body) {
  3687. return body;
  3688. },
  3689. '!text/html': function(response, body, arg) {
  3690. var contentType, hint, looksLikeHtml;
  3691. contentType = arg.contentType, hint = arg.hint;
  3692. if (contentType === hint) {
  3693. looksLikeHtml = false;
  3694. if (body.indexOf('<!DOCTYPE') >= 0 || body.indexOf('<!doctype') >= 0) {
  3695. looksLikeHtml = true;
  3696. } else if (body.indexOf('</html>') >= 0) {
  3697. looksLikeHtml = true;
  3698. } else if (body.indexOf('</body>') >= 0) {
  3699. looksLikeHtml = true;
  3700. }
  3701. if (looksLikeHtml) {
  3702. throw new ContentTypeRejectedError('Response must not be HTML.');
  3703. }
  3704. }
  3705. },
  3706. '!application/xhtml+xml': function() {
  3707. var args;
  3708. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  3709. return hintHandlers['!text/html'].apply(hintHandlers, args);
  3710. },
  3711. 'application/x-ns-proxy-autoconfig': function(response, body, arg) {
  3712. var contentType, hint;
  3713. contentType = arg.contentType, hint = arg.hint;
  3714. if (contentType === hint) {
  3715. return body;
  3716. }
  3717. if (body.indexOf('FindProxyForURL') >= 0) {
  3718. return body;
  3719. } else {
  3720. return void 0;
  3721. }
  3722. }
  3723. };
  3724. module.exports = fetchUrl;
  3725. },{"url":17,"xhr":18}],24:[function(require,module,exports){
  3726. var base, name, ref, value;
  3727. module.exports = {
  3728. Storage: require('./storage'),
  3729. Options: require('./options'),
  3730. ChromeTabs: require('./tabs'),
  3731. SwitchySharp: require('./switchysharp'),
  3732. ExternalApi: require('./external_api'),
  3733. WebRequestMonitor: require('./web_request_monitor'),
  3734. Inspect: require('./inspect'),
  3735. Url: require('url'),
  3736. proxy: require('./proxy')
  3737. };
  3738. ref = require('omega-target');
  3739. for (name in ref) {
  3740. value = ref[name];
  3741. if ((base = module.exports)[name] == null) {
  3742. base[name] = value;
  3743. }
  3744. }
  3745. },{"./external_api":22,"./inspect":25,"./options":26,"./proxy":27,"./storage":33,"./switchysharp":34,"./tabs":35,"./web_request_monitor":37,"omega-target":19,"url":17}],25:[function(require,module,exports){
  3746. var Inspect, OmegaPac, OmegaTarget, Promise,
  3747. hasProp = {}.hasOwnProperty;
  3748. OmegaTarget = require('omega-target');
  3749. OmegaPac = OmegaTarget.OmegaPac;
  3750. Promise = OmegaTarget.Promise;
  3751. module.exports = Inspect = (function() {
  3752. Inspect.prototype._enabled = false;
  3753. function Inspect(onInspect) {
  3754. this.onInspect = onInspect;
  3755. }
  3756. Inspect.prototype.enable = function() {
  3757. var webResource;
  3758. if (chrome.contextMenus == null) {
  3759. return;
  3760. }
  3761. if (chrome.i18n.getUILanguage == null) {
  3762. return;
  3763. }
  3764. if (this._enabled) {
  3765. return;
  3766. }
  3767. webResource = ["http://*/*", "https://*/*", "ftp://*/*"];
  3768. /* Not so useful...
  3769. chrome.contextMenus.create({
  3770. id: 'inspectPage'
  3771. title: chrome.i18n.getMessage('contextMenu_inspectPage')
  3772. contexts: ['page']
  3773. onclick: @inspect.bind(this)
  3774. documentUrlPatterns: webResource
  3775. })
  3776. */
  3777. chrome.contextMenus.create({
  3778. id: 'inspectFrame',
  3779. title: chrome.i18n.getMessage('contextMenu_inspectFrame'),
  3780. contexts: ['frame'],
  3781. onclick: this.inspect.bind(this),
  3782. documentUrlPatterns: webResource
  3783. });
  3784. chrome.contextMenus.create({
  3785. id: 'inspectLink',
  3786. title: chrome.i18n.getMessage('contextMenu_inspectLink'),
  3787. contexts: ['link'],
  3788. onclick: this.inspect.bind(this),
  3789. targetUrlPatterns: webResource
  3790. });
  3791. chrome.contextMenus.create({
  3792. id: 'inspectElement',
  3793. title: chrome.i18n.getMessage('contextMenu_inspectElement'),
  3794. contexts: ['image', 'video', 'audio'],
  3795. onclick: this.inspect.bind(this),
  3796. targetUrlPatterns: webResource
  3797. });
  3798. return this._enabled = true;
  3799. };
  3800. Inspect.prototype.disable = function() {
  3801. var menuId, ref;
  3802. if (!this._enabled) {
  3803. return;
  3804. }
  3805. ref = this.propForMenuItem;
  3806. for (menuId in ref) {
  3807. if (!hasProp.call(ref, menuId)) continue;
  3808. try {
  3809. chrome.contextMenus.remove(menuId);
  3810. } catch (error) {}
  3811. }
  3812. return this._enabled = false;
  3813. };
  3814. Inspect.prototype.propForMenuItem = {
  3815. 'inspectPage': 'pageUrl',
  3816. 'inspectFrame': 'frameUrl',
  3817. 'inspectLink': 'linkUrl',
  3818. 'inspectElement': 'srcUrl'
  3819. };
  3820. Inspect.prototype.inspect = function(info, tab) {
  3821. var url;
  3822. if (!info.menuItemId) {
  3823. return;
  3824. }
  3825. url = info[this.propForMenuItem[info.menuItemId]];
  3826. if (!url && info.menuItemId === 'inspectPage') {
  3827. url = tab.url;
  3828. }
  3829. if (!url) {
  3830. return;
  3831. }
  3832. return this.onInspect(url, tab);
  3833. };
  3834. return Inspect;
  3835. })();
  3836. },{"omega-target":19}],26:[function(require,module,exports){
  3837. var ChromeOptions, ChromePort, OmegaPac, OmegaTarget, Promise, Url, WebRequestMonitor, fetchUrl, querystring,
  3838. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  3839. hasProp = {}.hasOwnProperty,
  3840. slice = [].slice;
  3841. OmegaTarget = require('omega-target');
  3842. OmegaPac = OmegaTarget.OmegaPac;
  3843. Promise = OmegaTarget.Promise;
  3844. querystring = require('querystring');
  3845. WebRequestMonitor = require('./web_request_monitor');
  3846. ChromePort = require('./chrome_port');
  3847. fetchUrl = require('./fetch_url');
  3848. Url = require('url');
  3849. ChromeOptions = (function(superClass) {
  3850. extend(ChromeOptions, superClass);
  3851. function ChromeOptions() {
  3852. return ChromeOptions.__super__.constructor.apply(this, arguments);
  3853. }
  3854. ChromeOptions.prototype._inspect = null;
  3855. ChromeOptions.prototype.fetchUrl = fetchUrl;
  3856. ChromeOptions.prototype.updateProfile = function() {
  3857. var args;
  3858. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  3859. return ChromeOptions.__super__.updateProfile.apply(this, args).then(function(results) {
  3860. var error, profileName, result;
  3861. error = false;
  3862. for (profileName in results) {
  3863. if (!hasProp.call(results, profileName)) continue;
  3864. result = results[profileName];
  3865. if (result instanceof Error) {
  3866. error = true;
  3867. break;
  3868. }
  3869. }
  3870. if (error) {
  3871. /*
  3872. @setBadge(
  3873. text: '!'
  3874. color: '#faa732'
  3875. title: chrome.i18n.getMessage('browserAction_titleDownloadFail')
  3876. )
  3877. */
  3878. }
  3879. return results;
  3880. });
  3881. };
  3882. ChromeOptions.prototype._proxyNotControllable = null;
  3883. ChromeOptions.prototype.proxyNotControllable = function() {
  3884. return this._proxyNotControllable;
  3885. };
  3886. ChromeOptions.prototype.setProxyNotControllable = function(reason, badge) {
  3887. this._proxyNotControllable = reason;
  3888. if (reason) {
  3889. this._state.set({
  3890. 'proxyNotControllable': reason
  3891. });
  3892. return this.setBadge(badge);
  3893. } else {
  3894. this._state.remove(['proxyNotControllable']);
  3895. return this.clearBadge();
  3896. }
  3897. };
  3898. ChromeOptions.prototype._badgeTitle = null;
  3899. ChromeOptions.prototype.setBadge = function(options) {
  3900. if (!options) {
  3901. options = this._proxyNotControllable ? {
  3902. text: '=',
  3903. color: '#da4f49'
  3904. } : {
  3905. text: '?',
  3906. color: '#49afcd'
  3907. };
  3908. }
  3909. chrome.browserAction.setBadgeText({
  3910. text: options.text
  3911. });
  3912. chrome.browserAction.setBadgeBackgroundColor({
  3913. color: options.color
  3914. });
  3915. if (options.title) {
  3916. this._badgeTitle = options.title;
  3917. return chrome.browserAction.setTitle({
  3918. title: options.title
  3919. });
  3920. } else {
  3921. return this._badgeTitle = null;
  3922. }
  3923. };
  3924. ChromeOptions.prototype.clearBadge = function() {
  3925. var base;
  3926. if (this.externalApi.disabled) {
  3927. return;
  3928. }
  3929. if (this._badgeTitle) {
  3930. this.currentProfileChanged('clearBadge');
  3931. }
  3932. if (this._proxyNotControllable) {
  3933. this.setBadge();
  3934. } else {
  3935. if (typeof (base = chrome.browserAction).setBadgeText === "function") {
  3936. base.setBadgeText({
  3937. text: ''
  3938. });
  3939. }
  3940. }
  3941. };
  3942. ChromeOptions.prototype._quickSwitchInit = false;
  3943. ChromeOptions.prototype._quickSwitchHandlerReady = false;
  3944. ChromeOptions.prototype._quickSwitchCanEnable = false;
  3945. ChromeOptions.prototype.setQuickSwitch = function(quickSwitch, canEnable) {
  3946. var base, ref;
  3947. this._quickSwitchCanEnable = canEnable;
  3948. if (!this._quickSwitchHandlerReady) {
  3949. this._quickSwitchHandlerReady = true;
  3950. window.OmegaContextMenuQuickSwitchHandler = (function(_this) {
  3951. return function(info) {
  3952. var changes, setOptions;
  3953. changes = {};
  3954. changes['-enableQuickSwitch'] = info.checked;
  3955. setOptions = _this._setOptions(changes);
  3956. if (info.checked && !_this._quickSwitchCanEnable) {
  3957. return setOptions.then(function() {
  3958. return chrome.tabs.create({
  3959. url: chrome.extension.getURL('options.html#/ui')
  3960. });
  3961. });
  3962. }
  3963. };
  3964. })(this);
  3965. }
  3966. if (quickSwitch || (chrome.browserAction.setPopup == null)) {
  3967. if (typeof (base = chrome.browserAction).setPopup === "function") {
  3968. base.setPopup({
  3969. popup: ''
  3970. });
  3971. }
  3972. if (!this._quickSwitchInit) {
  3973. this._quickSwitchInit = true;
  3974. chrome.browserAction.onClicked.addListener((function(_this) {
  3975. return function(tab) {
  3976. var index, profiles;
  3977. _this.clearBadge();
  3978. if (!_this._options['-enableQuickSwitch']) {
  3979. chrome.tabs.create({
  3980. url: 'popup/index.html'
  3981. });
  3982. return;
  3983. }
  3984. profiles = _this._options['-quickSwitchProfiles'];
  3985. index = profiles.indexOf(_this._currentProfileName);
  3986. index = (index + 1) % profiles.length;
  3987. return _this.applyProfile(profiles[index]).then(function() {
  3988. var url;
  3989. if (_this._options['-refreshOnProfileChange']) {
  3990. url = tab.url;
  3991. if (!url) {
  3992. return;
  3993. }
  3994. if (url.substr(0, 6) === 'chrome') {
  3995. return;
  3996. }
  3997. if (url.substr(0, 6) === 'about:') {
  3998. return;
  3999. }
  4000. if (url.substr(0, 4) === 'moz-') {
  4001. return;
  4002. }
  4003. return chrome.tabs.reload(tab.id);
  4004. }
  4005. });
  4006. };
  4007. })(this));
  4008. }
  4009. } else {
  4010. chrome.browserAction.setPopup({
  4011. popup: 'popup/index.html'
  4012. });
  4013. }
  4014. if ((ref = chrome.contextMenus) != null) {
  4015. ref.update('enableQuickSwitch', {
  4016. checked: !!quickSwitch
  4017. });
  4018. }
  4019. return Promise.resolve();
  4020. };
  4021. ChromeOptions.prototype.setInspect = function(settings) {
  4022. if (this._inspect) {
  4023. if (settings.showMenu) {
  4024. this._inspect.enable();
  4025. } else {
  4026. this._inspect.disable();
  4027. }
  4028. }
  4029. return Promise.resolve();
  4030. };
  4031. ChromeOptions.prototype._requestMonitor = null;
  4032. ChromeOptions.prototype._monitorWebRequests = false;
  4033. ChromeOptions.prototype._tabRequestInfoPorts = null;
  4034. ChromeOptions.prototype.setMonitorWebRequests = function(enabled) {
  4035. var wildcardForReq;
  4036. this._monitorWebRequests = enabled;
  4037. if (enabled && (this._requestMonitor == null)) {
  4038. this._tabRequestInfoPorts = {};
  4039. wildcardForReq = function(req) {
  4040. return OmegaPac.wildcardForUrl(req.url);
  4041. };
  4042. this._requestMonitor = new WebRequestMonitor(wildcardForReq);
  4043. this._requestMonitor.watchTabs((function(_this) {
  4044. return function(tabId, info) {
  4045. var badge, ref;
  4046. if (!_this._monitorWebRequests) {
  4047. return;
  4048. }
  4049. if (info.errorCount > 0) {
  4050. info.badgeSet = true;
  4051. badge = {
  4052. text: info.errorCount.toString(),
  4053. color: '#f0ad4e'
  4054. };
  4055. chrome.browserAction.setBadgeText({
  4056. text: badge.text,
  4057. tabId: tabId
  4058. });
  4059. chrome.browserAction.setBadgeBackgroundColor({
  4060. color: badge.color,
  4061. tabId: tabId
  4062. });
  4063. } else if (info.badgeSet) {
  4064. info.badgeSet = false;
  4065. chrome.browserAction.setBadgeText({
  4066. text: '',
  4067. tabId: tabId
  4068. });
  4069. }
  4070. return (ref = _this._tabRequestInfoPorts[tabId]) != null ? ref.postMessage({
  4071. errorCount: info.errorCount,
  4072. summary: info.summary
  4073. }) : void 0;
  4074. };
  4075. })(this));
  4076. return chrome.runtime.onConnect.addListener((function(_this) {
  4077. return function(rawPort) {
  4078. var port, tabId;
  4079. if (rawPort.name !== 'tabRequestInfo') {
  4080. return;
  4081. }
  4082. if (!_this._monitorWebRequests) {
  4083. return;
  4084. }
  4085. tabId = null;
  4086. port = new ChromePort(rawPort);
  4087. port.onMessage.addListener(function(msg) {
  4088. var info;
  4089. tabId = msg.tabId;
  4090. _this._tabRequestInfoPorts[tabId] = port;
  4091. info = _this._requestMonitor.tabInfo[tabId];
  4092. if (info) {
  4093. return port.postMessage({
  4094. errorCount: info.errorCount,
  4095. summary: info.summary
  4096. });
  4097. }
  4098. });
  4099. return port.onDisconnect.addListener(function() {
  4100. if (tabId != null) {
  4101. return delete _this._tabRequestInfoPorts[tabId];
  4102. }
  4103. });
  4104. };
  4105. })(this));
  4106. }
  4107. };
  4108. ChromeOptions.prototype._alarms = null;
  4109. ChromeOptions.prototype.schedule = function(name, periodInMinutes, callback) {
  4110. name = 'omega.' + name;
  4111. if (typeof _alarms === "undefined" || _alarms === null) {
  4112. this._alarms = {};
  4113. chrome.alarms.onAlarm.addListener((function(_this) {
  4114. return function(alarm) {
  4115. var base, name1;
  4116. return typeof (base = _this._alarms)[name1 = alarm.name] === "function" ? base[name1]() : void 0;
  4117. };
  4118. })(this));
  4119. }
  4120. if (periodInMinutes < 0) {
  4121. delete this._alarms[name];
  4122. chrome.alarms.clear(name);
  4123. } else {
  4124. this._alarms[name] = callback;
  4125. chrome.alarms.create(name, {
  4126. periodInMinutes: periodInMinutes
  4127. });
  4128. }
  4129. return Promise.resolve();
  4130. };
  4131. ChromeOptions.prototype.printFixedProfile = function(profile) {
  4132. var i, len, pacResult, ref, result, scheme;
  4133. if (profile.profileType !== 'FixedProfile') {
  4134. return;
  4135. }
  4136. result = '';
  4137. ref = OmegaPac.Profiles.schemes;
  4138. for (i = 0, len = ref.length; i < len; i++) {
  4139. scheme = ref[i];
  4140. if (!profile[scheme.prop]) {
  4141. continue;
  4142. }
  4143. pacResult = OmegaPac.Profiles.pacResult(profile[scheme.prop]);
  4144. if (scheme.scheme) {
  4145. result += scheme.scheme + ": " + pacResult + "\n";
  4146. } else {
  4147. result += pacResult + "\n";
  4148. }
  4149. }
  4150. result || (result = chrome.i18n.getMessage('browserAction_profileDetails_DirectProfile'));
  4151. return result;
  4152. };
  4153. ChromeOptions.prototype.printProfile = function(profile) {
  4154. var type;
  4155. type = profile.profileType;
  4156. if (type.indexOf('RuleListProfile') >= 0) {
  4157. type = 'RuleListProfile';
  4158. }
  4159. if (type === 'FixedProfile') {
  4160. return this.printFixedProfile(profile);
  4161. } else if (type === 'PacProfile' && profile.pacUrl) {
  4162. return profile.pacUrl;
  4163. } else {
  4164. return chrome.i18n.getMessage('browserAction_profileDetails_' + type) || null;
  4165. }
  4166. };
  4167. ChromeOptions.prototype.upgrade = function(options, changes) {
  4168. return ChromeOptions.__super__.upgrade.call(this, options)["catch"]((function(_this) {
  4169. return function(err) {
  4170. var getOldOptions;
  4171. if (options != null ? options['schemaVersion'] : void 0) {
  4172. return Promise.reject(err);
  4173. }
  4174. getOldOptions = _this.switchySharp ? _this.switchySharp.getOptions().timeout(1000) : Promise.reject();
  4175. getOldOptions = getOldOptions["catch"](function() {
  4176. if (options != null ? options['config'] : void 0) {
  4177. return Promise.resolve(options);
  4178. } else if (localStorage['config']) {
  4179. return Promise.resolve(localStorage);
  4180. } else {
  4181. return Promise.reject(new OmegaTarget.Options.NoOptionsError());
  4182. }
  4183. });
  4184. return getOldOptions.then(function(oldOptions) {
  4185. var ex, i18n, upgraded;
  4186. i18n = {
  4187. upgrade_profile_auto: chrome.i18n.getMessage('upgrade_profile_auto')
  4188. };
  4189. try {
  4190. upgraded = require('./upgrade')(oldOptions, i18n);
  4191. } catch (error1) {
  4192. ex = error1;
  4193. _this.log.error(ex);
  4194. return Promise.reject(ex);
  4195. }
  4196. if (localStorage['config']) {
  4197. Object.getPrototypeOf(localStorage).clear.call(localStorage);
  4198. }
  4199. _this._state.set({
  4200. 'firstRun': 'upgrade'
  4201. });
  4202. return _this && ChromeOptions.__super__.upgrade.call(_this, upgraded, upgraded);
  4203. });
  4204. };
  4205. })(this));
  4206. };
  4207. ChromeOptions.prototype.onFirstRun = function(reason) {
  4208. return chrome.tabs.create({
  4209. url: chrome.extension.getURL('options.html')
  4210. });
  4211. };
  4212. ChromeOptions.prototype.getPageInfo = function(arg) {
  4213. var errorCount, getBadge, getInspectUrl, ref, ref1, result, tabId, url;
  4214. tabId = arg.tabId, url = arg.url;
  4215. errorCount = (ref = this._requestMonitor) != null ? (ref1 = ref.tabInfo[tabId]) != null ? ref1.errorCount : void 0 : void 0;
  4216. result = errorCount ? {
  4217. errorCount: errorCount
  4218. } : null;
  4219. getBadge = new Promise(function(resolve, reject) {
  4220. if (chrome.browserAction.getBadgeText == null) {
  4221. resolve('');
  4222. return;
  4223. }
  4224. return chrome.browserAction.getBadgeText({
  4225. tabId: tabId
  4226. }, function(result) {
  4227. return resolve(result);
  4228. });
  4229. });
  4230. getInspectUrl = this._state.get({
  4231. inspectUrl: ''
  4232. });
  4233. return Promise.join(getBadge, getInspectUrl, (function(_this) {
  4234. return function(badge, arg1) {
  4235. var domain, errorPagePrefix, inspectUrl;
  4236. inspectUrl = arg1.inspectUrl;
  4237. if (badge === '#' && inspectUrl) {
  4238. url = inspectUrl;
  4239. } else {
  4240. _this.clearBadge();
  4241. }
  4242. if (!url) {
  4243. return result;
  4244. }
  4245. if (url.substr(0, 6) === 'chrome') {
  4246. errorPagePrefix = 'chrome://errorpage/';
  4247. if (url.substr(0, errorPagePrefix.length) === errorPagePrefix) {
  4248. url = querystring.parse(url.substr(url.indexOf('?') + 1)).lasturl;
  4249. if (!url) {
  4250. return result;
  4251. }
  4252. } else {
  4253. return result;
  4254. }
  4255. }
  4256. if (url.substr(0, 6) === 'about:') {
  4257. return result;
  4258. }
  4259. if (url.substr(0, 4) === 'moz-') {
  4260. return result;
  4261. }
  4262. domain = OmegaPac.getBaseDomain(Url.parse(url).hostname);
  4263. return {
  4264. url: url,
  4265. domain: domain,
  4266. tempRuleProfileName: _this.queryTempRule(domain),
  4267. errorCount: errorCount
  4268. };
  4269. };
  4270. })(this));
  4271. };
  4272. return ChromeOptions;
  4273. })(OmegaTarget.Options);
  4274. module.exports = ChromeOptions;
  4275. },{"./chrome_port":21,"./fetch_url":23,"./upgrade":36,"./web_request_monitor":37,"omega-target":19,"querystring":15,"url":17}],27:[function(require,module,exports){
  4276. var ListenerProxyImpl, ScriptProxyImpl, SettingsProxyImpl;
  4277. ListenerProxyImpl = require('./proxy_impl_listener');
  4278. SettingsProxyImpl = require('./proxy_impl_settings');
  4279. ScriptProxyImpl = require('./proxy_impl_script');
  4280. exports.proxyImpls = [ListenerProxyImpl, ScriptProxyImpl, SettingsProxyImpl];
  4281. exports.getProxyImpl = function(log) {
  4282. var Impl, i, len, ref;
  4283. ref = exports.proxyImpls;
  4284. for (i = 0, len = ref.length; i < len; i++) {
  4285. Impl = ref[i];
  4286. if (Impl.isSupported()) {
  4287. return new Impl(log);
  4288. }
  4289. }
  4290. throw new Error('Your browser does not support proxy settings!');
  4291. };
  4292. },{"./proxy_impl_listener":30,"./proxy_impl_script":31,"./proxy_impl_settings":32}],28:[function(require,module,exports){
  4293. var OmegaPac, OmegaTarget, Promise, ProxyAuth;
  4294. OmegaTarget = require('omega-target');
  4295. OmegaPac = OmegaTarget.OmegaPac;
  4296. Promise = OmegaTarget.Promise;
  4297. module.exports = ProxyAuth = (function() {
  4298. function ProxyAuth(log) {
  4299. this._requests = {};
  4300. this.log = log;
  4301. }
  4302. ProxyAuth.prototype.listening = false;
  4303. ProxyAuth.prototype.listen = function() {
  4304. if (this.listening) {
  4305. return;
  4306. }
  4307. if (!chrome.webRequest) {
  4308. this.log.error('Proxy auth disabled! No webRequest permission.');
  4309. return;
  4310. }
  4311. if (!chrome.webRequest.onAuthRequired) {
  4312. this.log.error('Proxy auth disabled! onAuthRequired not available.');
  4313. return;
  4314. }
  4315. chrome.webRequest.onAuthRequired.addListener(this.authHandler.bind(this), {
  4316. urls: ['<all_urls>']
  4317. }, ['blocking']);
  4318. chrome.webRequest.onCompleted.addListener(this._requestDone.bind(this), {
  4319. urls: ['<all_urls>']
  4320. });
  4321. chrome.webRequest.onErrorOccurred.addListener(this._requestDone.bind(this), {
  4322. urls: ['<all_urls>']
  4323. });
  4324. return this.listening = true;
  4325. };
  4326. ProxyAuth.prototype._keyForProxy = function(proxy) {
  4327. return (proxy.host.toLowerCase()) + ":" + proxy.port;
  4328. };
  4329. ProxyAuth.prototype.setProxies = function(profiles) {
  4330. var auth, fallback, i, j, key, len, len1, list, profile, proxy, ref, ref1, ref2, results, scheme;
  4331. this._proxies = {};
  4332. this._fallbacks = [];
  4333. results = [];
  4334. for (i = 0, len = profiles.length; i < len; i++) {
  4335. profile = profiles[i];
  4336. if (!profile.auth) {
  4337. continue;
  4338. }
  4339. ref = OmegaPac.Profiles.schemes;
  4340. for (j = 0, len1 = ref.length; j < len1; j++) {
  4341. scheme = ref[j];
  4342. if (!profile[scheme.prop]) {
  4343. continue;
  4344. }
  4345. auth = (ref1 = profile.auth) != null ? ref1[scheme.prop] : void 0;
  4346. if (!auth) {
  4347. continue;
  4348. }
  4349. proxy = profile[scheme.prop];
  4350. key = this._keyForProxy(proxy);
  4351. list = this._proxies[key];
  4352. if (list == null) {
  4353. this._proxies[key] = list = [];
  4354. }
  4355. list.push({
  4356. config: proxy,
  4357. auth: auth,
  4358. name: profile.name + '.' + scheme.prop
  4359. });
  4360. }
  4361. fallback = (ref2 = profile.auth) != null ? ref2['all'] : void 0;
  4362. if (fallback != null) {
  4363. results.push(this._fallbacks.push({
  4364. auth: fallback,
  4365. name: profile.name + '.' + 'all'
  4366. }));
  4367. } else {
  4368. results.push(void 0);
  4369. }
  4370. }
  4371. return results;
  4372. };
  4373. ProxyAuth.prototype._proxies = {};
  4374. ProxyAuth.prototype._fallbacks = [];
  4375. ProxyAuth.prototype._requests = null;
  4376. ProxyAuth.prototype.authHandler = function(details) {
  4377. var key, list, listLen, proxy, req;
  4378. if (!details.isProxy) {
  4379. return {};
  4380. }
  4381. req = this._requests[details.requestId];
  4382. if (req == null) {
  4383. this._requests[details.requestId] = req = {
  4384. authTries: 0
  4385. };
  4386. }
  4387. key = this._keyForProxy({
  4388. host: details.challenger.host,
  4389. port: details.challenger.port
  4390. });
  4391. list = this._proxies[key];
  4392. listLen = list != null ? list.length : 0;
  4393. if (req.authTries < listLen) {
  4394. proxy = list[req.authTries];
  4395. } else {
  4396. proxy = this._fallbacks[req.authTries - listLen];
  4397. }
  4398. this.log.log('ProxyAuth', key, req.authTries, proxy != null ? proxy.name : void 0);
  4399. if (proxy == null) {
  4400. return {};
  4401. }
  4402. req.authTries++;
  4403. return {
  4404. authCredentials: proxy.auth
  4405. };
  4406. };
  4407. ProxyAuth.prototype._requestDone = function(details) {
  4408. return delete this._requests[details.requestId];
  4409. };
  4410. return ProxyAuth;
  4411. })();
  4412. },{"omega-target":19}],29:[function(require,module,exports){
  4413. var OmegaTarget, Promise, ProxyAuth, ProxyImpl,
  4414. hasProp = {}.hasOwnProperty;
  4415. OmegaTarget = require('omega-target');
  4416. Promise = OmegaTarget.Promise;
  4417. ProxyAuth = require('./proxy_auth');
  4418. ProxyImpl = (function() {
  4419. function ProxyImpl(log) {
  4420. this.log = log;
  4421. }
  4422. ProxyImpl.isSupported = function() {
  4423. return false;
  4424. };
  4425. ProxyImpl.prototype.applyProfile = function(profile, meta) {
  4426. return Promise.reject();
  4427. };
  4428. ProxyImpl.prototype.watchProxyChange = function(callback) {
  4429. return null;
  4430. };
  4431. ProxyImpl.prototype.parseExternalProfile = function(details, options) {
  4432. return null;
  4433. };
  4434. ProxyImpl.prototype._profileNotFound = function(name) {
  4435. this.log.error("Profile " + name + " not found! Things may go very, very wrong.");
  4436. return OmegaPac.Profiles.create({
  4437. name: name,
  4438. profileType: 'VirtualProfile',
  4439. defaultProfileName: 'direct'
  4440. });
  4441. };
  4442. ProxyImpl.prototype.setProxyAuth = function(profile, options) {
  4443. return Promise["try"]((function(_this) {
  4444. return function() {
  4445. var _, name, ref_set, referenced_profiles;
  4446. if (_this._proxyAuth == null) {
  4447. _this._proxyAuth = new ProxyAuth(_this.log);
  4448. }
  4449. _this._proxyAuth.listen();
  4450. referenced_profiles = [];
  4451. ref_set = OmegaPac.Profiles.allReferenceSet(profile, options, {
  4452. profileNotFound: _this._profileNotFound.bind(_this)
  4453. });
  4454. for (_ in ref_set) {
  4455. if (!hasProp.call(ref_set, _)) continue;
  4456. name = ref_set[_];
  4457. profile = OmegaPac.Profiles.byName(name, options);
  4458. if (profile) {
  4459. referenced_profiles.push(profile);
  4460. }
  4461. }
  4462. return _this._proxyAuth.setProxies(referenced_profiles);
  4463. };
  4464. })(this));
  4465. };
  4466. ProxyImpl.prototype.getProfilePacScript = function(profile, meta, options) {
  4467. var ast, prefix, profileName, script;
  4468. if (meta == null) {
  4469. meta = profile;
  4470. }
  4471. ast = OmegaPac.PacGenerator.script(options, profile, {
  4472. profileNotFound: this._profileNotFound.bind(this)
  4473. });
  4474. ast = OmegaPac.PacGenerator.compress(ast);
  4475. script = OmegaPac.PacGenerator.ascii(ast.print_to_string());
  4476. profileName = OmegaPac.PacGenerator.ascii(JSON.stringify(meta.name));
  4477. profileName = profileName.replace(/\*/g, '\\u002a');
  4478. profileName = profileName.replace(/\\/g, '\\u002f');
  4479. prefix = "/*OmegaProfile*" + profileName + "*" + meta.revision + "*/";
  4480. return prefix + script;
  4481. };
  4482. return ProxyImpl;
  4483. })();
  4484. module.exports = ProxyImpl;
  4485. },{"./proxy_auth":28,"omega-target":19}],30:[function(require,module,exports){
  4486. var ListenerProxyImpl, NativePromise, OmegaTarget, ProxyImpl,
  4487. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  4488. hasProp = {}.hasOwnProperty;
  4489. OmegaTarget = require('omega-target');
  4490. NativePromise = typeof Promise !== "undefined" && Promise !== null ? Promise : null;
  4491. ProxyImpl = require('./proxy_impl');
  4492. ListenerProxyImpl = (function(superClass) {
  4493. extend(ListenerProxyImpl, superClass);
  4494. ListenerProxyImpl.isSupported = function() {
  4495. var ref;
  4496. return (typeof Promise !== "undefined" && Promise !== null) && ((typeof browser !== "undefined" && browser !== null ? (ref = browser.proxy) != null ? ref.onRequest : void 0 : void 0) != null);
  4497. };
  4498. ListenerProxyImpl.prototype.features = ['fullUrl', 'socks5Auth'];
  4499. function ListenerProxyImpl() {
  4500. ListenerProxyImpl.__super__.constructor.apply(this, arguments);
  4501. this._optionsReady = new NativePromise((function(_this) {
  4502. return function(resolve) {
  4503. return _this._optionsReadyCallback = resolve;
  4504. };
  4505. })(this));
  4506. this._initRequestListeners();
  4507. }
  4508. ListenerProxyImpl.prototype._initRequestListeners = function() {
  4509. browser.proxy.onRequest.addListener(this.onRequest.bind(this), {
  4510. urls: ["<all_urls>"]
  4511. });
  4512. return browser.proxy.onError.addListener(this.onError.bind(this));
  4513. };
  4514. ListenerProxyImpl.prototype.watchProxyChange = function(callback) {
  4515. return null;
  4516. };
  4517. ListenerProxyImpl.prototype.applyProfile = function(profile, state, options) {
  4518. this._options = options;
  4519. this._profile = profile;
  4520. if (typeof this._optionsReadyCallback === "function") {
  4521. this._optionsReadyCallback();
  4522. }
  4523. this._optionsReadyCallback = null;
  4524. return this.setProxyAuth(profile, options);
  4525. };
  4526. ListenerProxyImpl.prototype.onRequest = function(requestDetails) {
  4527. return NativePromise.resolve(this._optionsReady.then((function(_this) {
  4528. return function() {
  4529. var auth, next, profile, proxy, request, result;
  4530. request = OmegaPac.Conditions.requestFromUrl(requestDetails.url);
  4531. profile = _this._profile;
  4532. while (profile) {
  4533. result = OmegaPac.Profiles.match(profile, request);
  4534. if (!result) {
  4535. switch (profile.profileType) {
  4536. case 'DirectProfile':
  4537. return {
  4538. type: 'direct'
  4539. };
  4540. case 'SystemProfile':
  4541. return void 0;
  4542. default:
  4543. throw new Error('Unsupported profile: ' + profile.profileType);
  4544. }
  4545. }
  4546. if (Array.isArray(result)) {
  4547. proxy = result[2];
  4548. auth = result[3];
  4549. if (proxy) {
  4550. return _this.proxyInfo(proxy, auth);
  4551. }
  4552. next = result[0];
  4553. } else if (result.profileName) {
  4554. next = OmegaPac.Profiles.nameAsKey(result.profileName);
  4555. } else {
  4556. break;
  4557. }
  4558. profile = OmegaPac.Profiles.byKey(next, _this._options);
  4559. }
  4560. throw new Error('Profile not found: ' + next);
  4561. };
  4562. })(this)));
  4563. };
  4564. ListenerProxyImpl.prototype.onError = function(error) {
  4565. return this.log.error(error);
  4566. };
  4567. ListenerProxyImpl.prototype.proxyInfo = function(proxy, auth) {
  4568. var proxyInfo;
  4569. proxyInfo = {
  4570. type: proxy.scheme,
  4571. host: proxy.host,
  4572. port: proxy.port
  4573. };
  4574. if (proxyInfo.type === 'socks5') {
  4575. proxyInfo.type = 'socks';
  4576. if (auth) {
  4577. proxyInfo.username = auth.username;
  4578. proxyInfo.password = auth.password;
  4579. }
  4580. }
  4581. if (proxyInfo.type === 'socks') {
  4582. proxyInfo.proxyDNS = true;
  4583. }
  4584. return [proxyInfo];
  4585. };
  4586. return ListenerProxyImpl;
  4587. })(ProxyImpl);
  4588. module.exports = ListenerProxyImpl;
  4589. },{"./proxy_impl":29,"omega-target":19}],31:[function(require,module,exports){
  4590. var OmegaTarget, Promise, ProxyImpl, ScriptProxyImpl,
  4591. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  4592. hasProp = {}.hasOwnProperty;
  4593. OmegaTarget = require('omega-target');
  4594. Promise = OmegaTarget.Promise;
  4595. ProxyImpl = require('./proxy_impl');
  4596. ScriptProxyImpl = (function(superClass) {
  4597. extend(ScriptProxyImpl, superClass);
  4598. function ScriptProxyImpl() {
  4599. return ScriptProxyImpl.__super__.constructor.apply(this, arguments);
  4600. }
  4601. ScriptProxyImpl.isSupported = function() {
  4602. var ref, ref1;
  4603. return ((typeof browser !== "undefined" && browser !== null ? (ref = browser.proxy) != null ? ref.register : void 0 : void 0) != null) || ((typeof browser !== "undefined" && browser !== null ? (ref1 = browser.proxy) != null ? ref1.registerProxyScript : void 0 : void 0) != null);
  4604. };
  4605. ScriptProxyImpl.prototype.features = ['socks5Auth'];
  4606. ScriptProxyImpl.prototype._proxyScriptUrl = 'js/omega_webext_proxy_script.min.js';
  4607. ScriptProxyImpl.prototype._proxyScriptDisabled = false;
  4608. ScriptProxyImpl.prototype._proxyScriptInitialized = false;
  4609. ScriptProxyImpl.prototype._proxyScriptState = {};
  4610. ScriptProxyImpl.prototype.watchProxyChange = function(callback) {
  4611. return null;
  4612. };
  4613. ScriptProxyImpl.prototype.applyProfile = function(profile, state, options) {
  4614. this.log.error('Your browser is outdated! Full-URL based matching, etc. unsupported! ' + "Please update your browser ASAP!");
  4615. state = state != null ? state : {};
  4616. this._options = options;
  4617. state.currentProfileName = profile.name;
  4618. if (profile.name === '') {
  4619. state.tempProfile = profile;
  4620. }
  4621. if (profile.profileType === 'SystemProfile') {
  4622. if (browser.proxy.unregister != null) {
  4623. browser.proxy.unregister();
  4624. } else {
  4625. browser.proxy.registerProxyScript('js/omega_invalid_proxy_script.js');
  4626. }
  4627. this._proxyScriptDisabled = true;
  4628. } else {
  4629. this._proxyScriptState = state;
  4630. Promise.all([browser.runtime.getBrowserInfo(), this._initWebextProxyScript()]).then((function(_this) {
  4631. return function(arg) {
  4632. var info;
  4633. info = arg[0];
  4634. if (info.vendor === 'Mozilla' && info.buildID < '20170918220054') {
  4635. _this.log.error('Your browser is outdated! SOCKS5 DNS/Auth unsupported! ' + ("Please update your browser ASAP! (Current Build " + info.buildID + ")"));
  4636. _this._proxyScriptState.useLegacyStringReturn = true;
  4637. }
  4638. return _this._proxyScriptStateChanged();
  4639. };
  4640. })(this));
  4641. }
  4642. return this.setProxyAuth(profile, options);
  4643. };
  4644. ScriptProxyImpl.prototype._initWebextProxyScript = function() {
  4645. var promise;
  4646. if (!this._proxyScriptInitialized) {
  4647. browser.proxy.onProxyError.addListener((function(_this) {
  4648. return function(err) {
  4649. if ((err != null ? err.message : void 0) != null) {
  4650. if (err.message.indexOf('Invalid Proxy Rule: DIRECT') >= 0) {
  4651. return;
  4652. }
  4653. if (err.message.indexOf('Return type must be a string') >= 0) {
  4654. _this.log.error('Your browser is outdated! SOCKS5 DNS/Auth unsupported! ' + 'Please update your browser ASAP!');
  4655. _this._proxyScriptState.useLegacyStringReturn = true;
  4656. _this._proxyScriptStateChanged();
  4657. return;
  4658. }
  4659. }
  4660. return _this.log.error(err);
  4661. };
  4662. })(this));
  4663. browser.runtime.onMessage.addListener((function(_this) {
  4664. return function(message) {
  4665. if (message.event !== 'proxyScriptLog') {
  4666. return;
  4667. }
  4668. if (message.level === 'error') {
  4669. return _this.log.error(message);
  4670. } else if (message.level === 'warn') {
  4671. return _this.log.error(message);
  4672. } else {
  4673. return _this.log.log(message);
  4674. }
  4675. };
  4676. })(this));
  4677. }
  4678. if (!this._proxyScriptInitialized || this._proxyScriptDisabled) {
  4679. promise = new Promise(function(resolve) {
  4680. var onMessage;
  4681. onMessage = function(message) {
  4682. if (message.event !== 'proxyScriptLoaded') {
  4683. return;
  4684. }
  4685. resolve();
  4686. browser.runtime.onMessage.removeListener(onMessage);
  4687. };
  4688. return browser.runtime.onMessage.addListener(onMessage);
  4689. });
  4690. if (browser.proxy.register != null) {
  4691. browser.proxy.register(this._proxyScriptUrl);
  4692. } else {
  4693. browser.proxy.registerProxyScript(this._proxyScriptUrl);
  4694. }
  4695. this._proxyScriptDisabled = false;
  4696. } else {
  4697. promise = Promise.resolve();
  4698. }
  4699. this._proxyScriptInitialized = true;
  4700. return promise;
  4701. };
  4702. ScriptProxyImpl.prototype._proxyScriptStateChanged = function() {
  4703. return browser.runtime.sendMessage({
  4704. event: 'proxyScriptStateChanged',
  4705. state: this._proxyScriptState,
  4706. options: this._options
  4707. }, {
  4708. toProxyScript: true
  4709. });
  4710. };
  4711. return ScriptProxyImpl;
  4712. })(ProxyImpl);
  4713. module.exports = ScriptProxyImpl;
  4714. },{"./proxy_impl":29,"omega-target":19}],32:[function(require,module,exports){
  4715. var OmegaPac, OmegaTarget, Promise, ProxyImpl, SettingsProxyImpl, chromeApiPromisify,
  4716. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  4717. hasProp = {}.hasOwnProperty;
  4718. OmegaTarget = require('omega-target');
  4719. OmegaPac = OmegaTarget.OmegaPac;
  4720. Promise = OmegaTarget.Promise;
  4721. chromeApiPromisify = require('../chrome_api').chromeApiPromisify;
  4722. ProxyImpl = require('./proxy_impl');
  4723. SettingsProxyImpl = (function(superClass) {
  4724. extend(SettingsProxyImpl, superClass);
  4725. function SettingsProxyImpl() {
  4726. return SettingsProxyImpl.__super__.constructor.apply(this, arguments);
  4727. }
  4728. SettingsProxyImpl.isSupported = function() {
  4729. var ref;
  4730. return (typeof chrome !== "undefined" && chrome !== null ? (ref = chrome.proxy) != null ? ref.settings : void 0 : void 0) != null;
  4731. };
  4732. SettingsProxyImpl.prototype.features = ['fullUrlHttp', 'pacScript', 'watchProxyChange'];
  4733. SettingsProxyImpl.prototype.applyProfile = function(profile, meta, options) {
  4734. var config;
  4735. if (meta == null) {
  4736. meta = profile;
  4737. }
  4738. if (profile.profileType === 'SystemProfile') {
  4739. return chromeApiPromisify(chrome.proxy.settings, 'clear')({}).then((function(_this) {
  4740. return function() {
  4741. chrome.proxy.settings.get({}, _this._proxyChangeListener);
  4742. };
  4743. })(this));
  4744. }
  4745. config = {};
  4746. if (profile.profileType === 'DirectProfile') {
  4747. config['mode'] = 'direct';
  4748. } else if (profile.profileType === 'PacProfile') {
  4749. config['mode'] = 'pac_script';
  4750. config['pacScript'] = !profile.pacScript || OmegaPac.Profiles.isFileUrl(profile.pacUrl) ? {
  4751. url: profile.pacUrl,
  4752. mandatory: true
  4753. } : {
  4754. data: OmegaPac.PacGenerator.ascii(profile.pacScript),
  4755. mandatory: true
  4756. };
  4757. } else if (profile.profileType === 'FixedProfile') {
  4758. config = this._fixedProfileConfig(profile);
  4759. } else {
  4760. config['mode'] = 'pac_script';
  4761. config['pacScript'] = {
  4762. mandatory: true,
  4763. data: this.getProfilePacScript(profile, meta, options)
  4764. };
  4765. }
  4766. return this.setProxyAuth(profile, options).then(function() {
  4767. return chromeApiPromisify(chrome.proxy.settings, 'set')({
  4768. value: config
  4769. });
  4770. }).then((function(_this) {
  4771. return function() {
  4772. chrome.proxy.settings.get({}, _this._proxyChangeListener);
  4773. };
  4774. })(this));
  4775. };
  4776. SettingsProxyImpl.prototype._fixedProfileConfig = function(profile) {
  4777. var bypassList, condition, config, j, k, l, len, len1, len2, protocol, protocolProxySet, protocols, ref, rules;
  4778. config = {};
  4779. config['mode'] = 'fixed_servers';
  4780. rules = {};
  4781. protocols = ['proxyForHttp', 'proxyForHttps', 'proxyForFtp'];
  4782. protocolProxySet = false;
  4783. for (j = 0, len = protocols.length; j < len; j++) {
  4784. protocol = protocols[j];
  4785. if (!(profile[protocol] != null)) {
  4786. continue;
  4787. }
  4788. rules[protocol] = profile[protocol];
  4789. protocolProxySet = true;
  4790. }
  4791. if (profile.fallbackProxy) {
  4792. if (profile.fallbackProxy.scheme === 'http') {
  4793. if (!protocolProxySet) {
  4794. rules['singleProxy'] = profile.fallbackProxy;
  4795. } else {
  4796. for (k = 0, len1 = protocols.length; k < len1; k++) {
  4797. protocol = protocols[k];
  4798. if (rules[protocol] == null) {
  4799. rules[protocol] = JSON.parse(JSON.stringify(profile.fallbackProxy));
  4800. }
  4801. }
  4802. }
  4803. } else {
  4804. rules['fallbackProxy'] = profile.fallbackProxy;
  4805. }
  4806. } else if (!protocolProxySet) {
  4807. config['mode'] = 'direct';
  4808. }
  4809. if (config['mode'] !== 'direct') {
  4810. rules['bypassList'] = bypassList = [];
  4811. ref = profile.bypassList;
  4812. for (l = 0, len2 = ref.length; l < len2; l++) {
  4813. condition = ref[l];
  4814. bypassList.push(this._formatBypassItem(condition));
  4815. }
  4816. config['rules'] = rules;
  4817. }
  4818. return config;
  4819. };
  4820. SettingsProxyImpl.prototype._formatBypassItem = function(condition) {
  4821. var i, str;
  4822. str = OmegaPac.Conditions.str(condition);
  4823. i = str.indexOf(' ');
  4824. return str.substr(i + 1);
  4825. };
  4826. SettingsProxyImpl.prototype._proxyChangeWatchers = null;
  4827. SettingsProxyImpl.prototype._proxyChangeListener = function(details) {
  4828. var j, len, ref, ref1, results, watcher;
  4829. ref1 = (ref = this._proxyChangeWatchers) != null ? ref : [];
  4830. results = [];
  4831. for (j = 0, len = ref1.length; j < len; j++) {
  4832. watcher = ref1[j];
  4833. results.push(watcher(details));
  4834. }
  4835. return results;
  4836. };
  4837. SettingsProxyImpl.prototype.watchProxyChange = function(callback) {
  4838. var ref, ref1;
  4839. if (this._proxyChangeWatchers == null) {
  4840. this._proxyChangeWatchers = [];
  4841. if ((typeof chrome !== "undefined" && chrome !== null ? (ref = chrome.proxy) != null ? (ref1 = ref.settings) != null ? ref1.onChange : void 0 : void 0 : void 0) != null) {
  4842. chrome.proxy.settings.onChange.addListener(this._proxyChangeListener.bind(this));
  4843. }
  4844. }
  4845. this._proxyChangeWatchers.push(callback);
  4846. };
  4847. SettingsProxyImpl.prototype.parseExternalProfile = function(details, options) {
  4848. var bypassCount, bypassSet, host, j, k, l, len, len1, len2, len3, m, pattern, profile, prop, props, proxies, ref, ref1, result, url;
  4849. if (details.name) {
  4850. return details;
  4851. }
  4852. switch (details.value.mode) {
  4853. case 'system':
  4854. return OmegaPac.Profiles.byName('system');
  4855. case 'direct':
  4856. return OmegaPac.Profiles.byName('direct');
  4857. case 'auto_detect':
  4858. return OmegaPac.Profiles.create({
  4859. profileType: 'PacProfile',
  4860. name: '',
  4861. pacUrl: 'http://wpad/wpad.dat'
  4862. });
  4863. case 'pac_script':
  4864. url = details.value.pacScript.url;
  4865. if (url) {
  4866. profile = null;
  4867. OmegaPac.Profiles.each(options, function(key, p) {
  4868. if (p.profileType === 'PacProfile' && p.pacUrl === url) {
  4869. return profile = p;
  4870. }
  4871. });
  4872. return profile != null ? profile : OmegaPac.Profiles.create({
  4873. profileType: 'PacProfile',
  4874. name: '',
  4875. pacUrl: url
  4876. });
  4877. } else {
  4878. return (function() {
  4879. var _, end, i, magic, profileName, revision, script, tokens;
  4880. profile = null;
  4881. script = details.value.pacScript.data;
  4882. OmegaPac.Profiles.each(options, function(key, p) {
  4883. if (p.profileType === 'PacProfile' && p.pacScript === script) {
  4884. return profile = p;
  4885. }
  4886. });
  4887. if (profile) {
  4888. return profile;
  4889. }
  4890. script = script.trim();
  4891. magic = '/*OmegaProfile*';
  4892. if (script.substr(0, magic.length) === magic) {
  4893. end = script.indexOf('*/');
  4894. if (end > 0) {
  4895. i = magic.length;
  4896. tokens = script.substring(magic.length, end).split('*');
  4897. profileName = tokens[0], revision = tokens[1];
  4898. try {
  4899. profileName = JSON.parse(profileName);
  4900. } catch (error) {
  4901. _ = error;
  4902. profileName = null;
  4903. }
  4904. if (profileName && revision) {
  4905. profile = OmegaPac.Profiles.byName(profileName, options);
  4906. if (OmegaPac.Revision.compare(profile.revision, revision) === 0) {
  4907. return profile;
  4908. }
  4909. }
  4910. }
  4911. }
  4912. return OmegaPac.Profiles.create({
  4913. profileType: 'PacProfile',
  4914. name: '',
  4915. pacScript: script
  4916. });
  4917. })();
  4918. }
  4919. break;
  4920. case 'fixed_servers':
  4921. props = ['proxyForHttp', 'proxyForHttps', 'proxyForFtp', 'fallbackProxy', 'singleProxy'];
  4922. proxies = {};
  4923. for (j = 0, len = props.length; j < len; j++) {
  4924. prop = props[j];
  4925. result = OmegaPac.Profiles.pacResult(details.value.rules[prop]);
  4926. if (prop === 'singleProxy' && (details.value.rules[prop] != null)) {
  4927. proxies['fallbackProxy'] = result;
  4928. } else {
  4929. proxies[prop] = result;
  4930. }
  4931. }
  4932. bypassSet = {};
  4933. bypassCount = 0;
  4934. if (details.value.rules.bypassList) {
  4935. ref = details.value.rules.bypassList;
  4936. for (k = 0, len1 = ref.length; k < len1; k++) {
  4937. pattern = ref[k];
  4938. bypassSet[pattern] = true;
  4939. bypassCount++;
  4940. }
  4941. }
  4942. if (bypassSet['<local>']) {
  4943. ref1 = OmegaPac.Conditions.localHosts;
  4944. for (l = 0, len2 = ref1.length; l < len2; l++) {
  4945. host = ref1[l];
  4946. if (!bypassSet[host]) {
  4947. continue;
  4948. }
  4949. delete bypassSet[host];
  4950. bypassCount--;
  4951. }
  4952. }
  4953. profile = null;
  4954. OmegaPac.Profiles.each(options, (function(_this) {
  4955. return function(key, p) {
  4956. var condition, len3, len4, m, n, ref2, rules;
  4957. if (p.profileType !== 'FixedProfile') {
  4958. return;
  4959. }
  4960. if (p.bypassList.length !== bypassCount) {
  4961. return;
  4962. }
  4963. ref2 = p.bypassList;
  4964. for (m = 0, len3 = ref2.length; m < len3; m++) {
  4965. condition = ref2[m];
  4966. if (!bypassSet[condition.pattern]) {
  4967. return;
  4968. }
  4969. }
  4970. rules = _this._fixedProfileConfig(p).rules;
  4971. if (rules['singleProxy']) {
  4972. rules['fallbackProxy'] = rules['singleProxy'];
  4973. delete rules['singleProxy'];
  4974. }
  4975. if (rules == null) {
  4976. return;
  4977. }
  4978. for (n = 0, len4 = props.length; n < len4; n++) {
  4979. prop = props[n];
  4980. if (rules[prop] || proxies[prop]) {
  4981. if (OmegaPac.Profiles.pacResult(rules[prop]) !== proxies[prop]) {
  4982. return;
  4983. }
  4984. }
  4985. }
  4986. return profile = p;
  4987. };
  4988. })(this));
  4989. if (profile) {
  4990. return profile;
  4991. } else {
  4992. profile = OmegaPac.Profiles.create({
  4993. profileType: 'FixedProfile',
  4994. name: ''
  4995. });
  4996. for (m = 0, len3 = props.length; m < len3; m++) {
  4997. prop = props[m];
  4998. if (details.value.rules[prop]) {
  4999. if (prop === 'singleProxy') {
  5000. profile['fallbackProxy'] = details.value.rules[prop];
  5001. } else {
  5002. profile[prop] = details.value.rules[prop];
  5003. }
  5004. }
  5005. }
  5006. profile.bypassList = (function() {
  5007. var results;
  5008. results = [];
  5009. for (pattern in bypassSet) {
  5010. if (!hasProp.call(bypassSet, pattern)) continue;
  5011. results.push({
  5012. conditionType: 'BypassCondition',
  5013. pattern: pattern
  5014. });
  5015. }
  5016. return results;
  5017. })();
  5018. return profile;
  5019. }
  5020. }
  5021. };
  5022. return SettingsProxyImpl;
  5023. })(ProxyImpl);
  5024. module.exports = SettingsProxyImpl;
  5025. },{"../chrome_api":20,"./proxy_impl":29,"omega-target":19}],33:[function(require,module,exports){
  5026. var ChromeStorage, OmegaTarget, Promise, chromeApiPromisify,
  5027. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  5028. hasProp = {}.hasOwnProperty;
  5029. chromeApiPromisify = require('./chrome_api').chromeApiPromisify;
  5030. OmegaTarget = require('omega-target');
  5031. Promise = OmegaTarget.Promise;
  5032. ChromeStorage = (function(superClass) {
  5033. extend(ChromeStorage, superClass);
  5034. ChromeStorage.parseStorageErrors = function(err) {
  5035. var sustainedPerMinute;
  5036. if (err != null ? err.message : void 0) {
  5037. sustainedPerMinute = 'MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE';
  5038. if (err.message.indexOf('QUOTA_BYTES_PER_ITEM') >= 0) {
  5039. err = new OmegaTarget.Storage.QuotaExceededError();
  5040. err.perItem = true;
  5041. } else if (err.message.indexOf('QUOTA_BYTES') >= 0) {
  5042. err = new OmegaTarget.Storage.QuotaExceededError();
  5043. } else if (err.message.indexOf('MAX_ITEMS') >= 0) {
  5044. err = new OmegaTarget.Storage.QuotaExceededError();
  5045. err.maxItems = true;
  5046. } else if (err.message.indexOf('MAX_WRITE_OPERATIONS_') >= 0) {
  5047. err = new OmegaTarget.Storage.RateLimitExceededError();
  5048. if (err.message.indexOf('MAX_WRITE_OPERATIONS_PER_HOUR') >= 0) {
  5049. err.perHour = true;
  5050. } else if (err.message.indexOf('MAX_WRITE_OPERATIONS_PER_MINUTE') >= 0) {
  5051. err.perMinute = true;
  5052. }
  5053. } else if (err.message.indexOf(sustainedPerMinute) >= 0) {
  5054. err = new OmegaTarget.Storage.RateLimitExceededError();
  5055. err.perMinute = true;
  5056. err.sustained = 10;
  5057. } else if (err.message.indexOf('is not available') >= 0) {
  5058. err = new OmegaTarget.Storage.StorageUnavailableError();
  5059. } else if (err.message.indexOf('Please set webextensions.storage.sync.enabled to true') >= 0) {
  5060. err = new OmegaTarget.Storage.StorageUnavailableError();
  5061. }
  5062. }
  5063. return Promise.reject(err);
  5064. };
  5065. function ChromeStorage(areaName1) {
  5066. var ref;
  5067. this.areaName = areaName1;
  5068. if (typeof browser !== "undefined" && browser !== null ? (ref = browser.storage) != null ? ref[this.areaName] : void 0 : void 0) {
  5069. this.storage = browser.storage[this.areaName];
  5070. } else {
  5071. this.storage = {
  5072. get: chromeApiPromisify(chrome.storage[this.areaName], 'get'),
  5073. set: chromeApiPromisify(chrome.storage[this.areaName], 'set'),
  5074. remove: chromeApiPromisify(chrome.storage[this.areaName], 'remove'),
  5075. clear: chromeApiPromisify(chrome.storage[this.areaName], 'clear')
  5076. };
  5077. }
  5078. }
  5079. ChromeStorage.prototype.get = function(keys) {
  5080. if (keys == null) {
  5081. keys = null;
  5082. }
  5083. return Promise.resolve(this.storage.get(keys))["catch"](ChromeStorage.parseStorageErrors);
  5084. };
  5085. ChromeStorage.prototype.set = function(items) {
  5086. if (Object.keys(items).length === 0) {
  5087. return Promise.resolve({});
  5088. }
  5089. return Promise.resolve(this.storage.set(items))["catch"](ChromeStorage.parseStorageErrors);
  5090. };
  5091. ChromeStorage.prototype.remove = function(keys) {
  5092. if (keys == null) {
  5093. return Promise.resolve(this.storage.clear());
  5094. }
  5095. if (Array.isArray(keys) && keys.length === 0) {
  5096. return Promise.resolve({});
  5097. }
  5098. return Promise.resolve(this.storage.remove(keys))["catch"](ChromeStorage.parseStorageErrors);
  5099. };
  5100. ChromeStorage.prototype.watch = function(keys, callback) {
  5101. var area, base, i, id, key, keyMap, len, name, watcher;
  5102. if ((base = ChromeStorage.watchers)[name = this.areaName] == null) {
  5103. base[name] = {};
  5104. }
  5105. area = ChromeStorage.watchers[this.areaName];
  5106. watcher = {
  5107. keys: keys,
  5108. callback: callback
  5109. };
  5110. id = Date.now().toString();
  5111. while (area[id]) {
  5112. id = Date.now().toString();
  5113. }
  5114. if (Array.isArray(keys)) {
  5115. keyMap = {};
  5116. for (i = 0, len = keys.length; i < len; i++) {
  5117. key = keys[i];
  5118. keyMap[key] = true;
  5119. }
  5120. keys = keyMap;
  5121. }
  5122. area[id] = {
  5123. keys: keys,
  5124. callback: callback
  5125. };
  5126. if (!ChromeStorage.onChangedListenerInstalled) {
  5127. chrome.storage.onChanged.addListener(ChromeStorage.onChangedListener);
  5128. ChromeStorage.onChangedListenerInstalled = true;
  5129. }
  5130. return function() {
  5131. return delete area[id];
  5132. };
  5133. };
  5134. ChromeStorage.onChangedListener = function(changes, areaName) {
  5135. var _, change, key, map, match, ref, results, watcher;
  5136. map = null;
  5137. ref = ChromeStorage.watchers[areaName];
  5138. results = [];
  5139. for (_ in ref) {
  5140. watcher = ref[_];
  5141. match = watcher.keys === null;
  5142. if (!match) {
  5143. for (key in changes) {
  5144. if (!hasProp.call(changes, key)) continue;
  5145. if (watcher.keys[key]) {
  5146. match = true;
  5147. break;
  5148. }
  5149. }
  5150. }
  5151. if (match) {
  5152. if (map == null) {
  5153. map = {};
  5154. for (key in changes) {
  5155. if (!hasProp.call(changes, key)) continue;
  5156. change = changes[key];
  5157. map[key] = change.newValue;
  5158. }
  5159. }
  5160. results.push(watcher.callback(map));
  5161. } else {
  5162. results.push(void 0);
  5163. }
  5164. }
  5165. return results;
  5166. };
  5167. ChromeStorage.onChangedListenerInstalled = false;
  5168. ChromeStorage.watchers = {};
  5169. return ChromeStorage;
  5170. })(OmegaTarget.Storage);
  5171. module.exports = ChromeStorage;
  5172. },{"./chrome_api":20,"omega-target":19}],34:[function(require,module,exports){
  5173. var ChromePort, OmegaPac, OmegaTarget, Promise, SwitchySharp;
  5174. OmegaTarget = require('omega-target');
  5175. OmegaPac = OmegaTarget.OmegaPac;
  5176. Promise = OmegaTarget.Promise;
  5177. ChromePort = require('./chrome_port');
  5178. module.exports = SwitchySharp = (function() {
  5179. function SwitchySharp() {}
  5180. SwitchySharp.extId = 'dpplabbmogkhghncfbfdeeokoefdjegm';
  5181. SwitchySharp.prototype.port = null;
  5182. SwitchySharp.prototype.monitor = function(action) {
  5183. if (location.href.substr(0, 4) === 'moz-') {
  5184. return;
  5185. }
  5186. if ((typeof port === "undefined" || port === null) && (this._monitorTimerId == null)) {
  5187. this._monitorTimerId = setInterval(this._connect.bind(this), 5000);
  5188. if (action !== 'reconnect') {
  5189. return this._connect();
  5190. }
  5191. }
  5192. };
  5193. SwitchySharp.prototype.getOptions = function() {
  5194. if (!this._getOptions) {
  5195. this._getOptions = new Promise((function(_this) {
  5196. return function(resolve) {
  5197. _this._getOptionsResolver = resolve;
  5198. return _this.monitor();
  5199. };
  5200. })(this));
  5201. }
  5202. return this._getOptions;
  5203. };
  5204. SwitchySharp.prototype._getOptions = null;
  5205. SwitchySharp.prototype._getOptionsResolver = null;
  5206. SwitchySharp.prototype._monitorTimerId = null;
  5207. SwitchySharp.prototype._onMessage = function(msg) {
  5208. if (this._monitorTimerId) {
  5209. clearInterval(this._monitorTimerId);
  5210. this._monitorTimerId = null;
  5211. }
  5212. switch (msg != null ? msg.action : void 0) {
  5213. case 'state':
  5214. OmegaTarget.Log.log(msg);
  5215. if (this._getOptionsResolver) {
  5216. return this.port.postMessage({
  5217. action: 'getOptions'
  5218. });
  5219. }
  5220. break;
  5221. case 'options':
  5222. if (typeof this._getOptionsResolver === "function") {
  5223. this._getOptionsResolver(msg.options);
  5224. }
  5225. return this._getOptionsResolver = null;
  5226. }
  5227. };
  5228. SwitchySharp.prototype._onDisconnect = function(msg) {
  5229. this.port = null;
  5230. this._getOptions = null;
  5231. this._getOptionsResolver = null;
  5232. return this.monitor('reconnect');
  5233. };
  5234. SwitchySharp.prototype._connect = function() {
  5235. var _, ref;
  5236. if (!this.port) {
  5237. this.port = new ChromePort(chrome.runtime.connect(SwitchySharp.extId));
  5238. this.port.onDisconnect.addListener(this._onDisconnect.bind(this));
  5239. if ((ref = this.port) != null) {
  5240. ref.onMessage.addListener(this._onMessage.bind(this));
  5241. }
  5242. }
  5243. try {
  5244. this.port.postMessage({
  5245. action: 'disable'
  5246. });
  5247. } catch (error) {
  5248. _ = error;
  5249. this.port = null;
  5250. }
  5251. return this.port != null;
  5252. };
  5253. return SwitchySharp;
  5254. })();
  5255. },{"./chrome_port":21,"omega-target":19}],35:[function(require,module,exports){
  5256. var ChromeTabs,
  5257. hasProp = {}.hasOwnProperty;
  5258. ChromeTabs = (function() {
  5259. ChromeTabs.prototype._defaultAction = null;
  5260. ChromeTabs.prototype._badgeTab = null;
  5261. function ChromeTabs(actionForUrl) {
  5262. this.actionForUrl = actionForUrl;
  5263. this._dirtyTabs = {};
  5264. return;
  5265. }
  5266. ChromeTabs.prototype.ignoreError = function() {
  5267. chrome.runtime.lastError;
  5268. };
  5269. ChromeTabs.prototype.watch = function() {
  5270. chrome.tabs.onUpdated.addListener(this.onUpdated.bind(this));
  5271. return chrome.tabs.onActivated.addListener((function(_this) {
  5272. return function(info) {
  5273. return chrome.tabs.get(info.tabId, function(tab) {
  5274. if (chrome.runtime.lastError) {
  5275. return;
  5276. }
  5277. if (_this._dirtyTabs.hasOwnProperty(info.tabId)) {
  5278. return _this.onUpdated(tab.id, {}, tab);
  5279. }
  5280. });
  5281. };
  5282. })(this));
  5283. };
  5284. ChromeTabs.prototype.resetAll = function(action) {
  5285. this._defaultAction = action;
  5286. chrome.tabs.query({}, (function(_this) {
  5287. return function(tabs) {
  5288. _this._dirtyTabs = {};
  5289. return tabs.forEach(function(tab) {
  5290. _this._dirtyTabs[tab.id] = tab.id;
  5291. if (tab.active) {
  5292. return _this.onUpdated(tab.id, {}, tab);
  5293. }
  5294. });
  5295. };
  5296. })(this));
  5297. if (chrome.browserAction.setPopup != null) {
  5298. chrome.browserAction.setTitle({
  5299. title: action.title
  5300. });
  5301. } else {
  5302. chrome.browserAction.setTitle({
  5303. title: action.shortTitle
  5304. });
  5305. }
  5306. return this.setIcon(action.icon);
  5307. };
  5308. ChromeTabs.prototype.onUpdated = function(tabId, changeInfo, tab) {
  5309. if (this._dirtyTabs.hasOwnProperty(tab.id)) {
  5310. delete this._dirtyTabs[tab.id];
  5311. } else if (changeInfo.url == null) {
  5312. if ((changeInfo.status != null) && changeInfo.status !== 'loading') {
  5313. return;
  5314. }
  5315. }
  5316. return this.processTab(tab, changeInfo);
  5317. };
  5318. ChromeTabs.prototype.processTab = function(tab, changeInfo) {
  5319. var base, id, ref;
  5320. if (this._badgeTab) {
  5321. ref = this._badgeTab;
  5322. for (id in ref) {
  5323. if (!hasProp.call(ref, id)) continue;
  5324. try {
  5325. if (typeof (base = chrome.browserAction).setBadgeText === "function") {
  5326. base.setBadgeText({
  5327. text: '',
  5328. tabId: id
  5329. });
  5330. }
  5331. } catch (error) {}
  5332. this._badgeTab = null;
  5333. }
  5334. }
  5335. if ((tab.url == null) || tab.url.indexOf("chrome") === 0) {
  5336. if (this._defaultAction) {
  5337. chrome.browserAction.setTitle({
  5338. title: this._defaultAction.title,
  5339. tabId: tab.id
  5340. });
  5341. this.clearIcon(tab.id);
  5342. }
  5343. return;
  5344. }
  5345. return this.actionForUrl(tab.url).then((function(_this) {
  5346. return function(action) {
  5347. if (!action) {
  5348. _this.clearIcon(tab.id);
  5349. return;
  5350. }
  5351. _this.setIcon(action.icon, tab.id);
  5352. if (chrome.browserAction.setPopup != null) {
  5353. return chrome.browserAction.setTitle({
  5354. title: action.title,
  5355. tabId: tab.id
  5356. });
  5357. } else {
  5358. return chrome.browserAction.setTitle({
  5359. title: action.shortTitle,
  5360. tabId: tab.id
  5361. });
  5362. }
  5363. };
  5364. })(this));
  5365. };
  5366. ChromeTabs.prototype.setTabBadge = function(tab, badge) {
  5367. var base, base1;
  5368. if (this._badgeTab == null) {
  5369. this._badgeTab = {};
  5370. }
  5371. this._badgeTab[tab.id] = true;
  5372. if (typeof (base = chrome.browserAction).setBadgeText === "function") {
  5373. base.setBadgeText({
  5374. text: badge.text,
  5375. tabId: tab.id
  5376. });
  5377. }
  5378. return typeof (base1 = chrome.browserAction).setBadgeBackgroundColor === "function" ? base1.setBadgeBackgroundColor({
  5379. color: badge.color,
  5380. tabId: tab.id
  5381. }) : void 0;
  5382. };
  5383. ChromeTabs.prototype.setIcon = function(icon, tabId) {
  5384. var params;
  5385. if (icon == null) {
  5386. return;
  5387. }
  5388. if (tabId != null) {
  5389. params = {
  5390. imageData: icon,
  5391. tabId: tabId
  5392. };
  5393. } else {
  5394. params = {
  5395. imageData: icon
  5396. };
  5397. }
  5398. return this._chromeSetIcon(params);
  5399. };
  5400. ChromeTabs.prototype._chromeSetIcon = function(params) {
  5401. var _, base, base1;
  5402. try {
  5403. return typeof (base = chrome.browserAction).setIcon === "function" ? base.setIcon(params, this.ignoreError) : void 0;
  5404. } catch (error) {
  5405. _ = error;
  5406. params.imageData = {
  5407. 19: params.imageData[19],
  5408. 38: params.imageData[38]
  5409. };
  5410. return typeof (base1 = chrome.browserAction).setIcon === "function" ? base1.setIcon(params, this.ignoreError) : void 0;
  5411. }
  5412. };
  5413. ChromeTabs.prototype.clearIcon = function(tabId) {
  5414. var ref;
  5415. if (((ref = this._defaultAction) != null ? ref.icon : void 0) == null) {
  5416. return;
  5417. }
  5418. return this._chromeSetIcon({
  5419. imageData: this._defaultAction.icon,
  5420. tabId: tabId
  5421. }, this.ignoreError);
  5422. };
  5423. return ChromeTabs;
  5424. })();
  5425. module.exports = ChromeTabs;
  5426. },{}],36:[function(require,module,exports){
  5427. var OmegaPac, OmegaTarget,
  5428. hasProp = {}.hasOwnProperty;
  5429. OmegaTarget = require('omega-target');
  5430. OmegaPac = OmegaTarget.OmegaPac;
  5431. module.exports = function(oldOptions, i18n) {
  5432. var Buffer, _, auto, boolItems, color, colorTranslations, conditionFromRule, config, defaultRule, exampleFixedProfileName, haslocalPattern, key, name, nameMap, num, oldKey, oldProfile, oldProfiles, options, profile, protocol, quickSwitch, ref, ref1, rule, rulelist, rules, seenFixedProfile, startupId, text, url;
  5433. config = (function() {
  5434. try {
  5435. return JSON.parse(oldOptions['config']);
  5436. } catch (error) {}
  5437. })();
  5438. if (config) {
  5439. options = typeof changes !== "undefined" && changes !== null ? changes : {};
  5440. options['schemaVersion'] = 2;
  5441. boolItems = {
  5442. '-confirmDeletion': 'confirmDeletion',
  5443. '-refreshOnProfileChange': 'refreshTab',
  5444. '-enableQuickSwitch': 'quickSwitch',
  5445. '-revertProxyChanges': 'preventProxyChanges'
  5446. };
  5447. for (key in boolItems) {
  5448. if (!hasProp.call(boolItems, key)) continue;
  5449. oldKey = boolItems[key];
  5450. options[key] = !!config[oldKey];
  5451. }
  5452. options['-downloadInterval'] = parseInt(config['ruleListReload']) || 15;
  5453. auto = OmegaPac.Profiles.create({
  5454. profileType: 'SwitchProfile',
  5455. name: i18n.upgrade_profile_auto,
  5456. color: '#55bb55',
  5457. defaultProfileName: 'direct'
  5458. });
  5459. OmegaPac.Profiles.updateRevision(auto);
  5460. options[OmegaPac.Profiles.nameAsKey(auto.name)] = auto;
  5461. rulelist = OmegaPac.Profiles.create({
  5462. profileType: 'RuleListProfile',
  5463. name: '__ruleListOf_' + auto.name,
  5464. color: '#dd6633',
  5465. format: config['ruleListAutoProxy'] ? 'AutoProxy' : 'Switchy',
  5466. defaultProfileName: 'direct',
  5467. sourceUrl: config['ruleListUrl'] || ''
  5468. });
  5469. options[OmegaPac.Profiles.nameAsKey(rulelist.name)] = rulelist;
  5470. auto.defaultProfileName = rulelist.name;
  5471. nameMap = {
  5472. 'auto': auto.name,
  5473. 'direct': 'direct'
  5474. };
  5475. oldProfiles = ((function() {
  5476. try {
  5477. return JSON.parse(oldOptions['profiles']);
  5478. } catch (error) {}
  5479. })()) || {};
  5480. colorTranslations = {
  5481. 'blue': '#99ccee',
  5482. 'green': '#99dd99',
  5483. 'red': '#ffaa88',
  5484. 'yellow': '#ffee99',
  5485. 'purple': '#d497ee',
  5486. '': '#99ccee'
  5487. };
  5488. seenFixedProfile = false;
  5489. for (_ in oldProfiles) {
  5490. if (!hasProp.call(oldProfiles, _)) continue;
  5491. oldProfile = oldProfiles[_];
  5492. profile = null;
  5493. switch (oldProfile['proxyMode']) {
  5494. case 'auto':
  5495. profile = OmegaPac.Profiles.create({
  5496. profileType: 'PacProfile'
  5497. });
  5498. url = oldProfile['proxyConfigUrl'];
  5499. if (url.substr(0, 5) === 'data:') {
  5500. text = url.substr(url.indexOf(',') + 1);
  5501. Buffer = require('buffer').Buffer;
  5502. text = new Buffer(text, 'base64').toString('utf8');
  5503. profile.pacScript = text;
  5504. } else {
  5505. profile.pacUrl = url;
  5506. }
  5507. break;
  5508. case 'manual':
  5509. seenFixedProfile = true;
  5510. profile = OmegaPac.Profiles.create({
  5511. profileType: 'FixedProfile'
  5512. });
  5513. if (!!oldProfile['useSameProxy']) {
  5514. profile.fallbackProxy = OmegaPac.Profiles.parseHostPort(oldProfile['proxyHttp'], 'http');
  5515. } else if (oldProfile['proxySocks']) {
  5516. protocol = oldProfile['socksVersion'] === 5 ? 'socks5' : 'socks4';
  5517. profile.fallbackProxy = OmegaPac.Profiles.parseHostPort(oldProfile['proxySocks'], protocol);
  5518. } else {
  5519. profile.proxyForHttp = OmegaPac.Profiles.parseHostPort(oldProfile['proxyHttp'], 'http');
  5520. profile.proxyForHttps = OmegaPac.Profiles.parseHostPort(oldProfile['proxyHttps'], 'http');
  5521. profile.proxyForFtp = OmegaPac.Profiles.parseHostPort(oldProfile['proxyFtp'], 'http');
  5522. }
  5523. if (oldProfile['proxyExceptions'] != null) {
  5524. haslocalPattern = false;
  5525. profile.bypassList = [];
  5526. oldProfile['proxyExceptions'].split(';').forEach(function(line) {
  5527. line = line.trim();
  5528. if (!line) {
  5529. return;
  5530. }
  5531. if (line === '<local>') {
  5532. haslocalPattern = true;
  5533. }
  5534. return profile.bypassList.push({
  5535. conditionType: 'BypassCondition',
  5536. pattern: line
  5537. });
  5538. });
  5539. if (haslocalPattern) {
  5540. profile.bypassList = profile.bypassList.filter(function(cond) {
  5541. return OmegaPac.Conditions.localHosts.indexOf(cond.pattern) < 0;
  5542. });
  5543. }
  5544. }
  5545. }
  5546. if (profile) {
  5547. color = oldProfile['color'];
  5548. profile.color = (ref = colorTranslations[color]) != null ? ref : colorTranslations[''];
  5549. name = (ref1 = oldProfile['name']) != null ? ref1 : oldProfile['id'];
  5550. name = name.trim();
  5551. if (name[0] === '_') {
  5552. name = 'p' + name;
  5553. }
  5554. profile.name = name;
  5555. num = 1;
  5556. while (OmegaPac.Profiles.byName(profile.name, options)) {
  5557. profile.name = name + num;
  5558. num++;
  5559. }
  5560. nameMap[oldProfile['id']] = profile.name;
  5561. OmegaPac.Profiles.updateRevision(profile);
  5562. options[OmegaPac.Profiles.nameAsKey(profile.name)] = profile;
  5563. }
  5564. }
  5565. if (!seenFixedProfile) {
  5566. exampleFixedProfileName = 'Example Profile';
  5567. options[OmegaPac.Profiles.nameAsKey(exampleFixedProfileName)] = {
  5568. bypassList: [
  5569. {
  5570. pattern: "127.0.0.1",
  5571. conditionType: "BypassCondition"
  5572. }, {
  5573. pattern: "::1",
  5574. conditionType: "BypassCondition"
  5575. }, {
  5576. pattern: "localhost",
  5577. conditionType: "BypassCondition"
  5578. }
  5579. ],
  5580. profileType: "FixedProfile",
  5581. name: exampleFixedProfileName,
  5582. color: "#99ccee",
  5583. fallbackProxy: {
  5584. port: 8080,
  5585. scheme: "http",
  5586. host: "proxy.example.com"
  5587. }
  5588. };
  5589. }
  5590. startupId = config['startupProfileId'];
  5591. options['-startupProfileName'] = nameMap[startupId] || '';
  5592. quickSwitch = (function() {
  5593. try {
  5594. return JSON.parse(oldOptions['quickSwitchProfiles']);
  5595. } catch (error) {}
  5596. })();
  5597. options['-quickSwitchProfiles'] = quickSwitch == null ? [] : quickSwitch.map(function(p) {
  5598. return nameMap[p];
  5599. });
  5600. if (config['ruleListProfileId']) {
  5601. rulelist.matchProfileName = nameMap[config['ruleListProfileId']] || 'direct';
  5602. }
  5603. defaultRule = (function() {
  5604. try {
  5605. return JSON.parse(oldOptions['defaultRule']);
  5606. } catch (error) {}
  5607. })();
  5608. if (defaultRule) {
  5609. rulelist.defaultProfileName = nameMap[defaultRule.profileId] || 'direct';
  5610. if (!config.ruleListEnabled) {
  5611. auto.defaultProfileName = rulelist.defaultProfileName;
  5612. }
  5613. }
  5614. OmegaPac.Profiles.updateRevision(rulelist);
  5615. rules = (function() {
  5616. try {
  5617. return JSON.parse(oldOptions['rules']);
  5618. } catch (error) {}
  5619. })();
  5620. if (rules) {
  5621. conditionFromRule = function(rule) {
  5622. var pattern;
  5623. switch (rule['patternType']) {
  5624. case 'wildcard':
  5625. pattern = rule['urlPattern'];
  5626. return OmegaPac.RuleList['Switchy'].conditionFromLegacyWildcard(pattern);
  5627. default:
  5628. return {
  5629. conditionType: 'UrlRegexCondition',
  5630. pattern: rule['urlPattern']
  5631. };
  5632. }
  5633. };
  5634. auto.rules = (function() {
  5635. var results;
  5636. results = [];
  5637. for (_ in rules) {
  5638. if (!hasProp.call(rules, _)) continue;
  5639. rule = rules[_];
  5640. results.push({
  5641. profileName: nameMap[rule['profileId']] || 'direct',
  5642. condition: conditionFromRule(rule),
  5643. note: rule.name
  5644. });
  5645. }
  5646. return results;
  5647. })();
  5648. }
  5649. return options;
  5650. }
  5651. };
  5652. },{"buffer":2,"omega-target":19}],37:[function(require,module,exports){
  5653. var Heap, Url, WebRequestMonitor,
  5654. hasProp = {}.hasOwnProperty;
  5655. Heap = require('heap');
  5656. Url = require('url');
  5657. module.exports = WebRequestMonitor = (function() {
  5658. function WebRequestMonitor(getSummaryId) {
  5659. this.getSummaryId = getSummaryId;
  5660. this._requests = {};
  5661. this._recentRequests = new Heap(function(a, b) {
  5662. return a._startTime - b._startTime;
  5663. });
  5664. this._callbacks = [];
  5665. this._tabCallbacks = [];
  5666. this.tabInfo = {};
  5667. }
  5668. WebRequestMonitor.prototype._callbacks = null;
  5669. WebRequestMonitor.prototype.watching = false;
  5670. WebRequestMonitor.prototype.timer = null;
  5671. WebRequestMonitor.prototype.watch = function(callback) {
  5672. this._callbacks.push(callback);
  5673. if (this.watching) {
  5674. return;
  5675. }
  5676. if (!chrome.webRequest) {
  5677. console.log('Request monitor disabled! No webRequest permission.');
  5678. return;
  5679. }
  5680. chrome.webRequest.onBeforeRequest.addListener(this._requestStart.bind(this), {
  5681. urls: ['<all_urls>']
  5682. });
  5683. chrome.webRequest.onHeadersReceived.addListener(this._requestHeadersReceived.bind(this), {
  5684. urls: ['<all_urls>']
  5685. });
  5686. chrome.webRequest.onBeforeRedirect.addListener(this._requestRedirected.bind(this), {
  5687. urls: ['<all_urls>']
  5688. });
  5689. chrome.webRequest.onCompleted.addListener(this._requestDone.bind(this), {
  5690. urls: ['<all_urls>']
  5691. });
  5692. chrome.webRequest.onErrorOccurred.addListener(this._requestError.bind(this), {
  5693. urls: ['<all_urls>']
  5694. });
  5695. return this.watching = true;
  5696. };
  5697. WebRequestMonitor.prototype._requests = null;
  5698. WebRequestMonitor.prototype._recentRequests = null;
  5699. WebRequestMonitor.prototype._requestStart = function(req) {
  5700. var callback, i, len, ref, results;
  5701. if (req.tabId < 0) {
  5702. return;
  5703. }
  5704. req._startTime = Date.now();
  5705. this._requests[req.requestId] = req;
  5706. this._recentRequests.push(req);
  5707. if (this.timer == null) {
  5708. this.timer = setInterval(this._tick.bind(this), 1000);
  5709. }
  5710. ref = this._callbacks;
  5711. results = [];
  5712. for (i = 0, len = ref.length; i < len; i++) {
  5713. callback = ref[i];
  5714. results.push(callback('start', req));
  5715. }
  5716. return results;
  5717. };
  5718. WebRequestMonitor.prototype._tick = function() {
  5719. var callback, i, len, now, ref, req, reqInfo, results;
  5720. now = Date.now();
  5721. results = [];
  5722. while ((req = this._recentRequests.peek())) {
  5723. reqInfo = this._requests[req.requestId];
  5724. if (reqInfo && !reqInfo.noTimeout) {
  5725. if (now - req._startTime < 5000) {
  5726. break;
  5727. } else {
  5728. reqInfo.timeoutCalled = true;
  5729. ref = this._callbacks;
  5730. for (i = 0, len = ref.length; i < len; i++) {
  5731. callback = ref[i];
  5732. callback('timeout', reqInfo);
  5733. }
  5734. }
  5735. }
  5736. results.push(this._recentRequests.pop());
  5737. }
  5738. return results;
  5739. };
  5740. WebRequestMonitor.prototype._requestHeadersReceived = function(req) {
  5741. var callback, i, len, ref, reqInfo, results;
  5742. reqInfo = this._requests[req.requestId];
  5743. if (!reqInfo) {
  5744. return;
  5745. }
  5746. reqInfo.noTimeout = true;
  5747. if (reqInfo.timeoutCalled) {
  5748. ref = this._callbacks;
  5749. results = [];
  5750. for (i = 0, len = ref.length; i < len; i++) {
  5751. callback = ref[i];
  5752. results.push(callback('ongoing', req));
  5753. }
  5754. return results;
  5755. }
  5756. };
  5757. WebRequestMonitor.prototype._requestRedirected = function(req) {
  5758. var url;
  5759. url = req.redirectUrl;
  5760. if (!url) {
  5761. return;
  5762. }
  5763. if (url.indexOf('data:') === 0 || url.indexOf('about:') === 0) {
  5764. return this._requestDone(req);
  5765. }
  5766. };
  5767. WebRequestMonitor.prototype._requestError = function(req) {
  5768. var callback, i, j, len, len1, ref, ref1, reqInfo, results;
  5769. reqInfo = this._requests[req.requestId];
  5770. delete this._requests[req.requestId];
  5771. if (req.tabId < 0) {
  5772. return;
  5773. }
  5774. if (req.error === 'net::ERR_INCOMPLETE_CHUNKED_ENCODING') {
  5775. return;
  5776. }
  5777. if (req.error.indexOf('BLOCKED') >= 0) {
  5778. return;
  5779. }
  5780. if (req.error.indexOf('net::ERR_FILE_') === 0) {
  5781. return;
  5782. }
  5783. if (req.error.indexOf('NS_ERROR_ABORT') === 0) {
  5784. return;
  5785. }
  5786. if (req.url.indexOf('file:') === 0) {
  5787. return;
  5788. }
  5789. if (req.url.indexOf('chrome') === 0) {
  5790. return;
  5791. }
  5792. if (req.url.indexOf('about:') === 0) {
  5793. return;
  5794. }
  5795. if (req.url.indexOf('moz-') === 0) {
  5796. return;
  5797. }
  5798. if (req.url.indexOf('://127.0.0.1') > 0) {
  5799. return;
  5800. }
  5801. if (!reqInfo) {
  5802. return;
  5803. }
  5804. if (req.error === 'net::ERR_ABORTED') {
  5805. if (reqInfo.timeoutCalled && !reqInfo.noTimeout) {
  5806. ref = this._callbacks;
  5807. for (i = 0, len = ref.length; i < len; i++) {
  5808. callback = ref[i];
  5809. callback('timeoutAbort', req);
  5810. }
  5811. }
  5812. return;
  5813. }
  5814. ref1 = this._callbacks;
  5815. results = [];
  5816. for (j = 0, len1 = ref1.length; j < len1; j++) {
  5817. callback = ref1[j];
  5818. results.push(callback('error', req));
  5819. }
  5820. return results;
  5821. };
  5822. WebRequestMonitor.prototype._requestDone = function(req) {
  5823. var callback, i, len, ref;
  5824. ref = this._callbacks;
  5825. for (i = 0, len = ref.length; i < len; i++) {
  5826. callback = ref[i];
  5827. callback('done', req);
  5828. }
  5829. return delete this._requests[req.requestId];
  5830. };
  5831. WebRequestMonitor.prototype.eventCategory = {
  5832. start: 'ongoing',
  5833. ongoing: 'ongoing',
  5834. timeout: 'error',
  5835. error: 'error',
  5836. timeoutAbort: 'error',
  5837. done: 'done'
  5838. };
  5839. WebRequestMonitor.prototype.tabsWatching = false;
  5840. WebRequestMonitor.prototype._tabCallbacks = null;
  5841. WebRequestMonitor.prototype.watchTabs = function(callback) {
  5842. var ref;
  5843. this._tabCallbacks.push(callback);
  5844. if (this.tabsWatching) {
  5845. return;
  5846. }
  5847. this.watch(this.setTabRequestInfo.bind(this));
  5848. this.tabsWatching = true;
  5849. chrome.tabs.onCreated.addListener((function(_this) {
  5850. return function(tab) {
  5851. if (!tab.id) {
  5852. return;
  5853. }
  5854. return _this.tabInfo[tab.id] = _this._newTabInfo();
  5855. };
  5856. })(this));
  5857. chrome.tabs.onRemoved.addListener((function(_this) {
  5858. return function(tab) {
  5859. return delete _this.tabInfo[tab.id];
  5860. };
  5861. })(this));
  5862. if ((ref = chrome.tabs.onReplaced) != null) {
  5863. ref.addListener((function(_this) {
  5864. return function(added, removed) {
  5865. var base;
  5866. if ((base = _this.tabInfo)[added] == null) {
  5867. base[added] = _this._newTabInfo();
  5868. }
  5869. return delete _this.tabInfo[removed];
  5870. };
  5871. })(this));
  5872. }
  5873. chrome.tabs.onUpdated.addListener((function(_this) {
  5874. return function(tabId, changeInfo, tab) {
  5875. var base, i, info, len, name, ref1, results;
  5876. info = (base = _this.tabInfo)[name = tab.id] != null ? base[name] : base[name] = _this._newTabInfo();
  5877. if (!info) {
  5878. return;
  5879. }
  5880. ref1 = _this._tabCallbacks;
  5881. results = [];
  5882. for (i = 0, len = ref1.length; i < len; i++) {
  5883. callback = ref1[i];
  5884. results.push(callback(tab.id, info, null, 'updated'));
  5885. }
  5886. return results;
  5887. };
  5888. })(this));
  5889. return chrome.tabs.query({}, (function(_this) {
  5890. return function(tabs) {
  5891. var base, i, len, name, results, tab;
  5892. results = [];
  5893. for (i = 0, len = tabs.length; i < len; i++) {
  5894. tab = tabs[i];
  5895. results.push((base = _this.tabInfo)[name = tab.id] != null ? base[name] : base[name] = _this._newTabInfo());
  5896. }
  5897. return results;
  5898. };
  5899. })(this));
  5900. };
  5901. WebRequestMonitor.prototype._newTabInfo = function() {
  5902. return {
  5903. requests: {},
  5904. requestCount: 0,
  5905. requestStatus: {},
  5906. ongoingCount: 0,
  5907. errorCount: 0,
  5908. doneCount: 0,
  5909. summary: {}
  5910. };
  5911. };
  5912. WebRequestMonitor.prototype.setTabRequestInfo = function(status, req) {
  5913. var callback, i, id, info, key, len, oldStatus, ref, ref1, results, summaryItem, value;
  5914. info = this.tabInfo[req.tabId];
  5915. if (info) {
  5916. if (status === 'start' && req.type === 'main_frame') {
  5917. if (req.url.indexOf('chrome://errorpage/') !== 0) {
  5918. ref = this._newTabInfo();
  5919. for (key in ref) {
  5920. if (!hasProp.call(ref, key)) continue;
  5921. value = ref[key];
  5922. info[key] = value;
  5923. }
  5924. }
  5925. }
  5926. if (info.requestCount > 1000) {
  5927. return;
  5928. }
  5929. info.requests[req.requestId] = req;
  5930. if ((oldStatus = info.requestStatus[req.requestId])) {
  5931. info[this.eventCategory[oldStatus] + 'Count']--;
  5932. } else {
  5933. if (status === 'timeoutAbort') {
  5934. return;
  5935. }
  5936. info.requestCount++;
  5937. }
  5938. info.requestStatus[req.requestId] = status;
  5939. info[this.eventCategory[status] + 'Count']++;
  5940. id = typeof this.getSummaryId === "function" ? this.getSummaryId(req) : void 0;
  5941. if (id != null) {
  5942. if (this.eventCategory[status] === 'error') {
  5943. if (this.eventCategory[oldStatus] !== 'error') {
  5944. summaryItem = info.summary[id];
  5945. if (summaryItem == null) {
  5946. summaryItem = info.summary[id] = {
  5947. errorCount: 0
  5948. };
  5949. }
  5950. summaryItem.errorCount++;
  5951. }
  5952. } else if (this.eventCategory[oldStatus] === 'error') {
  5953. summaryItem = info.summary[id];
  5954. if (summaryItem != null) {
  5955. summaryItem.errorCount--;
  5956. }
  5957. }
  5958. }
  5959. ref1 = this._tabCallbacks;
  5960. results = [];
  5961. for (i = 0, len = ref1.length; i < len; i++) {
  5962. callback = ref1[i];
  5963. results.push(callback(req.tabId, info, req, status));
  5964. }
  5965. return results;
  5966. }
  5967. };
  5968. return WebRequestMonitor;
  5969. })();
  5970. },{"heap":6,"url":17}],"OmegaTargetChromium":[function(require,module,exports){
  5971. module.exports = require('./src/module');
  5972. },{"./src/module":24}]},{},["OmegaTargetChromium"])("OmegaTargetChromium")
  5973. });